63216eb3d44bbcf91374961ef7da24d337c01a0c
[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                      "        User.email       ".
808                      "FROM Hand ".
809                      "LEFT JOIN User ON User.id=Hand.user_id ".
810                      "WHERE Hand.game_id='".$gameid."' ".
811                      "ORDER BY position ASC");
812
813   echo "<div class=\"table\">\n".
814     "  <img class=\"table\" src=\"pics/table.png\" alt=\"table\" />\n";
815   while($r = DB_fetch_array($result))
816     {
817       $name  = $r[0];
818       $pos   = $r[1];
819       $user  = $r[2];
820       $party = $r[3];
821       $sickness  = $r[4];
822       $call      = $r[5];
823       $hash      = $r[7];
824       $timezone  = $r[8];
825       $email     = $r[9];      
826       $wins      = DB_get_number_of_tricks($gameid,$pos);
827       date_default_timezone_set($defaulttimezone);
828       $lastlogin = strtotime($r[6]);
829       date_default_timezone_set($timezone);
830       $timenow   = strtotime(date("Y-m-d H:i:s"));
831       $gravatar = "$name<br /><img class=\"gravatar\" title=\"$name\" src=\"http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=identicon\" />";
832
833
834       echo "  <div class=\"table".($pos-1)."\">\n";
835
836       if($debug)
837         echo "   <a href=\"".$INDEX."?action=game&amp;me=".$hash."\">";
838       if($vacation = check_vacation($user))
839         {
840           $start   = $vacation[0];
841           $stop    = substr($vacation[1],0,10);
842           $comment = $vacation[2];
843
844               $title = "begin: $start  end: $stop $comment";
845               echo "   <span class=\"vacation\" title=\"$title\">$gravatar (on vacation until $stop)</span> \n";
846         }
847       else
848         echo "   $gravatar \n";
849       if($debug)
850         echo"</a>\n";
851
852       /* add hints for poverty, wedding, solo, etc */
853       if( $gametype != "solo")
854         if( $RULES["schweinchen"]=="both" && $GAME["schweinchen-who"]==$hash )
855           echo " Schweinchen. <br />";
856
857       if($GT=="poverty" && $party=="re")
858         if($sickness=="poverty")
859           {
860             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
861             $cards    = DB_get_all_hand($userhash);
862             $trumpNR  = count_trump($cards,'all');
863             if($trumpNR)
864               echo "   <img src=\"pics/button/poverty_trump_button.png\" class=\"button\" alt=\"poverty < trump back\" title=\"poverty - trump back\" />";
865             else
866               echo "   <img src=\"pics/button/poverty_notrump_button.png\" class=\"button\" alt=\"poverty <\" title=\"poverty - no trump back\" />";
867           }
868         else
869           echo "   <img src=\"pics/button/poverty_partner_button.png\" class=\"button\" alt=\"poverty >\" title=\"poverty partner\" />";
870
871       if($GT=="dpoverty")
872         if($party=="re")
873           if($sickness=="poverty")
874             {
875               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
876               $cards    = DB_get_all_hand($userhash);
877               $trumpNR  = count_trump($cards,'all');
878               if($trumpNR)
879                 echo "   <img src=\"pics/button/poverty_trump_button.png\" class=\"button\" alt=\"poverty < trump back\" title=\"poverty - trump back\" />";
880               else
881                 echo "   <img src=\"pics/button/poverty_notrump_button.png\" class=\"button\" alt=\"poverty <\" title=\"poverty - no trump back\" />";
882             }
883           else
884             echo "   <img src=\"pics/button/poverty_partner_button.png\" class=\"button\" alt=\"poverty >\" title=\"poverty partner\" />";
885         else
886           if($sickness=="poverty")
887             {
888               $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
889               $cards    = DB_get_all_hand($userhash);
890               $trumpNR  = count_trump($cards,'all');
891               if($trumpNR)
892                 echo "   <img src=\"pics/button/poverty2_trump_button.png\" class=\"button\" alt=\"poverty2 < trump back\" title=\"poverty2 - trump back\"/>";
893               else
894                 echo "   <img src=\"pics/button/poverty2_notrump_button.png\" class=\"button\" alt=\"poverty2 <\" title=\"poverty2 - no trump back\" />";
895             }
896           else
897             echo "   <img src=\"pics/button/poverty2_partner_button.png\" class=\"button\" alt=\"poverty2 >\" title=\"poverty2 partner\" />";
898
899       if($GT=="wedding" && $party=="re")
900         if($sickness=="wedding")
901           echo "   <img src=\"pics/button/wedding_button.png\" class=\"button\" alt=\"wedding\" title=\"wedding\" />";
902         else
903           echo "   <img src=\"pics/button/wedding_partner_button.png\" class=\"button\" alt=\"wedding partner\" title=\"wedding partner\" />";
904
905       if(ereg("solo",$GT) && $party=="re")
906         {
907           if(ereg("queen",$GT))
908             echo "   <img src=\"pics/button/queensolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Queen solo\" />";
909           else if(ereg("jack",$GT))
910             echo "   <img src=\"pics/button/jacksolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Jack solo\" />";
911           else if(ereg("club",$GT))
912             echo "   <img src=\"pics/button/clubsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Club solo\" />";
913           else if(ereg("spade",$GT))
914             echo "   <img src=\"pics/button/spadesolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Spade solo\" />";
915           else if(ereg("heart",$GT))
916             echo "   <img src=\"pics/button/heartsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Heart solo\" />";
917           else if(ereg("trumpless",$GT))
918             echo "   <img src=\"pics/button/notrumpsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Trumpless solo\" />";
919           else if(ereg("trump",$GT))
920             echo "   <img src=\"pics/button/trumpsolo_button.png\" class=\"button\" alt=\"$GT\" title=\"Trump solo\" />";
921         }
922
923       /* add point calls */
924       if($call!=NULL)
925         {
926           if($party=="re")
927             echo "  <img src=\"pics/button/re_button.png\" class=\"button\" alt=\"re\" title=\"Re\" />";
928           else
929             echo "  <img src=\"pics/button/contra_button.png\" class=\"button\" alt=\"contra\" title=\"Contra\" />";
930           switch($call)
931             {
932             case "0":
933               echo "   <img src=\"pics/button/0_button.png\" class=\"button\" alt=\"0\" title=\"Call 0\" />";
934               break;
935             case "30":
936               echo "   <img src=\"pics/button/30_button.png\" class=\"button\" alt=\"30\" title=\"Call 30\" />";
937               break;
938             case "60":
939               echo "   <img src=\"pics/button/60_button.png\" class=\"button\" alt=\"60\" title=\"Call 60\" />";
940               break;
941             case "90":
942               echo "   <img src=\"pics/button/90_button.png\" class=\"button\" alt=\"90\" title=\"Call 90\" />";
943               break;
944             }
945         }
946
947       echo "    <br />\n";
948       echo "    <span title=\"local time: ".date("Y-m-d H:i:s",$timenow).  " ".
949                              "last login: ".date("Y-m-d H:i:s",$lastlogin)."\">".
950                              "<img src=\"pics/button/time-info.png\" class=\"tinybutton\" alt=\"time info\" />".
951                              "</span>\n";
952
953       /* show how many tricks the person made */
954       switch($wins)
955         {
956         case 0:
957           echo "#tricks 0"; break;
958         case 1:
959           echo "#tricks 1"; break;
960         case 2:
961         case 3:
962         case 4:
963           echo "#tricks few"; break;
964         default:
965           echo "#tricks many"; break;
966         }
967
968       echo "   </div>\n";
969
970     }
971   echo  "</div>\n"; /* end output table */
972
973
974   return;
975 }
976
977
978 function display_user_menu($id)
979 {
980   global $WIKI,$INDEX;
981
982   $result = DB_query("SELECT Hand.hash,Hand.game_id,Game.player from Hand".
983                      " LEFT JOIN Game On Hand.game_id=Game.id".
984                      " WHERE Hand.user_id='$id'".
985                      " AND ( Game.player='$id' OR ISNULL(Game.player) )".
986                      " AND ( Game.status='pre' OR Game.status='play' )".
987                      " ORDER BY Game.session" );
988
989   $i=0;
990   while( $r = DB_fetch_array($result))
991     {
992       if($i==0)
993         {
994           echo "<div class=\"usermenu\">\n";
995           echo "It's your turn in these games:<br />\n";
996         }
997
998       $i++;
999       echo "<a href=\"".$INDEX."?action=game&amp;me=".$r[0].
1000         "\">game ".DB_format_gameid($r[1])." </a><br />\n";
1001       if($i>4)
1002         {
1003           echo "...<br />\n";
1004           break;
1005         }
1006     }
1007
1008   if($i)
1009     echo  "</div>\n";
1010   return;
1011 }
1012
1013 function generate_score_table($session)
1014 {
1015   /* returns an array with N entries
1016    * $score[$i]["gameid"]   = gameid
1017    * $score[$i]["players"] = array (id=>total points)
1018    * $score[$i]["points"]   = points for this game
1019    * $score[$i]["solo"]     = 1 or 0
1020    */
1021   $score = array();
1022   $i=0;
1023
1024   /* get all ids */
1025   $gameids = DB_get_gameids_of_finished_games_by_session($session);
1026
1027   if($gameids == NULL)
1028     return $score;
1029
1030   /* get player id, names... from the first game */
1031   $player = array();
1032   $result = DB_query("SELECT User.id, User.fullname from Hand".
1033                      " LEFT JOIN User On Hand.user_id=User.id".
1034                      " WHERE Hand.game_id=".$gameids[0]);
1035   while( $r = DB_fetch_array($result))
1036     $player[$r[0]] = 0;
1037
1038   /* get points and generate table */
1039   foreach($gameids as $gameid)
1040     {
1041       $re_score = DB_get_score_by_gameid($gameid);
1042       $gametype = DB_get_gametype_by_gameid($gameid);
1043       foreach($player as $id=>$points)
1044         {
1045           $party = DB_get_party_by_gameid_and_userid($gameid,$id);
1046           if($party == "re")
1047             if($gametype=="solo")
1048               $player[$id] += 3*$re_score;
1049             else
1050               $player[$id] += $re_score;
1051           else if ($party == "contra")
1052             $player[$id] -= $re_score;
1053         }
1054       $score[$i]['gameid']  = $gameid ;
1055       $score[$i]['players'] = $player;
1056       $score[$i]['points']  = abs($re_score);
1057       $score[$i]['solo']    = ($gametype=="solo");
1058
1059       $i++;
1060     }
1061
1062   return $score;
1063 }
1064
1065 function generate_global_score_table()
1066 {
1067   $return = array();
1068
1069   /* get all ids */
1070   $gameids = DB_get_gameids_of_finished_games_by_session(0);
1071
1072   if($gameids == NULL)
1073     return '';
1074
1075   /* get player id, names... from the User table */
1076   $player = array();
1077   $result = DB_query('SELECT User.id, User.fullname FROM User');
1078
1079   /* save information in an array */
1080   while( $r = DB_fetch_array($result))
1081     $player[$r[0]] = array('name'=> $r[1], 'points' => 0 ,'nr' => 0);
1082
1083   /* get points and generate table */
1084   foreach($gameids as $gameid)
1085     {
1086       $re_score = DB_get_score_by_gameid($gameid);
1087       $gametype = DB_get_gametype_by_gameid($gameid);
1088
1089       /* get players involved in this game */
1090       $result = DB_query('SELECT user_id FROM Hand WHERE game_id='.DB_quote_smart($gameid));
1091       while($r = DB_fetch_array($result))
1092         {
1093           $id = $r[0];
1094           $party = DB_get_party_by_gameid_and_userid($gameid,$id);
1095           if($party == 're')
1096             if($gametype=='solo')
1097               $player[$id]['points'] += 3*$re_score;
1098             else
1099               $player[$id]['points'] += $re_score;
1100           else if ($party == 'contra')
1101             $player[$id]['points'] -= $re_score;
1102           if($party)
1103             $player[$id]['nr']+=1;
1104         }
1105     }
1106
1107   function cmp($a,$b)
1108   {
1109     if($a['nr']==0 ) return 1;
1110     if($b['nr']==0) return 1;
1111
1112     $a=$a['points']/$a['nr'];
1113     $b=$b['points']/$b['nr'];
1114
1115     if ($a == $b)
1116       return 0;
1117     return ($a > $b) ? -1 : 1;
1118   }
1119   usort($player,'cmp');
1120
1121   foreach($player as $pl)
1122     {
1123       /* limit to players with at least 10 games */
1124       if($pl['nr']>10)
1125         $return[] = array( $pl['name'], round($pl['points']/$pl['nr'],3), $pl['points'],$pl['nr']);
1126     }
1127
1128   return $return;
1129 }
1130
1131 function format_score_table_ascii($score)
1132 {
1133   $output="";
1134   if(sizeof($score)==0)
1135     return "";
1136
1137   /* truncate table if we have too many games */
1138   $max = sizeof($score);
1139   if($max>6) $output.=" (table truncated to last 6 games)\n";
1140
1141   /* output header */
1142   foreach($score[0]['players'] as $id=>$points)
1143     {
1144       $name = DB_get_name('userid',$id); /*TODO*/
1145       $output.= "  ".substr($name,0,2)."  |";
1146     }
1147   $output.="  P   |\n";
1148   $output.= "------+------+------+------+------+\n";
1149
1150   /* output score for each game */
1151   $i=0;
1152   foreach($score as $game)
1153     {
1154       $i++;
1155       if($i-1<$max-6) continue;
1156
1157       foreach($game['players'] as $id=>$points)
1158         $output.=str_pad($points,6," ",STR_PAD_LEFT)."|";
1159       $output.=str_pad($game['points'],4," ",STR_PAD_LEFT);
1160
1161       /* check for solo */
1162       if($game['solo'])
1163         $output.= " S|";
1164       else
1165         $output.= "  |";
1166
1167       $output.="\n";
1168     }
1169   return $output;
1170 }
1171
1172 function format_score_table_html($score,$userid)
1173 {
1174   global $INDEX;
1175
1176   if(sizeof($score)==0)
1177     return "";
1178
1179   $output = "<div class=\"scoretable\">\n<table class=\"score\">\n";
1180
1181   /* output header */
1182   $header = "";
1183   $header.= " <thead>\n  <tr>\n";
1184   $header.= "   <th> No </th>";
1185   foreach($score[0]['players'] as $id=>$points)
1186     {
1187       $name = DB_get_name('userid',$id); /*TODO*/
1188       $header.= "<th> ".substr($name,0,2)." </th>";
1189     }
1190   $header.="<th>P</th>\n  </tr>\n </thead>\n";
1191
1192   /* use the same as footer */
1193   $footer = "";
1194   $footer.= " <tfoot>\n  <tr>\n";
1195   $footer.= "   <td> No </td>";
1196   foreach($score[0]['players'] as $id=>$points)
1197     {
1198       $name = DB_get_name('userid',$id); /*TODO*/
1199       $footer.= "<td> ".substr($name,0,2)." </td>";
1200     }
1201   $footer.="<td>P</td>\n  </tr>\n </tfoot>\n";
1202
1203   /* body */
1204   $body = "";
1205   $body.= " <tbody>\n";
1206   $i=0;
1207   foreach($score as $game)
1208     {
1209       $i++;
1210       $body.="  <tr>";
1211       $userhash = DB_get_hash_from_gameid_and_userid($game['gameid'],$userid);
1212       /* create link to old games only if you are logged in and its your game*/
1213       if(isset($_SESSION['id']) && $_SESSION['id']==$userid)
1214         $body.="  <td> <a href=\"".$INDEX."?action=game&amp;me=".$userhash."\">$i</a></td>";
1215       else
1216         $body.="  <td>$i</td>";
1217
1218       foreach($game['players'] as $id=>$points)
1219         $body.="<td>".$points."</td>";
1220       $body.="<td>".$game['points'];
1221
1222       /* check for solo */
1223       if($game['solo'])
1224         $body.= " S";
1225       $body.="</td></tr>\n";
1226     }
1227
1228   $output.=$header;
1229   if($i>12)
1230     $output.=$footer;
1231   $output.=$body;
1232
1233   $output.=" </tbody>\n</table>\n</div>\n";
1234
1235   return $output;
1236 }
1237
1238 function createCache($content, $cacheFile)
1239 {
1240   $fp = fopen($cacheFile,"w");
1241   if($fp)
1242     {
1243       fwrite($fp,$content);
1244       fclose($fp);
1245     }
1246   else
1247     echo "WARNING: couldn't create cache file";
1248
1249   return;
1250 }
1251
1252 function getCache($cacheFile, $expireTime)
1253 {
1254   if( file_exists($cacheFile) &&
1255       filemtime($cacheFile )>( time() - $expireTime ) )
1256     {
1257       return file_get_contents($cacheFile);
1258     }
1259
1260   return false;
1261 }
1262
1263 function check_vacation($userid)
1264 {
1265   /* get start date */
1266   $result = DB_query_array("SELECT value FROM User_Prefs".
1267                      " WHERE user_id='$userid' AND pref_key='vacation start'" );
1268   if($result)
1269     $start = $result[0];
1270   else
1271     return NULL;
1272
1273   /* get end date */
1274   $result = DB_query_array("SELECT value FROM User_Prefs".
1275                      " WHERE user_id='$userid' AND pref_key='vacation stop'" );
1276   if($result)
1277     $stop = $result[0];
1278   else
1279     return NULL;
1280
1281   /* get comment */
1282   $result = DB_query_array("SELECT value FROM User_Prefs".
1283                      " WHERE user_id='$userid' AND pref_key='vacation comment'" );
1284   if($result)
1285     $comment = $result[0];
1286   else
1287     $comment = '';
1288
1289   /* check if user is on vacation. TODO: use user's timezone */
1290   if( (time() - strtotime($start) >0) &&
1291       (strtotime($stop) - time()  >0))
1292     return array ($start,$stop,$comment);
1293   else
1294     return NULL;
1295 }
1296
1297 function cancel_game($why,$gameid)
1298 {
1299   $gameid = DB_quote_smart($gameid);
1300
1301   /* update the game table */
1302   switch($why)
1303     {
1304     case 'timedout':
1305       DB_query("UPDATE Game SET status='cancel-timedout' WHERE id=$gameid");
1306       break;
1307     case 'nines':
1308       DB_query("UPDATE Game SET status='cancel-nines' WHERE id=$gameid");
1309       break;
1310     case 'trump':
1311       DB_query("UPDATE Game SET status='cancel-trump' WHERE id=$gameid");
1312       break;
1313     case 'noplay':
1314       DB_query("UPDATE Game SET status='cancel-noplay' WHERE id=$gameid");
1315       break;
1316     }
1317   /* set each player to gameover */
1318   $result = DB_query("SELECT id FROM Hand WHERE game_id=".DB_quote_smart($gameid));
1319   while($r = DB_fetch_array($result))
1320     {
1321       $id = $r[0];
1322       DB_query("UPDATE Hand SET status='gameover' WHERE id=".DB_quote_smart($id));
1323     }
1324
1325   return;
1326 }
1327
1328 ?>