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