added copyright notice and GPL reference
[e-DoKo.git] / include / db.php
1 <?php
2 /* Copyright 2006, 2007, 2008, 2009, 2010 Arun Persaud <arun@nubati.net>
3  *
4  *   This file is part of e-DoKo.
5  *
6  *   e-DoKo is free software: you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation, either version 3 of the License, or
9  *   (at your option) any later version.
10  *
11  *   e-DoKo is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with e-DoKo.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20
21 /* make sure that we are not called from outside the scripts,
22  * use a variable defined in config.php to check this
23  */
24 if(!isset($HOST))
25   exit;
26
27 /*
28  * open database
29  */
30
31 function DB_open()
32 {
33   global $DB,$DB_user,$DB_host,$DB_database,$DB_password;
34   $DB = @mysql_connect($DB_host,$DB_user, $DB_password);
35   if ( $DB )
36     {
37       mysql_select_db($DB_database) or die('Could not select database');
38     }
39   else
40     {
41       echo mysql_errno() . ": " . mysql_error(). "\n";
42       return -1;
43     }
44   return 0;
45 }
46
47 function DB_close()
48 {
49   global $DB;
50   mysql_close($DB);
51   return;
52 }
53
54 function DB_quote_smart($value)
55 {
56     /* Stripslashes */
57     if (get_magic_quotes_gpc()) {
58         $value = stripslashes($value);
59     }
60     /* Quote if not a number or a numeric string */
61     if (!is_numeric($value)) {
62         $value = "'" . mysql_real_escape_string($value) . "'";
63     }
64     return $value;
65 }
66
67 function DB_test()
68 {
69   $result = DB_query("SELECT * FROM User");
70   while($r = DB_fetch_array($result))
71     {
72       foreach($r as $thing)
73         echo "  $thing ";
74       echo "<br />\n";
75     }
76   return;
77 }
78
79 /* use Mysql in the background */
80 function DB_query($query)
81 {
82   /* debug/optimize the database
83   $time = microtime();
84   $return = mysql_query($query);
85   $time = $time - microtime();
86
87   if($time > 0.05) // this way we can find only the long ones
88   {
89     $logfile=fopen('/tmp/DBlog.log','a+');
90     fwrite($logfile,"EXPLAIN $query ;\n");
91     fwrite($logfile,"time of above query: $time\n");
92     fclose($logfile);
93   };
94
95   return $return;
96   */
97
98   return mysql_query($query);
99 }
100
101 function DB_fetch_array($result)
102 {
103   return mysql_fetch_array($result,MYSQL_NUM);
104 }
105
106 function DB_insert_id()
107 {
108   return mysql_insert_id();
109 }
110
111 function DB_num_rows($result)
112 {
113   return mysql_num_rows($result);
114 }
115 /* end Mysql functions */
116
117 function DB_query_array($query)
118 {
119   $result = DB_query($query);
120   $return = DB_fetch_array($result);
121
122   return $return;
123 }
124
125 function DB_query_array_all($query)
126 {
127   $result = array();
128
129   $queryresult  = DB_query($query);
130   while($row = DB_fetch_array($queryresult))
131     $result[] = $row;
132
133   return $result;
134 }
135
136 function DB_get_version()
137 {
138   $version = DB_query_array('SELECT version FROM Version');
139   return $version[0];
140 }
141
142 function DB_get_passwd_by_name($name)
143 {
144   $r = DB_query_array("SELECT password FROM User WHERE fullname=".DB_quote_smart($name)."");
145
146   if($r)
147     return $r[0];
148   else
149     return "";
150 }
151
152 function DB_get_passwd_by_userid($id)
153 {
154   $r = DB_query_array("SELECT password FROM User WHERE id=".DB_quote_smart($id)."");
155
156   if($r)
157     return $r[0];
158   else
159     return "";
160 }
161
162 function DB_check_recovery_passwords($password,$email)
163 {
164   $r = DB_query_array("SELECT User.id FROM User".
165                       " LEFT JOIN Recovery ON User.id=Recovery.user_id".
166                       " WHERE email=".DB_quote_smart($email).
167                       " AND Recovery.password=".DB_quote_smart($password).
168                       " AND DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= Recovery.create_date");
169   if($r)
170     return 1;
171   else
172     return 0;
173 }
174
175 function DB_get_handid($type,$var1='',$var2='')
176 {
177   switch($type)
178     {
179     case 'hash':
180       $r = DB_query_array("SELECT id FROM Hand WHERE hash=".DB_quote_smart($var1));
181       break;
182     case 'gameid-position':
183       $r = DB_query_array("SELECT id FROM Hand WHERE game_id=".
184                           DB_quote_smart($var1)." AND position=".
185                           DB_quote_smart($var2));
186       break;
187     case 'gameid-userid':
188       $r = DB_query_array("SELECT id FROM Hand WHERE game_id=".
189                           DB_quote_smart($var1)." AND user_id=".
190                           DB_quote_smart($var2));
191       break;
192     }
193
194   if($r)
195     return $r[0];
196   else
197     return 0;
198 }
199
200 function DB_get_pos_by_hash($hash)
201 {
202   $r= DB_query_array("SELECT position FROM Hand WHERE hash=".DB_quote_smart($hash));
203
204   if($r)
205     return $r[0];
206   else
207     return 0;
208 }
209
210 function DB_get_status_by_hash($hash)
211 {
212   $r= DB_query_array("SELECT status FROM Hand WHERE hash=".DB_quote_smart($hash));
213
214   if($r)
215     return $r[0];
216   else
217     return 0;
218 }
219
220 function DB_set_game_status_by_gameid($id,$status)
221 {
222   DB_query("UPDATE Game SET status='".$status."' WHERE id=".DB_quote_smart($id));
223   return;
224 }
225
226 function DB_set_sickness_by_gameid($id,$status)
227 {
228   DB_query("UPDATE Game SET sickness='".$status."' WHERE id=".DB_quote_smart($id));
229   return;
230 }
231 function DB_get_sickness_by_gameid($id)
232 {
233   $r = DB_query_array("SELECT sickness FROM Game WHERE id=".DB_quote_smart($id));
234
235   if($r)
236     return $r[0];
237   else
238     return NULL;
239 }
240
241 function DB_get_game_status_by_gameid($id)
242 {
243   $r = DB_query_array("SELECT status FROM Game WHERE id=".DB_quote_smart($id));
244
245   if($r)
246     return $r[0];
247   else
248     return NULL;
249 }
250
251 function DB_set_hand_status_by_hash($hash,$status)
252 {
253   DB_query("UPDATE Hand SET status='".$status."' WHERE hash=".DB_quote_smart($hash));
254   return;
255 }
256
257 function DB_get_hand_status_by_userid_and_gameid($uid,$gid)
258 {
259   $r = DB_query_array("SELECT status FROM Hand WHERE user_id=".DB_quote_smart($uid).
260                       " AND game_id=".DB_quote_smart($gid));
261   if($r)
262     return $r[0];
263   else
264     return 0;
265 }
266
267 function DB_get_sickness_by_userid_and_gameid($uid,$gid)
268 {
269   $r = DB_query_array("SELECT sickness FROM Hand WHERE user_id=".DB_quote_smart($uid).
270                       " AND game_id=".DB_quote_smart($gid));
271   if($r)
272     return $r[0];
273   else
274     return 0;
275 }
276
277 function DB_get_sickness_by_pos_and_gameid($pos,$gid)
278 {
279   $r = DB_query_array("SELECT sickness FROM Hand WHERE position=".DB_quote_smart($pos).
280                       " AND game_id=".DB_quote_smart($gid));
281   if($r)
282     return $r[0];
283   else
284     return 0;
285 }
286
287 function DB_get_gameid_by_hash($hash)
288 {
289   $r = DB_query_array("SELECT game_id FROM Hand WHERE hash=".DB_quote_smart($hash));
290
291   if($r)
292     return $r[0];
293   else
294     return 0;
295 }
296
297 function DB_get_hand($me)
298 {
299   $cards = array();
300
301   $handid = DB_get_handid('hash',$me);
302
303   $result = DB_query("SELECT card_id FROM Hand_Card WHERE hand_id=".DB_quote_smart($handid)." and played='false' ");
304   while($r = DB_fetch_array($result))
305     $cards[]=$r[0];
306
307   return $cards;
308 }
309
310 function DB_get_all_hand($me)
311 {
312   $cards = array();
313
314   $handid = DB_get_handid('hash',$me);
315
316   $result = DB_query("SELECT card_id FROM Hand_Card WHERE hand_id=".DB_quote_smart($handid));
317   while($r = DB_fetch_array($result))
318     $cards[]=$r[0];
319
320   return $cards;
321 }
322
323 function DB_get_cards_by_trick($id)
324 {
325   $cards = array();
326   $i     = 1;
327
328   $result = DB_query("SELECT card_id,position FROM Play LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id ".
329                      "LEFT JOIN Hand ON Hand.id=Hand_Card.hand_id ".
330                      "WHERE trick_id=".
331                      DB_quote_smart($id)." ORDER BY sequence ASC");
332   while($r = DB_fetch_array($result))
333     {
334       $cards[$i]=array("card"=>$r[0],"pos"=>$r[1]);
335       $i++;
336     }
337
338   return $cards;
339 }
340
341
342 function DB_set_solo_by_hash($hash,$solo)
343 {
344   DB_query("UPDATE Hand SET solo=".DB_quote_smart($solo)." WHERE hash=".DB_quote_smart($hash));
345   return;
346 }
347
348 function DB_set_solo_by_gameid($id,$solo)
349 {
350   DB_query("UPDATE Game SET solo=".DB_quote_smart($solo)." WHERE id=".DB_quote_smart($id));
351   return;
352 }
353
354 function DB_set_sickness_by_hash($hash,$sickness)
355 {
356   DB_query("UPDATE Hand SET sickness=".DB_quote_smart($sickness)." WHERE hash=".DB_quote_smart($hash));
357   return;
358 }
359
360 function DB_get_current_trickid($gameid)
361 {
362   $trickid  = NULL;
363   $sequence = NULL;
364   $number   = 0;
365
366   $result = DB_query("SELECT Trick.id,MAX(Play.sequence) FROM Play ".
367                      "LEFT JOIN Trick ON Play.trick_id=Trick.id ".
368                      "WHERE Trick.game_id=".DB_quote_smart($gameid)." ".
369                      "GROUP BY Trick.id");
370   while( $r = DB_fetch_array($result) )
371     {
372       $trickid  = $r[0];
373       $sequence = $r[1];
374       $number++;
375     };
376
377   if(!$sequence || $sequence==4)
378     {
379       DB_query("INSERT INTO Trick VALUES (NULL,NULL,NULL, ".DB_quote_smart($gameid).",NULL)");
380       $trickid  = DB_insert_id();
381       $sequence = 1;
382       $number++;
383     }
384   else
385     {
386       $sequence++;
387     }
388
389   return array($trickid,$sequence,$number);
390 }
391
392 function DB_get_max_trickid($gameid)
393 {
394   $r = DB_query_array("SELECT MAX(id) FROM Trick WHERE game_id=".DB_quote_smart($gameid));
395
396   return ($r?$r[0]:NULL);
397 }
398
399 function DB_play_card($trickid,$handcardid,$sequence)
400 {
401   DB_query("INSERT INTO Play VALUES(NULL,NULL,NULL,".DB_quote_smart($trickid).
402            ",".DB_quote_smart($handcardid).",".DB_quote_smart($sequence).")");
403
404   $playid = DB_insert_id();
405   return $playid;
406 }
407
408 function DB_get_all_names_by_gameid($id)
409 {
410   $names = array();
411
412   $result = DB_query("SELECT fullname FROM Hand LEFT JOIN User ON Hand.user_id=User.id WHERE game_id=".
413                      DB_quote_smart($id)." ORDER BY position ASC");
414   while($r = DB_fetch_array($result))
415     $names[] = $r[0];
416
417   return $names;
418 }
419
420 function DB_get_all_userid_by_gameid($id)
421 {
422   $names = array();
423
424   $result = DB_query("SELECT user_id FROM Hand WHERE game_id=".
425                      DB_quote_smart($id)." ORDER BY position ");
426   while($r = DB_fetch_array($result))
427     $names[] = $r[0];
428
429   return $names;
430 }
431
432 function DB_get_hash_from_game_and_pos($id,$pos)
433 {
434   $r = DB_query_array("SELECT hash FROM Hand WHERE game_id=".DB_quote_smart($id)." and position=".DB_quote_smart($pos));
435
436   if($r)
437     return $r[0];
438   else
439     return "";
440 }
441
442 function DB_get_hash_from_gameid_and_userid($id,$user)
443 {
444   $r = DB_query_array("SELECT hash FROM Hand WHERE game_id=".DB_quote_smart($id)." and user_id=".DB_quote_smart($user));
445
446   if($r)
447     return $r[0];
448   else
449     return "";
450 }
451
452 function DB_get_all_names()
453 {
454   $names  = array();
455
456   $result = DB_query("SELECT fullname FROM User");
457
458   while($r = DB_fetch_array($result))
459     $names[] = $r[0];
460
461   return $names;
462 }
463
464 function DB_get_all_user_names_open_for_games()
465 {
466   $names  = array();
467
468   DB_query("DROP   TEMPORARY TABLE IF EXISTS Usertmp;");
469   DB_query("CREATE TEMPORARY TABLE Usertmp SELECT id,fullname FROM User;");
470   DB_query("DELETE FROM Usertmp WHERE id IN (SELECT user_id FROM User_Prefs WHERE pref_key='open for games' and value='no')");
471
472   $result = DB_query("SELECT fullname FROM Usertmp");
473   DB_query("DROP   TEMPORARY TABLE IF EXISTS Usertmp;");
474
475   while($r = DB_fetch_array($result))
476     $names[] = $r[0];
477
478   return $names;
479 }
480
481 function DB_get_names_of_last_logins($N)
482 {
483   $names  = array();
484
485   $result = DB_query("SELECT fullname FROM User ORDER BY last_login DESC LIMIT $N");
486   while($r = DB_fetch_array($result))
487     $names[] = $r[0];
488
489   return $names;
490 }
491
492 function DB_get_emails_of_last_logins($N)
493 {
494   $emails  = array();
495
496   $result = DB_query("SELECT email FROM User ORDER BY last_login DESC LIMIT $N");
497   while($r = DB_fetch_array($result))
498     $emails[] = $r[0];
499
500   return $emails;
501 }
502
503 function DB_get_names_of_new_logins($N)
504 {
505   $names  = array();
506
507   $result = DB_query("SELECT fullname FROM User ORDER BY create_date DESC, id DESC LIMIT $N");
508   while($r = DB_fetch_array($result))
509     $names[] = $r[0];
510
511   return $names;
512 }
513
514 function DB_update_game_timestamp($gameid)
515 {
516   DB_query("UPDATE Game SET mod_date = CURRENT_TIMESTAMP WHERE id=".DB_quote_smart($gameid));
517   return;
518 }
519
520 function DB_get_game_timestamp($gameid)
521 {
522   $r = DB_query_array("SELECT mod_date FROM Game WHERE id=".DB_quote_smart($gameid));
523
524   if($r)
525     return $r[0];
526   else
527     return NULL;
528 }
529
530 function DB_update_user_timestamp($userid)
531 {
532   DB_query("UPDATE User SET last_login = CURRENT_TIMESTAMP WHERE id=".DB_quote_smart($userid));
533   return;
534 }
535
536 function DB_get_user_timestamp($userid)
537 {
538   $r = DB_query_array("SELECT last_login FROM User WHERE id=".DB_quote_smart($userid));
539
540   if($r)
541     return $r[0];
542   else
543     return NULL;
544 }
545
546 function DB_get_user_creation_date($userid)
547 {
548   $r = DB_query_array("SELECT create_date FROM User WHERE id=".DB_quote_smart($userid));
549
550   if($r)
551     return $r[0];
552   else
553     return NULL;
554 }
555
556 function DB_get_user_timezone($userid)
557 {
558   $r = DB_query_array("SELECT timezone FROM User WHERE id=".DB_quote_smart($userid));
559
560   if($r)
561     return $r[0];
562   else
563     return "Europe/London";
564 }
565
566 function DB_insert_comment($comment,$playid,$userid)
567 {
568   DB_query("INSERT INTO Comment VALUES (NULL,NULL,NULL,$userid,$playid, ".DB_quote_smart($comment).")");
569
570   return;
571 }
572
573 function DB_insert_note($comment,$gameid,$userid)
574 {
575   DB_query("INSERT INTO Notes VALUES (NULL,NULL,NULL,$userid,$gameid, ".DB_quote_smart($comment).")");
576
577   return;
578 }
579
580 function DB_get_notes_by_userid_and_gameid($userid,$gameid)
581 {
582   $notes = array();
583
584   $result = DB_query("SELECT comment FROM Notes WHERE user_id=".DB_quote_smart($userid) .
585                      " AND game_id=".DB_quote_smart($gameid));
586
587   while($r = DB_fetch_array($result))
588     $notes[] = $r[0];
589
590   return $notes;
591 }
592
593
594 function DB_get_gametype_by_gameid($id)
595 {
596   $r = DB_query_array("SELECT type FROM Game WHERE id=".DB_quote_smart($id));
597
598   if($r)
599     return $r[0]."";
600   else
601     return "";
602 }
603
604 function DB_set_gametype_by_gameid($id,$p)
605 {
606   DB_query("UPDATE Game SET type='".$p."' WHERE id=".DB_quote_smart($id));
607   return;
608 }
609
610 function DB_get_solo_by_gameid($id)
611 {
612   $r = DB_query_array("SELECT solo FROM Game WHERE id=".DB_quote_smart($id));
613
614   if($r)
615     return $r[0]."";
616   else
617     return "";
618 }
619
620
621 function DB_get_startplayer_by_gameid($id)
622 {
623   $r = DB_query_array("SELECT startplayer FROM Game WHERE id=".DB_quote_smart($id));
624
625   if($r)
626     return $r[0];
627   else
628     return 0;
629 }
630
631 function DB_set_startplayer_by_gameid($id,$p)
632 {
633   DB_query("UPDATE Game SET startplayer='".$p."' WHERE id=".DB_quote_smart($id));
634   return;
635 }
636
637 function DB_get_player_by_gameid($id)
638 {
639   $r = DB_query_array("SELECT player FROM Game WHERE id=".DB_quote_smart($id));
640
641   if($r)
642     return $r[0];
643   else
644     return 0;
645 }
646 function DB_set_player_by_gameid($id,$p)
647 {
648   DB_query("UPDATE Game SET player='".DB_quote_smart($p)."' WHERE id=".DB_quote_smart($id));
649   return;
650 }
651
652
653
654 function DB_get_ruleset_by_gameid($id)
655 {
656   $r = DB_query_array("SELECT ruleset FROM Game WHERE id=".DB_quote_smart($id));
657
658   if($r)
659     return $r[0];
660   else
661     return NULL;
662 }
663
664 function DB_get_session_by_gameid($id)
665 {
666   $r = DB_query_array("SELECT session FROM Game WHERE id=".DB_quote_smart($id));
667
668   if($r)
669     return $r[0];
670   else
671     return NULL;
672 }
673
674 function DB_get_max_session()
675 {
676   $r = DB_query_array("SELECT MAX(session) FROM Game");
677
678   if($r)
679     return $r[0];
680   else
681     return 0;
682 }
683
684 function DB_get_hashes_by_session($session,$user)
685 {
686   $r = array();
687
688   $result = DB_query("SELECT Hand.hash FROM Hand".
689                      " LEFT JOIN Game ON Game.id=Hand.game_id ".
690                      " WHERE Game.session=".DB_quote_smart($session).
691                      " AND Hand.user_id=".DB_quote_smart($user).
692                      " ORDER BY Game.create_date ASC");
693   while($t = DB_fetch_array($result))
694     $r[] = $t[0];
695
696   return $r;
697 }
698
699 function DB_get_ruleset($dullen,$schweinchen,$call)
700 {
701   $r = array();
702
703   $result = DB_query("SELECT id FROM Rulesets WHERE".
704                      " dullen=".DB_quote_smart($dullen)." AND ".
705                      " Rulesets.call=".DB_quote_smart($call)." AND ".
706                      " schweinchen=".DB_quote_smart($schweinchen));
707   if($result)
708     $r    = DB_fetch_array($result);
709
710   if($r)
711     return $r[0]; /* found ruleset */
712   else
713     {
714       /* create new one */
715       $result = DB_query("INSERT INTO Rulesets VALUES (NULL, NULL, ".
716                          DB_quote_smart($dullen).",".
717                          DB_quote_smart($schweinchen).",".
718                          DB_quote_smart($call).
719                          ", NULL)");
720       if($result)
721         return DB_insert_id();
722     };
723
724   return -1; /* something went wrong */
725 }
726
727 function DB_get_party_by_hash($hash)
728 {
729   $r = DB_query_array("SELECT party FROM Hand WHERE hash=".DB_quote_smart($hash));
730
731   if($r)
732     return $r[0];
733   else
734     return NULL;
735 }
736
737 function DB_get_party_by_gameid_and_userid($gameid,$userid)
738 {
739   $r = DB_query_array("SELECT party FROM Hand".
740                       " WHERE game_id=".DB_quote_smart($gameid).
741                       "  AND user_id=".DB_quote_smart($userid));
742   if($r)
743     return $r[0];
744   else
745     return NULL;
746 }
747
748 function DB_set_party_by_hash($hash,$party)
749 {
750   DB_query("UPDATE Hand SET party=".DB_quote_smart($party)." WHERE hash=".DB_quote_smart($hash));
751   return;
752 }
753
754 function DB_get_PREF($myid)
755 {
756   /* set defaults */
757   $PREF['cardset']              = 'english';
758   $PREF['email']                = 'emailnonaddict';
759   $PREF['digest']               = 'digest-off';
760   $PREF['autosetup']            = 'no';
761   $PREF['sorting']              = 'high-low';
762   $PREF['open_for_games']       = 'yes';
763   $PREF['vacation_start']       =  NULL;
764   $PREF['vacation_stop']        =  NULL;
765   $PREF['vacation_comment']     =  '';
766
767   /* get all preferences */
768   $r = DB_query('SELECT pref_key, value FROM User_Prefs'.
769                       " WHERE user_id='$myid' " );
770   while($pref = DB_fetch_array($r) )
771     {
772       switch($pref[0])
773         {
774         case 'cardset':
775           /* licence only valid until then */
776           if($pref[1]=='altenburg' && (time()-strtotime( '2009-12-31 23:59:59')<0) )
777             $PREF['cardset']='altenburg';
778           break;
779
780         case 'email':
781           if($pref[1]=='emailaddict')
782             $PREF['email']='emailaddict';
783           break;
784
785         case 'digest':
786           if($pref[1])
787             $PREF['digest'] = $pref[1];
788           break;
789
790         case 'autosetup':
791           if($pref[1]=='yes')
792             $PREF['autosetup']='yes';
793           break;
794
795         case 'sorting':
796           if($pref[1])
797             $PREF['sorting'] = $pref[1];
798           break;
799
800         case 'open for games':
801           if($pref[1])
802             $PREF['open_for_games'] = $pref[1];
803           break;
804
805         case 'vacation start':
806           if($pref[1])
807             $PREF['vacation_start'] = $pref[1];
808           break;
809
810         case 'vacation stop':
811           if($pref[1])
812             $PREF['vacation_stop'] = $pref[1];
813           break;
814
815         case 'vacation comment':
816           if($pref[1])
817             $PREF['vacation_comment'] = $pref[1];
818           break;
819         }
820     }
821   return $PREF;
822 }
823
824 function DB_get_RULES($gameid)
825 {
826   $r = DB_query_array("SELECT * FROM Rulesets".
827                       " LEFT JOIN Game ON Game.ruleset=Rulesets.id ".
828                       " WHERE Game.id='$gameid'" );
829
830   $RULES["dullen"]      = $r[2];
831   $RULES["schweinchen"] = $r[3];
832   $RULES["call"]        = $r[4];
833
834   return $RULES;
835 }
836
837 function DB_get_email_pref_by_hash($hash)
838 {
839   $r = DB_query_array("SELECT value FROM Hand".
840                       " LEFT JOIN User_Prefs ON Hand.user_id=User_Prefs.user_id".
841                       " WHERE hash='$hash' AND pref_key='email'" );
842   if($r)
843     {
844       if($r[0]=="emailaddict")
845         return "emailaddict";
846       else
847         return "emailnonaddict";
848     }
849   else
850     return "emailnonaddict";
851 }
852
853 function DB_get_email_pref_by_uid($uid)
854 {
855   $r = DB_query_array("SELECT value FROM User_Prefs ".
856                       " WHERE user_id='$uid' AND pref_key='email'" );
857   if($r)
858     {
859       if($r[0]=="emailaddict")
860         return "emailaddict";
861       else
862         return "emailnonaddict";
863     }
864   else
865     return "emailnonaddict";
866 }
867
868 function DB_get_unused_randomnumbers($userstr)
869 {
870   /* optimized version of this query using temporary tables (perhaps we should use a procedure here?).
871      First we create a copy of the Game table using just the gameid and the cards.
872      Then in a second round we delete all the gameids of games where our players are in.
873      At the end we return only the first entry in the temporary table.
874   */
875   DB_query("DROP   TEMPORARY TABLE IF EXISTS gametmp;");
876   DB_query("CREATE TEMPORARY TABLE gametmp SELECT id,randomnumbers FROM Game;");
877   DB_query("DELETE FROM gametmp WHERE randomnumbers IN (SELECT randomnumbers FROM Hand LEFT JOIN Game ON Game.id=game_id WHERE user_id IN (".$userstr."));");
878
879   $r = DB_query_array("SELECT randomnumbers FROM gametmp LIMIT 1;");
880   DB_query("DROP   TEMPORARY TABLE IF EXISTS gametmp;");
881
882   if($r)
883     return $r[0];
884   else
885     return "";
886 }
887
888 function DB_get_number_of_passwords_recovery($user)
889 {
890   $r = DB_query_array("SELECT COUNT(*) FROM Recovery ".
891                       "  WHERE user_id=$user ".
892                       "  AND DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= create_date".
893                       "  GROUP BY user_id " );
894   if($r)
895     return $r[0];
896   else
897     return 0;
898 }
899
900 function DB_set_recovery_password($user,$newpw)
901 {
902   DB_query("INSERT INTO Recovery VALUES(NULL,".DB_quote_smart($user).
903            ",".DB_quote_smart($newpw).",NULL)");
904   return;
905 }
906
907 function DB_get_card_name($card)
908 {
909   if($card==0)
910     return 'backside';
911
912   $r = DB_query_array("SELECT strength,suite FROM Card WHERE id='$card'");
913
914   if($r)
915     return $r[0]." of ".$r[1];
916   else
917     return "Error during get_card_name ".$card;
918 }
919
920 function DB_get_current_playid($gameid)
921 {
922   $trick = DB_get_max_trickid($gameid);
923
924   if(!$trick) return NULL;
925
926   $r = DB_query_array("SELECT id FROM Play WHERE trick_id='$trick' ORDER BY create_date DESC LIMIT 1");
927
928   if($r)
929     return $r[0];
930
931   return "";
932 }
933
934 function DB_get_call_by_hash($hash)
935 {
936   $r = DB_query_array("SELECT point_call FROM Hand WHERE hash='$hash'");
937
938   if($r)
939     return $r[0];
940
941   return NULL;
942 }
943
944 function DB_get_partner_call_by_hash($hash)
945 {
946   $partner = DB_get_partner_hash_by_hash($hash);
947
948   if($partner)
949     {
950       $r = DB_query_array("SELECT point_call FROM Hand WHERE hash='$partner'");
951
952       if($r)
953         return $r[0];
954     }
955
956   return NULL;
957 }
958
959 function DB_get_partner_hash_by_hash($hash)
960 {
961   $gameid = DB_get_gameid_by_hash($hash);
962   $party  = DB_get_party_by_hash($hash);
963
964   $r = DB_query_array("SELECT hash FROM Hand WHERE game_id='$gameid' AND party='$party' AND hash<>'$hash'");
965
966   if($r)
967     return $r[0];
968
969   return NULL;
970 }
971
972 function DB_format_gameid($gameid)
973 {
974   /* get session and create date */
975   $r = DB_query_array("SELECT session, create_date FROM Game WHERE id='$gameid' ");
976   $session = $r[0];
977   $date    = $r[1];
978
979   /* get number of game */
980   $r = DB_query_array("SELECT SUM(TIME_TO_SEC(TIMEDIFF(create_date, '$date'))<=0) ".
981                       " FROM Game".
982                       " WHERE session='$session' ");
983   return $session.'.'.$r[0];
984 }
985
986 function DB_get_reminder($user,$gameid)
987 {
988   $r = DB_query_array("SELECT COUNT(*) FROM Reminder ".
989                       "  WHERE user_id=$user ".
990                       "  AND game_id=$gameid ".
991                       "  AND DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= create_date".
992                       "  GROUP BY user_id " );
993   if($r)
994     return $r[0];
995   else
996     return 0;
997 }
998
999 function DB_set_reminder($user,$gameid)
1000 {
1001   DB_query("INSERT INTO Reminder ".
1002            "  VALUES(NULL, ".DB_quote_smart($user).", ".DB_quote_smart($gameid).
1003            ", NULL) ");
1004   return 0;
1005 }
1006
1007 function DB_is_session_active($session)
1008 {
1009   $r = DB_query_array("SELECT COUNT(*) FROM Game ".
1010                       "  WHERE session=$session ".
1011                       "  AND status IN ('pre','play') ");
1012   if($r)
1013     return $r[0];
1014   else
1015     return -1;
1016 }
1017
1018 function DB_get_score_by_gameid($gameid)
1019 {
1020   /* returns the points of a game from the point of the re parth (<0 if they lost) */
1021   $queryresult = DB_query("SELECT COUNT(*),party FROM Score ".
1022                           "  WHERE game_id=$gameid ".
1023                           "  GROUP BY party ");
1024   $re     = 0;
1025   $contra = 0;
1026
1027   while($r = DB_fetch_array($queryresult) )
1028     {
1029       if($r[1] == "re")
1030         $re += $r[0];
1031       else if ($r[1] == "contra")
1032         $contra += $r[0];
1033     };
1034
1035   return ($re - $contra);
1036 }
1037
1038 function DB_get_gameids_of_finished_games_by_session($session)
1039 {
1040   $ids = array ();
1041
1042   if($session==0) /* return all games */
1043     $queryresult = DB_query("SELECT id FROM Game ".
1044                             " WHERE status='gameover' ".
1045                             " ORDER BY create_date ASC");
1046   else   /* return games in a session */
1047     $queryresult = DB_query("SELECT id FROM Game ".
1048                             "  WHERE session=$session ".
1049                             "   AND status='gameover' ".
1050                             " ORDER BY create_date ASC");
1051
1052   $i=0;
1053   while($r = DB_fetch_array($queryresult) )
1054     {
1055       $ids[$i] = $r[0];
1056       $i++;
1057     }
1058
1059   return $ids;
1060 }
1061
1062 function DB_get_card_value_by_cardid($id)
1063 {
1064   $r = DB_query_array("SELECT points FROM Card ".
1065                       "  WHERE id=$id ");
1066
1067   if($r)
1068     return $r[0];
1069   else
1070     return NULL;
1071 }
1072
1073 function DB_get_userid($type,$var1="",$var2="")
1074 {
1075   /* get the userid of a user
1076    * this can be done several ways, which are all handled below
1077    * if a email/password combination is given and it doesn't work, we also
1078    * need to check the recovery table for additional passwords
1079    */
1080
1081   $r = NULL;
1082
1083   switch($type)
1084     {
1085     case 'name':
1086       $result = DB_query("SELECT id FROM User WHERE fullname=".DB_quote_smart($var1));
1087       break;
1088     case 'hash':
1089       $result = DB_query("SELECT user_id FROM Hand WHERE hash=".DB_quote_smart($var1));
1090       break;
1091     case 'password':
1092       $result = DB_query("SELECT id FROM User WHERE password=".DB_quote_smart($var1));
1093       break;
1094     case 'email':
1095       $result = DB_query("SELECT id FROM User WHERE email=".DB_quote_smart($var1));
1096       break;
1097     case 'email-password':
1098       $result = DB_query("SELECT id FROM User WHERE email=".DB_quote_smart($var1)." AND password=".DB_quote_smart($var2));
1099       $r = DB_fetch_array($result);
1100       /* test if a recovery password has been set */
1101       if(!$r)
1102         {
1103           /* testing alternative password */
1104           $result = DB_query("SELECT User.id FROM User".
1105                              " LEFT JOIN Recovery ON User.id=Recovery.user_id".
1106                              " WHERE email=".DB_quote_smart($var1).
1107                              " AND Recovery.password=".DB_quote_smart($var2).
1108                              " AND DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= Recovery.create_date");
1109         }
1110       break;
1111     case 'gameid-position':
1112       $result = DB_query("SELECT user_id FROM Hand WHERE game_id=".
1113                          DB_quote_smart($var1)." AND position=".
1114                          DB_quote_smart($var2));
1115       break;
1116     }
1117
1118   if(!$r)
1119     $r = DB_fetch_array($result);
1120
1121   if($r)
1122     return $r[0];
1123   else
1124     return 0;
1125 }
1126
1127 function DB_get_email($type,$var1='',$var2='')
1128 {
1129   /* return the email of a user
1130    * this is used for sending out emails, but also for
1131    * testing the login for example
1132    */
1133   switch($type)
1134     {
1135     case 'name':
1136       $result = DB_query("SELECT email FROM User WHERE fullname=".DB_quote_smart($var1)."");
1137       break;
1138     case 'userid':
1139       $result = DB_query("SELECT email FROM User WHERE id=".DB_quote_smart($var1)."");
1140       break;
1141     case 'hash':
1142       $result = DB_query("SELECT User.email FROM User ".
1143                          "LEFT JOIN Hand ON Hand.user_id=User.id ".
1144                          "WHERE Hand.hash=".DB_quote_smart($var1)."");
1145       break;
1146     case 'position-gameid':
1147       $result = DB_query("SELECT email FROM User ".
1148                          "LEFT JOIN Hand ON User.id=Hand.user_id ".
1149                          "LEFT JOIN Game ON Game.id=Hand.game_id ".
1150                          "WHERE Game.id=".DB_quote_smart($var2)." ".
1151                          "AND Hand.position=".DB_quote_smart($var1)."");
1152       break;
1153     }
1154
1155   $r = DB_fetch_array($result);
1156
1157   if($r)
1158     return $r[0];
1159   else
1160     return "";
1161 }
1162
1163 function DB_get_name($type,$var1='')
1164 {
1165   /* get the full name of a user
1166    * a user can be uniquely identified several ways
1167    */
1168   switch($type)
1169     {
1170     case 'hash':
1171       $r = DB_query_array("SELECT fullname FROM Hand LEFT JOIN User ON Hand.user_id=User.id WHERE hash=".DB_quote_smart($var1));
1172       break;
1173     case 'email':
1174       $r = DB_query_array("SELECT fullname FROM User WHERE email=".DB_quote_smart($var1));
1175       break;
1176     case 'userid':
1177       $r = DB_query_array("SELECT fullname FROM User  WHERE id=".DB_quote_smart($var1));
1178     }
1179
1180   if($r)
1181     return $r[0];
1182   else
1183     return "";
1184 }
1185
1186 function DB_add_exchanged_card($card,$old_hand_id,$new_hand_id)
1187 {
1188   DB_query("INSERT INTO Card_Exchange VALUES (NULL,$new_hand_id,$old_hand_id,$card)");
1189   return;
1190 }
1191
1192 function DB_get_exchanged_cards($hash)
1193 {
1194   $cards = array();
1195
1196   $handid = DB_get_handid('hash',$hash);
1197
1198   $result = DB_query("SELECT card_id FROM Card_Exchange WHERE orig_hand_id=".DB_quote_smart($handid));
1199   while($r = DB_fetch_array($result))
1200     $cards[]=$r[0];
1201
1202   return $cards;
1203 }
1204
1205 function DB_played_by_others($gameid)
1206 {
1207   $gameids = array();
1208   $result = DB_query("SELECT id FROM Game WHERE randomnumbers=(SELECT randomnumbers FROM Game WHERE id=$gameid) AND status='gameover'");
1209   while($r = DB_fetch_array($result))
1210     if($r[0]!=$gameid)
1211       $gameids[]=$r[0];
1212   return $gameids;
1213 }
1214
1215 function DB_get_number_of_tricks($gameid,$position)
1216 {
1217   $r = DB_query_array("SELECT COUNT(winner) FROM Trick Where game_id='$gameid' and winner='$position'");
1218   return $r[0];
1219 }
1220
1221 function DB_digest_insert_email($To,$message)
1222 {
1223   DB_query("INSERT INTO digest_email VALUES (NULL,".DB_quote_smart($To).",NULL,".DB_quote_smart($message).")");
1224   return;
1225 }
1226
1227 function DB_get_digest_users()
1228 {
1229   $users = array();
1230
1231   $result = DB_query("SELECT user_id FROM User_Prefs WHERE pref_key='digest' and value <> 'digest-off'");
1232   while($r = DB_fetch_array($result))
1233     $users[]=$r[0];
1234
1235   return $users;
1236 }
1237
1238 function DB_get_digest_message_by_email($email)
1239 {
1240   $messages = array();
1241
1242   $result = DB_query("SELECT id,content FROM digest_email Where email='$email'");
1243   while($r = DB_fetch_array($result))
1244     $messages[]=$r;
1245
1246   return $messages;
1247 }
1248
1249 function DB_digest_delete_message($id)
1250 {
1251   DB_query("Delete from digest_email where id='$id'");
1252 }
1253
1254 ?>