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