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