a06f3d425ed4c1acf4ae189b446f162b052ef650
[e-DoKo.git] / include / functions.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 function config_check()
28 {
29   global $EmailName,$EMAIL_REPLY,$ADMIN_NAME,$ADMIN_EMAIL,$DB_work;
30
31   /* check if some variables are set in the config file, else set defaults */
32   if(!isset($EmailName))
33     $EmailName="[DoKo] ";
34   if(isset($EMAIL_REPLY))
35     {
36       ini_set("sendmail_from",$EMAIL_REPLY);
37     }
38   if(!isset($ADMIN_NAME))
39     {
40       output_header();
41       echo "<h1>Setup not completed</h1>";
42       echo "You need to set \$ADMIN_NAME in config.php.";
43       output_footer();
44       exit();
45     }
46   if(!isset($ADMIN_EMAIL))
47     {
48       output_header();
49       echo "<h1>Setup not completed</h1>";
50       echo "You need to set \$ADMIN_EMAIL in config.php. ".
51         "If something goes wrong an email will be send to this address.";
52       output_footer();
53       exit();
54     }
55   if(!isset($DB_work))
56     {
57       output_header();
58       echo "<h1>Setup not completed</h1>";
59       echo "You need to set \$DB_work in config.php. ".
60         "If this is set to 1, the game will be suspended and one can work safely on the database.".
61         "The default should be 0 for the game to work.";
62       output_footer();
63       exit();
64     }
65   if($DB_work)
66     {
67       output_header();
68       echo "Working on the database...please check back later.";
69       output_footer();
70       exit();
71     }
72
73   return;
74 }
75
76 function mymail($uid,$subject,$message)
77 {
78   global $EmailName;
79
80   /* do we send the email right away or save it in the database? */
81   $send_now = 1;
82
83   /* add standard header and footer */
84   $subject = "$EmailName".$subject;
85
86   /* standard goodbye */
87   $footer  = "\nHave a nice day\n".
88     "   your E-Doko service department\n\n".
89     "-- \n".
90     "You can change your mail delivery mode in the preference menu.\n".
91     'web: http://doko.nubati.net   '.
92     'help: http://wiki.nubati.net/EmailDoko   '.
93     'bugs: http://wiki.nubati.net/EmailDokoIssues';
94
95   if(is_array($uid))
96     {
97       /* send email to more than one person */
98
99       $header  = "Hello all\n\n";
100
101       foreach($uid as $user)
102         {
103           $all[] = DB_get_email('userid',$user);
104         }
105       $To = implode(",",$all);
106     }
107   else
108     {
109       /* standard greeting */
110       $name    = DB_get_name('userid',$uid);
111       $header  = "Hello $name\n\n";
112
113       $To = DB_get_email('userid',$uid);
114
115       /* check if user wants email right away or if we should save it in
116        * the database for later delivery
117        */
118
119       $PREF = DB_get_PREF($uid);
120       if( $PREF['digest'] != 'digest-off' )
121         $send_now = 0;
122     }
123
124   if($send_now)
125     sendmail($To,$subject,$header.$message.$footer);
126   else
127     {
128       /* store email in database */
129       DB_digest_insert_email($To,$message);
130     }
131 }
132
133 function sendmail($To,$Subject,$message)
134 {
135   /* this function sends the mail or outputs to the screen in case of debugging */
136   global $debug,$EMAIL_REPLY;
137
138   $header = "";
139
140   if(isset($EMAIL_REPLY))
141     $header .= "From: e-DoKo daemon <$EMAIL_REPLY>\r\n";
142
143   if($debug)
144     {
145       /* display email on screen,
146        * change txt -> html
147        */
148       $message = str_replace("\n","<br />\n",$message);
149       $message = preg_replace("#(\w+://[^<>\s]+[\w/]*)#",
150                               "<a href=\"$1\">$1</a>", $message);
151
152       echo "<br />To: $To<br />";
153       if($header != "")
154         echo $header."<br />";
155       echo "Subject: $Subject <br />$message<br />\n";
156     }
157   else
158     if($header != "")
159       mail($To,$Subject,$message,$header);
160     else
161       mail($To,$Subject,$message);
162   return;
163 }
164
165 function myisset()
166 {
167   /* returns 1 if all names passed as args are defined by a GET or POST statement,
168    * else return 0
169    */
170
171   $ok   = 1;
172   $args = func_get_args();
173
174   foreach($args as $arg)
175     {
176       $ok = $ok * isset($_REQUEST[$arg]);
177       /*echo "$arg: ok = $ok <br />";
178        */
179     }
180   return $ok;
181 }
182
183 function myerror($message)
184 {
185   echo "<span class=\"error\">".htmlspecialchars($message)."</span>\n";
186   sendmail($ADMIN_EMAIL,$EmailName." Error in Code",$message);
187   return;
188 }
189
190 function pos_array($c,$arr)
191 {
192   $ret = 0;
193
194   $i   = 0;
195   foreach($arr as $a)
196     {
197       $i++;
198       if($a == $c)
199         {
200           $ret = $i;
201           break;
202         }
203     }
204   return $ret;
205 }
206
207 function is_trump($c)
208 {
209   global $CARDS;
210
211   if(in_array($c,$CARDS["trump"]))
212     return 1;
213   else
214     return 0;
215 }
216
217 function is_same_suite($c1,$c2)
218 {
219   global $CARDS;
220
221   if(in_array($c1,$CARDS["trump"]   ) && in_array($c2,$CARDS["trump"]   ) ) return 1;
222   if(in_array($c1,$CARDS["clubs"]   ) && in_array($c2,$CARDS["clubs"]   ) ) return 1;
223   if(in_array($c1,$CARDS["hearts"]  ) && in_array($c2,$CARDS["hearts"]  ) ) return 1;
224   if(in_array($c1,$CARDS["spades"]  ) && in_array($c2,$CARDS["spades"]  ) ) return 1;
225   if(in_array($c1,$CARDS["diamonds"]) && in_array($c2,$CARDS["diamonds"]) ) return 1;
226
227   return 0;
228 }
229
230 function compare_cards($a,$b,$game)
231 {
232   /* if "a" is higher than "b" return 1, else 0, "a" being the card first played */
233
234   global $CARDS;
235   global $RULES;
236   global $GAME;
237
238   /* first map all cards to the odd number,
239    * this insure that the first card wins the trick
240    * if they are the same card
241    */
242   if( $a/2 - (int)($a/2) != 0.5)
243     $a--;
244   if( $b/2 - (int)($b/2) != 0.5)
245     $b--;
246
247   /* check for schweinchen and ten of hearts*/
248   switch($game)
249     {
250     case "normal":
251     case "silent":
252     case "trump":
253       if($RULES['schweinchen']=='both' && $GAME['schweinchen-who'])
254         {
255           if($a == 19 || $a == 20 )
256             return 1;
257           if($b == 19 || $b == 20 )
258             return 0;
259         }
260       else if($RULES['schweinchen']=='second' && $GAME['schweinchen-second'])
261         {
262           if($a == 19 || $a == 20 )
263             return 1;
264           if($b == 19 || $b == 20 )
265             return 0;
266         }
267       else if($RULES['schweinchen']=='secondaftercall' && $GAME['schweinchen-who'] && $GAME['schweinchen-second'] )
268         {
269           /* check if a call was made either by the player or his partner. If so activate Schweinchen rule. */
270           if(DB_get_call_by_hash($GAME['schweinchen-who']) || DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
271             {
272               if($a == 19 || $a == 20 )
273                 return 1;
274               if($b == 19 || $b == 20 )
275                 return 0;
276             }
277           /* if not, do nothing and the foxes are just handeled as normal trump */
278         }
279         ;
280     case "heart":
281     case "spade":
282     case "club":
283       /* check for ten of hearts rule */
284       if($RULES["dullen"]=="secondwins")
285         if($a==1 && $b==1) /* both 10 of hearts */
286           return 0;        /* second one wins.*/
287     case "trumpless":
288     case "jack":
289     case "queen":
290       /* no special cases here */
291     }
292
293   /* normal case */
294   if(is_trump($a) && is_trump($b) && $a<=$b)
295     return 1;
296   else if(is_trump($a) && is_trump($b) )
297     return 0;
298   else
299     { /*$a is not a trump */
300       if(is_trump($b))
301         return 0;
302       else
303         { /* both no trump */
304
305           /* both clubs? */
306           $posA = pos_array($a,$CARDS["clubs"]);
307           $posB = pos_array($b,$CARDS["clubs"]);
308           if($posA && $posB)
309             if($posA <= $posB)
310               return 1;
311             else
312               return 0;
313
314           /* both spades? */
315           $posA = pos_array($a,$CARDS["spades"]);
316           $posB = pos_array($b,$CARDS["spades"]);
317           if($posA && $posB)
318             if($posA <= $posB)
319               return 1;
320             else
321               return 0;
322
323           /* both hearts? */
324           $posA = pos_array($a,$CARDS["hearts"]);
325           $posB = pos_array($b,$CARDS["hearts"]);
326           if($posA && $posB)
327             if($posA <= $posB)
328               return 1;
329             else
330               return 0;
331
332           /* both diamonds? */
333           $posA = pos_array($a,$CARDS["diamonds"]);
334           $posB = pos_array($b,$CARDS["diamonds"]);
335           if($posA && $posB)
336             if($posA <= $posB)
337               return 1;
338             else
339               return 0;
340
341           /* not the same suit and no trump: a wins */
342           return 1;
343         }
344     }
345 }
346
347 function get_winner($p,$mode)
348 {
349   /* get all 4 cards played in a trick, in the order they are played */
350   $tmp = $p[1];
351   $c1    = $tmp["card"];
352   $c1pos = $tmp["pos"];
353
354   $tmp = $p[2];
355   $c2    = $tmp["card"];
356   $c2pos = $tmp["pos"];
357
358   $tmp = $p[3];
359   $c3    = $tmp["card"];
360   $c3pos = $tmp["pos"];
361
362   $tmp = $p[4];
363   $c4    = $tmp["card"];
364   $c4pos = $tmp["pos"];
365
366   /* first card is better than all the rest */
367   if( compare_cards($c1,$c2,$mode) && compare_cards($c1,$c3,$mode) && compare_cards($c1,$c4,$mode) )
368     return $c1pos;
369
370   /* second card is better than first and better than the rest */
371   if( !compare_cards($c1,$c2,$mode) &&  compare_cards($c2,$c3,$mode) && compare_cards($c2,$c4,$mode) )
372     return $c2pos;
373
374   /* third card is better than first card and better than last */
375   if( !compare_cards($c1,$c3,$mode) &&  compare_cards($c3,$c4,$mode) )
376     /* if second card is better than first, third card needs to be even better */
377     if( !compare_cards($c1,$c2,$mode) && !compare_cards($c2,$c3,$mode) )
378       return $c3pos;
379     /* second is worse than first, e.g. not following suite */
380     else if (compare_cards($c1,$c2,$mode) )
381       return $c3pos;
382
383   /* non of the above */
384   return $c4pos;
385 }
386
387 function count_nines($cards)
388 {
389   $nines = 0;
390
391   foreach($cards as $c)
392     {
393       if($c == "25" || $c == "26") $nines++;
394       else if($c == "33" || $c == "34") $nines++;
395       else if($c == "41" || $c == "42") $nines++;
396       else if($c == "47" || $c == "48") $nines++;
397     }
398
399   return $nines;
400 }
401
402 function check_wedding($cards)
403 {
404
405   if( in_array("3",$cards) && in_array("4",$cards) )
406     return 1;
407
408   return 0;
409 }
410
411 function count_trump($cards,$status='pregame')
412 {
413   global $RULES;
414
415   $trump = 0;
416
417   /* count each trump, including the foxes, since this is used to determine poverty status */
418   foreach($cards as $c)
419     if( (int)($c) <27)
420       $trump++;
421
422   /* In case we really want to know the amount of trump, we can use the status variable.
423    * This is needed for example to figure out what icon to display on the table in case of
424    * trump given back in poverty */
425   if($status=='all') return $trump;
426
427   /* normally foxes don't count as trump, so we substract them here
428    * in case someone has schweinchen, one or two of them should count as trump
429    * though, so we need to add one trump for those cases */
430
431   /* subtract foxes */
432   if( in_array("19",$cards))
433     $trump--;
434   if( in_array("20",$cards) )
435     $trump--;
436
437   /* handle case where player has schweinchen */
438   if( in_array("19",$cards) && in_array("20",$cards) )
439     switch($RULES["schweinchen"])
440       {
441       case "both":
442         /* add two, in case the player has both foxes (schweinchen) */
443         $trump++;
444         $trump++;
445         break;
446       case "second":
447       case "secondaftercall":
448         /* add one, in case the player has both foxes (schweinchen) */
449         $trump++;
450         break;
451       case "none":
452         break;
453       }
454
455   return $trump;
456 }
457
458 function check_low_trump($cards)
459 {
460   global $RULES;
461
462   if($RULES['lowtrump']=='none')
463     return 0;
464
465   /* check if we have low trump */
466
467   $lowtrump=1;
468   foreach($cards as $card)
469     {
470       /* card a trump, but not a diamond? */
471       if( $card<19 )
472          $lowtrump=0;
473     }
474
475   /* handle case where player has schweinchen */
476   if( in_array("19",$cards) && in_array("20",$cards) )
477     switch($RULES["schweinchen"])
478       {
479       case "both":
480       case "second":
481       case "secondaftercall":
482         $lowtrump=0;
483         break;
484       case "none":
485         break;
486       }
487
488   return $lowtrump;
489 }
490
491 function  create_array_of_random_numbers($useridA,$useridB,$useridC,$useridD)
492 {
493   global $debug;
494
495   $r = array();
496
497   if($debug)
498     {
499       $r[ 0]=1;     $r[12]=47;   $r[24]=13;       $r[36]=37;
500       $r[ 1]=2;     $r[13]=23;   $r[25]=14;       $r[37]=38;
501       $r[ 2]=3;     $r[14]=27;   $r[26]=15;       $r[38]=39;
502       $r[ 3]=4;     $r[15]=16;   $r[27]=28;       $r[39]=40;
503       $r[ 4]=5;     $r[16]=17;   $r[28]=29;       $r[40]=21;
504       $r[ 5]=18;    $r[17]=6;    $r[29]=30;       $r[41]=42;
505       $r[ 6]=41;    $r[18]=7;    $r[30]=31;       $r[42]=43;
506       $r[ 7]=22;    $r[19]=8;    $r[31]=32;       $r[43]=20;
507       $r[ 8]=45;    $r[20]=9;    $r[32]=33;       $r[44]=19;
508       $r[ 9]=46;    $r[21]=10;   $r[33]=44;       $r[45]=24;
509       $r[10]=35;    $r[22]=11;   $r[34]=48;       $r[46]=25;
510       $r[11]=36;    $r[23]=12;   $r[35]=34;       $r[47]=26;
511     }
512   else
513     {
514       /* check if we can find a game were non of the player was involved and return
515        * cards insted
516        */
517       $userstr = "'".implode("','",array($useridA,$useridB,$useridC,$useridD))."'";
518       $randomnumbers = DB_get_unused_randomnumbers($userstr);
519       $randomnumbers = explode(":",$randomnumbers);
520
521       if(sizeof($randomnumbers)==48)
522         return $randomnumbers;
523
524       /* need to create new numbers */
525       for($i=0;$i<48;$i++)
526         $r[$i]=$i+1;
527
528       /* shuffle using a better random generator than the standard one */
529       for ($i = 0; $i <48; $i++)
530         {
531           $j = @mt_rand(0, $i);
532           $tmp = $r[$i];
533           $r[$i] = $r[$j];
534           $r[$j] = $tmp;
535         }
536     };
537
538   return $r;
539 }
540
541 function display_cards($me,$myturn)
542 {
543   return;
544 }
545
546 function have_suit($cards,$c)
547 {
548   global $CARDS;
549   $suite = array();
550
551   if(in_array($c,$CARDS["trump"]))
552     $suite = $CARDS["trump"];
553   else if(in_array($c,$CARDS["clubs"]))
554     $suite = $CARDS["clubs"];
555   else if(in_array($c,$CARDS["spades"]))
556     $suite = $CARDS["spades"];
557   else if(in_array($c,$CARDS["hearts"]))
558     $suite = $CARDS["hearts"];
559   else if(in_array($c,$CARDS["diamonds"]))
560     $suite = $CARDS["diamonds"];
561
562   foreach($cards as $card)
563     {
564       if(in_array($card,$suite))
565         return 1;
566     }
567
568   return 0;
569 }
570
571 function same_type($card,$c)
572 {
573   global $CARDS;
574   $suite = "";
575
576   /* figure out what kind of card c is */
577   if(in_array($c,$CARDS["trump"]))
578     $suite = $CARDS["trump"];
579   else if(in_array($c,$CARDS["clubs"]))
580     $suite = $CARDS["clubs"];
581   else if(in_array($c,$CARDS["spades"]))
582     $suite = $CARDS["spades"];
583   else if(in_array($c,$CARDS["hearts"]))
584     $suite = $CARDS["hearts"];
585   else if(in_array($c,$CARDS["diamonds"]))
586     $suite = $CARDS["diamonds"];
587
588   /* card is the same suid return 1 */
589   if(in_array($card,$suite))
590     return 1;
591
592   return 0;
593 }
594
595 function set_gametype($gametype)
596 {
597   global $CARDS;
598   global $RULES;
599   global $GAME;
600
601   switch($gametype)
602     {
603     case "normal":
604     case "wedding":
605     case "poverty":
606     case "dpoverty":
607     case "trump":
608     case "silent":
609       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
610                                  '17','18','19','20','21','22','23','24','25','26');
611       $CARDS["diamonds"] = array();
612       $CARDS["clubs"]    = array('27','28','29','30','31','32','33','34');
613       $CARDS["spades"]   = array('35','36','37','38','39','40','41','42');
614       $CARDS["hearts"]   = array('43','44','45','46','47','48');
615       $CARDS["foxes"]    = array('19','20');
616       if($RULES["dullen"]=='none')
617         {
618           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
619                                      '17','18','19','20','21','22','23','24','25','26');
620           $CARDS["hearts"]   = array('43','44','1','2','45','46','47','48');
621         }
622       /* do we need to reorder for Schweinchen? need to search for it because of special case for dullen above*/
623       if($RULES['schweinchen']=='both'&& $GAME['schweinchen-who'])
624         {
625           /* find the fox and put them at the top of the stack */
626           foreach(array('19','20') as $fox)
627             {
628               /* search for fox */
629               $trump = $CARDS['trump'];
630               $key = array_keys($trump, $fox);
631
632               /* reorder */
633               $foxa = array();
634               $foxa[]=$trump[$key[0]];
635               unset($trump[$key[0]]);
636               $trump = array_merge($foxa,$trump);
637               $CARDS['trump'] = $trump;
638             }
639         }
640       else if( ($RULES['schweinchen']=='second' || $RULES['schweinchen']=='secondaftercall')
641                && $GAME['schweinchen-who'])
642         {
643           /* find the fox and put them at the top of the stack */
644           $trump = $CARDS['trump'];
645           $key = array_keys($trump, '19');
646
647           /* reorder */
648           $foxa = array();
649           $foxa[]=$trump[$key[0]];
650           unset($trump[$key[0]]);
651           $trump = array_merge($foxa,$trump);
652           $CARDS['trump'] = $trump;
653         }
654       break;
655     case "queen":
656       $CARDS["trump"]    = array('3','4','5','6','7','8','9','10');
657       $CARDS["clubs"]    = array('27','28','29','30','31','32','11','12','33','34');
658       $CARDS["spades"]   = array('35','36','37','38','39','40','13','14','41','42');
659       $CARDS["hearts"]   = array('43','44', '1', '2','45','46','15','16','47','48');
660       $CARDS["diamonds"] = array('19','20','21','22','23','24','17','18','25','26');
661       $CARDS["foxes"]    = array();
662       break;
663     case "jack":
664       $CARDS["trump"]    = array('11','12','13','14','15','16','17','18');
665       $CARDS["clubs"]    = array('27','28','29','30','31','32','3', '4','33','34');
666       $CARDS["spades"]   = array('35','36','37','38','39','40','5', '6','41','42');
667       $CARDS["hearts"]   = array('43','44', '1', '2','45','46','7', '8','47','48');
668       $CARDS["diamonds"] = array('19','20','21','22','23','24','9','10','25','26');
669       $CARDS["foxes"]    = array();
670       break;
671     case "trumpless":
672       $CARDS["trump"]    = array();
673       $CARDS["clubs"]    = array('27','28','29','30','31','32','3', '4','11','12','33','34');
674       $CARDS["spades"]   = array('35','36','37','38','39','40','5', '6','13','14','41','42');
675       $CARDS["hearts"]   = array('43','44', '1', '2','45','46','7', '8','15','16','47','48');
676       $CARDS["diamonds"] = array('19','20','21','22','23','24','9','10','17','18','25','26');
677       $CARDS["foxes"]    = array();
678       break;
679     case "club":
680       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
681                                  '17','18','27','28','29','30','31','32','33','34');
682       $CARDS["clubs"]    = array();
683       $CARDS["spades"]   = array('35','36','37','38','39','40','41','42');
684       $CARDS["hearts"]   = array('43','44','45','46','47','48');
685       $CARDS["diamonds"] = array('19','20','21','22','23','24','25','26');
686       $CARDS["foxes"]    = array();
687       if($RULES["dullen"]=='none')
688         {
689           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
690                                      '17','18','27','28','29','30','31','32','33','34');
691           $CARDS["hearts"]   = array('43','44','1','2','45','46','47','48');
692         }
693       break;
694     case "spade":
695       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
696                                  '17','18','35','36','37','38','39','40','41','42');
697       $CARDS["clubs"]    = array('27','28','29','30','31','32','33','34');
698       $CARDS["spades"]   = array();
699       $CARDS["hearts"]   = array('43','44','45','46','47','48');
700       $CARDS["diamonds"] = array('19','20','21','22','23','24','25','26');
701       $CARDS["foxes"]    = array();
702       if($RULES["dullen"]=='none')
703         {
704           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
705                                      '17','18','35','36','37','38','39','40','41','42');
706           $CARDS["hearts"]   = array('43','44','1','2','45','46','47','48');
707         }
708       break;
709     case "heart":
710       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
711                                  '17','18','43','44','45','46','47','48');
712       $CARDS["clubs"]    = array('27','28','29','30','31','32','33','34');
713       $CARDS["spades"]   = array('35','36','37','38','39','40','41','42');
714       $CARDS["hearts"]   = array();
715       $CARDS["diamonds"] = array('19','20','21','22','23','24','25','26');
716       $CARDS["foxes"]    = array();
717       if($RULES["dullen"]=='none')
718         {
719           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
720                             '17','18','43','44','1','2','45','46','47','48');
721         }
722       break;
723     }
724 }
725
726 function mysort($cards,$gametype)
727 {
728   global $PREF;
729   if(isset($PREF['sorting']))
730     if($PREF['sorting']=='high-low')
731       usort ( $cards, 'sort_comp_high_low' );
732     else
733       usort ( $cards, 'sort_comp_low_high' );
734   else
735     usort ( $cards, 'sort_comp_high_low' );
736   return $cards;
737 }
738
739 function sort_comp_high_low($a,$b)
740 {
741   global $CARDS;
742
743   $ALL = array();
744   $ALL = array_merge($CARDS['trump'],$CARDS['diamonds'],$CARDS['clubs'],
745                      $CARDS['hearts'],$CARDS['spades']);
746
747   return pos_array($a,$ALL)-pos_array($b,$ALL);
748 }
749
750 function sort_comp_low_high($a,$b)
751 {
752   global $CARDS;
753
754   $ALL = array();
755   $ALL = array_merge($CARDS['trump'],$CARDS['diamonds'],$CARDS['clubs'],
756                      $CARDS['hearts'],$CARDS['spades']);
757
758   return -pos_array($a,$ALL)+pos_array($b,$ALL);
759 }
760
761 function can_call($what,$hash)
762 {
763   /* figure out if a person can make a call:
764    $what in 0,30,60,90,120 = points of the call
765    $hash                   = the hash of the person who wants to make the call
766
767    return values:
768    0   can't make that call
769    1   can make the call
770    2   can make the call, but this is the last chance to do so...
771    */
772
773   global $RULES;
774
775   /* get some information
776    */
777   $gameid   = DB_get_gameid_by_hash($hash);
778   $gametype = DB_get_gametype_by_gameid($gameid);
779   $oldcall  = DB_get_call_by_hash($hash); /* did the person already made a call? */
780   $pcall    = DB_get_partner_call_by_hash($hash); /* did the partner already made a call */
781
782
783   /* you're call must be better than the one you or your partner already made
784    */
785   if( ($pcall!=NULL && ($what >= $pcall))
786       || ($oldcall!=NULL && ($what >=$oldcall)) )
787     {
788       return 0;
789     }
790
791   /* for some rules we need to know how many cards people have
792    */
793   $NRcards  = count(DB_get_hand($hash));
794
795   $NRallcards = 0;
796   for ($i=1;$i<5;$i++)
797     {
798       $user         = DB_get_hash_from_game_and_pos($gameid,$i);
799       $NRallcards  += count(DB_get_hand($user));
800     };
801
802   /* in case of a wedding, everything will be delayed by an offset
803    */
804   $offset = 0;
805   if($gametype=="wedding")
806     {
807       $offset = DB_get_sickness_by_gameid($gameid);
808       if ($offset <0) /* not resolved */
809         return 0;
810     };
811
812   /* now check if the call is allowed depending on the rule set
813    */
814   switch ($RULES["call"])
815     {
816     case "1st-own-card":
817       /* calls can be made before/while you play your card...
818        * first card = 120, second card = 90, etc.
819        */
820       if( 4-($what/30) == 12 - ($NRcards + $offset))
821         return 2;
822       if( 4-($what/30) > 12 - ($NRcards + $offset))
823         return 1;
824       break;
825     case "5th-card":
826       /* you can make the first call anytime during the first trick
827        */
828       if( 27+4*($what/30) == $NRallcards + $offset*4)
829         return 2;
830       if( 27+4*($what/30) < $NRallcards + $offset*4)
831         return 1;
832       break;
833     case "9-cards":
834       /* you can call 120 with 12 cards, 90 with 9 or more cards, 60 with 6 or more, etc.
835        * you can't skip a call though
836        */
837
838       /* figure out last call
839        */
840       if($oldcall!=NULL && $pcall!=NULL)
841         $mincall = ($oldcall>$pcall) ? $pcall : $oldcall;
842       else if($oldcall!=NULL)
843         $mincall = $oldcall;
844       else if ($pcall!=NULL)
845         $mincall = $pcall;
846       else
847         $mincall = -1;
848
849
850       if( 12 == ($NRcards + $offset))
851         {
852           return 2;
853         }
854       else if( 12 < ($NRcards + $offset))
855         {
856           return 1;
857         }
858       else if ( 9 == ($NRcards + $offset))
859         {
860           if( ($mincall>=0 && $mincall==120) )
861             return 2;
862         }
863       else if ( 9 < ($NRcards + $offset))
864         {
865           if( ($mincall>=0 && $mincall==120) )
866             return 1;
867         }
868       else if ( 6 == ($NRcards + $offset))
869         {
870           if( ($mincall>=0 && $mincall<=90 && $what<=60 ) )
871             return 2;
872         }
873       else if ( 6 < ($NRcards + $offset))
874         {
875           if( ($mincall>=0 && $mincall<=90 && $what<=60 ) )
876             return 1;
877         }
878       else if ( 3 == ($NRcards + $offset))
879         {
880           if( ($mincall>=0 && $mincall<=60 && $what<=30 ) )
881             return 2;
882         }
883       else if ( 3 < ($NRcards + $offset))
884         {
885           if( ($mincall>=0 && $mincall<=60 && $what<=30 ) )
886             return 1;
887         }
888       else if ( 0 == ($NRcards + $offset))
889         {
890           if( ($mincall>=0 && $mincall<=30 && $what==0 ) )
891             return 2;
892         }
893       else if ( 0 < ($NRcards + $offset))
894         {
895           if( ($mincall>=0 && $mincall<=30 && $what==0 ) )
896             return 1;
897         };
898       break;
899     }
900
901   return 0;
902 }
903
904 function display_table ()
905 {
906   global $gameid, $GT, $debug,$INDEX,$defaulttimezone,$session;
907   global $RULES,$GAME,$gametype;
908
909   $result = DB_query("SELECT  User.fullname as name,".
910                      "        Hand.position as position, ".
911                      "        User.id, ".
912                      "        Hand.party as party, ".
913                      "        Hand.sickness as sickness, ".
914                      "        Hand.point_call, ".
915                      "        User.last_login, ".
916                      "        Hand.hash,       ".
917                      "        User.timezone,    ".
918                      "        User.email       ".
919                      "FROM Hand ".
920                      "LEFT JOIN User ON User.id=Hand.user_id ".
921                      "WHERE Hand.game_id='".$gameid."' ".
922                      "ORDER BY position ASC");
923
924   echo "<div class=\"table\">\n".
925     "  <img class=\"table\" src=\"pics/table.png\" alt=\"table\" />\n";
926   while($r = DB_fetch_array($result))
927     {
928       $name  = $r[0];
929       $pos   = $r[1];
930       $user  = $r[2];
931       $party = $r[3];
932       $sickness  = $r[4];
933       $call      = $r[5];
934       $hash      = $r[7];
935       $timezone  = $r[8];
936       $email     = $r[9];
937       $wins      = DB_get_number_of_tricks($gameid,$pos);
938       date_default_timezone_set($defaulttimezone);
939       $lastlogin = strtotime($r[6]);
940       date_default_timezone_set($timezone);
941       $timenow   = strtotime(date("Y-m-d H:i:s"));
942       $gravatar = "$name<br /><img class=\"gravatar\" title=\"$name\" src=\"http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=identicon\" />";
943
944
945       echo "  <div class=\"table".($pos-1)."\">\n";
946
947       if($debug)
948         echo "   <a href=\"".$INDEX."?action=game&amp;me=".$hash."\">";
949       if($vacation = check_vacation($user))
950         {
951           $start   = $vacation[0];
952           $stop    = substr($vacation[1],0,10);
953           $comment = $vacation[2];
954
955               $title = "begin: $start  end: $stop $comment";
956               echo "   <span class=\"vacation\" title=\"$title\">$gravatar (on vacation until $stop)</span> \n";
957         }
958       else
959         echo "   $gravatar \n";
960       if($debug)
961         echo"</a>\n";
962
963       /* add hints for poverty, wedding, solo, etc */
964       if( $gametype != "solo")
965         if( $RULES["schweinchen"]=="both" && $GAME["schweinchen-who"]==$hash )
966           echo " Schweinchen. <br />";
967
968       if($GT=="poverty" && $party=="re")
969         if($sickness=="poverty" || ($RULES['lowtrump']=='poverty' && $sickness=='lowtrump'))
970           {
971             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
972             $cards    = DB_get_all_hand($userhash);
973             $trumpNR  = count_trump($cards,'all');
974             if($trumpNR)
975               echo "   <img src=\"pics/button/poverty_trump_button.png\" class=\"button\" alt=\"poverty < trump back\" title=\"poverty - trump back\" />";
976             else
977               echo "   <img src=\"pics/button/poverty_notrump_button.png\" class=\"button\" alt=\"poverty <\" title=\"poverty - no trump back\" />";
978           }
979         else
980           echo "   <img src=\"pics/button/poverty_partner_button.png\" class=\"button\" alt=\"poverty >\" title=\"poverty partner\" />";
981
982       if($GT=="dpoverty")
983         if($party=="re")
984           if($sickness=="poverty" || ($RULES['lowtrump']=='poverty' && $sickness=='lowtrump'))
985             {
986               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
987               $cards    = DB_get_all_hand($userhash);
988               $trumpNR  = count_trump($cards,'all');
989               if($trumpNR)
990                 echo "   <img src=\"pics/button/poverty_trump_button.png\" class=\"button\" alt=\"poverty < trump back\" title=\"poverty - trump back\" />";
991               else
992                 echo "   <img src=\"pics/button/poverty_notrump_button.png\" class=\"button\" alt=\"poverty <\" title=\"poverty - no trump back\" />";
993             }
994           else
995             echo "   <img src=\"pics/button/poverty_partner_button.png\" class=\"button\" alt=\"poverty >\" title=\"poverty partner\" />";
996         else
997           if($sickness=="poverty"  || ($RULES['lowtrump']=='poverty' && $sickness=='lowtrump'))
998             {
999               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1000               $cards    = DB_get_all_hand($userhash);
1001               $trumpNR  = count_trump($cards,'all');
1002               if($trumpNR)
1003                 echo "   <img src=\"pics/button/poverty2_trump_button.png\" class=\"button\" alt=\"poverty2 < trump back\" title=\"poverty2 - trump back\"/>";
1004               else
1005                 echo "   <img src=\"pics/button/poverty2_notrump_button.png\" class=\"button\" alt=\"poverty2 <\" title=\"poverty2 - no trump back\" />";
1006             }
1007           else
1008             echo "   <img src=\"pics/button/poverty2_partner_button.png\" class=\"button\" alt=\"poverty2 >\" title=\"poverty2 partner\" />";
1009
1010       if($GT=="wedding" && $party=="re")
1011         if($sickness=="wedding")
1012           echo "   <img src=\"pics/button/wedding_button.png\" class=\"button\" alt=\"wedding\" title=\"wedding\" />";
1013         else
1014           echo "   <img src=\"pics/button/wedding_partner_button.png\" class=\"button\" alt=\"wedding partner\" title=\"wedding partner\" />";
1015
1016       if( (strpos($GT,"solo")!==false) && $party=="re")
1017         {
1018           if(strpos($GT,"queen")!==false)
1019             echo "   <img src=\"pics/button/queensolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Queen solo\" />";
1020           else if(strpos($GT,"jack")!==false)
1021             echo "   <img src=\"pics/button/jacksolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Jack solo\" />";
1022           else if(strpos($GT,"club")!==false)
1023             echo "   <img src=\"pics/button/clubsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Club solo\" />";
1024           else if(strpos($GT,"spade")!==false)
1025             echo "   <img src=\"pics/button/spadesolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Spade solo\" />";
1026           else if(strpos($GT,"heart")!==false)
1027             echo "   <img src=\"pics/button/heartsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Heart solo\" />";
1028           else if(strpos($GT,"trumpless")!==false)
1029             echo "   <img src=\"pics/button/notrumpsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Trumpless solo\" />";
1030           else if(strpos($GT,"trump")!==false)
1031             echo "   <img src=\"pics/button/trumpsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Trump solo\" />";
1032         }
1033
1034       /* add point calls */
1035       if($call!=NULL)
1036         {
1037           if($party=="re")
1038             echo "  <img src=\"pics/button/re_button.png\" class=\"button\" alt=\"re\" title=\"Re\" />";
1039           else
1040             echo "  <img src=\"pics/button/contra_button.png\" class=\"button\" alt=\"contra\" title=\"Contra\" />";
1041           switch($call)
1042             {
1043             case "0":
1044               echo "   <img src=\"pics/button/0_button.png\" class=\"button\" alt=\"0\" title=\"Call 0\" />";
1045               break;
1046             case "30":
1047               echo "   <img src=\"pics/button/30_button.png\" class=\"button\" alt=\"30\" title=\"Call 30\" />";
1048               break;
1049             case "60":
1050               echo "   <img src=\"pics/button/60_button.png\" class=\"button\" alt=\"60\" title=\"Call 60\" />";
1051               break;
1052             case "90":
1053               echo "   <img src=\"pics/button/90_button.png\" class=\"button\" alt=\"90\" title=\"Call 90\" />";
1054               break;
1055             }
1056         }
1057
1058       echo "    <br />\n";
1059       echo "    <span title=\"local time: ".date("Y-m-d H:i:s",$timenow).  " ".
1060                              "last login: ".date("Y-m-d H:i:s",$lastlogin)."\">".
1061                              "<img src=\"pics/button/time-info.png\" class=\"tinybutton\" alt=\"time info\" />".
1062                              "</span>\n";
1063
1064       /* show how many tricks the person made */
1065       switch($wins)
1066         {
1067         case 0:
1068           echo "#tricks 0"; break;
1069         case 1:
1070           echo "#tricks 1"; break;
1071         case 2:
1072         case 3:
1073         case 4:
1074           echo "#tricks few"; break;
1075         default:
1076           echo "#tricks many"; break;
1077         }
1078
1079       echo "   </div>\n";
1080
1081     }
1082   echo  "</div>\n"; /* end output table */
1083
1084
1085   return;
1086 }
1087
1088
1089 function display_user_menu($id)
1090 {
1091   global $WIKI,$INDEX;
1092
1093   $result = DB_query("SELECT Hand.hash,Hand.game_id,Game.player from Hand".
1094                      " LEFT JOIN Game On Hand.game_id=Game.id".
1095                      " WHERE Hand.user_id='$id'".
1096                      " AND ( Game.player='$id' OR ISNULL(Game.player) )".
1097                      " AND ( Game.status='pre' OR Game.status='play' )".
1098                      " ORDER BY Game.session" );
1099
1100   $i=0;
1101   while( $r = DB_fetch_array($result))
1102     {
1103       if($i==0)
1104         {
1105           echo "<div class=\"usermenu\">\n";
1106           echo "It's your turn in these games:<br />\n";
1107         }
1108
1109       $i++;
1110       echo "<a href=\"".$INDEX."?action=game&amp;me=".$r[0].
1111         "\">game ".DB_format_gameid($r[1])." </a><br />\n";
1112       if($i>4)
1113         {
1114           echo "...<br />\n";
1115           break;
1116         }
1117     }
1118
1119   if($i)
1120     echo  "</div>\n";
1121   return;
1122 }
1123
1124 function generate_score_table($session)
1125 {
1126   /* returns an array with N entries
1127    * $score[$i]["gameid"]   = gameid
1128    * $score[$i]["players"] = array (id=>total points)
1129    * $score[$i]["points"]   = points for this game
1130    * $score[$i]["solo"]     = 1 or 0
1131    */
1132   $score = array();
1133   $i=0;
1134
1135   /* get all ids */
1136   $gameids = DB_get_gameids_of_finished_games_by_session($session);
1137
1138   if($gameids == NULL)
1139     return $score;
1140
1141   /* get player id, names... from the first game */
1142   $player = array();
1143   $result = DB_query("SELECT User.id, User.fullname from Hand".
1144                      " LEFT JOIN User On Hand.user_id=User.id".
1145                      " WHERE Hand.game_id=".$gameids[0]);
1146   while( $r = DB_fetch_array($result))
1147     $player[$r[0]] = 0;
1148
1149   /* get points and generate table */
1150   foreach($gameids as $gameid)
1151     {
1152       $re_score = DB_get_score_by_gameid($gameid);
1153       $gametype = DB_get_gametype_by_gameid($gameid);
1154       foreach($player as $id=>$points)
1155         {
1156           $party = DB_get_party_by_gameid_and_userid($gameid,$id);
1157           if($party == "re")
1158             if($gametype=="solo")
1159               $player[$id] += 3*$re_score;
1160             else
1161               $player[$id] += $re_score;
1162           else if ($party == "contra")
1163             $player[$id] -= $re_score;
1164         }
1165       $score[$i]['gameid']  = $gameid ;
1166       $score[$i]['players'] = $player;
1167       $score[$i]['points']  = abs($re_score);
1168       $score[$i]['solo']    = ($gametype=="solo");
1169
1170       $i++;
1171     }
1172
1173   return $score;
1174 }
1175
1176 function generate_global_score_table()
1177 {
1178   $return = array();
1179
1180   /* get all ids */
1181   $gameids = DB_get_gameids_of_finished_games_by_session(0);
1182
1183   if($gameids == NULL)
1184     return '';
1185
1186   /* get player id, names... from the User table */
1187   $player = array();
1188   $result = DB_query('SELECT User.id, User.fullname FROM User');
1189
1190   /* save information in an array */
1191   while( $r = DB_fetch_array($result))
1192     $player[$r[0]] = array('name'=> $r[1], 'points' => 0 , 'nr' => 0, 'active' => 0,
1193                            'response' => 0 , 'solo' => 0, 'soloavg' => 0);
1194
1195   /* get points and generate table */
1196   foreach($gameids as $gameid)
1197     {
1198       $re_score = DB_get_score_by_gameid($gameid);
1199       $gametype = DB_get_gametype_by_gameid($gameid);
1200
1201       /* get players involved in this game */
1202       $result = DB_query('SELECT user_id FROM Hand WHERE game_id='.DB_quote_smart($gameid));
1203       while($r = DB_fetch_array($result))
1204         {
1205           $id = $r[0];
1206           $party = DB_get_party_by_gameid_and_userid($gameid,$id);
1207           if($party == 're')
1208             if($gametype=='solo')
1209               $player[$id]['points'] += 3*$re_score;
1210             else
1211               $player[$id]['points'] += $re_score;
1212           else if ($party == 'contra')
1213             $player[$id]['points'] -= $re_score;
1214           if($party)
1215             $player[$id]['nr']+=1;
1216         }
1217     }
1218
1219   /* add number of active games */
1220   $result = DB_query_array_all("SELECT user_id, COUNT(*) as c  " .
1221                                " FROM Hand".
1222                                " LEFT JOIN Game ON Game.id=game_id".
1223                                " WHERE Game.status IN ('pre','play')".
1224                                " GROUP BY user_id");
1225
1226   foreach($result as $res)
1227     {
1228       $player[$res[0]]['active'] = $res[1];
1229     }
1230
1231   /* response time of users*/
1232   $result = DB_query_array_all("SELECT user_id,".
1233                               "IFNULL(AVG(if(P1.sequence in (2,3,4),".
1234                               "-timestampdiff(MINUTE,mod_date,(select mod_date from Play P2 where P1.trick_id=P2.trick_id  and P2.sequence=P1.sequence-1)),NULL )),1e9) as a ".
1235                               "FROM Play P1 ".
1236                               "LEFT JOIN Hand_Card ON P1.hand_card_id=Hand_Card.id ".
1237                               "LEFT JOIN Hand ON Hand.id=Hand_Card.hand_id ".
1238                               "GROUP BY user_id ");
1239
1240   foreach($result as $res)
1241     {
1242       $player[$res[0]]['response'] = $res[1];
1243     }
1244
1245   /* most solos */
1246   $result = DB_query_array_all("SELECT user_id as uid,".
1247                                "       COUNT(*), ".
1248                                "       COUNT(*)/(SELECT COUNT(*) FROM Hand LEFT JOIN User ON User.id=Hand.user_id WHERE User.id=uid) as c ".
1249                                " FROM Game ".
1250                                " LEFT JOIN Hand ON Hand.position=startplayer AND Game.id=Hand.game_id ".
1251                                " WHERE type='solo' AND Game.status='gameover' ".
1252                                " GROUP BY user_id ");
1253
1254   foreach($result as $res)
1255     {
1256       $player[$res[0]]['solo'] = $res[1];
1257       $player[$res[0]]['soloavg'] = $res[2];
1258     }
1259
1260
1261   /* sort everything nicely */
1262
1263   function cmp($a,$b)
1264   {
1265     if($a['nr']==0) return 1;
1266     if($b['nr']==0) return 1;
1267
1268     $a=$a['points']/$a['nr'];
1269     $b=$b['points']/$b['nr'];
1270
1271     if ($a == $b)
1272       return 0;
1273     return ($a > $b) ? -1 : 1;
1274   }
1275   usort($player,'cmp');
1276
1277
1278   foreach($player as $pl)
1279     {
1280       /* limit to players with at least 10 games */
1281       if($pl['nr']>10)
1282         $return[] = array( $pl['name'], round($pl['points']/$pl['nr'],3), $pl['points'],$pl['nr'],$pl['active'],
1283                            $pl['response'],$pl['solo'],$pl['soloavg']);
1284     }
1285
1286   return $return;
1287 }
1288
1289 function format_score_table_ascii($score)
1290 {
1291   $output="";
1292   if(sizeof($score)==0)
1293     return "";
1294
1295   /* truncate table if we have too many games */
1296   $max = sizeof($score);
1297   if($max>6) $output.=" (table truncated to last 6 games)\n";
1298
1299   /* output header */
1300   foreach($score[0]['players'] as $id=>$points)
1301     {
1302       $name = DB_get_name('userid',$id); /*TODO*/
1303       $output.= "  ".substr($name,0,2)."  |";
1304     }
1305   $output.="  P   |\n";
1306   $output.= "------+------+------+------+------+\n";
1307
1308   /* output score for each game */
1309   $i=0;
1310   foreach($score as $game)
1311     {
1312       $i++;
1313       if($i-1<$max-6) continue;
1314
1315       foreach($game['players'] as $id=>$points)
1316         $output.=str_pad($points,6," ",STR_PAD_LEFT)."|";
1317       $output.=str_pad($game['points'],4," ",STR_PAD_LEFT);
1318
1319       /* check for solo */
1320       if($game['solo'])
1321         $output.= " S|";
1322       else
1323         $output.= "  |";
1324
1325       $output.="\n";
1326     }
1327   return $output;
1328 }
1329
1330 function format_score_table_html($score,$userid)
1331 {
1332   global $INDEX;
1333
1334   if(sizeof($score)==0)
1335     return "";
1336
1337   $output = "<div class=\"scoretable\">\n<table class=\"score\">\n";
1338
1339   /* output header */
1340   $header = "";
1341   $header.= " <thead>\n  <tr>\n";
1342   $header.= "   <th> No </th>";
1343   foreach($score[0]['players'] as $id=>$points)
1344     {
1345       $name = DB_get_name('userid',$id); /*TODO*/
1346       $header.= "<th> ".substr($name,0,2)." </th>";
1347     }
1348   $header.="<th>P</th>\n  </tr>\n </thead>\n";
1349
1350   /* use the same as footer */
1351   $footer = "";
1352   $footer.= " <tfoot>\n  <tr>\n";
1353   $footer.= "   <td> No </td>";
1354   foreach($score[0]['players'] as $id=>$points)
1355     {
1356       $name = DB_get_name('userid',$id); /*TODO*/
1357       $footer.= "<td> ".substr($name,0,2)." </td>";
1358     }
1359   $footer.="<td>P</td>\n  </tr>\n </tfoot>\n";
1360
1361   /* body */
1362   $body = "";
1363   $body.= " <tbody>\n";
1364   $i=0;
1365   foreach($score as $game)
1366     {
1367       $i++;
1368       $body.="  <tr>";
1369       $userhash = DB_get_hash_from_gameid_and_userid($game['gameid'],$userid);
1370       /* create link to old games only if you are logged in and its your game*/
1371       if(isset($_SESSION['id']) && $_SESSION['id']==$userid)
1372         $body.="  <td> <a href=\"".$INDEX."?action=game&amp;me=".$userhash."\">$i</a></td>";
1373       else
1374         $body.="  <td>$i</td>";
1375
1376       foreach($game['players'] as $id=>$points)
1377         $body.="<td>".$points."</td>";
1378       $body.="<td>".$game['points'];
1379
1380       /* check for solo */
1381       if($game['solo'])
1382         $body.= " S";
1383       $body.="</td></tr>\n";
1384     }
1385
1386   $output.=$header;
1387   if($i>12)
1388     $output.=$footer;
1389   $output.=$body;
1390
1391   $output.=" </tbody>\n</table>\n</div>\n";
1392
1393   return $output;
1394 }
1395
1396 function createCache($content, $cacheFile)
1397 {
1398   $fp = fopen($cacheFile,"w");
1399   if($fp)
1400     {
1401       fwrite($fp,$content);
1402       fclose($fp);
1403     }
1404   else
1405     echo "WARNING: couldn't create cache file";
1406
1407   return;
1408 }
1409
1410 function getCache($cacheFile, $expireTime)
1411 {
1412   if( file_exists($cacheFile) &&
1413       filemtime($cacheFile )>( time() - $expireTime ) )
1414     {
1415       return file_get_contents($cacheFile);
1416     }
1417
1418   return false;
1419 }
1420
1421 function check_vacation($userid)
1422 {
1423   /* get start date */
1424   $result = DB_query_array("SELECT value FROM User_Prefs".
1425                      " WHERE user_id='$userid' AND pref_key='vacation start'" );
1426   if($result)
1427     $start = $result[0];
1428   else
1429     return NULL;
1430
1431   /* get end date */
1432   $result = DB_query_array("SELECT value FROM User_Prefs".
1433                      " WHERE user_id='$userid' AND pref_key='vacation stop'" );
1434   if($result)
1435     $stop = $result[0];
1436   else
1437     return NULL;
1438
1439   /* get comment */
1440   $result = DB_query_array("SELECT value FROM User_Prefs".
1441                      " WHERE user_id='$userid' AND pref_key='vacation comment'" );
1442   if($result)
1443     $comment = $result[0];
1444   else
1445     $comment = '';
1446
1447   /* check if user is on vacation. TODO: use user's timezone */
1448   if( (time() - strtotime($start) >0) &&
1449       (strtotime($stop) - time()  >0))
1450     return array ($start,$stop,$comment);
1451   else
1452     return NULL;
1453 }
1454
1455 function cancel_game($why,$gameid)
1456 {
1457   $gameid = DB_quote_smart($gameid);
1458
1459   /* update the game table */
1460   switch($why)
1461     {
1462     case 'timedout':
1463       DB_query("UPDATE Game SET status='cancel-timedout' WHERE id=$gameid");
1464       break;
1465     case 'nines':
1466       DB_query("UPDATE Game SET status='cancel-nines' WHERE id=$gameid");
1467       break;
1468     case 'trump':
1469       DB_query("UPDATE Game SET status='cancel-trump' WHERE id=$gameid");
1470       break;
1471     case 'noplay':
1472       DB_query("UPDATE Game SET status='cancel-noplay' WHERE id=$gameid");
1473       break;
1474     case 'lowtrump':
1475       DB_query("UPDATE Game SET status='cancel-lowtrump' WHERE id=$gameid");
1476       break;
1477     }
1478   /* set each player to gameover */
1479   $result = DB_query("SELECT id FROM Hand WHERE game_id=".DB_quote_smart($gameid));
1480   while($r = DB_fetch_array($result))
1481     {
1482       $id = $r[0];
1483       DB_query("UPDATE Hand SET status='gameover' WHERE id=".DB_quote_smart($id));
1484     }
1485
1486   return;
1487 }
1488
1489 function get_user_token($userid)
1490 {
1491
1492   $token = NULL;
1493
1494   $date = DB_get_user_creation_date($userid);
1495   $name = DB_get_name('userid',$userid);
1496
1497   if($date && $name)
1498     $token = md5("token".$name.$date);
1499
1500   return $token;
1501 }
1502
1503 ?>