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