php-q-source-snircd /q_register.php

Language PHP Lines 671
MD5 Hash 4b535082d92d48e79929b11ade158f9f Estimated Cost $16,189 (why?)
Repository https://bitbucket.org/gregorytoullie/php-q-source-snircd View Raw File View Project SPDX
  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
<?php
/*
Classe Register
Enregistrement des utilisateurs et salons
*/
class QRegister {
	private static $_instance;
	public static function getInstance(){
		if(!isset(self::$_instance)) self::$_instance = new self;
		return self::$_instance;
	}
	function __construct(){
		echo __CLASS__,": crיation de l'instance\n";
		self::load();
	}
	function __destruct(){ echo __CLASS__,": destruction de l'instance\n"; }
	function __clone(){trigger_error("Le clפnage n'est pas autorisי.",E_USER_ERROR);}
	private static $channels = array();
	private static $accounts = array();
	private static $queue = array();
	private static $glines = array();
	public static $last_ticket = 2;
	###########################################
	## Fonctions d'enregistrement des canaux ##
	###########################################
	# Ex: addreg("#crap","dumbass","lameoper","classic",null)
	public static function addreg($name,$founder,$oper,$chantype=null,$chanflags=null){
		if(!array_key_exists(strtolower($name),self::$channels)){
			$chars = QChars::getInstance();
			if($chanflags==null){$chanflags=$chars->chanflags_encode("agj");}else{$chanflags=$chars->chanflags_encode($chanflags);}
			if($chantype==null){$chantype = "classic";}
			$chanlev = (int)$chars->chanlev_encode('amnotvfxs');
			$chanmode = (int)$chars->chanmode_encode('ntCNu');
			$id = (count(self::$channels)+1);
			self::$channels[strtolower($name)] = array(
				'id' => $id,
				'name' => $name,# Nom du salon sans rיduction de casse
				'created' => time(),
				'founder' => $founder,# Compte du Fondateur
				'adder' => $oper,# Compte de l'opיrateur ayant crיי le salon
				'chantype' => $chantype,# Par dיfaut: classic
				'chanmode' => $chanmode,# Par dיfaut: +ntCN
				'chanflags' => $chanflags,# Par dיfaut: +j
				'chanlev' => array(strtolower($founder) => $chanlev),# Le chanlev est conservי dans le canal, si ce dernier est dיtruit, tous les niveaux d'accטs seront perdus
				'welcome' => (string)null,# Le message de bienvenue
				'topic' => (string)null,# Le sujet du canal
			);
		}
	}
	public static function delreg($name){
		if(array_key_exists(strtolower($name),self::$channels)){
			unset(self::$channels[strtolower($name)]);
			echo __FUNCTION__,": le salon $name a יtי supprimי\n";
		} else { echo __FUNCTION__,": le salon $name ne peut ךtre supprimי car il n'existe pas\n"; }
	}
	public static function getreg($name,$field){
		if(array_key_exists(strtolower($name),self::$channels)){
			if(array_key_exists(strtolower($field),self::$channels[strtolower($name)])){ return self::$channels[strtolower($name)][strtolower($field)]; }
		}
		return false;
	}
	public static function updatereg($name,$field,$value){
		if(array_key_exists(strtolower($name),self::$channels)){
			self::$channels[strtolower($name)][$field] = $value;
			if(array_key_exists($field,self::$channels[strtolower($name)])){echo __FUNCTION__,": mise א jour du champ $field du canal $name א la valeur $value\n";}
			else{echo __FUNCTION__,": inscription du champ $field du canal $name א la valeur $value\n";}
		}
	}
	public static function isreg($name){
		if(array_key_exists(strtolower($name),self::$channels)){return (int)1;}
		else {return (int)0;}
	}
	public static function getregs(){
		$return = array();
		foreach(self::$channels AS $name => $params){$return[$params['name']]=$params;}
		return($return);
	}
	public static function isvoice($name,$account){return self::getchanlev($name,$account,'v');}
	public static function isop($name,$account){return self::getchanlev($name,$account,'o');}
	public static function ismaster($name,$account){return self::getchanlev($name,$account,'m');}
	public static function isowner($name,$account){return self::getchanlev($name,$account,'n');}
	public static function issupervw($name,$account){return self::getchanlev($name,$account,'x');}
	public static function isfounder($name,$account){return self::getchanlev($name,$account,'f');}
	#################################################
	####### Fonctions des chanlevs/chanflags ########
	#################################################
	# $params[in] name Nom du canal
	# $params[in] account Compte du client
	public static function ischanlev($name,$account){
		if(array_key_exists(strtolower($name),self::$channels)){
			if(array_key_exists(strtolower($account),self::$channels[strtolower($name)]['chanlev'])){return (int)1;}
			else {return (int)0;}
		}
	}
	# $params[in] name Nom du canal
	# $params[in] account Compte du client
	# $params[in] flag L'attribut א vיrifier
	public static function getchanlev($name,$account,$flag){# Fonction qui retourne les flags associיs א un compte salon
		if(array_key_exists(strtolower($account),self::$channels[strtolower($name)]['chanlev'])){
			$chars = QChars::getInstance();
			$hflag = $chars->chanlev_encode($flag);
			if($hflag & self::$channels[strtolower($name)]['chanlev'][strtolower($account)]) return (int)1;
			else return (int)0;
		}
		return false;
	}
	public static function ischanflag($name,$flag){# Fonction qui vיrifie l'existence d'un chanflag
		if(array_key_exists('chanflags',self::$channels[strtolower($name)])){
			$chars = QChars::getInstance();
			$hflag = $chars->chanflags_encode($flag);
			if($hflag & self::$channels[strtolower($name)]['chanflags']) return (int)1;
			else return (int)0;
		}
		trigger_error(__CLASS__.": Le canal ne contient aucun chanflag",E_USER_WARNING);
	}
	#################################################
	####### Fonctions des comptes sur salons ########
	#################################################
	public static function getRegaccount($name,$account){
		if(array_key_exists(strtolower($name),self::$channels)){
			if(array_key_exists(strtolower($account),self::$channels[strtolower($name)]['chanlev'])){
				$chars = QChars::getInstance();
				return $chars->chanlev_decode(self::$channels[strtolower($name)]['chanlev'][strtolower($account)]);
			}
		}
		return false;
	}
	#################################################
	## Fonctions d'enregistrement des utilisateurs ##
	#################################################
	public static function addaccount($account,$email,$level = 1){
		if(!array_key_exists(strtolower($account),self::$accounts)){
			$id = (count(self::$accounts)+1);
			if($level>1000) $level = (int)1000;
			if(!is_numeric($level)) $level = 1;
			self::$accounts[strtolower($account)] = array(
				'name' => $account,# Nom du compte sans rיduction de casse
				'id' => $id,# Incrיmentי automatiquement א chaque nouvel utilisateur
				'created' => time(),# Date de crיation du compte
				'level' => (int)$level,# Obligatoire, par dיfaut le niveau est 1 ( utilisateur enregistrי )
				'clients' => array(),# Ceci est la partie 'numיrics' des utilisateurs utilisant le compte ( max 3 )
				'email' => (string)$email,# Obligatoire, sinon la requטte d'inscription n'est pas valable
				'password' => (string)null,# Mot-de-passe, tant qu'il n'est pas choisi le compte n'est pas activי
				'userflags' => 0x1,# Par dיfaut, reחoit des notices
				'noexpires' => (bool)0,# Rיservי aux opיrateurs et administrateurs
				'lastconnect' => time(),# Date de la derniטre connexion
				'greeting' => (string)'',# Le message d'accueil א afficher lors de l'entrיe de l'utilisateur
				'vhost' => (string)'',# Hפte virtuel ( rיservי au staff rיseau, optionnel )
			);
		}
		else echo __CLASS__.": le compte $account existe dיjא\n";
	}
	public static function delaccount($account){
		if(array_key_exists(strtolower($account),self::$accounts)){
			unset(self::$accounts[strtolower($account)]);
			echo __CLASS__.": compte $account supprimי\n";
		}else{echo __CLASS__.": le compte $account n'existe pas\n";}
	}
	public static function getaccount($account,$field){
		if(array_key_exists(strtolower($account),self::$accounts)){
			if(array_key_exists(strtolower($field),self::$accounts[strtolower($account)])){
				if(isset(self::$accounts[strtolower($account)][strtolower($field)])){return self::$accounts[strtolower($account)][strtolower($field)];}
			}else echo __CLASS__.": le champ $field n'existe pas dans le compte $account\n";
		}else echo __CLASS__.": le compte $account n'existe pas\n";
		return false;
	}
	public static function updateaccount($account,$field,$value){
		if(array_key_exists(strtolower($account),self::$accounts)){
			self::$accounts[strtolower($account)][strtolower($field)] = $value;
			if(array_key_exists(strtolower($field),self::$accounts[strtolower($account)])){echo __CLASS__.": mise א jour du champ $field du compte $account א la valeur $value\n";
			}else{echo __CLASS__.": crיation de la clef $field du compte $account א la valeur $value\n";
			}
		}else{echo __CLASS__.": le compte $account n'existe pas\n";
		}
	}
	public static function isaccount($account){
		if(array_key_exists(strtolower($account),self::$accounts)){return (int)1;}else{return (int)0;}
	}
	#############################################
	#### Fonctions des utilisateurs de compte ###
	#############################################
	public static function addAccountclient($account,$client){
		if(array_key_exists(strtolower($account),self::$accounts)){
			if(!array_key_exists('clients',self::$accounts[strtolower($account)])){ self::$accounts[strtolower($account)]['clients'] = array(); }
			if(!in_array($client,self::$accounts[strtolower($account)]['clients'])){
				self::$accounts[strtolower($account)]['clients'][] = $client;
				echo __CLASS__.": client $client ajoutי au compte $account\n";
			} else echo __CLASS__.": le client $client ne peut ךtre ajoutי au compte $account\n";
		} else echo __CLASS__.": le compte $account n'existe pas\n";
	}
	public static function delAccountclient($account,$client){
		if(array_key_exists(strtolower($account),self::$accounts)){
			if(!array_key_exists('clients',self::$accounts[strtolower($account)])){ self::$accounts[strtolower($account)]['clients'] = array(); }
			if(in_array($client,self::$accounts[strtolower($account)]['clients'])){
				unset(self::$accounts[strtolower($account)]['clients'][$client]);
				echo __CLASS__.": client $client retirי du compte $account\n";
			} else echo __CLASS__.": le client $client ne peut ךtre retirי du compte $account\n";
		} else echo __CLASS__.": le compte $account n'existe pas\n";
	}
	public static function isAccountclient($account,$client){
		if(array_key_exists(strtolower($account),self::$accounts)){
			if(in_array($client,self::$accounts[strtolower($account)]['clients'])) return (int)1;
			else return (int)0;
		} else echo __CLASS__.": le compte $account n'existe pas\n";
	}
	public static function getAccountclients($account){
		if(array_key_exists(strtolower($account),self::$accounts)){
			if(!array_key_exists('clients',self::$accounts[strtolower($account)])) self::$accounts[strtolower($account)]['clients'] = array();
			if(count(self::$accounts[strtolower($account)]['clients'])>0) return self::$accounts[strtolower($account)]['clients'];
		} else echo __CLASS__.": le compte $account n'existe pas\n";
		return false;
	}
	# Permet de retrouver le compte client א partir d'un numיrique
	public static function getClientaccount($client){
		foreach(self::$accounts AS $account => $params){
			if(array_key_exists('clients',$params)){
				if(in_array($client,$params['clients'])) return $account;
			}
		}
		return false;
	}
	######################################################
	## Fonctions sur les comptes en attente de crיation ##
	######################################################
	public static function addqueued($account,$email){
		if(!array_key_exists(strtolower($account),self::$queue)){
			$id = (count(self::$queue)+1);
			$key = substr(str_shuffle(str_repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\\\]\[\}\{\`",10)),0,10);
			self::$queue[strtolower($account)] = array(
				'id' => (int)$id,
				'name' => (string)$account,
				'created' => time(),
				'email' => (string)$email,
				'key' => $key,
				'try' => (int)3
			);
			var_dump(self::$queue[strtolower($account)]);
			echo __CLASS__.": le compte $account ( $email ) a יtי mis en instance, clef: $key\n";
		} else { echo __CLASS__.": impossible de mettre le compte $account en instance car il existe dיjא\n"; }
	}
	public static function delqueued($account){
		if(array_key_exists(strtolower($account),self::$queue)){
			unset(self::$queue[strtolower($account)]);
			echo __CLASS__.": le compte $account a יtי retirי d'instance\n";
		} else { echo __CLASS__.": impossible de retirer le compte $account d'instance car il n'existe pas\n"; }
	}
	public static function isqueued($account){
		if(array_key_exists(strtolower($account),self::$queue)){ return (int)1; }
		else { return (int)0; }
	}
	public static function getqueued($account,$field){
		if(array_key_exists(strtolower($account),self::$queue)){
			if(array_key_exists(strtolower($field),self::$queue[strtolower($account)])){ return self::$queue[strtolower($account)][strtolower($field)]; }
		}
		return false;
	}
	##############################
	## Fonctions sur les glines ##
	##############################
	public static function addGline($mask,$expiration,$raison){
		if(!array_key_exists(base64_encode($mask),self::$glines)){
			self::$glines[base64_encode($mask)] = array(
				'id' => (int)(count(self::$glines)+1),
				'mask' => (string)$mask,
				'expiration' => (int)$expiration,
				'reason' => (string)$reason
			);
			echo __CLASS__.": Gline $mask ( expiration le $expiration ) au motif de $raison, ajoutיe\n";
		}
	}
	####################################################
	############### Parser chanlevs ####################
	####################################################
	public static function parsechanlev($name,$account,$string){
		$allowed_flags = array('a','b','d','g','j','k','m','n','o','s','t','v','w','x');
		$chars = QChars::getInstance();
		$tokens = str_split(strtolower($string),1);
		$add = array(); $del = array(); $t = null;
		foreach($tokens AS $token){
			switch($token){
				case "+":$t="+";break;
				case "-":$t="-";break;
				default:
					if($t=="+"){$add[]=$token;}
					else {$del[]=$token;}
				break;
			}
		}
		if(count($del)>0){
			if(self::ischanlev($name,$account)){
				$cur = self::$channels[strtolower($name)]['chanlev'][strtolower($account)];
				$current = str_split($chars->chanlev_decode($cur));
				foreach($del AS $token){
					if(in_array($token,$current)&&in_array($token,$allowed_flags)){unset($current[array_search($token,$current)]);}
				}
				$current = implode($current);
				echo __CLASS__.": nouveau chanlev pour le compte $account sur $name: $current\n";
				self::$channels[strtolower($name)]['chanlev'][strtolower($account)] = $chars->chanlev_encode($current);
			} else { echo __CLASS__.": il est impossible de retirer des flags d'un compte non ajoutי au CHANLEV\n"; }
		} else { echo __CLASS__.": aucun flag n'a יtי retirי du compte $account sur $name\n"; }
		if(count($add)>0){
			if(array_key_exists(strtolower($account),self::$channels[strtolower($name)]['chanlev'])){
				$cur = self::$channels[strtolower($name)]['chanlev'][strtolower($account)];
				$current = str_split($chars->chanlev_decode($cur));
			}else{$current=array();$current[strtolower($account)]=null;}# Ici nous autorisons le tableau vide car le chanlev peut ךtre crיי
			foreach($add AS $token){
				if(!in_array($token,$current)&&in_array($token,$allowed_flags)){$current[]=$token;}
			}
			$current = implode($current);
			self::$channels[strtolower($name)]['chanlev'][strtolower($account)] = $chars->chanlev_encode($current);
		} else { echo __CLASS__.": aucun flag n'a יtי ajoutי du compte $account sur $name\n"; }
	}
	## Chanflags Parser
	public static function parseChanflags($name,$string){
		$allowed_flags = array('a','b','c','d','e','f','g','h','i','k','m','o','p','q','r','s','t','v','w','x');# Le chanflag 'j' ne peut ךtre modifiי
		$chars = QChars::getInstance();
		$tokens = str_split(strtolower($string),1);
		$add = array(); $del = array(); $t = null;
		foreach($tokens AS $token){
			switch($token){
				case "+":$t="+";break;
				case "-":$t="-";break;
				default:
					if($t=="+"){$add[]=$token;}
					else {$del[]=$token;}
				break;
			}
		}
		if(count($del)>0){
			$cur = self::$channels[strtolower($name)]['chanflags'];
			$currar = str_split($chars->chanflags_decode($cur),1);
			$remove = array();
			foreach($del AS $token){
				if(in_array($token,$currar)&&in_array($token,$allowed_flags)){ $remove[]=$token; }
			}
			$current = implode(array_diff($currar,$remove));
			echo __CLASS__.": nouveaux chanflags pour le canal $name: $current\n";
			self::updatereg($name,"chanflags",$chars->chanflags_encode($current));
		} else { echo __CLASS__.": aucun chanflag א retirer pour le canal $name\n"; }
		if(count($add)>0){
			$cur = self::$channels[strtolower($name)]['chanflags'];
			$currar = str_split($chars->chanflags_decode($cur),1);
			foreach($add AS $token){
				if(!in_array($token,$currar)&&in_array($token,$allowed_flags)){ $currar[]=$token; }
			}
			$current = implode($currar);
			self::updatereg($name,"chanflags",$chars->chanflags_encode($current));
		}
	}
	## Chanmode parser
	# Les paramטtres +l/k/A/U ne sont pas inclus dans CHANMODE
	# Ils sont disponibles dans APASS UPASS KEY LIMIT
	public static function parseChmodes($name,$string){
		$noargs=str_split('imnpstrDdRucCNMTovb');# Nous crייons notre tableau de modes sans arguments et ajoutons ovb ( car non pris en charge par cette fonction )
		$chars = QChars::getInstance();
		$array = explode(' ',$string);
		$tokens = str_split($array[0],1);# Sensible א la casse, on ne la rיduit pas
		$add=array();$del=array();
		$addTargets=null;$delTargets=null;$ti=1;
		foreach($tokens AS $token){
			switch($token){
				case "+":$t="+";break;
				case "-":$t="-";break;
				default:
					if($t=="+"){
						if(preg_match('#[kl]+#',$token)) $addTargets[]=$array[$ti];$ti++;
						$add[]=$token;
					}
					else {
						if(preg_match('#[k]+#',$token)) $delTargets[]=$array[$ti];$ti++;
						$del[]=$token;
					}
				break;
			}
		}
		if(count($del)>0){
			$cur = $chars->chanmode_decode(self::$channels[strtolower($name)]['chanmode']);
			$current = str_split($cur,1);# Crיe le tableau de modes
			if(array_key_exists('key',self::$channels[strtolower($name)])) $key = (string)self::$channels[strtolower($name)]['key'];
			if(array_key_exists('limit',self::$channels[strtolower($name)])) $limit = (int)self::$channels[strtolower($name)]['limit'];
			foreach($del AS $token){
				if(in_array($token,$current)){# Ne supprime pas les modes inexistants
					switch($token){
						case 'k':self::updatereg($name,'key',null);break;# Dיsinstalle la clef du tableau salon
						case 'l':self::updatereg($name,'limit',null);break;# Dיsinstalle la limite du tableau salon
						case 'U':self::updatereg($name,'upass',null);break;
						case 'A':self::updatereg($name,'apass',null);break;
					}
					unset($current[array_search($token,$current)]);
				}
			}
			if(count($current)>0){
				self::updatereg($name,'chanmode',$chars->chanmode_encode(implode($current)));
				echo __CLASS__.": nouveau chanmode pour le canal $name:\n";print_r($current);
			} else { self::updatereg($name,'chanmode',null); }
		}
		if(count($add)>0){
			$args=array_diff($noargs,$add);print_r($args);
			$cur = $chars->chanmode_decode(self::$channels[strtolower($name)]['chanmode']);
			$current = str_split($cur);
			foreach($add AS $token){
				if(!in_array($token,$current)){
					if(in_array($token,$args)){
						$argpos=array_search($token,$args);
						switch($token){
							case 'l':$r->updatereg($name,'limit',$addTargets[$argpos]);break;
							case 'k':$r->updatereg($name,'key',$addTargets[$argpos]);break;
							case 'U':$r->updatereg($name,'upass',$addTargets[$argpos]);break;
							case 'A':$r->updatereg($name,'apass',$addTargets[$argpos]);break;
						}
					}
					$current[]=$token;
				}else{echo __CLASS__.": mode non ajoutי $token car existant.\n";}
			}
			self::updatereg($name,"chanmode",$chars->chanmode_encode(implode($current)));
		}else{echo __CLASS__.": Aucun mode ajoutי\n";}
	}
	#############################################
	##### Fonctions de chargement/sauvegarde ####
	#############################################
	public static function save(){
		$link = mysql_connect(MYSQL_HOSTNAME,MYSQL_USERNAME,MYSQL_PASSWORD) or trigger_error("Sauvegarde impossible: ".mysql_error(),E_USER_ERROR);
		if($link){
			@mysql_query("USE q",$link);
			# Ici nous supprimons les salons orphelins de mysql
			$results = mysql_query("SELECT * FROM `channels`",$link);
			if(count(self::$channels)>0 && mysql_num_rows($results)!=0){
				while($table = mysql_fetch_assoc($results)){
					if(!array_key_exists(strtolower($table['name']),self::$channels)){
						mysql_query(sprintf("DELETE FROM channels WHERE `name`='%s';",$table['name']),$link);
						echo __CLASS__.": canal orphelin ".$table['name']." supprimי de mysql\n";
					}
				}
			}
			# Injection
			foreach(self::$channels AS $name => $values){
			$name = mysql_real_escape_string($name);
			$results = mysql_query(sprintf("SELECT * FROM `channels` WHERE name='%s'",$name),$link);
			if(mysql_num_rows($results)==0){
				# injection des nouveaux canaux
				mysql_query(sprintf("INSERT INTO `channels` (`id`,`name`,`created`,`founder`,`adder`,`chantype`,`chanmode`,`chanflags`,`chanlev`,`welcome`,`topic`) VALUES ('%d','%s','%d','%s','%s','%s','%d','%d','%s','%s','%s')",
				$values['id'],
				mysql_real_escape_string($values['name']),$values['created'],
				mysql_real_escape_string($values['founder']),
				mysql_real_escape_string($values['adder']),$values['chantype'],
				mysql_real_escape_string($values['chanmode']),$values['chanflags'],
				mysql_real_escape_string(json_encode($values['chanlev'])),
				mysql_real_escape_string($values['welcome']),
				mysql_real_escape_string($values['topic']))
				,$link);
			}else{
				$last = mysql_fetch_assoc($results);
				if($values['topic']!==$last['topic']){mysql_query(sprintf("UPDATE `channels` SET `topic`='%s' WHERE `name`='%s'",mysql_real_escape_string($values["topic"]),$name),$link);}
				if($values['welcome']!==$last['welcome']){mysql_query(sprintf("UPDATE `channels` SET `welcome`='%s' WHERE `name`='%s'",mysql_real_escape_string($values["welcome"]),$name),$link);}
				if($values['chanmode']!==$last['chanmode']){mysql_query(sprintf("UPDATE `channels` SET `chanmode`='%s' WHERE `name`='%s'",$values["chanmode"],$name),$link);}
				if($values['chanflags']!==$last['chanflags']){mysql_query(sprintf("UPDATE `channels` SET `chanflags`='%d' WHERE `name`='%s'",$values["chanflags"],$name),$link);}
				if($values['chanlev']!==$last['chanlev']){mysql_query(sprintf("UPDATE `channels` SET `chanlev`='%s' WHERE `name`='%s'",json_encode($values["chanlev"]),$name),$link);}
			}
			if(mysql_error()){echo __CLASS__.": Erreur MySQL: ".mysql_error()."\n";}
			}
			# Ici nous supprimons les comptes orphelins de mysql
			$results = mysql_query("SELECT * FROM accounts",$link);
			if(count(self::$accounts)>0 && mysql_num_rows($results)!=0){
				while($table = mysql_fetch_assoc($results)){
					if(!array_key_exists(strtolower($table['name']),self::$accounts)){
						mysql_query(sprintf("DELETE FROM `accounts` WHERE `name`='%s';",$table['name']),$link);
						echo __CLASS__.": entrיe orpheline ".$table['name']." retirיe de la table ACCOUNTS\n";
					}
				}
			}
			# Injection
			foreach(self::$accounts AS $account => $values){
				$account = mysql_real_escape_string($account);
				$results = mysql_query(sprintf("SELECT * FROM accounts WHERE name='%s'",$account),$link);
				if(mysql_num_rows($results)==0){
					# injection des nouveaux comptes
					mysql_query(sprintf("INSERT INTO `accounts` (`id`,`name`,`created`,`level`,`email`,`password`,`userflags`,`noexpires`,`lastconnect`,`greeting`,`vhost`) VALUES ('%d','%s','%d','%d','%s','%s','%d','%d','%d','%s','%s')",
					$values['id'],
					mysql_real_escape_string($values['name']),$values['created'],$values['level'],
					mysql_real_escape_string($values['email']),
					mysql_real_escape_string($values['password']),$values['userflags'],$values['noexpires'],$values['lastconnect'],
					mysql_real_escape_string($values['greeting']),$values['vhost'])
					,$link);
				}else{
					$last = mysql_fetch_assoc($results);
					if($values['password']!==$last['password']){mysql_query(sprintf("UPDATE `accounts` SET `password`='%d' WHERE `name`='%s'",mysql_real_escape_string($values["password"]),$account));}
					if($values['userflags']!==$last['userflags']){mysql_query(sprintf("UPDATE `accounts` SET `userflags`='%d' WHERE `name`='%s'",$values["userflags"],$account));}
					if($values['noexpires']!==$last['noexpires']){mysql_query(sprintf("UPDATE `accounts` SET `noexpires`='%d' WHERE `name`='%s'",$values["noexpires"],$account));}
					if($values['greeting']!==$last['greeting']){mysql_query(sprintf("UPDATE `accounts` SET `greeting`='%s' WHERE `name`='%s'",mysql_real_escape_string($values["greeting"]),$account));}
					if($values['vhost']!==$last['vhost']){mysql_query(sprintf("UPDATE `accounts` SET `vhost`='%s' WHERE `name`='%s'",mysql_real_escape_string($values["vhost"]),$account));}
				}
			}
			# Ici nous supprimons les entrיes d'instance orphelines
			$results = mysql_query("SELECT * FROM `queue`",$link);
			if(mysql_num_rows($results)!=0){
				while($table = mysql_fetch_assoc($results)){
					if(!array_key_exists(strtolower($table['name']),self::$queue)){mysql_query(sprintf("DELETE FROM `queue` WHERE `name`='%s';",$table['name']),$link);echo __CLASS__.": instance orpheline ".$table['name']." supprimיe de la table QUEUE\n";}
				}
			}else{echo __CLASS__.": Aucune entrיe orpheline retirיe de la table QUEUE\n";}
			# Injection
			if(count(self::$queue)>0){ # C'est utile car les instances peuvent ךtre vides ( y'a pas יcrit La Poste lא! )
				foreach(self::$queue AS $instance => $values){
					$instance = mysql_real_escape_string($instance);
					$results = mysql_query(sprintf("SELECT * FROM queue WHERE name='%s'",$instance),$link);
					if(mysql_num_rows($results)==0){mysql_query(sprintf("INSERT INTO `queue` (`id`,`name`,`created`,`email`,`key`,`try`) VALUES ('%d','%s','%d','%s','%s','%d')",
						$values['id'],mysql_real_escape_string($values['name']),$values['created'],mysql_real_escape_string($values['email']),mysql_real_escape_string($values['key']),$values['try']),$link);
					}else{
						$last = mysql_fetch_assoc($results);
						if($values['try']!==$last['try']){mysql_query(sprintf("UPDATE `queue` SET `try`='%d' WHERE `name`='%s'",$values['try'],$instance));}
					}
				}
			}
			# ici nous supprimons les entrיes de glines orphelines
			if(count(self::$glines)>0){
				$results = mysql_query('SELECT * FROM `glines`',$link);
				if(mysql_num_rows($results)>0){
					while($table = mysql_fetch_assoc($results)){
						if(!array_key_exists(base64_decode($table['mask']),self::$glines)){mysql_query(sprintf('DELETE FROM `glines` WHERE `mask`=\'%s\';',mysql_real_escape_string($table['mask'])),$link);echo __CLASS__.": entrיe orpheline ".$table['mask']." retirיe de la table GLINES\n";}
					}
					}else{echo __CLASS__.": Aucune entrיe orpheline retirיe de la table GLINES\n";}
				}
			if(mysql_error()){trigger_error(__CLASS__.": erreur mysql ".mysql_error(),E_WARNING);
			}else{echo __CLASS__." Sauvegarde terminיe\n";}
			mysql_close($link);
		}
	}
	public static function load(){
		$link = mysql_connect(MYSQL_HOSTNAME,MYSQL_USERNAME,MYSQL_PASSWORD) or trigger_error("Chargement impossible: ".mysql_error(),E_USER_ERROR);
		if($link){
			@mysql_query("CREATE DATABASE IF NOT EXISTS q",$link);# Peut retourner FALSE, on s'en fiche c'est une routine anti-erreurs
			@mysql_query("USE q",$link);
			//@mysql_query("DROP TABLE `channels`",$link);// a commenter aprטs les tests
			@mysql_query("CREATE TABLE IF NOT EXISTS `channels` (
				`id` INT(5) ZEROFILL,
				`name` TEXT(200) NOT NULL,
				`created` INT(10) ZEROFILL DEFAULT '0946753235',
				`founder` TEXT(16) NOT NULL,
				`adder` TEXT(16),
				`chantype` TINYTEXT DEFAULT NULL,
				`chanmode` INT(6) DEFAULT '69641',
				`chanflags` INT(6) DEFAULT '12084',
				`chanlev` LONGTEXT DEFAULT NULL,
				`welcome` TEXT(512) DEFAULT NULL,
				`topic` TEXT(250) DEFAULT NULL,
				`limit` INT(5) DEFAULT NULL,
				`key` TEXT(23) DEFAULT NULL,
				`apass` TEXT(23) DEFAULT NULL,
				`upass` TEXT(23) DEFAULT NULL,
				PRIMARY KEY (`id`)
			)",$link);
			@mysql_query("CREATE TABLE IF NOT EXISTS `accounts` (
				`id` INT(5) ZEROFILL,
				`name` TEXT(16) NOT NULL,
				`created` INT(10) ZEROFILL DEFAULT '0946753235',
				`level` INT(4) ZEROFILL,
				`email` TEXT(256) NOT NULL,
				`password` TEXT(10),
				`userflags` BINARY(4),
				`noexpires` BOOL DEFAULT 0,
				`lastconnect` INT(10) ZEROFILL DEFAULT '0',
				`greeting` TEXT(100) DEFAULT NULL,
				`vhost` TEXT(128) DEFAULT NULL,
				PRIMARY KEY (`id`)
			)",$link);
			@mysql_query("CREATE TABLE IF NOT EXISTS `queue` (
				`id` INT(5) ZEROFILL,
				`name` TEXT(16) NOT NULL,
				`created` INT(10) ZEROFILL,
				`email` TEXT(128) NOT NULL,
				`key` TEXT(10) NOT NULL,
				`try` INT(1) DEFAULT NULL,
				PRIMARY KEY (`id`)
			)",$link);
			@mysql_query("CREATE TABLE IF NOT EXISTS `glines` (
				`id` INT(5) ZEROFILL,
				`mask` TEXT(256) NOT NULL,
				`expiration` INT(10) ZEROFILL,
				`reason` TEXT(256) NOT NULL,
				PRIMARY KEY (`id`)
			)",$link);
			@mysql_query("CREATE TABLE IF NOT EXISTS `memos` (
				`id` INT(5) ZEROFILL,
				`message` TEXT(256) NOT NULL,
				`from` TEXT(16) NOT NULL,
				`to` TEXT(16) NOT NULL,
				PRIMARY KEY (`id`)
			)",$link);
			# Rיcupיration des donnיes enregistrיes
			$results = mysql_query("SELECT * FROM `channels`",$link);
			if(mysql_num_rows($results)>0){
				while($table = mysql_fetch_assoc($results)){
				self::$channels[strtolower($table['name'])] = array(
					'id' => (int)$table['id'],
					'name' => (string)$table['name'],
					'created' => (int)$table['created'],
					'founder' => (string)$table['founder'],
					'adder' => (string)$table['adder'],
					'chantype' => $table['chantype'],
					'chanmode' => (int)$table['chanmode'],
					'chanflags' => (int)$table['chanflags'],
					'chanlev' => json_decode($table['chanlev'],true),
					'welcome' => (string)$table['welcome'],
					'topic' => (string)$table['topic'],
					'limit' => (int)$table['limit'],
					'key' => (string)$table['key'],
					'apass' => (string)$table['apass'],
					'upass' => (string)$table['upass']
					);
				}
			}
			// id 	name 	created 	level 	email 	password 	userflags 	noexpires 	lastconnect 	greeting 	vhost
			$results = mysql_query("SELECT * FROM `accounts`",$link);
			if(mysql_num_rows($results)>0){
				while($table = mysql_fetch_assoc($results)){
				self::$accounts[strtolower($table['name'])] = array(
					'id' => $table['id'],
					'name' => $table['name'],
					'created' => $table['created'],
					'level' => $table['level'],
					'email' => $table['email'],
					'password' => $table['password'],
					'userflags' => $table['userflags'],
					'noexpires' => (bool)$table['noexpires'],
					'lastconnect' => $table['lastconnect'],
					'greeting' => $table['greeting'],
					'vhost' => $table['vhost']
				);
				}
			}
			$results = mysql_query("SELECT * FROM `queue`",$link);
			if(mysql_num_rows($results)>0){
				while($table = mysql_fetch_assoc($results)){
				self::$queue[strtolower($table['name'])] = array(
					'id' => (int)$table['id'],
					'name' => (string)$table['name'],
					'created' => (int)$table['created'],
					'email' => (string)$table['email'],
					'key' => (string)$table['key'],
					'try' => (int)$table['try']
				);
				}
			}
			$results = mysql_query("SELECT * FROM `glines`",$link);
			if(mysql_num_rows($results)>0){
				while($table = mysql_fetch_assoc($results)){
				self::$glines[$table['id']] = array(
					'id' => (int)$table['id'],
					'mask' => (string)$table['mask'],
					'expiration' => (int)$table['expiration'],
					'reason' => (string)$table['reason']
				);
				}
			}
			$results = mysql_query('SELECT * FROM `memos`',$link);
			if(mysql_num_rows($results)>0){
				while($table = mysql_fetch_assoc($results)){
				self::$memos[strtolower($table['from'])]=array(
					'id' => (int)$table['id'],
					'message' => (string)$table['message'],
					'from' => (string)$table['from'],
					'to' => (string)$table['to']
				);
				}
			}
			echo "Chargement des donnיes terminי\n";
			mysql_close($link);
		}
	}
}
?>
Back to Top