ecb9811a4028bade70286e75b56e22d9d47cb21b
[e-DoKo.git] / include / functions.php
1 <?php
2 /* make sure that we are not called from outside the scripts,
3  * use a variable defined in config.php to check this
4  */
5 if(!isset($HOST))
6   exit;
7
8 function config_check()
9 {
10   global $EmailName,$EMAIL_REPLY,$ADMIN_NAME,$ADMIN_EMAIL,$DB_work;
11
12   /* check if some variables are set in the config file, else set defaults */
13   if(!isset($EmailName))
14     $EmailName="[DoKo] ";
15   if(isset($EMAIL_REPLY))
16     {
17       ini_set("sendmail_from",$EMAIL_REPLY);
18     }
19   if(!isset($ADMIN_NAME))
20     {
21       output_header();
22       echo "<h1>Setup not completed</h1>";
23       echo "You need to set \$ADMIN_NAME in config.php.";
24       output_footer();
25       exit();
26     }
27   if(!isset($ADMIN_EMAIL))
28     {
29       output_header();
30       echo "<h1>Setup not completed</h1>";
31       echo "You need to set \$ADMIN_EMAIL in config.php. ".
32         "If something goes wrong an email will be send to this address.";
33       output_footer();
34       exit();
35     }
36   if(!isset($DB_work))
37     {
38       output_header();
39       echo "<h1>Setup not completed</h1>";
40       echo "You need to set \$DB_work in config.php. ".
41         "If this is set to 1, the game will be suspended and one can work safely on the database.".
42         "The default should be 0 for the game to work.";
43       output_footer();
44       exit();
45     }
46   if($DB_work)
47     {
48       output_header();
49       echo "Working on the database...please check back later.";
50       output_footer();
51       exit();
52     }
53
54   return;
55 }
56
57 function mymail($To,$Subject,$message,$header="")
58 {
59   global $debug,$EMAIL_REPLY;
60
61   if(isset($EMAIL_REPLY))
62     $header .= "From: e-DoKo daemon <$EMAIL_REPLY>\r\n";
63
64   if($debug)
65     {
66       /* display email on screen,
67        * change txt -> html
68        */
69       $message = str_replace("\n","<br />\n",$message);
70       $message = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]",
71                      "<a href=\"\\0\">\\0</a>", $message);
72
73       echo "<br />To: $To<br />";
74       if($header != "")
75         echo $header."<br />";
76       echo "Subject: $Subject <br />$message<br />\n";
77     }
78   else
79     if($header != "")
80       mail($To,$Subject,$message,$header);
81     else
82       mail($To,$Subject,$message);
83   return;
84 }
85
86 function myisset()
87 {
88   /* returns 1 if all names passed as args are defined by a GET or POST statement,
89    * else return 0
90    */
91
92   $ok   = 1;
93   $args = func_get_args();
94
95   foreach($args as $arg)
96     {
97       $ok = $ok * isset($_REQUEST[$arg]);
98       /*echo "$arg: ok = $ok <br />";
99        */
100     }
101   return $ok;
102 }
103
104 function myerror($message)
105 {
106   echo "<span class=\"error\">".htmlspecialchars($message)."</span>\n";
107   mymail($ADMIN_EMAIL,$EmailName." Error in Code",$message);
108   return;
109 }
110
111 function pos_array($c,$arr)
112 {
113   $ret = 0;
114
115   $i   = 0;
116   foreach($arr as $a)
117     {
118       $i++;
119       if($a == $c)
120         {
121           $ret = $i;
122           break;
123         }
124     }
125   return $ret;
126 }
127
128 function is_trump($c)
129 {
130   global $CARDS;
131
132   if(in_array($c,$CARDS["trump"]))
133     return 1;
134   else
135     return 0;
136 }
137
138 function is_same_suite($c1,$c2)
139 {
140   global $CARDS;
141
142   if(in_array($c1,$CARDS["trump"]   ) && in_array($c2,$CARDS["trump"]   ) ) return 1;
143   if(in_array($c1,$CARDS["clubs"]   ) && in_array($c2,$CARDS["clubs"]   ) ) return 1;
144   if(in_array($c1,$CARDS["hearts"]  ) && in_array($c2,$CARDS["hearts"]  ) ) return 1;
145   if(in_array($c1,$CARDS["spades"]  ) && in_array($c2,$CARDS["spades"]  ) ) return 1;
146   if(in_array($c1,$CARDS["diamonds"]) && in_array($c2,$CARDS["diamonds"]) ) return 1;
147
148   return 0;
149 }
150
151 function compare_cards($a,$b,$game)
152 {
153   /* if "a" is higher than "b" return 1, else 0, "a" being the card first played */
154
155   global $CARDS;
156   global $RULES;
157   global $GAME;
158
159   /* first map all cards to the odd number,
160    * this insure that the first card wins the trick
161    * if they are the same card
162    */
163   if( $a/2 - (int)($a/2) != 0.5)
164     $a--;
165   if( $b/2 - (int)($b/2) != 0.5)
166     $b--;
167
168   /* check for schweinchen and ten of hearts*/
169   switch($game)
170     {
171     case "normal":
172     case "silent":
173     case "trump":
174       if($RULES['schweinchen']=='both' && $GAME['schweinchen-who'])
175         {
176           if($a == 19 || $a == 20 )
177             return 1;
178           if($b == 19 || $b == 20 )
179             return 0;
180         }
181       else if($RULES['schweinchen']=='second' && $GAME['schweinchen-second'])
182         {
183           if($a == 19 || $a == 20 )
184             return 1;
185           if($b == 19 || $b == 20 )
186             return 0;
187         }
188       else if($RULES['schweinchen']=='secondaftercall' && $GAME['schweinchen-who'] && $GAME['schweinchen-second'] )
189         {
190           /* check if a call was made either by the player or his partner. If so activate Schweinchen rule. */
191           if(DB_get_call_by_hash($GAME['schweinchen-who']) || DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
192             {
193               if($a == 19 || $a == 20 )
194                 return 1;
195               if($b == 19 || $b == 20 )
196                 return 0;
197             }
198           /* if not, do nothing and the foxes are just handeled as normal trump */
199         }
200         ;
201     case "heart":
202     case "spade":
203     case "club":
204       /* check for ten of hearts rule */
205       if($RULES["dullen"]=="secondwins")
206         if($a==1 && $b==1) /* both 10 of hearts */
207           return 0;        /* second one wins.*/
208     case "trumpless":
209     case "jack":
210     case "queen":
211       /* no special cases here */
212     }
213
214   /* normal case */
215   if(is_trump($a) && is_trump($b) && $a<=$b)
216     return 1;
217   else if(is_trump($a) && is_trump($b) )
218     return 0;
219   else
220     { /*$a is not a trump */
221       if(is_trump($b))
222         return 0;
223       else
224         { /* both no trump */
225
226           /* both clubs? */
227           $posA = pos_array($a,$CARDS["clubs"]);
228           $posB = pos_array($b,$CARDS["clubs"]);
229           if($posA && $posB)
230             if($posA <= $posB)
231               return 1;
232             else
233               return 0;
234
235           /* both spades? */
236           $posA = pos_array($a,$CARDS["spades"]);
237           $posB = pos_array($b,$CARDS["spades"]);
238           if($posA && $posB)
239             if($posA <= $posB)
240               return 1;
241             else
242               return 0;
243
244           /* both hearts? */
245           $posA = pos_array($a,$CARDS["hearts"]);
246           $posB = pos_array($b,$CARDS["hearts"]);
247           if($posA && $posB)
248             if($posA <= $posB)
249               return 1;
250             else
251               return 0;
252
253           /* both diamonds? */
254           $posA = pos_array($a,$CARDS["diamonds"]);
255           $posB = pos_array($b,$CARDS["diamonds"]);
256           if($posA && $posB)
257             if($posA <= $posB)
258               return 1;
259             else
260               return 0;
261
262           /* not the same suit and no trump: a wins */
263           return 1;
264         }
265     }
266 }
267
268 function get_winner($p,$mode)
269 {
270   /* get all 4 cards played in a trick, in the order they are played */
271   $tmp = $p[1];
272   $c1    = $tmp["card"];
273   $c1pos = $tmp["pos"];
274
275   $tmp = $p[2];
276   $c2    = $tmp["card"];
277   $c2pos = $tmp["pos"];
278
279   $tmp = $p[3];
280   $c3    = $tmp["card"];
281   $c3pos = $tmp["pos"];
282
283   $tmp = $p[4];
284   $c4    = $tmp["card"];
285   $c4pos = $tmp["pos"];
286
287   /* first card is better than all the rest */
288   if( compare_cards($c1,$c2,$mode) && compare_cards($c1,$c3,$mode) && compare_cards($c1,$c4,$mode) )
289     return $c1pos;
290
291   /* second card is better than first and better than the rest */
292   if( !compare_cards($c1,$c2,$mode) &&  compare_cards($c2,$c3,$mode) && compare_cards($c2,$c4,$mode) )
293     return $c2pos;
294
295   /* third card is better than first card and better than last */
296   if( !compare_cards($c1,$c3,$mode) &&  compare_cards($c3,$c4,$mode) )
297     /* if second card is better than first, third card needs to be even better */
298     if( !compare_cards($c1,$c2,$mode) && !compare_cards($c2,$c3,$mode) )
299       return $c3pos;
300     /* second is worse than first, e.g. not following suite */
301     else if (compare_cards($c1,$c2,$mode) )
302       return $c3pos;
303
304   /* non of the above */
305   return $c4pos;
306 }
307
308 function count_nines($cards)
309 {
310   $nines = 0;
311
312   foreach($cards as $c)
313     {
314       if($c == "25" || $c == "26") $nines++;
315       else if($c == "33" || $c == "34") $nines++;
316       else if($c == "41" || $c == "42") $nines++;
317       else if($c == "47" || $c == "48") $nines++;
318     }
319
320   return $nines;
321 }
322
323 function check_wedding($cards)
324 {
325
326   if( in_array("3",$cards) && in_array("4",$cards) )
327     return 1;
328
329   return 0;
330 }
331
332 function count_trump($cards)
333 {
334   global $RULES;
335
336   $trump = 0;
337
338   /* count each trump, including the foxes */
339   foreach($cards as $c)
340     if( (int)($c) <27)
341       $trump++;
342
343   /* normally foxes don't count as trump, so we substract them here
344    * in case someone has schweinchen, one or two of them should count as trump
345    * though, so we need to add one trump for those cases */
346
347   /* subtract foxes */
348   if( in_array("19",$cards))
349     $trump--;
350   if( in_array("20",$cards) )
351     $trump--;
352
353   /* handle case where player has schweinchen */
354   if( in_array("19",$cards) && in_array("20",$cards) )
355     switch($RULES["schweinchen"])
356       {
357       case "both":
358         /* add two, in case the player has both foxes (schweinchen) */
359         $trump++;
360         $trump++;
361         break;
362       case "second":
363       case "secondaftercall":
364         /* add one, in case the player has both foxes (schweinchen) */
365         $trump++;
366         break;
367       case "none":
368         break;
369       }
370
371   return $trump;
372 }
373
374 function  create_array_of_random_numbers($useridA,$useridB,$useridC,$useridD)
375 {
376   global $debug;
377
378   $r = array();
379
380   if($debug)
381     {
382       $r[ 0]=1;     $r[12]=47;   $r[24]=13;       $r[36]=37;
383       $r[ 1]=2;     $r[13]=23;   $r[25]=14;       $r[37]=38;
384       $r[ 2]=3;     $r[14]=27;   $r[26]=15;       $r[38]=39;
385       $r[ 3]=4;     $r[15]=16;   $r[27]=28;       $r[39]=40;
386       $r[ 4]=5;     $r[16]=17;   $r[28]=29;       $r[40]=41;
387       $r[ 5]=18;    $r[17]=6;    $r[29]=30;       $r[41]=42;
388       $r[ 6]=21;    $r[18]=7;    $r[30]=31;       $r[42]=43;
389       $r[ 7]=22;    $r[19]=8;    $r[31]=32;       $r[43]=44;
390       $r[ 8]=45;    $r[20]=9;    $r[32]=19;       $r[44]=33;
391       $r[ 9]=46;    $r[21]=10;   $r[33]=20;       $r[45]=24;
392       $r[10]=35;    $r[22]=11;   $r[34]=48;       $r[46]=25;
393       $r[11]=36;    $r[23]=12;   $r[35]=34;       $r[47]=26;
394     }
395   else
396     {
397       /* check if we can find a game were non of the player was involved and return
398        * cards insted
399        */
400       $userstr = "'".implode("','",array($useridA,$useridB,$useridC,$useridD))."'";
401       $randomnumbers = DB_get_unused_randomnumbers($userstr);
402       $randomnumbers = explode(":",$randomnumbers);
403
404       if(sizeof($randomnumbers)==48)
405         return $randomnumbers;
406
407       /* need to create new numbers */
408       for($i=0;$i<48;$i++)
409         $r[$i]=$i+1;
410
411       /* shuffle using a better random generator than the standard one */
412       for ($i = 0; $i <48; $i++)
413         {
414           $j = @mt_rand(0, $i);
415           $tmp = $r[$i];
416           $r[$i] = $r[$j];
417           $r[$j] = $tmp;
418         }
419     };
420
421   return $r;
422 }
423
424 function display_cards($me,$myturn)
425 {
426   return;
427 }
428
429 function have_suit($cards,$c)
430 {
431   global $CARDS;
432   $suite = array();
433
434   if(in_array($c,$CARDS["trump"]))
435     $suite = $CARDS["trump"];
436   else if(in_array($c,$CARDS["clubs"]))
437     $suite = $CARDS["clubs"];
438   else if(in_array($c,$CARDS["spades"]))
439     $suite = $CARDS["spades"];
440   else if(in_array($c,$CARDS["hearts"]))
441     $suite = $CARDS["hearts"];
442   else if(in_array($c,$CARDS["diamonds"]))
443     $suite = $CARDS["diamonds"];
444
445   foreach($cards as $card)
446     {
447       if(in_array($card,$suite))
448         return 1;
449     }
450
451   return 0;
452 }
453
454 function same_type($card,$c)
455 {
456   global $CARDS;
457   $suite = "";
458
459   /* figure out what kind of card c is */
460   if(in_array($c,$CARDS["trump"]))
461     $suite = $CARDS["trump"];
462   else if(in_array($c,$CARDS["clubs"]))
463     $suite = $CARDS["clubs"];
464   else if(in_array($c,$CARDS["spades"]))
465     $suite = $CARDS["spades"];
466   else if(in_array($c,$CARDS["hearts"]))
467     $suite = $CARDS["hearts"];
468   else if(in_array($c,$CARDS["diamonds"]))
469     $suite = $CARDS["diamonds"];
470
471   /* card is the same suid return 1 */
472   if(in_array($card,$suite))
473     return 1;
474
475   return 0;
476 }
477
478 function set_gametype($gametype)
479 {
480   global $CARDS;
481   global $RULES;
482   global $GAME;
483
484   switch($gametype)
485     {
486     case "normal":
487     case "wedding":
488     case "poverty":
489     case "dpoverty":
490     case "trump":
491     case "silent":
492       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
493                                  '17','18','19','20','21','22','23','24','25','26');
494       $CARDS["diamonds"] = array();
495       $CARDS["clubs"]    = array('27','28','29','30','31','32','33','34');
496       $CARDS["spades"]   = array('35','36','37','38','39','40','41','42');
497       $CARDS["hearts"]   = array('43','44','45','46','47','48');
498       $CARDS["foxes"]    = array('19','20');
499       if($RULES["dullen"]=='none')
500         {
501           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
502                                      '17','18','19','20','21','22','23','24','25','26');
503           $CARDS["hearts"]   = array('43','44','1','2','45','46','47','48');
504         }
505       /* do we need to reorder for Schweinchen? need to search for it because of special case for dullen above*/
506       if($RULES['schweinchen']=='both'&& $GAME['schweinchen-who'])
507         {
508           /* find the fox and put them at the top of the stack */
509           foreach(array('19','20') as $fox)
510             {
511               /* search for fox */
512               $trump = $CARDS['trump'];
513               $key = array_keys($trump, $fox);
514
515               /* reorder */
516               $foxa = array();
517               $foxa[]=$trump[$key[0]];
518               unset($trump[$key[0]]);
519               $trump = array_merge($foxa,$trump);
520               $CARDS['trump'] = $trump;
521             }
522         }
523       else if( ($RULES['schweinchen']=='second' || $RULES['schweinchen']=='secondaftercall')
524                && $GAME['schweinchen-who'])
525         {
526           /* find the fox and put them at the top of the stack */
527           $trump = $CARDS['trump'];
528           $key = array_keys($trump, '19');
529
530           /* reorder */
531           $foxa = array();
532           $foxa[]=$trump[$key[0]];
533           unset($trump[$key[0]]);
534           $trump = array_merge($foxa,$trump);
535           $CARDS['trump'] = $trump;
536         }
537       break;
538     case "queen":
539       $CARDS["trump"]    = array('3','4','5','6','7','8','9','10');
540       $CARDS["clubs"]    = array('27','28','29','30','31','32','11','12','33','34');
541       $CARDS["spades"]   = array('35','36','37','38','39','40','13','14','41','42');
542       $CARDS["hearts"]   = array('43','44', '1', '2','45','46','15','16','47','48');
543       $CARDS["diamonds"] = array('19','20','21','22','23','24','17','18','25','26');
544       $CARDS["foxes"]    = array();
545       break;
546     case "jack":
547       $CARDS["trump"]    = array('11','12','13','14','15','16','17','18');
548       $CARDS["clubs"]    = array('27','28','29','30','31','32','3', '4','33','34');
549       $CARDS["spades"]   = array('35','36','37','38','39','40','5', '6','41','42');
550       $CARDS["hearts"]   = array('43','44', '1', '2','45','46','7', '8','47','48');
551       $CARDS["diamonds"] = array('19','20','21','22','23','24','9','10','25','26');
552       $CARDS["foxes"]    = array();
553       break;
554     case "trumpless":
555       $CARDS["trump"]    = array();
556       $CARDS["clubs"]    = array('27','28','29','30','31','32','3', '4','11','12','33','34');
557       $CARDS["spades"]   = array('35','36','37','38','39','40','5', '6','13','14','41','42');
558       $CARDS["hearts"]   = array('43','44', '1', '2','45','46','7', '8','15','16','47','48');
559       $CARDS["diamonds"] = array('19','20','21','22','23','24','9','10','17','18','25','26');
560       $CARDS["foxes"]    = array();
561       break;
562     case "club":
563       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
564                                  '17','18','27','28','29','30','31','32','33','34');
565       $CARDS["clubs"]    = array();
566       $CARDS["spades"]   = array('35','36','37','38','39','40','41','42');
567       $CARDS["hearts"]   = array('43','44','45','46','47','48');
568       $CARDS["diamonds"] = array('19','20','21','22','23','24','25','26');
569       $CARDS["foxes"]    = array();
570       if($RULES["dullen"]=='none')
571         {
572           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
573                                      '17','18','27','28','29','30','31','32','33','34');
574           $CARDS["hearts"]   = array('43','44','1','2','45','46','47','48');
575         }
576       break;
577     case "spade":
578       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
579                                  '17','18','35','36','37','38','39','40','41','42');
580       $CARDS["clubs"]    = array('27','28','29','30','31','32','33','34');
581       $CARDS["spades"]   = array();
582       $CARDS["hearts"]   = array('43','44','45','46','47','48');
583       $CARDS["diamonds"] = array('19','20','21','22','23','24','25','26');
584       $CARDS["foxes"]    = array();
585       if($RULES["dullen"]=='none')
586         {
587           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
588                                      '17','18','35','36','37','38','39','40','41','42');
589           $CARDS["hearts"]   = array('43','44','1','2','45','46','47','48');
590         }
591       break;
592     case "heart":
593       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
594                                  '17','18','43','44','45','46','47','48');
595       $CARDS["clubs"]    = array('27','28','29','30','31','32','33','34');
596       $CARDS["spades"]   = array('35','36','37','38','39','40','41','42');
597       $CARDS["hearts"]   = array();
598       $CARDS["diamonds"] = array('19','20','21','22','23','24','25','26');
599       $CARDS["foxes"]    = array();
600       if($RULES["dullen"]=='none')
601         {
602           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
603                             '17','18','43','44','1','2','45','46','47','48');
604         }
605       break;
606     }
607 }
608
609 function mysort($cards,$gametype)
610 {
611   usort ( $cards, "sort_comp" );
612   return $cards;
613 }
614
615 function sort_comp($a,$b)
616 {
617   global $CARDS;
618
619   $ALL = array();
620   $ALL = array_merge($CARDS["trump"],$CARDS["diamonds"],$CARDS["clubs"],
621                      $CARDS["hearts"],$CARDS["spades"]);
622
623   return pos_array($a,$ALL)-pos_array($b,$ALL);
624 }
625
626 function can_call($what,$hash)
627 {
628   global $RULES;
629
630   $gameid   = DB_get_gameid_by_hash($hash);
631   $gametype = DB_get_gametype_by_gameid($gameid);
632   $oldcall  = DB_get_call_by_hash($hash);
633   $pcall    = DB_get_partner_call_by_hash($hash);
634
635   if( ($pcall!=NULL && $what >= $pcall) ||
636       ($oldcall!=NULL && $what >=$oldcall) )
637     {
638       return 0;
639     }
640
641   $NRcards  = count(DB_get_hand($hash));
642
643   $NRallcards = 0;
644   for ($i=1;$i<5;$i++)
645     {
646       $user         = DB_get_hash_from_game_and_pos($gameid,$i);
647       $NRallcards  += count(DB_get_hand($user));
648     };
649
650   /* in case of a wedding, everything will be delayed by an offset */
651   $offset = 0;
652   if($gametype=="wedding")
653     {
654       $offset = DB_get_sickness_by_gameid($gameid);
655       if ($offset <0) /* not resolved */
656         return 0;
657     };
658
659   switch ($RULES["call"])
660     {
661     case "1st-own-card":
662       if( 4-($what/30) >= 12 - ($NRcards + $offset))
663         return 1;
664       break;
665     case "5th-card":
666       if( 27+4*($what/30) <= $NRallcards + $offset*4)
667         return 1;
668       break;
669     case "9-cards":
670
671       if($oldcall!=NULL && $pcall!=NULL)
672         $mincall = ($oldcall>$pcall) ? $pcall : $oldcall;
673       else if($oldcall!=NULL)
674         $mincall = $oldcall;
675       else if ($pcall!=NULL)
676         $mincall = $pcall;
677       else
678         $mincall = -1;
679
680       if( 12 <= ($NRcards + $offset))
681         {
682           return 1;
683         }
684       else if ( 9 <= ($NRcards + $offset))
685         {
686           if( ($mincall>=0 && $mincall==120) )
687             return 1;
688         }
689       else if ( 6 <= ($NRcards + $offset))
690         {
691           if( ($mincall>=0 && $mincall<=90 && $what<=60 ) )
692             return 1;
693         }
694       else if ( 3 <= ($NRcards + $offset))
695         {
696           if( ($mincall>=0 && $mincall<=60 && $what<=30 ) )
697             return 1;
698         }
699       else if ( 0 <= ($NRcards + $offset))
700         {
701           if( ($mincall>=0 && $mincall<=30 && $what==0 ) )
702             return 1;
703         };
704       break;
705     }
706
707   return 0;
708 }
709
710 function display_table ()
711 {
712   global $gameid, $GT, $debug,$INDEX,$defaulttimezone;
713   global $RULES,$GAME,$gametype;
714
715   $result = DB_query("SELECT  User.fullname as name,".
716                      "        Hand.position as position, ".
717                      "        User.id, ".
718                      "        Hand.party as party, ".
719                      "        Hand.sickness as sickness, ".
720                      "        Hand.point_call, ".
721                      "        User.last_login, ".
722                      "        Hand.hash,       ".
723                      "        User.timezone    ".
724                      "FROM Hand ".
725                      "LEFT JOIN User ON User.id=Hand.user_id ".
726                      "WHERE Hand.game_id='".$gameid."' ".
727                      "ORDER BY position ASC");
728
729   echo "<div class=\"table\">\n".
730     "  <img class=\"table\" src=\"pics/table.png\" alt=\"table\" />\n";
731   while($r = DB_fetch_array($result))
732     {
733       $name  = $r[0];
734       $pos   = $r[1];
735       $user  = $r[2];
736       $party = $r[3];
737       $sickness  = $r[4];
738       $call      = $r[5];
739       $hash      = $r[7];
740       $timezone  = $r[8];
741       date_default_timezone_set($defaulttimezone);
742       $lastlogin = strtotime($r[6]);
743       date_default_timezone_set($timezone);
744       $timenow   = strtotime(date("Y-m-d H:i:s"));
745
746       echo "  <div class=\"table".($pos-1)."\">\n";
747       if(!$debug)
748         echo "   $name \n";
749       else
750         echo "   <a href=\"".$INDEX."?action=game&amp;me=".$hash."\">$name</a>\n";
751
752       /* add hints for poverty, wedding, solo, etc */
753       if( $gametype != "solo")
754         if( $RULES["schweinchen"]=="both" && $GAME["schweinchen-who"]==$hash )
755           echo " Schweinchen. <br />";
756
757       if($GT=="poverty" && $party=="re")
758         if($sickness=="poverty")
759           {
760             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
761             $cards    = DB_get_all_hand($userhash);
762             $trumpNR  = count_trump($cards);
763             if($trumpNR)
764               echo "   <img src=\"pics/button/poverty_trump_button.png\" class=\"button\" alt=\"poverty < trump back\" />";
765             else
766               echo "   <img src=\"pics/button/poverty_notrump_button.png\" class=\"button\" alt=\"poverty <\" />";
767           }
768         else
769           echo "   <img src=\"pics/button/poverty_partner_button.png\" class=\"button\" alt=\"poverty >\" />";
770
771       if($GT=="dpoverty")
772         if($party=="re")
773           if($sickness=="poverty")
774             {
775               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
776               $cards    = DB_get_all_hand($userhash);
777               $trumpNR  = count_trump($cards);
778               if($trumpNR)
779                 echo "   <img src=\"pics/button/poverty_trump_button.png\" class=\"button\" alt=\"poverty < trump back\" />";
780               else
781                 echo "   <img src=\"pics/button/poverty_notrump_button.png\" class=\"button\" alt=\"poverty <\" />";
782             }
783           else
784             echo "   <img src=\"pics/button/poverty_partner_button.png\" class=\"button\" alt=\"poverty >\" />";
785         else
786           if($sickness=="poverty")
787             {
788               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
789               $cards    = DB_get_all_hand($userhash);
790               $trumpNR  = count_trump($cards);
791               if($trumpNR)
792                 echo "   <img src=\"pics/button/poverty2_trump_button.png\" class=\"button\" alt=\"poverty2 < trump back\" />";
793               else
794                 echo "   <img src=\"pics/button/poverty2_notrump_button.png\" class=\"button\" alt=\"poverty2 <\" />";
795             }
796           else
797             echo "   <img src=\"pics/button/poverty2_partner_button.png\" class=\"button\" alt=\"poverty2 >\" />";
798
799       if($GT=="wedding" && $party=="re")
800         if($sickness=="wedding")
801           echo "   <img src=\"pics/button/wedding_button.png\" class=\"button\" alt=\"wedding\" />";
802         else
803           echo "   <img src=\"pics/button/wedding_partner_button.png\" class=\"button\" alt=\"wedding partner\" />";
804
805       if(ereg("solo",$GT) && $party=="re")
806         {
807           if(ereg("queen",$GT))
808             echo "   <img src=\"pics/button/queensolo_button.png\" class=\"button\" alt=\"$GT\" />";
809           else if(ereg("jack",$GT))
810             echo "   <img src=\"pics/button/jacksolo_button.png\" class=\"button\" alt=\"$GT\" />";
811           else if(ereg("club",$GT))
812             echo "   <img src=\"pics/button/clubsolo_button.png\" class=\"button\" alt=\"$GT\" />";
813           else if(ereg("spade",$GT))
814             echo "   <img src=\"pics/button/spadesolo_button.png\" class=\"button\" alt=\"$GT\" />";
815           else if(ereg("heart",$GT))
816             echo "   <img src=\"pics/button/heartsolo_button.png\" class=\"button\" alt=\"$GT\" />";
817           else if(ereg("trumpless",$GT))
818             echo "   <img src=\"pics/button/notrumpsolo_button.png\" class=\"button\" alt=\"$GT\" />";
819           else if(ereg("trump",$GT))
820             echo "   <img src=\"pics/button/trumpsolo_button.png\" class=\"button\" alt=\"$GT\" />";
821         }
822
823       /* add point calls */
824       if($call!=NULL)
825         {
826           if($party=="re")
827             echo "  <img src=\"pics/button/re_button.png\" class=\"button\" alt=\"re\" />";
828           else
829             echo "  <img src=\"pics/button/contra_button.png\" class=\"button\" alt=\"contra\" />";
830           switch($call)
831             {
832             case "0":
833               echo "   <img src=\"pics/button/0_button.png\" class=\"button\" alt=\"0\" />";
834               break;
835             case "30":
836               echo "   <img src=\"pics/button/30_button.png\" class=\"button\" alt=\"30\" />";
837               break;
838             case "60":
839               echo "   <img src=\"pics/button/60_button.png\" class=\"button\" alt=\"60\" />";
840               break;
841             case "90":
842               echo "   <img src=\"pics/button/90_button.png\" class=\"button\" alt=\"90\" />";
843               break;
844             }
845         }
846
847       echo "    <br />\n";
848       echo "    <span title=\"".date("Y-m-d H:i:s",$timenow).  "\">local time</span>\n";
849       echo "    <span title=\"".date("Y-m-d H:i:s",$lastlogin)."\">last login</span>\n";
850       echo "   </div>\n";
851
852     }
853   echo  "</div>\n"; /* end output table */
854
855
856   return;
857 }
858
859
860 function display_user_menu($id)
861 {
862   global $WIKI,$INDEX;
863
864   $result = DB_query("SELECT Hand.hash,Hand.game_id,Game.player from Hand".
865                      " LEFT JOIN Game On Hand.game_id=Game.id".
866                      " WHERE Hand.user_id='$id'".
867                      " AND ( Game.player='$id' OR ISNULL(Game.player) )".
868                      " AND Game.status<>'gameover'".
869                      " ORDER BY Game.session" );
870
871   $i=0;
872   while( $r = DB_fetch_array($result))
873     {
874       if($i==0)
875         {
876           echo "<div class=\"usermenu\">\n";
877           echo "It's your turn in these games:<br />\n";
878         }
879
880       $i++;
881       echo "<a href=\"".$INDEX."?action=game&amp;me=".$r[0].
882         "\">game ".DB_format_gameid($r[1])." </a><br />\n";
883       if($i>4)
884         {
885           echo "...<br />\n";
886           break;
887         }
888     }
889
890   if($i)
891     echo  "</div>\n";
892   return;
893 }
894
895 function generate_score_table($session)
896 {
897   /* returns an array with N entries
898    * $score[$i]["gameid"]   = gameid
899    * $score[$i]["players"] = array (id=>total points)
900    * $score[$i]["points"]   = points for this game
901    * $score[$i]["solo"]     = 1 or 0
902    */
903   $score = array();
904   $i=0;
905
906   /* get all ids */
907   $gameids = DB_get_gameids_of_finished_games_by_session($session);
908
909   if($gameids == NULL)
910     return $score;
911
912   /* get player id, names... from the first game */
913   $player = array();
914   $result = DB_query("SELECT User.id, User.fullname from Hand".
915                      " LEFT JOIN User On Hand.user_id=User.id".
916                      " WHERE Hand.game_id=".$gameids[0]);
917   while( $r = DB_fetch_array($result))
918     $player[$r[0]] = 0;
919
920   /* get points and generate table */
921   foreach($gameids as $gameid)
922     {
923       $re_score = DB_get_score_by_gameid($gameid);
924       foreach($player as $id=>$points)
925         {
926           $party = DB_get_party_by_gameid_and_userid($gameid,$id);
927           if($party == "re")
928             if(DB_get_gametype_by_gameid($gameid)=="solo")
929               $player[$id] += 3*$re_score;
930             else
931               $player[$id] += $re_score;
932           else if ($party == "contra")
933             $player[$id] -= $re_score;
934         }
935       $score[$i]['gameid']  = $gameid ;
936       $score[$i]['players'] = $player;
937       $score[$i]['points']  = abs($re_score);
938       $score[$i]['solo']    = (DB_get_gametype_by_gameid($gameid)=="solo");
939
940       $i++;
941     }
942
943   return $score;
944 }
945
946 function generate_global_score_table()
947 {
948   $return = array();
949
950   /* get all ids */
951   $gameids = DB_get_gameids_of_finished_games_by_session(0);
952
953   if($gameids == NULL)
954     return "";
955
956   /* get player id, names... from the User table */
957   $player = array();
958   $result = DB_query("SELECT User.id, User.fullname FROM User");
959
960   while( $r = DB_fetch_array($result))
961     $player[] = array( 'id' => $r[0], 'name'=> $r[1], 'points' => 0 ,'nr' => 0);
962
963   /* get points and generate table */
964   foreach($gameids as $gameid)
965     {
966       $re_score = DB_get_score_by_gameid($gameid);
967       /* TODO: this shouldn't loop over all players, just the 4 players that are in the game */
968       foreach($player as $key=>$pl)
969         {
970           $party = DB_get_party_by_gameid_and_userid($gameid,$pl['id']);
971           if($party == "re")
972             if(DB_get_gametype_by_gameid($gameid)=="solo")
973               $player[$key]['points'] += 3*$re_score;
974             else
975               $player[$key]['points'] += $re_score;
976           else if ($party == "contra")
977             $player[$key]['points'] -= $re_score;
978           if($party)
979             $player[$key]['nr']+=1;
980         }
981     }
982
983   function cmp($a,$b)
984   {
985     if($a['nr']==0 ) return 1;
986     if($b['nr']==0) return 1;
987
988     $a=$a['points']/$a['nr'];
989     $b=$b['points']/$b['nr'];
990
991     if ($a == $b)
992       return 0;
993     return ($a > $b) ? -1 : 1;
994   }
995   usort($player,"cmp");
996
997   foreach($player as $pl)
998     {
999       /* limit to players with at least 10 games */
1000       if($pl['nr']>10)
1001         $return[] = array( $pl['name'], round($pl['points']/$pl['nr'],3) );
1002     }
1003
1004   return $return;
1005 }
1006
1007 function format_score_table_ascii($score)
1008 {
1009   $output="";
1010   if(sizeof($score)==0)
1011     return "";
1012
1013   //  if(sizeof($score)>5) $header.=   "                ...   \n";
1014
1015   /* output header */
1016   foreach($score[0]['players'] as $id=>$points)
1017     {
1018       $name = DB_get_name('userid',$id); /*TODO*/
1019       $output.= "  ".substr($name,0,2)."  |";
1020     }
1021   $output.="  P   |\n ";
1022   $output.= "------+------+------+------+------+\n";
1023
1024   $max = sizeof($score);
1025   $i=0;
1026
1027   if($i<$max-6) $output.="       ...\n";
1028
1029   foreach($score as $game)
1030     {
1031       $i++;
1032       if($i-1<$max-6) continue;
1033       foreach($game['players'] as $id=>$points)
1034         $output.=str_pad($points,6," ",STR_PAD_LEFT)."|";
1035       $output.=str_pad($game['points'],4," ",STR_PAD_LEFT);
1036
1037       /* check for solo */
1038       if($game['solo'])
1039         $output.= " S|";
1040       else
1041         $output.= "  |";
1042
1043       $output.="\n";
1044     }
1045   return $output;
1046 }
1047
1048 function format_score_table_html($score,$userid)
1049 {
1050   global $INDEX;
1051
1052   if(sizeof($score)==0)
1053     return "";
1054
1055   $output = "<div class=\"scoretable\">\n<table class=\"score\">\n <thead><tr>\n";
1056
1057   /* output header */
1058   $output.= "  <th> No </th>";
1059   foreach($score[0]['players'] as $id=>$points)
1060     {
1061       $name = DB_get_name('userid',$id); /*TODO*/
1062       $output.= "<th> ".substr($name,0,2)." </th>";
1063     }
1064   $output.="<th>P</th>\n </tr>\n</thead>\n<tbody>\n";
1065
1066   $i=0;
1067   foreach($score as $game)
1068     {
1069       $i++;
1070       $output.=" <tr>";
1071       $userhash = DB_get_hash_from_gameid_and_userid($game['gameid'],$userid);
1072       /* create link to old games only if you are logged in and its your game*/
1073       if(isset($_SESSION['id']) && $_SESSION['id']==$userid)
1074         $output.="  <td> <a href=\"".$INDEX."?action=game&amp;me=".$userhash."\">$i</a></td>";
1075       else
1076         $output.="  <td>$i</td>";
1077
1078       foreach($game['players'] as $id=>$points)
1079         $output.="<td>".$points."</td>";
1080       $output.="<td>".$game['points'];
1081
1082       /* check for solo */
1083       if($game['solo'])
1084         $output.= " S";
1085       $output.="</td></tr>\n";
1086     }
1087
1088   $output.="</tbody>\n</table></div>\n";
1089
1090   return $output;
1091 }
1092
1093 function createCache($content, $cacheFile)
1094 {
1095   $fp = fopen($cacheFile,"w");
1096   if($fp)
1097     {
1098       fwrite($fp,$content);
1099       fclose($fp);
1100     }
1101   else
1102     echo "WARNING: couldn't create cache file";
1103
1104   return;
1105 }
1106
1107 function getCache($cacheFile, $expireTime)
1108 {
1109   if( file_exists($cacheFile) &&
1110       filemtime($cacheFile )>( time() - $expireTime ) )
1111     {
1112       return file_get_contents($cacheFile);
1113     }
1114
1115   return false;
1116 }
1117
1118
1119 ?>