NEW FEATURE + CLEANUP: added some table sorting to the statistics page via jquery
[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,$status='pregame')
333 {
334   global $RULES;
335
336   $trump = 0;
337
338   /* count each trump, including the foxes, since this is used to determine poverty status */
339   foreach($cards as $c)
340     if( (int)($c) <27)
341       $trump++;
342
343   /* In case we really want to know the amount of trump, we can use the status variable.
344    * This is needed for example to figure out what icon to display on the table in case of
345    * trump given back in poverty */
346   if($status=='all') return $trump;
347
348   /* normally foxes don't count as trump, so we substract them here
349    * in case someone has schweinchen, one or two of them should count as trump
350    * though, so we need to add one trump for those cases */
351
352   /* subtract foxes */
353   if( in_array("19",$cards))
354     $trump--;
355   if( in_array("20",$cards) )
356     $trump--;
357
358   /* handle case where player has schweinchen */
359   if( in_array("19",$cards) && in_array("20",$cards) )
360     switch($RULES["schweinchen"])
361       {
362       case "both":
363         /* add two, in case the player has both foxes (schweinchen) */
364         $trump++;
365         $trump++;
366         break;
367       case "second":
368       case "secondaftercall":
369         /* add one, in case the player has both foxes (schweinchen) */
370         $trump++;
371         break;
372       case "none":
373         break;
374       }
375
376   return $trump;
377 }
378
379 function  create_array_of_random_numbers($useridA,$useridB,$useridC,$useridD)
380 {
381   global $debug;
382
383   $r = array();
384
385   if($debug)
386     {
387       $r[ 0]=1;     $r[12]=47;   $r[24]=13;       $r[36]=37;
388       $r[ 1]=2;     $r[13]=23;   $r[25]=14;       $r[37]=38;
389       $r[ 2]=3;     $r[14]=27;   $r[26]=15;       $r[38]=39;
390       $r[ 3]=4;     $r[15]=16;   $r[27]=28;       $r[39]=40;
391       $r[ 4]=5;     $r[16]=17;   $r[28]=29;       $r[40]=41;
392       $r[ 5]=18;    $r[17]=6;    $r[29]=30;       $r[41]=42;
393       $r[ 6]=21;    $r[18]=7;    $r[30]=31;       $r[42]=43;
394       $r[ 7]=22;    $r[19]=8;    $r[31]=32;       $r[43]=44;
395       $r[ 8]=45;    $r[20]=9;    $r[32]=19;       $r[44]=33;
396       $r[ 9]=46;    $r[21]=10;   $r[33]=20;       $r[45]=24;
397       $r[10]=35;    $r[22]=11;   $r[34]=48;       $r[46]=25;
398       $r[11]=36;    $r[23]=12;   $r[35]=34;       $r[47]=26;
399     }
400   else
401     {
402       /* check if we can find a game were non of the player was involved and return
403        * cards insted
404        */
405       $userstr = "'".implode("','",array($useridA,$useridB,$useridC,$useridD))."'";
406       $randomnumbers = DB_get_unused_randomnumbers($userstr);
407       $randomnumbers = explode(":",$randomnumbers);
408
409       if(sizeof($randomnumbers)==48)
410         return $randomnumbers;
411
412       /* need to create new numbers */
413       for($i=0;$i<48;$i++)
414         $r[$i]=$i+1;
415
416       /* shuffle using a better random generator than the standard one */
417       for ($i = 0; $i <48; $i++)
418         {
419           $j = @mt_rand(0, $i);
420           $tmp = $r[$i];
421           $r[$i] = $r[$j];
422           $r[$j] = $tmp;
423         }
424     };
425
426   return $r;
427 }
428
429 function display_cards($me,$myturn)
430 {
431   return;
432 }
433
434 function have_suit($cards,$c)
435 {
436   global $CARDS;
437   $suite = array();
438
439   if(in_array($c,$CARDS["trump"]))
440     $suite = $CARDS["trump"];
441   else if(in_array($c,$CARDS["clubs"]))
442     $suite = $CARDS["clubs"];
443   else if(in_array($c,$CARDS["spades"]))
444     $suite = $CARDS["spades"];
445   else if(in_array($c,$CARDS["hearts"]))
446     $suite = $CARDS["hearts"];
447   else if(in_array($c,$CARDS["diamonds"]))
448     $suite = $CARDS["diamonds"];
449
450   foreach($cards as $card)
451     {
452       if(in_array($card,$suite))
453         return 1;
454     }
455
456   return 0;
457 }
458
459 function same_type($card,$c)
460 {
461   global $CARDS;
462   $suite = "";
463
464   /* figure out what kind of card c is */
465   if(in_array($c,$CARDS["trump"]))
466     $suite = $CARDS["trump"];
467   else if(in_array($c,$CARDS["clubs"]))
468     $suite = $CARDS["clubs"];
469   else if(in_array($c,$CARDS["spades"]))
470     $suite = $CARDS["spades"];
471   else if(in_array($c,$CARDS["hearts"]))
472     $suite = $CARDS["hearts"];
473   else if(in_array($c,$CARDS["diamonds"]))
474     $suite = $CARDS["diamonds"];
475
476   /* card is the same suid return 1 */
477   if(in_array($card,$suite))
478     return 1;
479
480   return 0;
481 }
482
483 function set_gametype($gametype)
484 {
485   global $CARDS;
486   global $RULES;
487   global $GAME;
488
489   switch($gametype)
490     {
491     case "normal":
492     case "wedding":
493     case "poverty":
494     case "dpoverty":
495     case "trump":
496     case "silent":
497       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
498                                  '17','18','19','20','21','22','23','24','25','26');
499       $CARDS["diamonds"] = array();
500       $CARDS["clubs"]    = array('27','28','29','30','31','32','33','34');
501       $CARDS["spades"]   = array('35','36','37','38','39','40','41','42');
502       $CARDS["hearts"]   = array('43','44','45','46','47','48');
503       $CARDS["foxes"]    = array('19','20');
504       if($RULES["dullen"]=='none')
505         {
506           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
507                                      '17','18','19','20','21','22','23','24','25','26');
508           $CARDS["hearts"]   = array('43','44','1','2','45','46','47','48');
509         }
510       /* do we need to reorder for Schweinchen? need to search for it because of special case for dullen above*/
511       if($RULES['schweinchen']=='both'&& $GAME['schweinchen-who'])
512         {
513           /* find the fox and put them at the top of the stack */
514           foreach(array('19','20') as $fox)
515             {
516               /* search for fox */
517               $trump = $CARDS['trump'];
518               $key = array_keys($trump, $fox);
519
520               /* reorder */
521               $foxa = array();
522               $foxa[]=$trump[$key[0]];
523               unset($trump[$key[0]]);
524               $trump = array_merge($foxa,$trump);
525               $CARDS['trump'] = $trump;
526             }
527         }
528       else if( ($RULES['schweinchen']=='second' || $RULES['schweinchen']=='secondaftercall')
529                && $GAME['schweinchen-who'])
530         {
531           /* find the fox and put them at the top of the stack */
532           $trump = $CARDS['trump'];
533           $key = array_keys($trump, '19');
534
535           /* reorder */
536           $foxa = array();
537           $foxa[]=$trump[$key[0]];
538           unset($trump[$key[0]]);
539           $trump = array_merge($foxa,$trump);
540           $CARDS['trump'] = $trump;
541         }
542       break;
543     case "queen":
544       $CARDS["trump"]    = array('3','4','5','6','7','8','9','10');
545       $CARDS["clubs"]    = array('27','28','29','30','31','32','11','12','33','34');
546       $CARDS["spades"]   = array('35','36','37','38','39','40','13','14','41','42');
547       $CARDS["hearts"]   = array('43','44', '1', '2','45','46','15','16','47','48');
548       $CARDS["diamonds"] = array('19','20','21','22','23','24','17','18','25','26');
549       $CARDS["foxes"]    = array();
550       break;
551     case "jack":
552       $CARDS["trump"]    = array('11','12','13','14','15','16','17','18');
553       $CARDS["clubs"]    = array('27','28','29','30','31','32','3', '4','33','34');
554       $CARDS["spades"]   = array('35','36','37','38','39','40','5', '6','41','42');
555       $CARDS["hearts"]   = array('43','44', '1', '2','45','46','7', '8','47','48');
556       $CARDS["diamonds"] = array('19','20','21','22','23','24','9','10','25','26');
557       $CARDS["foxes"]    = array();
558       break;
559     case "trumpless":
560       $CARDS["trump"]    = array();
561       $CARDS["clubs"]    = array('27','28','29','30','31','32','3', '4','11','12','33','34');
562       $CARDS["spades"]   = array('35','36','37','38','39','40','5', '6','13','14','41','42');
563       $CARDS["hearts"]   = array('43','44', '1', '2','45','46','7', '8','15','16','47','48');
564       $CARDS["diamonds"] = array('19','20','21','22','23','24','9','10','17','18','25','26');
565       $CARDS["foxes"]    = array();
566       break;
567     case "club":
568       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
569                                  '17','18','27','28','29','30','31','32','33','34');
570       $CARDS["clubs"]    = array();
571       $CARDS["spades"]   = array('35','36','37','38','39','40','41','42');
572       $CARDS["hearts"]   = array('43','44','45','46','47','48');
573       $CARDS["diamonds"] = array('19','20','21','22','23','24','25','26');
574       $CARDS["foxes"]    = array();
575       if($RULES["dullen"]=='none')
576         {
577           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
578                                      '17','18','27','28','29','30','31','32','33','34');
579           $CARDS["hearts"]   = array('43','44','1','2','45','46','47','48');
580         }
581       break;
582     case "spade":
583       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
584                                  '17','18','35','36','37','38','39','40','41','42');
585       $CARDS["clubs"]    = array('27','28','29','30','31','32','33','34');
586       $CARDS["spades"]   = array();
587       $CARDS["hearts"]   = array('43','44','45','46','47','48');
588       $CARDS["diamonds"] = array('19','20','21','22','23','24','25','26');
589       $CARDS["foxes"]    = array();
590       if($RULES["dullen"]=='none')
591         {
592           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
593                                      '17','18','35','36','37','38','39','40','41','42');
594           $CARDS["hearts"]   = array('43','44','1','2','45','46','47','48');
595         }
596       break;
597     case "heart":
598       $CARDS["trump"]    = array('1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16',
599                                  '17','18','43','44','45','46','47','48');
600       $CARDS["clubs"]    = array('27','28','29','30','31','32','33','34');
601       $CARDS["spades"]   = array('35','36','37','38','39','40','41','42');
602       $CARDS["hearts"]   = array();
603       $CARDS["diamonds"] = array('19','20','21','22','23','24','25','26');
604       $CARDS["foxes"]    = array();
605       if($RULES["dullen"]=='none')
606         {
607           $CARDS["trump"]    = array('3','4','5','6','7','8','9','10','11','12','13','14','15','16',
608                             '17','18','43','44','1','2','45','46','47','48');
609         }
610       break;
611     }
612 }
613
614 function mysort($cards,$gametype)
615 {
616   global $PREF;
617   if(isset($PREF['sorting']))
618     if($PREF['sorting']=='high-low')
619       usort ( $cards, 'sort_comp_high_low' );
620     else
621       usort ( $cards, 'sort_comp_low_high' );
622   else
623     usort ( $cards, 'sort_comp_high_low' );
624   return $cards;
625 }
626
627 function sort_comp_high_low($a,$b)
628 {
629   global $CARDS;
630
631   $ALL = array();
632   $ALL = array_merge($CARDS['trump'],$CARDS['diamonds'],$CARDS['clubs'],
633                      $CARDS['hearts'],$CARDS['spades']);
634
635   return pos_array($a,$ALL)-pos_array($b,$ALL);
636 }
637
638 function sort_comp_low_high($a,$b)
639 {
640   global $CARDS;
641
642   $ALL = array();
643   $ALL = array_merge($CARDS['trump'],$CARDS['diamonds'],$CARDS['clubs'],
644                      $CARDS['hearts'],$CARDS['spades']);
645
646   return -pos_array($a,$ALL)+pos_array($b,$ALL);
647 }
648
649 function can_call($what,$hash)
650 {
651   global $RULES;
652
653   $gameid   = DB_get_gameid_by_hash($hash);
654   $gametype = DB_get_gametype_by_gameid($gameid);
655   $oldcall  = DB_get_call_by_hash($hash);
656   $pcall    = DB_get_partner_call_by_hash($hash);
657
658   if( ($pcall!=NULL && $what >= $pcall) ||
659       ($oldcall!=NULL && $what >=$oldcall) )
660     {
661       return 0;
662     }
663
664   $NRcards  = count(DB_get_hand($hash));
665
666   $NRallcards = 0;
667   for ($i=1;$i<5;$i++)
668     {
669       $user         = DB_get_hash_from_game_and_pos($gameid,$i);
670       $NRallcards  += count(DB_get_hand($user));
671     };
672
673   /* in case of a wedding, everything will be delayed by an offset */
674   $offset = 0;
675   if($gametype=="wedding")
676     {
677       $offset = DB_get_sickness_by_gameid($gameid);
678       if ($offset <0) /* not resolved */
679         return 0;
680     };
681
682   switch ($RULES["call"])
683     {
684     case "1st-own-card":
685       if( 4-($what/30) >= 12 - ($NRcards + $offset))
686         return 1;
687       break;
688     case "5th-card":
689       if( 27+4*($what/30) <= $NRallcards + $offset*4)
690         return 1;
691       break;
692     case "9-cards":
693
694       if($oldcall!=NULL && $pcall!=NULL)
695         $mincall = ($oldcall>$pcall) ? $pcall : $oldcall;
696       else if($oldcall!=NULL)
697         $mincall = $oldcall;
698       else if ($pcall!=NULL)
699         $mincall = $pcall;
700       else
701         $mincall = -1;
702
703       if( 12 <= ($NRcards + $offset))
704         {
705           return 1;
706         }
707       else if ( 9 <= ($NRcards + $offset))
708         {
709           if( ($mincall>=0 && $mincall==120) )
710             return 1;
711         }
712       else if ( 6 <= ($NRcards + $offset))
713         {
714           if( ($mincall>=0 && $mincall<=90 && $what<=60 ) )
715             return 1;
716         }
717       else if ( 3 <= ($NRcards + $offset))
718         {
719           if( ($mincall>=0 && $mincall<=60 && $what<=30 ) )
720             return 1;
721         }
722       else if ( 0 <= ($NRcards + $offset))
723         {
724           if( ($mincall>=0 && $mincall<=30 && $what==0 ) )
725             return 1;
726         };
727       break;
728     }
729
730   return 0;
731 }
732
733 function display_table ()
734 {
735   global $gameid, $GT, $debug,$INDEX,$defaulttimezone,$session;
736   global $RULES,$GAME,$gametype;
737
738   $result = DB_query("SELECT  User.fullname as name,".
739                      "        Hand.position as position, ".
740                      "        User.id, ".
741                      "        Hand.party as party, ".
742                      "        Hand.sickness as sickness, ".
743                      "        Hand.point_call, ".
744                      "        User.last_login, ".
745                      "        Hand.hash,       ".
746                      "        User.timezone    ".
747                      "FROM Hand ".
748                      "LEFT JOIN User ON User.id=Hand.user_id ".
749                      "WHERE Hand.game_id='".$gameid."' ".
750                      "ORDER BY position ASC");
751
752   echo "<div class=\"table\">\n".
753     "  <img class=\"table\" src=\"pics/table.png\" alt=\"table\" />\n";
754   while($r = DB_fetch_array($result))
755     {
756       $name  = $r[0];
757       $pos   = $r[1];
758       $user  = $r[2];
759       $party = $r[3];
760       $sickness  = $r[4];
761       $call      = $r[5];
762       $hash      = $r[7];
763       $timezone  = $r[8];
764       date_default_timezone_set($defaulttimezone);
765       $lastlogin = strtotime($r[6]);
766       date_default_timezone_set($timezone);
767       $timenow   = strtotime(date("Y-m-d H:i:s"));
768
769       echo "  <div class=\"table".($pos-1)."\">\n";
770
771       if($debug)
772         echo "   <a href=\"".$INDEX."?action=game&amp;me=".$hash."\">";
773       if($vacation = check_vacation($user))
774         {
775           $start   = $vacation[0];
776           $stop    = substr($vacation[1],0,10);
777           $comment = $vacation[2];
778
779               $title = "begin: $start  end: $stop $comment";
780               echo "   <span class=\"vacation\" title=\"$title\">$name (on vacation until $stop)</span> \n";
781         }
782       else
783         echo "   $name \n";
784       if($debug)
785         echo"</a>\n";
786
787       /* add hints for poverty, wedding, solo, etc */
788       if( $gametype != "solo")
789         if( $RULES["schweinchen"]=="both" && $GAME["schweinchen-who"]==$hash )
790           echo " Schweinchen. <br />";
791
792       if($GT=="poverty" && $party=="re")
793         if($sickness=="poverty")
794           {
795             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
796             $cards    = DB_get_all_hand($userhash);
797             $trumpNR  = count_trump($cards,'all');
798             if($trumpNR)
799               echo "   <img src=\"pics/button/poverty_trump_button.png\" class=\"button\" alt=\"poverty < trump back\" title=\"poverty - trump back\" />";
800             else
801               echo "   <img src=\"pics/button/poverty_notrump_button.png\" class=\"button\" alt=\"poverty <\" title=\"poverty - no trump back\" />";
802           }
803         else
804           echo "   <img src=\"pics/button/poverty_partner_button.png\" class=\"button\" alt=\"poverty >\" title=\"poverty partner\" />";
805
806       if($GT=="dpoverty")
807         if($party=="re")
808           if($sickness=="poverty")
809             {
810               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
811               $cards    = DB_get_all_hand($userhash);
812               $trumpNR  = count_trump($cards,'all');
813               if($trumpNR)
814                 echo "   <img src=\"pics/button/poverty_trump_button.png\" class=\"button\" alt=\"poverty < trump back\" title=\"poverty - trump back\" />";
815               else
816                 echo "   <img src=\"pics/button/poverty_notrump_button.png\" class=\"button\" alt=\"poverty <\" title=\"poverty - no trump back\" />";
817             }
818           else
819             echo "   <img src=\"pics/button/poverty_partner_button.png\" class=\"button\" alt=\"poverty >\" title=\"poverty partner\" />";
820         else
821           if($sickness=="poverty")
822             {
823               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
824               $cards    = DB_get_all_hand($userhash);
825               $trumpNR  = count_trump($cards,'all');
826               if($trumpNR)
827                 echo "   <img src=\"pics/button/poverty2_trump_button.png\" class=\"button\" alt=\"poverty2 < trump back\" title=\"poverty2 - trump back\"/>";
828               else
829                 echo "   <img src=\"pics/button/poverty2_notrump_button.png\" class=\"button\" alt=\"poverty2 <\" title=\"poverty2 - no trump back\" />";
830             }
831           else
832             echo "   <img src=\"pics/button/poverty2_partner_button.png\" class=\"button\" alt=\"poverty2 >\" title=\"poverty2 partner\" />";
833
834       if($GT=="wedding" && $party=="re")
835         if($sickness=="wedding")
836           echo "   <img src=\"pics/button/wedding_button.png\" class=\"button\" alt=\"wedding\" title=\"wedding\" />";
837         else
838           echo "   <img src=\"pics/button/wedding_partner_button.png\" class=\"button\" alt=\"wedding partner\" title=\"wedding partner\" />";
839
840       if(ereg("solo",$GT) && $party=="re")
841         {
842           if(ereg("queen",$GT))
843             echo "   <img src=\"pics/button/queensolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Queen solo\" />";
844           else if(ereg("jack",$GT))
845             echo "   <img src=\"pics/button/jacksolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Jack solo\" />";
846           else if(ereg("club",$GT))
847             echo "   <img src=\"pics/button/clubsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Club solo\" />";
848           else if(ereg("spade",$GT))
849             echo "   <img src=\"pics/button/spadesolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Spade solo\" />";
850           else if(ereg("heart",$GT))
851             echo "   <img src=\"pics/button/heartsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Heart solo\" />";
852           else if(ereg("trumpless",$GT))
853             echo "   <img src=\"pics/button/notrumpsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Trumpless solo\" />";
854           else if(ereg("trump",$GT))
855             echo "   <img src=\"pics/button/trumpsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Trump solo\" />";
856         }
857
858       /* add point calls */
859       if($call!=NULL)
860         {
861           if($party=="re")
862             echo "  <img src=\"pics/button/re_button.png\" class=\"button\" alt=\"re\" title=\"Re\" />";
863           else
864             echo "  <img src=\"pics/button/contra_button.png\" class=\"button\" alt=\"contra\" title=\"Contra\" />";
865           switch($call)
866             {
867             case "0":
868               echo "   <img src=\"pics/button/0_button.png\" class=\"button\" alt=\"0\" title=\"Call 0\" />";
869               break;
870             case "30":
871               echo "   <img src=\"pics/button/30_button.png\" class=\"button\" alt=\"30\" title=\"Call 30\" />";
872               break;
873             case "60":
874               echo "   <img src=\"pics/button/60_button.png\" class=\"button\" alt=\"60\" title=\"Call 60\" />";
875               break;
876             case "90":
877               echo "   <img src=\"pics/button/90_button.png\" class=\"button\" alt=\"90\" title=\"Call 90\" />";
878               break;
879             }
880         }
881
882       echo "    <br />\n";
883       echo "    <span title=\"local time: ".date("Y-m-d H:i:s",$timenow).  " ".
884                              "last login: ".date("Y-m-d H:i:s",$lastlogin)."\">time info</span>\n";
885       echo "   </div>\n";
886
887     }
888   echo  "</div>\n"; /* end output table */
889
890
891   return;
892 }
893
894
895 function display_user_menu($id)
896 {
897   global $WIKI,$INDEX;
898
899   $result = DB_query("SELECT Hand.hash,Hand.game_id,Game.player from Hand".
900                      " LEFT JOIN Game On Hand.game_id=Game.id".
901                      " WHERE Hand.user_id='$id'".
902                      " AND ( Game.player='$id' OR ISNULL(Game.player) )".
903                      " AND Game.status<>'gameover'".
904                      " ORDER BY Game.session" );
905
906   $i=0;
907   while( $r = DB_fetch_array($result))
908     {
909       if($i==0)
910         {
911           echo "<div class=\"usermenu\">\n";
912           echo "It's your turn in these games:<br />\n";
913         }
914
915       $i++;
916       echo "<a href=\"".$INDEX."?action=game&amp;me=".$r[0].
917         "\">game ".DB_format_gameid($r[1])." </a><br />\n";
918       if($i>4)
919         {
920           echo "...<br />\n";
921           break;
922         }
923     }
924
925   if($i)
926     echo  "</div>\n";
927   return;
928 }
929
930 function generate_score_table($session)
931 {
932   /* returns an array with N entries
933    * $score[$i]["gameid"]   = gameid
934    * $score[$i]["players"] = array (id=>total points)
935    * $score[$i]["points"]   = points for this game
936    * $score[$i]["solo"]     = 1 or 0
937    */
938   $score = array();
939   $i=0;
940
941   /* get all ids */
942   $gameids = DB_get_gameids_of_finished_games_by_session($session);
943
944   if($gameids == NULL)
945     return $score;
946
947   /* get player id, names... from the first game */
948   $player = array();
949   $result = DB_query("SELECT User.id, User.fullname from Hand".
950                      " LEFT JOIN User On Hand.user_id=User.id".
951                      " WHERE Hand.game_id=".$gameids[0]);
952   while( $r = DB_fetch_array($result))
953     $player[$r[0]] = 0;
954
955   /* get points and generate table */
956   foreach($gameids as $gameid)
957     {
958       $re_score = DB_get_score_by_gameid($gameid);
959       $gametype = DB_get_gametype_by_gameid($gameid);
960       foreach($player as $id=>$points)
961         {
962           $party = DB_get_party_by_gameid_and_userid($gameid,$id);
963           if($party == "re")
964             if($gametype=="solo")
965               $player[$id] += 3*$re_score;
966             else
967               $player[$id] += $re_score;
968           else if ($party == "contra")
969             $player[$id] -= $re_score;
970         }
971       $score[$i]['gameid']  = $gameid ;
972       $score[$i]['players'] = $player;
973       $score[$i]['points']  = abs($re_score);
974       $score[$i]['solo']    = ($gametype=="solo");
975
976       $i++;
977     }
978
979   return $score;
980 }
981
982 function generate_global_score_table()
983 {
984   $return = array();
985
986   /* get all ids */
987   $gameids = DB_get_gameids_of_finished_games_by_session(0);
988
989   if($gameids == NULL)
990     return '';
991
992   /* get player id, names... from the User table */
993   $player = array();
994   $result = DB_query('SELECT User.id, User.fullname FROM User');
995
996   /* save information in an array */
997   while( $r = DB_fetch_array($result))
998     $player[$r[0]] = array('name'=> $r[1], 'points' => 0 ,'nr' => 0);
999
1000   /* get points and generate table */
1001   foreach($gameids as $gameid)
1002     {
1003       $re_score = DB_get_score_by_gameid($gameid);
1004       $gametype = DB_get_gametype_by_gameid($gameid);
1005
1006       /* get players involved in this game */
1007       $result = DB_query('SELECT user_id FROM Hand WHERE game_id='.DB_quote_smart($gameid));
1008       while($r = DB_fetch_array($result))
1009         {
1010           $id = $r[0];
1011           $party = DB_get_party_by_gameid_and_userid($gameid,$id);
1012           if($party == 're')
1013             if($gametype=='solo')
1014               $player[$id]['points'] += 3*$re_score;
1015             else
1016               $player[$id]['points'] += $re_score;
1017           else if ($party == 'contra')
1018             $player[$id]['points'] -= $re_score;
1019           if($party)
1020             $player[$id]['nr']+=1;
1021         }
1022     }
1023
1024   function cmp($a,$b)
1025   {
1026     if($a['nr']==0 ) return 1;
1027     if($b['nr']==0) return 1;
1028
1029     $a=$a['points']/$a['nr'];
1030     $b=$b['points']/$b['nr'];
1031
1032     if ($a == $b)
1033       return 0;
1034     return ($a > $b) ? -1 : 1;
1035   }
1036   usort($player,'cmp');
1037
1038   foreach($player as $pl)
1039     {
1040       /* limit to players with at least 10 games */
1041       if($pl['nr']>10)
1042         $return[] = array( $pl['name'], round($pl['points']/$pl['nr'],3), $pl['points'],$pl['nr']);
1043     }
1044
1045   return $return;
1046 }
1047
1048 function format_score_table_ascii($score)
1049 {
1050   $output="";
1051   if(sizeof($score)==0)
1052     return "";
1053
1054   /* truncate table if we have too many games */
1055   $max = sizeof($score);
1056   if($max>6) $output.=" (table truncated to last 6 games)\n";
1057
1058   /* output header */
1059   foreach($score[0]['players'] as $id=>$points)
1060     {
1061       $name = DB_get_name('userid',$id); /*TODO*/
1062       $output.= "  ".substr($name,0,2)."  |";
1063     }
1064   $output.="  P   |\n";
1065   $output.= "------+------+------+------+------+\n";
1066
1067   /* output score for each game */
1068   $i=0;
1069   foreach($score as $game)
1070     {
1071       $i++;
1072       if($i-1<$max-6) continue;
1073
1074       foreach($game['players'] as $id=>$points)
1075         $output.=str_pad($points,6," ",STR_PAD_LEFT)."|";
1076       $output.=str_pad($game['points'],4," ",STR_PAD_LEFT);
1077
1078       /* check for solo */
1079       if($game['solo'])
1080         $output.= " S|";
1081       else
1082         $output.= "  |";
1083
1084       $output.="\n";
1085     }
1086   return $output;
1087 }
1088
1089 function format_score_table_html($score,$userid)
1090 {
1091   global $INDEX;
1092
1093   if(sizeof($score)==0)
1094     return "";
1095
1096   $output = "<div class=\"scoretable\">\n<table class=\"score\">\n";
1097
1098   /* output header */
1099   $header = "";
1100   $header.= " <thead>\n  <tr>\n";
1101   $header.= "   <th> No </th>";
1102   foreach($score[0]['players'] as $id=>$points)
1103     {
1104       $name = DB_get_name('userid',$id); /*TODO*/
1105       $header.= "<th> ".substr($name,0,2)." </th>";
1106     }
1107   $header.="<th>P</th>\n  </tr>\n </thead>\n";
1108
1109   /* use the same as footer */
1110   $footer = "";
1111   $footer.= " <tfoot>\n  <tr>\n";
1112   $footer.= "   <td> No </td>";
1113   foreach($score[0]['players'] as $id=>$points)
1114     {
1115       $name = DB_get_name('userid',$id); /*TODO*/
1116       $footer.= "<td> ".substr($name,0,2)." </td>";
1117     }
1118   $footer.="<td>P</td>\n  </tr>\n </tfoot>\n";
1119
1120   /* body */
1121   $body = "";
1122   $body.= " <tbody>\n";
1123   $i=0;
1124   foreach($score as $game)
1125     {
1126       $i++;
1127       $body.="  <tr>";
1128       $userhash = DB_get_hash_from_gameid_and_userid($game['gameid'],$userid);
1129       /* create link to old games only if you are logged in and its your game*/
1130       if(isset($_SESSION['id']) && $_SESSION['id']==$userid)
1131         $body.="  <td> <a href=\"".$INDEX."?action=game&amp;me=".$userhash."\">$i</a></td>";
1132       else
1133         $body.="  <td>$i</td>";
1134
1135       foreach($game['players'] as $id=>$points)
1136         $body.="<td>".$points."</td>";
1137       $body.="<td>".$game['points'];
1138
1139       /* check for solo */
1140       if($game['solo'])
1141         $body.= " S";
1142       $body.="</td></tr>\n";
1143     }
1144
1145   $output.=$header;
1146   if($i>12)
1147     $output.=$footer;
1148   $output.=$body;
1149
1150   $output.=" </tbody>\n</table>\n</div>\n";
1151
1152   return $output;
1153 }
1154
1155 function createCache($content, $cacheFile)
1156 {
1157   $fp = fopen($cacheFile,"w");
1158   if($fp)
1159     {
1160       fwrite($fp,$content);
1161       fclose($fp);
1162     }
1163   else
1164     echo "WARNING: couldn't create cache file";
1165
1166   return;
1167 }
1168
1169 function getCache($cacheFile, $expireTime)
1170 {
1171   if( file_exists($cacheFile) &&
1172       filemtime($cacheFile )>( time() - $expireTime ) )
1173     {
1174       return file_get_contents($cacheFile);
1175     }
1176
1177   return false;
1178 }
1179
1180 function check_vacation($userid)
1181 {
1182   /* get start date */
1183   $result = DB_query_array("SELECT value FROM User_Prefs".
1184                      " WHERE user_id='$userid' AND pref_key='vacation start'" );
1185   if($result)
1186     $start = $result[0];
1187   else
1188     return NULL;
1189
1190   /* get end date */
1191   $result = DB_query_array("SELECT value FROM User_Prefs".
1192                      " WHERE user_id='$userid' AND pref_key='vacation stop'" );
1193   if($result)
1194     $stop = $result[0];
1195   else
1196     return NULL;
1197
1198   /* get comment */
1199   $result = DB_query_array("SELECT value FROM User_Prefs".
1200                      " WHERE user_id='$userid' AND pref_key='vacation comment'" );
1201   if($result)
1202     $comment = $result[0];
1203   else
1204     $comment = '';
1205
1206   /* check if user is on vacation. TODO: use user's timezone */
1207   if( (time() - strtotime($start) >0) &&
1208       (strtotime($stop) - time()  >0))
1209     return array ($start,$stop,$comment);
1210   else
1211     return NULL;
1212 }
1213
1214 ?>