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