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