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