-
Notifications
You must be signed in to change notification settings - Fork 132
/
LMS.class.php
3298 lines (2895 loc) · 119 KB
/
LMS.class.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
/*
* LMS version 1.3-cvs
*
* (C) Copyright 2001-2004 LMS Developers
*
* Please, see the doc/AUTHORS for more information about authors!
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License Version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
* USA.
*
* $Id$
*/
// LMS Class - contains internal LMS database functions used
// to fetch data like usernames, searching for mac's by ID, etc..
class LMS
{
var $DB; // obiekt bazy danych
var $SESSION; // obiekt z Session.class.php (zarz±dzanie sesj±)
var $CONFIG; // tablica zawieraj±ca zmienne z lms.ini
var $_version = '1.3-cvs'; // wersja klasy
var $_revision = '$Revision$';
var $MENU = array();
function LMS(&$DB, &$SESSION, &$CONFIG) // ustawia zmienne klasy
{
if($SESSION !== NULL)
{
$this->SESSION = &$SESSION;
$this->modules[] = 'SESSION';
}
$this->DB = &$DB;
$this->CONFIG = &$CONFIG;
$this->modules[] = 'CORE';
$this->CORE = &$this;
// za³aduj ekstra klasy:
if($dirhandle = @opendir($this->CONFIG['directories']['lib_dir'].'/modules/'))
{
while(FALSE !== ($file = readdir($dirhandle)))
{
if(ereg('^[0-9a-z]+\.class.php$',$file))
{
$classname = ereg_replace('\.class.php$','',$file);
@require_once($this->CONFIG['directories']['lib_dir'].'/modules/'.$classname.'.class.php');
$this->$classname = new $classname($this);
$this->modules[] = $classname;
}
}
}
// poustawiajmy ->version
foreach($this->modules as $module)
{
$this->$module->_revision = eregi_replace('^.Revision: ([0-9.]+).*','\1',$this->$module->_revision);
$this->$module->version = $this->$module->_version.' ('.$this->$module->_revision.')';
}
// a teraz postinit
foreach($this->modules as $module)
if(! ($this->$module != NULL ? $this->$module->_postinit() : TRUE))
trigger_error('Wyst±pi³y problemy z inicjalizacj± modu³u '.$module.'.');
// to siê rozejdzie po modu³ach:
$this->AddMenu('Helpdesk', 'ticket.gif', '?m=rtqueuelist', 'Obs³uga zg³oszeñ (RT)', 'r', 60);
$this->AddMenu('Witamy !', 'l.gif', '?', '', '', 0);
$this->AddMenu('U¿ytkownicy', 'user.gif', '?m=userlist', 'U¿ytkownicy: lista, wyszukiwanie, dodanie nowego', 'u', 10);
$this->AddMenu('Komputery', 'node.gif', '?m=nodelist', 'Komputery: lista, wyszukiwanie, dodawanie', 'k', 15);
$this->AddMenu('Osprzêt sieciowy', 'netdev.gif', '?m=netdevlist', 'Ewidencja sprzêtu sieciowego', 'o', 20);
$this->AddMenu('Sieci IP', 'network.gif', '?m=netlist', 'Zarz±dzanie klasami adresowymi IP', 's', 25);
$this->AddMenu('Taryfy i finanse', 'money.gif', '?m=tarifflist', 'Zarz±dzanie taryfami oraz finansami sieci', 't', 30);
$this->AddMenu('Mailing', 'mail.gif', '?m=mailing', 'Korespondencja seryjna', 'm', 35);
$this->AddMenu('Prze³adowanie', 'reload.gif', '?m=reload', '', 'r', 40);
$this->AddMenu('Bazy danych', 'db.gif', '?m=dblist', 'Zarz±dzanie kopiami zapasowymi bazy danych', 'b', 45);
$this->AddMenu('Administratorzy', 'admins.gif', '?m=adminlist', 'Konta administratorów systemu', 'd', 50);
$this->AddMenu('Statystyki', 'traffic.gif', '?m=traffic', 'Statystyki wykorzystania ³±cza', 'x', 55);
}
function _postinit()
{
return TRUE;
}
/*
* Funkcje podstawowe (ró¿ne)
*/
function AddMenu($name = '', $img = '', $link = '', $tip = '', $accesskey = '', $prio = 99)
{
if($name != '')
{
foreach(array('name', 'img', 'link', 'tip', 'accesskey', 'prio') as $key)
$this->MENU[$key][] = $$key;
array_multisort($this->MENU[prio], SORT_NUMERIC, SORT_ASC, $this->MENU[name], SORT_STRING, SORT_ASC, $this->MENU[img], $this->MENU[link], $this->MENU[accesskey], $this->MENU[tip]);
return TRUE;
}
return FALSE;
}
/*
* Funkcje bazodanowe (backupy, timestampy)
*/
function SetTS($table) // ustawia timestamp tabeli w tabeli 'timestamps'
{
if($this->DB->GetOne('SELECT * FROM timestamps WHERE tablename=?', array($table)))
$this->DB->Execute('UPDATE timestamps SET time = ?NOW? WHERE tablename=?', array($table));
else
$this->DB->Execute('INSERT INTO timestamps (tablename, time) VALUES (?, ?NOW?)', array($table));
if($this->DB->GetOne('SELECT * FROM timestamps WHERE tablename=?', array('_global')))
$this->DB->Execute('UPDATE timestamps SET time = ?NOW? WHERE tablename=?', array('_global'));
else
$this->DB->Execute('INSERT INTO timestamps (tablename, time) VALUES (?, ?NOW?)', array('_global'));
}
function GetTS($table) // zwraca timestamp tabeli zapisany w tabeli 'timestamps'
{
return $this->DB->GetOne('SELECT time FROM timestamps WHERE tablename=?', array($table));
}
function DeleteTS($table) // usuwa timestamp tabeli zapisany w tabeli 'timestamps'
{
return $this->DB->Execute('DELETE FROM timestamps WHERE tablename=?', array($table));
}
function DatabaseList() // zwraca listê kopii baz danych w katalogu z backupami
{
if ($handle = opendir($this->CONFIG['directories']['backup_dir']))
{
while (false !== ($file = readdir($handle)))
{
if ($file != '.' && $file != '..')
{
$path = pathinfo($file);
if($path['extension'] = 'sql')
{
if(substr($path['basename'],0,4)=='lms-')
{
$dblist['time'][] = substr(basename("$file",'.sql'),4);
$dblist['size'][] = filesize($this->CONFIG['directories']['backup_dir'].'/'.$file);
}
}
}
}
closedir($handle);
}
if(sizeof($dblist['time']))
array_multisort($dblist['time'],$dblist['size']);
$dblist['total'] = sizeof($dblist['time']);
return $dblist;
}
function DatabaseRecover($dbtime) // wczytuje backup bazy danych o podanym timestampie
{
if(file_exists($this->CONFIG['directories']['backup_dir'].'/lms-'.$dbtime.'.sql'))
{
return $this->DBLoad($this->CONFIG['directories']['backup_dir'].'/lms-'.$dbtime.'.sql');
}
else
return FALSE;
}
function DBLoad($filename=NULL) // wczytuje plik z backupem bazy danych
{
if(!$filename)
return FALSE;
$file = fopen($filename,'r');
$this->DB->BeginTrans(); // przyspieszmy dzia³anie je¿eli baza danych obs³uguje transakcje
while(!feof($file))
{
$line = fgets($file,4096);
if($line!='')
{
$line=str_replace(';\n','',$line);
$this->DB->Execute($line);
}
}
$this->DB->CommitTrans();
fclose($file);
// Okej, zróbmy parê bzdurek db depend :S
// Postgres sux ! (warden)
// Tak, a ³y¿ka na to 'niemo¿liwe' i polecia³a za wann± potr±caj±c bannanem musztardê (lukasz)
switch($this->CONFIG['database']['type'])
{
case 'postgres':
// uaktualnijmy sequencery postgresa
foreach($this->DB->ListTables() as $tablename)
$this->DB->Execute("SELECT setval('".$tablename."_id_seq',max(id)) FROM ".$tablename);
break;
}
}
function DBDump($filename=NULL) // zrzuca bazê danych do pliku
{
if(! $filename)
return FALSE;
if($dumpfile = fopen($filename,'w'))
{
foreach($this->DB->ListTables() as $tablename)
{
fputs($dumpfile,"DELETE FROM $tablename;\n");
if($dump = $this->DB->GetAll('SELECT * FROM '.$tablename))
foreach($dump as $row)
{
fputs($dumpfile,"INSERT INTO $tablename (");
foreach($row as $field => $value)
{
$fields[] = $field;
if(isset($value))
$values[] = "'".addcslashes($value,"\r\n\'\"\\")."'";
else
$values[] = 'NULL';
}
fputs($dumpfile,implode(', ',$fields));
fputs($dumpfile,') VALUES (');
fputs($dumpfile,implode(', ',$values));
fputs($dumpfile,");\n");
unset($fields);
unset($values);
}
}
fclose($dumpfile);
}
else
return FALSE;
}
function DatabaseCreate() // wykonuje zrzut kopii bazy danych
{
return $this->DBDump($this->CONFIG['directories']['backup_dir'].'/lms-'.time().'.sql');
}
function DatabaseDelete($dbtime) // usuwa plik ze zrzutem
{
if(@file_exists($this->CONFIG['directories']['backup_dir'].'/lms-'.$dbtime.'.sql'))
{
return @unlink($this->CONFIG['directories']['backup_dir'].'/lms-'.$dbtime.'.sql');
}
else
return FALSE;
}
function DatabaseFetchContent($dbtime) // zwraca zawarto¶æ tekstow± kopii bazy danych
{
if(file_exists($this->CONFIG['directories']['backup_dir'].'/lms-'.$dbtime.'.sql'))
{
$content = file($this->CONFIG['directories']['backup_dir'].'/lms-'.$dbtime.'.sql');
foreach($content as $value)
$database['content'] .= $value;
$database['size'] = filesize($this->CONFIG['directories']['backup_dir'].'/lms-'.$dbtime.'.sql');
$database['time'] = $dbtime;
return $database;
}
else
return FALSE;
}
/*
* Zarz±dzanie kontami administratorów
*/
function SetAdminPassword($id,$passwd) // ustawia has³o admina o id równym $id na $passwd
{
$this->SetTS('admins');
$this->DB->Execute('UPDATE admins SET passwd=? WHERE id=?', array(crypt($passwd),$id));
}
function GetAdminName($id) // zwraca imiê admina
{
return $this->DB->GetOne('SELECT name FROM admins WHERE id=?', array($id));
}
function GetAdminList() // zwraca listê administratorów
{
if($adminslist = $this->DB->GetAll('SELECT id, login, name, lastlogindate, lastloginip FROM admins WHERE deleted=0 ORDER BY login ASC'))
{
foreach($adminslist as $idx => $row)
{
if($row['lastlogindate'])
$adminslist[$idx]['lastlogin'] = date('Y/m/d H:i',$row['lastlogindate']);
else
$adminslist[$idx]['lastlogin'] = '-';
if(check_ip($row['lastloginip']))
$adminslist[$idx]['lastloginhost'] = gethostbyaddr($row['lastloginip']);
else
{
$adminslist[$idx]['lastloginhost'] = '-';
$adminslist[$idx]['lastloginip'] = '-';
}
}
}
$adminslist['total'] = sizeof($adminslist);
return $adminslist;
}
function GetAdminIDByLogin($login) // zwraca id admina na podstawie loginu
{
return $this->DB->GetOne('SELECT id FROM admins WHERE login=?', array($login));
}
function AdminAdd($adminadd) // dodaje admina. wymaga tablicy zawieraj±cej dane admina
{
$this->SetTS('admins');
if($this->DB->Execute('INSERT INTO admins (login, name, email, passwd, rights) VALUES (?, ?, ?, ?, ?)', array($adminadd['login'], $adminadd['name'], $adminadd['email'], crypt($adminadd['password']),$adminadd['rights'])))
return $this->DB->GetOne('SELECT id FROM admins WHERE login=?', array($adminadd['login']));
else
return FALSE;
}
function AdminDelete($id) // usuwa admina o podanym id
{
$this->SetTS('admins');
return $this->DB->Execute('UPDATE admins SET deleted=1 WHERE id=?', array($id));
}
function AdminExists($id) // zwraca TRUE/FALSE zale¿nie od tego czy admin istnieje czy nie
{
switch($this->DB->GetOne('SELECT deleted FROM admins WHERE id=?', array($id)))
{
case '0':
return TRUE;
break;
case '1':
return -1;
break;
case '':
default:
return FALSE;
break;
}
}
function GetAdminInfo($id) // zwraca pe³ne info o podanym adminie
{
if($admininfo = $this->DB->GetRow('SELECT id, login, name, email, lastlogindate, lastloginip, failedlogindate, failedloginip, deleted FROM admins WHERE id=?', array($id)))
{
if($admininfo['lastlogindate'])
$admininfo['lastlogin'] = date('Y/m/d H:i',$admininfo['lastlogindate']);
else
$admininfo['lastlogin'] = '-';
if($admininfo['failedlogindate'])
$admininfo['faillogin'] = date('Y/m/d H:i',$admininfo['failedlogindate']);
else
$admininfo['faillogin'] = '-';
if(check_ip($admininfo['lastloginip']))
$admininfo['lastloginhost'] = gethostbyaddr($admininfo['lastloginip']);
else
{
$admininfo['lastloginhost'] = '-';
$admininfo['lastloginip'] = '-';
}
if(check_ip($admininfo['failedloginip']))
$admininfo['failloginhost'] = gethostbyaddr($admininfo['failedloginip']);
else
{
$admininfo['failloginhost'] = '-';
$admininfo['failloginip'] = '-';
}
}
return $admininfo;
}
function AdminUpdate($admininfo) // uaktualnia rekord admina.
{
$this->SetTS('admins');
return $this->DB->Execute('UPDATE admins SET login=?, name=?, email=?, rights=? WHERE id=?', array($admininfo['login'],$admininfo['name'],$admininfo['email'],$admininfo['rights'],$admininfo['id']));
}
function GetAdminRights($id)
{
$mask = $this->DB->GetOne('SELECT rights FROM admins WHERE id=?', array($id));
if($mask == '')
$mask = '1';
$len = strlen($mask);
for($cnt=$len; $cnt > 0; $cnt --)
$bin = sprintf('%04b',hexdec($mask[$cnt-1])).$bin;
for($cnt=strlen($bin)-1; $cnt >= 0; $cnt --)
if($bin[$cnt] == '1')
$result[] = strlen($bin) - $cnt -1;
return $result;
}
/*
* Funkcje do obs³ugi rekordów u¿ytkowników
*/
function GetUserName($id)
{
return $this->DB->GetOne('SELECT '.$this->DB->Concat('UPPER(lastname)',"' '",'name').' FROM users WHERE id=?', array($id));
}
function GetEmails($group, $network=NULL, $usergroup=NULL)
{
if($network)
$net = $this->GetNetworkParams($network);
return $this->DB->GetAll('SELECT email, '.$this->DB->Concat('lastname', "' '", 'users.name').' AS username FROM users '
.($network ? ', nodes' : '')
.($usergroup ? ', userassignments' : '')
." WHERE deleted = 0 AND email != '' ".($state ? ' AND status = '.$state : '')
.($network ? ' AND users.id=nodes.ownerid AND (ipaddr > '.$net['address'].' AND ipaddr < '.$net['broadcast'].')' : '')
.($usergroup ? ' AND users.id=userassignments.userid AND usergroupid='.$usergroup : '')
.' GROUP BY email, lastname, users.name ORDER BY username');
}
function GetUserEmail($id)
{
return $this->DB->GetOne('SELECT email FROM users WHERE id=?', array($id));
}
function GetUserServiceAddress($id)
{
return $this->DB->GetOne('SELECT serviceaddr FROM users WHERE id=?', array($id));
}
function UserExists($id)
{
switch($this->DB->GetOne('SELECT deleted FROM users WHERE id=?', array($id)))
{
case '0':
return TRUE;
break;
case '1':
return -1;
break;
case '':
default:
return FALSE;
break;
}
}
function RecoverUser($id)
{
$this->SetTS('users');
return $this->DB->Execute('UPDATE users SET deleted=0 WHERE id=?', array($id));
}
// confusing function name, gets number of tariff assignments, not number of users with this tariff
function GetUsersWithTariff($id)
{
return $this->DB->GetOne('SELECT COUNT(userid) FROM assignments, users WHERE users.id = userid AND deleted = 0 AND tariffid = ?', array($id));
}
function UserAdd($useradd)
{
if($this->DB->Execute('INSERT INTO users (name, lastname, phone1, phone2, phone3, gguin, address, zip, city, email, nip, pesel, status, creationdate, creatorid, info, serviceaddr, message) VALUES (?, UPPER(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?NOW?, ?, ?, ?, ?)', array(ucwords($useradd['name']), $useradd['lastname'], $useradd['phone1'], $useradd['phone2'], $useradd['phone3'], $useradd['gguin'], $useradd['address'], $useradd['zip'], $useradd['city'], $useradd['email'], $useradd['nip'], $useradd['pesel'], $useradd['status'], $this->SESSION->id, $useradd['info'], $useradd['serviceaddr'], $useradd['message']))) {
$this->SetTS('users');
return $this->DB->GetOne('SELECT MAX(id) FROM users');
} else
return FALSE;
}
function DeleteUser($id)
{
$this->SetTS('users');
$this->SetTS('nodes');
$this->SetTS('userassignments');
$res1=$this->DB->Execute('DELETE FROM nodes WHERE ownerid=?', array($id));
$res2=$this->DB->Execute('DELETE FROM userassignments WHERE userid=?', array($id));
$res3=$this->DB->Execute('UPDATE users SET deleted=1 WHERE id=?', array($id));
return $res1 || $res2 || res3;
}
function UserUpdate($userdata)
{
$this->SetTS('users');
return $this->DB->Execute('UPDATE users SET status=?, phone1=?, phone2=?, phone3=?, address=?, zip=?, city=?, email=?, gguin=?, nip=?, pesel=?, moddate=?NOW?, modid=?, info=?, serviceaddr=?, lastname=UPPER(?), name=?, deleted=0, message=? WHERE id=?', array( $userdata['status'], $userdata['phone1'], $userdata['phone2'], $userdata['phone3'], $userdata['address'], $userdata['zip'], $userdata['city'], $userdata['email'], $userdata['gguin'], $userdata['nip'], $userdata['pesel'], $this->SESSION->id, $userdata['info'], $userdata['serviceaddr'], $userdata['lastname'], ucwords($userdata['name']), $userdata['message'], $userdata['id'] ) );
}
function GetUserNodesNo($id)
{
return $this->DB->GetOne('SELECT COUNT(*) FROM nodes WHERE ownerid=?', array($id));
}
function GetUserIDByIP($ipaddr)
{
return $this->DB->GetOne('SELECT ownerid FROM nodes WHERE ipaddr=inet_aton(?)', array($ipaddr));
}
function GetCashByID($id)
{
return $this->DB->GetRow('SELECT time, adminid, type, value, taxvalue, userid, comment FROM cash WHERE id=?', array($id));
}
function GetUserStatus($id)
{
return $this->DB->GetOne('SELECT status FROM users WHERE id=?', array($id));
}
function GetUser($id)
{
if($result = $this->DB->GetRow('SELECT id, '.$this->DB->Concat('UPPER(lastname)',"' '",'name').' AS username, lastname, name, status, email, gguin, phone1, phone2, phone3, address, zip, nip, pesel, city, info, serviceaddr, creationdate, moddate, creatorid, modid, deleted, message FROM users WHERE id=?', array($id)))
{
$result['createdby'] = $this->GetAdminName($result['creatorid']);
$result['modifiedby'] = $this->GetAdminName($result['modid']);
$result['creationdateh'] = date("Y-m-d, H:i",$result['creationdate']);
$result['moddateh'] = date('Y-m-d, H:i',$result['moddate']);
$result['balance'] = $this->GetUserBalance($result['id']);
$result['tariffsvalue'] = $this->GetUserTariffsValue($result['id']);
return $result;
}else
return FALSE;
}
function GetUserNames()
{
return $this->DB->GetAll('SELECT id, '.$this->DB->Concat('UPPER(lastname)',"' '",'name').' AS username FROM users WHERE status=3 AND deleted = 0 ORDER BY username');
}
function GetUserNodesAC($id)
{
if($acl = $this->DB->GetALL('SELECT access FROM nodes WHERE ownerid=?', array($id)))
{
foreach($acl as $value)
if($value['access'])
$y++;
else
$n++;
if($y && !$n) return TRUE;
if($n && !$y) return FALSE;
}
if($this->DB->GetOne('SELECT COUNT(*) FROM nodes WHERE ownerid=?', array($id)))
return 2;
else
return FALSE;
}
function SearchUserList($order=NULL,$state=NULL,$search=NULL)
{
list($order,$direction)=explode(',',$order);
($direction != 'desc') ? $direction = 'asc' : $direction = 'desc';
switch($order){
case 'phone':
$sqlord = 'ORDER BY deleted ASC, phone1';
break;
case 'id':
$sqlord = 'ORDER BY deleted ASC, id';
break;
case 'address':
$sqlord = 'ORDER BY deleted ASC, address';
break;
case 'email':
$sqlord = 'ORDER BY deleted ASC, email';
break;
case 'balance':
$sqlord = 'ORDER BY deleted ASC, balance';
break;
case 'gg':
$sqlord = 'ORDER BY deleted ASC, gguin';
break;
case 'nip':
$sqlord = 'ORDER BY deleted ASC, nip, pesel';
break;
default:
$sqlord = 'ORDER BY deleted ASC, '.$this->DB->Concat('UPPER(lastname)',"' '",'name');
break;
}
if(sizeof($search))
foreach($search as $key => $value)
{
$value = str_replace(' ','%',trim($value));
if($value!='')
{
$value = "'%".$value."%'";
if($key=='phone')
$searchargs[] = "(phone1 ?LIKE? $value OR phone2 ?LIKE? $value OR phone3 ?LIKE? $value)";
elseif($key=='username')
$searchargs[] = $this->DB->Concat('UPPER(lastname)',"' '",'name').' ?LIKE? '.$value;
elseif($key!='s')
$searchargs[] = $key.' ?LIKE? '.$value;
}
}
if($searchargs)
$sqlsarg = implode(' AND ',$searchargs);
if($state>3)
$state = 0;
if($userlist = $this->DB->GetAll('SELECT users.id AS id, '.$this->DB->Concat('UPPER(lastname)',"' '",'users.name').' AS username, deleted, status, email, phone1, address, gguin, nip, pesel, zip, city, info, COALESCE(SUM((type * -2 + 7) * value), 0.00) AS balance FROM users LEFT JOIN cash ON users.id = cash.userid AND (cash.type = 3 OR cash.type = 4) WHERE 1=1 '.($state !=0 ? " AND status = '".$state."'":'').($sqlsarg !='' ? ' AND '.$sqlsarg :'').' GROUP BY users.id, deleted, lastname, users.name, status, email, phone1, phone2, phone3, address, gguin, nip, pesel, zip, city, info '.($sqlord !='' ? $sqlord.' '.$direction:'')))
{
$week = $this->DB->GetAllByKey('SELECT users.id AS id, SUM(value)*4 AS value FROM assignments, tariffs, users WHERE userid = users.id AND tariffid = tariffs.id AND deleted = 0 AND period = 0 AND (datefrom <= ?NOW? OR datefrom = 0) AND (dateto > ?NOW? OR dateto = 0) GROUP BY users.id', 'id');
$month = $this->DB->GetAllByKey('SELECT users.id AS id, SUM(value) AS value FROM assignments, tariffs, users WHERE userid = users.id AND tariffid = tariffs.id AND deleted = 0 AND period = 1 AND (datefrom <= ?NOW? OR datefrom = 0) AND (dateto > ?NOW? OR dateto = 0) GROUP BY users.id', 'id');
$quarter = $this->DB->GetAllByKey('SELECT users.id AS id, SUM(value)/3 AS value FROM assignments, tariffs, users WHERE userid = users.id AND tariffid = tariffs.id AND deleted = 0 AND period = 2 AND (datefrom <= ?NOW? OR datefrom = 0) AND (dateto > ?NOW? OR dateto = 0) GROUP BY users.id', 'id');
$year = $this->DB->GetAllByKey('SELECT users.id AS id, SUM(value)/12 AS value FROM assignments, tariffs, users WHERE userid = users.id AND tariffid = tariffs.id AND deleted = 0 AND period = 3 AND (datefrom <= ?NOW? OR datefrom = 0) AND (dateto > ?NOW? OR dateto = 0) GROUP BY users.id', 'id');
$access = $this->DB->GetAllByKey('SELECT ownerid AS id, SUM(access) AS acsum, COUNT(access) AS account FROM nodes GROUP BY ownerid','id');
$warning = $this->DB->GetAllByKey('SELECT ownerid AS id, SUM(warning) AS warnsum, COUNT(warning) AS warncount FROM nodes GROUP BY ownerid','id');
foreach($userlist as $idx => $row)
{
$userlist[$idx]['tariffvalue'] = $week[$row['id']]['value']+$month[$row['id']]['value']+$quarter[$row['id']]['value']+$year[$row['id']]['value'];
$userlist[$idx]['account'] = $access[$row['id']]['account'];
$userlist[$idx]['warncount'] = $warning[$row['id']]['warncount'];
if($access[$row['id']]['account'] == $access[$row['id']]['acsum'])
$userlist[$idx]['nodeac'] = 1;
elseif($access[$row['id']]['acsum'] == 0)
$userlist[$idx]['nodeac'] = 0;
else
$userlist[$idx]['nodeac'] = 2;
if($warning[$row['id']]['warncount'] == $warning[$row['id']]['warnsum'])
$userlist[$idx]['nodewarn'] = 1;
elseif($warning[$row['id']]['warnsum'] == 0)
$userlist[$idx]['nodewarn'] = 0;
else
$userlist[$idx]['nodewarn'] = 2;
if($userlist[$idx]['balance'] > 0)
$over += $userlist[$idx]['balance'];
elseif($userlist[$idx]['balance'] < 0)
$below += $userlist[$idx]['balance'];
}
$userlist['total']=sizeof($userlist);
$userlist['state']=$state;
$userlist['order']=$order;
$userlist['below']=$below;
$userlist['over']=$over;
$userlist['direction']=$direction;
}
return $userlist;
}
function GetUserList($order='username,asc', $state=NULL, $network=NULL, $usergroup=NULL)
{
list($order,$direction)=explode(',',$order);
($direction != 'desc') ? $direction = 'asc' : $direction = 'desc';
switch($order)
{
case 'phone':
$sqlord = 'ORDER BY phone1';
break;
case 'id':
$sqlord = 'ORDER BY users.id';
break;
case 'address':
$sqlord = 'ORDER BY address';
break;
case 'email':
$sqlord = 'ORDER BY email';
break;
case 'balance':
$sqlord = 'ORDER BY balance';
break;
case 'gg':
$sqlord = 'ORDER BY gguin';
break;
case 'nip':
$sqlord = 'ORDER BY nip, pesel';
break;
default:
$sqlord = 'ORDER BY username';
break;
}
if($state == 4) {
$deleted = 1;
// don't use usergroup and network filtering
// when user is deleted because we drop group assignments and nodes
// in DeleteUser()
$network=NULL;
$usergroup=NULL;
}
else
$deleted = 0;
$disabled = ($state == 5) ? 1 : 0;
$indebted = ($state == 6) ? 1 : 0;
if($state>3)
$state = 0;
if($network)
$net = $this->GetNetworkParams($network);
if($userlist = $this->DB->GetAll(
'SELECT users.id AS id, '.$this->DB->Concat('UPPER(lastname)',"' '",'users.name').' AS username, status, email, phone1, users.address, gguin, nip, pesel, zip, city, info, '
.($network ? 'COALESCE(SUM((type * -2 + 7) * value), 0.00)/(CASE COUNT(DISTINCT nodes.id) WHEN 0 THEN 1 ELSE COUNT(DISTINCT nodes.id) END) AS balance ' : 'COALESCE(SUM((type * -2 + 7) * value), 0.00) AS balance ')
.'FROM users LEFT JOIN cash ON (users.id=cash.userid AND (type = 3 OR type = 4)) '
.($network ? 'LEFT JOIN nodes ON (users.id=ownerid) ' : '')
.($usergroup ? 'LEFT JOIN userassignments ON (users.id=userassignments.userid) ':'')
.'WHERE deleted = '.$deleted
.($state !=0 ? ' AND status = '.$state :'')
.($network ? ' AND (ipaddr > '.$net['address'].' AND ipaddr < '.$net['broadcast'].')' : '')
.($usergroup ? ' AND usergroupid='.$usergroup : '')
.' GROUP BY users.id, lastname, users.name, status, email, phone1, users.address, gguin, nip, pesel, zip, city, info '
.($indebted ? ' HAVING SUM((type * -2 + 7) * value) < 0 ' : '')
.($sqlord !='' ? $sqlord.' '.$direction:'')
))
{
$week = $this->DB->GetAllByKey('SELECT users.id AS id, SUM(value)*4 AS value FROM assignments, tariffs, users WHERE userid = users.id AND tariffid = tariffs.id AND deleted = 0 AND period = 0 AND (datefrom <= ?NOW? OR datefrom = 0) AND (dateto > ?NOW? OR dateto = 0) GROUP BY users.id', 'id');
$month = $this->DB->GetAllByKey('SELECT users.id AS id, SUM(value) AS value FROM assignments, tariffs, users WHERE userid = users.id AND tariffid = tariffs.id AND deleted = 0 AND period = 1 AND (datefrom <= ?NOW? OR datefrom = 0) AND (dateto > ?NOW? OR dateto = 0) GROUP BY users.id', 'id');
$quarter = $this->DB->GetAllByKey('SELECT users.id AS id, SUM(value)/3 AS value FROM assignments, tariffs, users WHERE userid = users.id AND tariffid = tariffs.id AND deleted = 0 AND period = 2 AND (datefrom <= ?NOW? OR datefrom = 0) AND (dateto > ?NOW? OR dateto = 0) GROUP BY users.id', 'id');
$year = $this->DB->GetAllByKey('SELECT users.id AS id, SUM(value)/12 AS value FROM assignments, tariffs, users WHERE userid = users.id AND tariffid = tariffs.id AND deleted = 0 AND period = 3 AND (datefrom <= ?NOW? OR datefrom = 0) AND (dateto > ?NOW? OR dateto = 0) GROUP BY users.id', 'id');
$access = $this->DB->GetAllByKey('SELECT ownerid AS id, SUM(access) AS acsum, COUNT(access) AS account FROM nodes GROUP BY ownerid','id');
$warning = $this->DB->GetAllByKey('SELECT ownerid AS id, SUM(warning) AS warnsum, COUNT(warning) AS warncount FROM nodes GROUP BY ownerid','id');
$userlist2 = NULL;
foreach($userlist as $idx => $row)
{
$userlist[$idx]['tariffvalue'] = $week[$row['id']]['value']+$month[$row['id']]['value']+$quarter[$row['id']]['value']+$year[$row['id']]['value'];
$userlist[$idx]['account'] = $access[$row['id']]['account'];
$userlist[$idx]['warncount'] = $warning[$row['id']]['warncount'];
if($access[$row['id']]['account'] == $access[$row['id']]['acsum'])
$userlist[$idx]['nodeac'] = 1;
elseif($access[$row['id']]['acsum'] == 0)
$userlist[$idx]['nodeac'] = 0;
else
$userlist[$idx]['nodeac'] = 2;
if($warning[$row['id']]['warncount'] == $warning[$row['id']]['warnsum'])
$userlist[$idx]['nodewarn'] = 1;
elseif($warning[$row['id']]['warnsum'] == 0)
$userlist[$idx]['nodewarn'] = 0;
else
$userlist[$idx]['nodewarn'] = 2;
if (($disabled && $userlist[$idx]['nodeac'] != 1) || !$disabled)
if($userlist[$idx]['balance'] > 0)
$over += $userlist[$idx]['balance'];
elseif($userlist[$idx]['balance'] < 0)
$below += $userlist[$idx]['balance'];
if ($disabled && $userlist[$idx]['nodeac'] != 1)
$userlist2[] = $userlist[$idx];
}
if ($disabled)
$userlist = $userlist2;
}
switch($order)
{
case 'tariff':
foreach($userlist as $idx => $row)
{
$tarifftable['idx'][] = $idx;
$tarifftable['tariffvalue'][] = $row['tariffvalue'];
}
if(is_array($tarifftable))
{
array_multisort($tarifftable['tariffvalue'],($direction == "desc" ? SORT_DESC : SORT_ASC),$tarifftable['idx']);
foreach($tarifftable['idx'] as $idx)
$nuserelist[] = $userlist[$idx];
}
$userlist = $nuserelist;
break;
}
$userlist['total']=sizeof($userlist);
$userlist['state']=$state;
$userlist['network']=$network;
$userlist['usergroup']=$usergroup;
$userlist['order']=$order;
$userlist['below']=$below;
$userlist['over']=$over;
$userlist['direction']=$direction;
return $userlist;
}
function GetUserNodes($id)
{
if($result = $this->DB->GetAll('SELECT id, name, mac, ipaddr, inet_ntoa(ipaddr) AS ip, access, warning FROM nodes WHERE ownerid=? ORDER BY name ASC', array($id))){
$result['total'] = sizeof($result);
$result['ownerid'] = $id;
}
return $result;
}
function GetUserBalance($id, $taxvalue='-1')
{
if ($taxvalue == '-1')
{
$bin = $this->DB->GetOne('SELECT SUM(value) FROM cash WHERE userid=? AND type=3', array($id));
$bou = $this->DB->GetOne('SELECT SUM(value) FROM cash WHERE userid=? AND type=4', array($id));
}
else
if ($taxvalue == 'zw.')
{
$bin = $this->DB->GetOne('SELECT SUM(value) FROM cash WHERE userid=? AND taxvalue IS NULL AND type=3', array($id, $taxvalue));
$bou = $this->DB->GetOne('SELECT SUM(value) FROM cash WHERE userid=? AND taxvalue IS NULL AND type=4', array($id, $taxvalue));
}
else
{
$bin = $this->DB->GetOne('SELECT SUM(value) FROM cash WHERE userid=? AND taxvalue=? AND type=3', array($id, $taxvalue));
$bou = $this->DB->GetOne('SELECT SUM(value) FROM cash WHERE userid=? AND taxvalue=? AND type=4', array($id, $taxvalue));
}
return round($bin-$bou,2);
}
function GetUserBalanceList($id)
{
/* // wrapper do starego formatu
if($talist = $this->DB->GetAll("SELECT id, name FROM admins"))
foreach($talist as $idx => $row)
$adminslist[$row['id']] = $row['name'];
to mo¿na zrobiæ jednym zapytaniem, patrz ni¿ej
*/
// wrapper do starego formatu
if($tslist = $this->DB->GetAll('SELECT cash.id AS id, time, type, value, taxvalue, userid, comment, invoiceid, name AS adminname FROM cash LEFT JOIN admins ON admins.id=adminid WHERE userid=? ORDER BY time', array($id)))
// if($tslist = $this->DB->GetAll("SELECT id, time, adminid, type, value, userid, comment, invoiceid FROM cash WHERE userid=? ORDER BY time", array($id)))
foreach($tslist as $row)
foreach($row as $column => $value)
$saldolist[$column][] = $value;
if(sizeof($saldolist['id']) > 0)
{
foreach($saldolist['id'] as $i => $v)
{
($i>0) ? $saldolist['before'][$i] = $saldolist['after'][$i-1] : $saldolist['before'][$i] = 0;
// $saldolist['adminname'][$i] = $adminslist[$saldolist['adminid'][$i]];
$saldolist['value'][$i] = round($saldolist['value'][$i],3);
switch ($saldolist['type'][$i]){
case '3':
$saldolist['after'][$i] = round(($saldolist['before'][$i] + $saldolist['value'][$i]),4);
$saldolist['name'][$i] = 'Wp³ata';
break;
case '4':
$saldolist['after'][$i] = round(($saldolist['before'][$i] - $saldolist['value'][$i]),4);
$saldolist['name'][$i] = 'Obci±¿enie';
break;
}
$saldolist['date'][$i]=date('Y/m/d H:i',$saldolist['time'][$i]);
(strlen($saldolist['comment'][$i])<3) ? $saldolist['comment'][$i] = $saldolist['name'][$i] : $saldolist['comment'][$i] = $saldolist['comment'][$i];
}
$saldolist['balance'] = $saldolist['after'][sizeof($saldolist['id'])-1];
$saldolist['total'] = sizeof($saldolist['id']);
} else
$saldolist['balance'] = 0;
if($saldolist['total'])
{
foreach($saldolist['value'] as $key => $value)
$saldolist['value'][$key] = $value;
foreach($saldolist['after'] as $key => $value)
$saldolist['after'][$key] = $value;
foreach($saldolist['before'] as $key => $value)
$saldolist['before'][$key] = $value;
}
$saldolist['userid'] = $id;
return $saldolist;
}
function GetUserBalanceListByDate($id, $date=NULL)
{
if($tslist = $this->DB->GetAll('SELECT cash.id AS id, time, type, value, taxvalue, userid, comment, invoiceid, name AS adminname FROM cash LEFT JOIN admins ON admins.id=adminid WHERE userid=? ORDER BY time', array($id)))
foreach($tslist as $row)
foreach($row as $column => $value)
$saldolist[$column][] = $value;
if(sizeof($saldolist['id']) > 0)
{
foreach($saldolist['id'] as $i => $v)
{
($i>0) ? $saldolist['before'][$i] = $saldolist['after'][$i-1] : $saldolist['before'][$i] = 0;
$saldolist['value'][$i] = round($saldolist['value'][$i],3);
switch ($saldolist['type'][$i]){
case '3':
$saldolist['after'][$i] = round(($saldolist['before'][$i] + $saldolist['value'][$i]),4);
$saldolist['name'][$i] = 'wp³ata';
break;
case '4':
$saldolist['after'][$i] = round(($saldolist['before'][$i] - $saldolist['value'][$i]),4);
$saldolist['name'][$i] = 'obci±¿enie';
break;
}
if($saldolist['time'][$i]>=$date['from'] && $saldolist['time'][$i]<=$date['to'])
{
$list['id'][] = $saldolist['id'][$i];
$list['after'][] = $saldolist['after'][$i];
$list['before'][] = $saldolist['before'][$i];
$list['value'][] = $saldolist['value'][$i];
$list['taxvalue'][] = $saldolist['taxvalue'][$i];
$list['name'][] = $saldolist['name'][$i];
switch($saldolist['name'][$i])
{
case 'wp³ata': $list['summary'] += $saldolist['value'][$i]; break;
case 'obci±¿enie': $list['summary'] -= $saldolist['value'][$i]; break;
}
$list['date'][] = date('Y/m/d H:i',$saldolist['time'][$i]);
$list['adminname'][] = $saldolist['adminname'][$i];
(strlen($saldolist['comment'][$i])<3) ? $list['comment'][] = $saldolist['name'][$i] : $list['comment'][] = $saldolist['comment'][$i];
}
}
$list['balance'] = $saldolist['after'][sizeof($saldolist['id'])-1];
$list['total'] = sizeof($list['id']);
} else
$list['balance'] = 0;
if($list['total'])
{
foreach($list['value'] as $key => $value)
$list['value'][$key] = $value;
foreach($list['after'] as $key => $value)
$list['after'][$key] = $value;
foreach($list['before'] as $key => $value)
$list['before'][$key] = $value;
}
$list['userid'] = $id;
return $list;
}
function UserStats()
{
$result['total'] = $this->DB->GetOne('SELECT COUNT(id) FROM users WHERE deleted=0');
$result['connected'] = $this->DB->GetOne('SELECT COUNT(id) FROM users WHERE status=3 AND deleted=0');
$result['awaiting'] = $this->DB->GetOne('SELECT COUNT(id) FROM users WHERE status=2 AND deleted=0');
$result['interested'] = $this->DB->GetOne('SELECT COUNT(id) FROM users WHERE status=1 AND deleted=0');
$result['debt'] = 0;
$result['debtvalue'] = 0;
if($balances = $this->DB->GetCol('SELECT SUM((type * -2 + 7)*value) FROM cash LEFT JOIN users ON userid = users.id WHERE deleted = 0 GROUP BY userid HAVING SUM((type * -2 + 7)*value) < 0'))
{
foreach($balances as $idx)
$result['debtvalue'] -= $idx;
$result['debt'] = sizeof($balances);
}
return $result;
}
/*
* Obs³uga grup u¿ytkowników
*/
function UsergroupWithUserGet($id)
{
return $this->DB->GetOne('SELECT COUNT(userid) FROM userassignments, users WHERE users.id = userid AND usergroupid = ?', array($id));
}
function UsergroupAdd($usergroupdata)
{
$this->SetTS('usergroups');
if($this->DB->Execute('INSERT INTO usergroups (name, description) VALUES (?, ?)', array($usergroupdata['name'], $usergroupdata['description'])))
return $this->DB->GetOne('SELECT id FROM usergroups WHERE name=?', array($usergroupdata['name']));
else
return FALSE;
}
function UsergroupUpdate($usergroupdata)
{
$this->SetTS('usergroups');
return $this->DB->Execute('UPDATE usergroups SET name=?, description=? WHERE id=?', array($usergroupdata['name'], $usergroupdata['description'], $usergroupdata['id']));
}
function UsergroupDelete($id)
{
if (!$this->UsergroupWithUserGet($id))
{
$this->SetTS('usergroups');