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