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