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