8ab6f312d3d1e4bc283c0e0a705493737e6db110
[e-DoKo.git] / include / game.php
1 <?php
2 /* Copyright 2006, 2007, 2008, 2009, 2010 Arun Persaud <arun@nubati.net>
3  *
4  *   This file is part of e-DoKo.
5  *
6  *   e-DoKo is free software: you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation, either version 3 of the License, or
9  *   (at your option) any later version.
10  *
11  *   e-DoKo is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with e-DoKo.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20
21 /* make sure that we are not called from outside the scripts,
22  * use a variable defined in config.php to check this
23  */
24 if(!isset($HOST))
25   exit;
26
27 /* calling game.php only makes sense when we give it a hash for a game */
28 if(!myisset('me'))
29   {
30     echo "Hmm, you really shouldn't mess with the urls.<br />\n";
31     return;
32   }
33 $me = $_REQUEST['me'];
34
35 /* Ok, got a hash, but is it valid? */
36 $myid = DB_get_userid('hash',$me);
37 if(!$myid)
38   {
39     echo "Can't find you in the database, please check the url.<br />\n";
40     echo "perhaps the game has been canceled, check by login in <a href=\"$INDEX\">here</a>.";
41     return;
42   }
43
44 global $GAME,$RULES,$CARDS;
45
46 /* get some information from the DB */
47 $gameid   = DB_get_gameid_by_hash($me);
48 $myname   = DB_get_name('hash',$me);
49 $mystatus = DB_get_status_by_hash($me);
50 $origmystatus = DB_get_status_by_hash($me); /* to show "it's your turn" menu when game has just finished */
51 $mypos    = DB_get_pos_by_hash($me);
52 $myhand   = DB_get_handid('hash',$me);
53 $myparty  = DB_get_party_by_hash($me);
54 $session  = DB_get_session_by_gameid($gameid);
55
56 /* get prefs and save them in a variable*/
57 $PREF = DB_get_PREF(isset($_SESSION['id'])?$_SESSION['id']:$myid);
58
59 /* get rule set for this game */
60 $RULES = DB_get_RULES($gameid);
61
62 /* get some infos about the game */
63 $gametype   = DB_get_gametype_by_gameid($gameid);
64 $gamestatus = DB_get_game_status_by_gameid($gameid);
65 $GT         = $gametype;
66 if($gametype=='solo')
67   {
68     $gametype = DB_get_solo_by_gameid($gameid);
69     $GT  = $gametype.' '.$GT;
70   }
71
72 /* do we need to worry about Schweinchen?
73  * check gametype and rules
74  * if yes, figure out if someone actually has Schweinchen
75  * save information in $GAME
76  */
77 $ok=0;
78 if( $gamestatus == 'pre' )
79   {
80     /* always need to use Schweinchen to figure out for example who has poverty */
81     $ok=1;
82     /* unless the gametype is set and we know that we are in poverty were schweinchen is not valid */
83     if( in_array( $gametype,array('poverty','dpoverty') ))
84       $ok=0;
85   }
86 else
87   {
88     /* in a game Schweinchen is not valid in all types of games */
89     if( in_array($gametype,array('normal','wedding','trump','silent') ))
90       if( in_array($RULES['schweinchen'],array('both','second','secondaftercall')) )
91         $ok=1;
92   }
93
94 /* these are the defaults */
95 $GAME['schweinchen-who']    = NULL;
96 $GAME['schweinchen-first']  = NULL;
97 $GAME['schweinchen-second'] = NULL;
98
99 if($ok)
100 {
101   /* need to check for Schweinchen */
102   for($i=1;$i<5;$i++)
103     {
104       $hash  = DB_get_hash_from_game_and_pos($gameid,$i);
105       $cards = DB_get_all_hand($hash);
106       if( in_array('19',$cards) && in_array('20',$cards) )
107         $GAME['schweinchen-who']=$hash;
108     };
109   $GAME['schweinchen-first']  = 0; /* to keep track if they have been played already */
110   $GAME['schweinchen-second'] = 0;
111 }
112 /* end check for Schweinchen */
113
114 /* set the $CARDS variable, needed for sorting the cards
115  * we set it to normal so that the pre-game phase is handled ok
116  * and later set it to the correct game type that is played
117  */
118 set_gametype('normal');
119
120 /* put everyting in a form */
121 echo "<form action=\"index.php?action=game&amp;me=$me\" method=\"post\">\n";
122
123 /* handle user notes (only possible while game is running)*/
124 if( $mystatus!='gameover' )
125   if(myisset('note'))
126     {
127       $note = $_REQUEST['note'];
128
129       if($note != '')
130         DB_insert_note($note,$gameid,$myid);
131     };
132
133 /* handle calls, output a comment to show when the call was made */
134 /* initialize comments */
135 $comment  =  '';
136
137 /* check for calls, set comment */
138 if(myisset('call')  && $_REQUEST['call']  == '120' && can_call(120,$me))
139   {
140     $result = DB_query("UPDATE Hand SET point_call='120' WHERE hash='$me' ");
141     if($myparty=='re')
142       $comment .= "Re";
143     else if($myparty=='contra')
144       $comment .= "Contra";
145   }
146 if(myisset('call')  && $_REQUEST['call']  == '90' && can_call(90,$me))
147   {
148     $result = DB_query("UPDATE Hand SET point_call='90'  WHERE hash='$me' ");
149     $comment .= "No 90";
150   }
151 if(myisset('call')  && $_REQUEST['call']  == '60' && can_call(60,$me))
152   {
153     $result = DB_query("UPDATE Hand SET point_call='60'  WHERE hash='$me' ");
154     $comment .= "No 60";
155   }
156 if(myisset('call')  && $_REQUEST['call']  == '30' && can_call(30,$me))
157   {
158     $result = DB_query("UPDATE Hand SET point_call='30'  WHERE hash='$me' ");
159     $comment .= "No 30";
160   }
161 if(myisset('call')  && $_REQUEST['call']  == '0' && can_call(0,$me))
162   {
163     $result = DB_query("UPDATE Hand SET point_call='0'   WHERE hash='$me' ");
164     $comment .= "Zero";
165   }
166
167 /* get information needed to submit comment */
168 $playid = DB_get_current_playid($gameid);
169
170 /* set comment */
171 if($comment != '')
172   DB_insert_comment($comment,$playid,$myid);
173 /* clear up */
174 unset($comment);
175 /* end check for calls */
176
177
178 /* output extra division in case this game is part of a session */
179 if($session)
180   {
181     echo "<div class=\"session\">\n";
182     echo "  <div class=\"sessionrules\">\n    "._('Rules').":\n";
183     switch($RULES['dullen'])
184       {
185       case 'none':
186         echo "    <img class=\"rulesicon\" alt=\""._('no ten of hearts').
187           "\" src=\"pics/button/no-ten-of-hearts.png\"/>\n"; break;
188       case 'firstwins':
189         echo "    <img class=\"rulesicon\" alt=\""._('ten of hearts').
190           "\" src=\"pics/button/ten-of-hearts.png\"/>\n"; break;
191       case 'secondwins':
192         echo "    <img class=\"rulesicon\" alt=\""._('second ten of hearts').
193           "\" src=\"pics/button/second-ten-of-hearts.png\"/>\n"; break;
194       }
195     switch($RULES['schweinchen'])
196       {
197       case 'none':
198         echo "    <img class=\"rulesicon\" alt=\""._('no schweinchen')."\" ".
199           "src=\"pics/button/no-schweinchen.png\"/>\n"; break;
200       case 'both':
201         echo "    <img class=\"rulesicon\" alt=\""._('two schweinchen')."\" ".
202           "src=\"pics/button/two-schweinchen.png\"/>\n"; break;
203       case 'second':
204         echo "    <img class=\"rulesicon\" alt=\"".('second schweinchen')."\" ".
205           "src=\"pics/button/second-schweinchen.png\"/>\n"; break;
206       case 'secondaftercall':
207         echo "    <img class=\"rulesicon\" alt=\""._('second schweinchen after call')."\" ".
208           "src=\"pics/button/second-schweinchen-after-call.png\"/>\n"; break;
209       }
210     switch($RULES['call'])
211       {
212       case '1st-own-card':
213         echo "    <img class=\"rulesicon\" alt=\""._('1st-own-card')."\" src=\"pics/button/1st-own-card.png\"/>\n"; break;
214       case '5th-card':
215         echo "    <img class=\"rulesicon\" alt=\""._('5th-card')."\" src=\"pics/button/5th-card.png\"/>\n"; break;
216       case '9-cards':
217         echo "    <img class=\"rulesicon\" alt=\""._('9-cards')."\" src=\"pics/button/9-cards.png\"/>\n"; break;
218       }
219     echo "    <div>\n";
220     echo '         '._('10ofhearts').":  {$RULES['dullen']}      <br />\n";
221     echo '         '._('schweinchen').": {$RULES['schweinchen']} <br />\n";
222     echo '         '._('call').":        {$RULES['call']}        <br />\n";
223     echo '         '._('lowtrump').":    {$RULES['lowtrump']}    <br />\n";
224     echo "    </div>\n  </div>\n";
225
226     /* show score */
227
228     echo "  <div class=\"sessionscore\">";
229
230     $score   = generate_score_table($session);
231
232     /* get the last entry to show on the main page */
233     $tmpscore= $score;
234     $finalscore = array_pop($tmpscore);
235     $finalscore = $finalscore['players'];
236
237     if($finalscore)
238       {
239         echo _('Score').": \n";
240         foreach($finalscore as $user=>$value)
241           {
242             $name = DB_get_name('userid',$user);
243             echo " ".substr($name,0,2).": $value ";
244           }
245       }
246     else
247       {
248         /* first game, no score yet */
249         echo "&nbsp;";
250       }
251
252     /* output all games for the score table */
253     echo format_score_table_html($score,$myid);
254     echo "  </div>\n";
255
256     /* figure out which game in a session we are in and link to the
257      * previous and next game if possible
258      */
259     $hashes = DB_get_hashes_by_session($session,$myid);
260     $next     = NULL;
261     $i = 1;
262     foreach($hashes as $hash)
263       {
264         if($hash == $me)
265           $j=$i;
266         $i++;
267         $lasthash=$hash;
268       }
269     $i--;
270
271     if($j>1)
272       $previous = $hashes[$j-2];
273     else
274       $previous = NULL;
275     if($j<$i)
276       $next = $hashes[$j];
277     else
278       $next = NULL;
279
280     /* check for solo, add game type to session number */
281     echo "    Game $session.$j";
282     if($GT !='normal')
283       echo " ($GT)";
284     if(isset($_SESSION['id']) && $_SESSION['id']==$myid)
285       {
286         if($previous)
287           echo "&nbsp;&nbsp;&nbsp;<a href=\"{$INDEX}?action=game&amp;me=$previous\">"._('previous')."</a> \n";
288         if($next)
289           echo "&nbsp;&nbsp;&nbsp;<a href=\"{$INDEX}?action=game&amp;me=$next\">"._('next')."</a> \n";
290       }
291     if($j != $i )
292       echo "&nbsp;&nbsp;&nbsp;<a href=\"{$INDEX}?action=game&amp;me=$lasthash\">last</a> \n";
293
294     echo "\n</div>\n";
295   }
296
297 /* display the table and the names */
298 display_table();
299
300 /* mystatus gets the player through the different stages of a game.
301  * start:    does the player want to play?
302  * init:     check for sickness
303  * check:    check for return values from init
304  * poverty:  handle poverty, wait here until all player have reached this state
305  *           display sickness and move on to game
306  * play:     game in progress
307  * gameover: are we revisiting a game
308  */
309
310 /* the user has done something, update the timestamp. Use $myid in
311  * active games and check for session-id in old games (myid might be wrong in that case)
312  */
313 if($mystatus!='gameover')
314   DB_update_user_timestamp($myid);
315  else
316    if(isset($_SESSION['id']))
317      DB_update_user_timestamp($_SESSION['id']);
318
319 switch($mystatus)
320   {
321   case 'start':
322     /* don't ask if user has autosetup set to yest */
323     $skip = 0;
324     if($PREF['autosetup']=='yes') $skip = 1;
325
326     if( !myisset('in') && !$skip)
327       {
328         /* asks the player, if he wants to join the game */
329         output_check_want_to_play($me);
330         echo '<div class="mycards"></div>';
331         break;
332       }
333     else
334       {
335         /* check the result, if player wants to join, got next stage, else cancel game */
336         if(!$skip && $_REQUEST['in'] == 'no' )
337           {
338             /* cancel the game */
339             $message = "Hello, \n\n".
340               "the game has been canceled due to the request of one of the players.\n\n";
341
342             $userids = DB_get_all_userid_by_gameid($gameid);
343             foreach($userids as $user)
344               {
345                 mymail($user,$gameid,GAME_CANCELED,$message);
346               }
347
348             /* update game status */
349             cancel_game('noplay',$gameid);
350             break;
351           }
352         else
353           {
354             /* user wants to join the game */
355
356             /* move on to the next stage,
357              * no break statement to immediately go to the next stage
358              */
359
360             DB_set_hand_status_by_hash($me,'init');
361
362             /* check if everyone has reached this stage, send out email */
363             $userids = DB_get_all_userid_by_gameid($gameid);
364             $ok = 1;
365             foreach($userids as $user)
366               {
367                 $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
368                 if($userstat!='init')
369                   {
370                     /* whos turn is it? */
371                     DB_set_player_by_gameid($gameid,$user);
372                     $ok = 0;
373                     break;
374                   }
375               };
376             if($ok)
377               {
378                 /* all done, send out email unless this player is the startplayer */
379                 $startplayer = DB_get_startplayer_by_gameid($gameid);
380                 if($mypos == $startplayer)
381                   {
382                     /* do nothing, go to next stage */
383                   }
384                 else
385                   {
386                     /* email startplayer */
387                     /*
388                      $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
389                      $who         = DB_get_userid('hash',$hash);
390                      DB_set_player_by_gameid($gameid,$who);
391
392                      $message = "It's your turn now in game ".DB_format_gameid($gameid).".\n".
393                      "Use this link to go the game: ".$HOST.$INDEX."?action=game&me=".$hash."\n\n" ;
394                      mymail($who, $gameid, GAME_READY,$message);
395                     */
396                   }
397               }
398           }
399       }
400   case 'init':
401     /* here we ask the player if he is sick */
402     $mycards = DB_get_hand($me);
403     $mycards = mysort($mycards,$gametype);
404
405     if(!myisset('solo','wedding','poverty','nines','lowtrump') )
406       {
407         /* output sickness of other playes, in case the already selected and are sitting in front of the current player */
408         echo "\n<ul class=\"tricks\">\n";
409         echo "  <li onclick=\"hl('0');\" class=\"current\"><a href=\"#\">Pre</a>\n".
410           "    <div class=\"trick\" id=\"trick0\">\n";
411
412         for($pos=1;$pos<5;$pos++)
413           {
414             $usersick   = DB_get_sickness_by_pos_and_gameid($pos,$gameid);
415             $userid     = DB_get_userid('gameid-position',$gameid,$pos);
416             $userstatus = DB_get_hand_status_by_userid_and_gameid($userid,$gameid);
417
418             if($userstatus=='start' || $userstatus=='init')
419               echo " <div class=\"vorbehalt".($pos-1)."\"> still needs <br/ > to decide </div>\n"; /* show this to everyone */
420             else
421               if($usersick!=NULL && $pos<=$mypos ) /* only show this for people sitting before the player */
422                 echo " <div class=\"vorbehalt".($pos-1)."\"> sick </div>\n";
423               else if($usersick==NULL && $pos<=$mypos)
424                 echo " <div class=\"vorbehalt".($pos-1)."\"> healthy </div>\n";
425           }
426         echo "    </div>\n  </li>\n</ul>\n";  /* end div trick, end li trick , end tricks*/
427         /* end displaying sickness */
428
429         output_check_for_sickness($me,$mycards);
430
431         echo '<div class="mycards">'._('Your cards are').": <br />\n";
432         foreach($mycards as $card)
433           display_card($card,$PREF['cardset']);
434         echo "</div>\n";
435
436         break;
437       }
438     else
439       {
440         /* check if someone selected more than one sickness */
441         $Nsickness = 0;
442         if($_REQUEST['solo']!='No')       $Nsickness++;
443         if($_REQUEST['wedding']  == 'yes') $Nsickness++;
444         if($_REQUEST['poverty']  == 'yes') $Nsickness++;
445         if($_REQUEST['nines']    == 'yes') $Nsickness++;
446         if($_REQUEST['lowtrump'] == 'yes') $Nsickness++;
447
448         if($Nsickness>1)
449           {
450             echo "<p class=\"message\"> You selected more than one sickness, please go back ".
451               "and answer the <a href=\"$INDEX?action=game&amp;me=$me&amp;in=yes\">question</a> again.</p>";
452
453             echo '<div class="mycards">'._('Your cards are').": <br />\n";
454             foreach($mycards as $card)
455               display_card($card,$PREF['cardset']);
456             echo "</div>\n";
457
458             break;
459           }
460         else
461           {
462             /* everything is ok, save what user said and proceed */
463             echo "<p class=\"message\">Processing what you selected in the last step...";
464
465             /* check if this sickness needs to be handled first */
466             $gametype    = DB_get_gametype_by_gameid($gameid);
467             $startplayer = DB_get_startplayer_by_gameid($gameid); /* need this to check which solo goes first */
468
469             if( $_REQUEST['solo']!='No' )
470               {
471                 /* user wants to play a solo */
472
473                 /* store the info in the user's hand info */
474                 DB_set_solo_by_hash($me,$_REQUEST['solo']);
475                 DB_set_sickness_by_hash($me,'solo');
476
477                 echo "<br />Seems like you want to play a {$_REQUEST['solo']} solo. Got it.<br />\n";
478
479                 if($gametype == 'solo' && $startplayer<$mypos)
480                   {}/* do nothing, since someone else already is playing solo */
481                 else
482                   {
483                     /* this solo comes first
484                      * store info in game table
485                      */
486                     DB_set_gametype_by_gameid($gameid,'solo');
487                     DB_set_startplayer_by_gameid($gameid,$mypos);
488                     DB_set_solo_by_gameid($gameid,$_REQUEST['solo']);
489                   };
490               }
491             else if($_REQUEST['wedding'] == 'yes')
492               {
493                 /* silent solo is set further down */
494                 echo _("Ok, you don't want to play a silent solo...wedding was chosen.")."<br />\n";
495                 DB_set_sickness_by_hash($me,'wedding');
496               }
497             else if($_REQUEST['poverty'] == 'yes')
498               {
499                 echo _("Don't think you can win with just a few trump...? Ok, poverty chosen.")." <br />\n";
500                 DB_set_sickness_by_hash($me,'poverty');
501               }
502             else if($_REQUEST['nines'] == 'yes')
503               {
504                 echo _("What? You just don't want to play a game because you have a few nines? Well, if no one".
505                        " is playing solo, this game will be canceled.")."<br />\n";
506                 DB_set_sickness_by_hash($me,'nines');
507               }
508             else if($_REQUEST['lowtrump'] == 'yes')
509               {
510                 if($RULES['lowtrump']=='cancel')
511                   echo _("What? You just don't want to play a game because you have low trump? Well, if no one".
512                          " is playing solo, this game will be canceled.")."<br />\n";
513                 else
514                   echo _("Don't think you can win with low trumps...? Ok, poverty chosen.")." <br />.<br />\n";
515
516                 DB_set_sickness_by_hash($me,'lowtrump');
517               }
518
519             echo "</p>\n";
520
521             /* move on to the next stage*/
522             DB_set_hand_status_by_hash($me,'check');
523             $mystatus='check';
524           };
525       };
526
527   case 'check':
528     /* here we check what all players said and figure out what game we are playing
529      * this can therefore only be handled once all players finished the last stage
530      */
531
532     $mycards = DB_get_hand($me);
533     $mycards = mysort($mycards,$gametype);
534
535     /* output sickness of other playes, in case they already selected and are sitting in front of the current player */
536     echo "\n<ul class=\"tricks\">\n";
537     echo "  <li onclick=\"hl('0');\" class=\"current\"><a href=\"#\">Pre</a>\n".
538       "    <div class=\"trick\" id=\"trick0\">\n";
539
540     for($pos=1;$pos<5;$pos++)
541       {
542         $usersick   = DB_get_sickness_by_pos_and_gameid($pos,$gameid);
543         $userid     = DB_get_userid('gameid-position',$gameid,$pos);
544         $userstatus = DB_get_hand_status_by_userid_and_gameid($userid,$gameid);
545
546         if($userstatus=='start' || $userstatus=='init')
547           echo " <div class=\"vorbehalt".($pos-1)."\"> still needs <br />to decide </div>\n"; /* show this to everyone */
548         else
549           if($usersick!=NULL) /* in the init-phase we only showed players with $pos<$mypos, now we can show all */
550             echo " <div class=\"vorbehalt".($pos-1)."\"> sick </div>\n";
551           else
552             echo " <div class=\"vorbehalt".($pos-1)."\"> healthy </div>\n";
553       }
554     echo "    </div>\n  </li>\n</ul>\n";  /* end div trick, end li trick , end tricks*/
555     /* end displaying sickness */
556
557     echo "<div class=\"message\">\n";
558     echo '<p> '._('Checking if someone else selected solo, nines, wedding or poverty.').'</p>';
559
560     /* check if everyone has reached this stage */
561     $userids = DB_get_all_userid_by_gameid($gameid);
562     $ok = 1;
563     foreach($userids as $user)
564       {
565         $userstat = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
566         if($userstat!='check')
567           {
568             $ok = 0;
569             DB_set_player_by_gameid($gameid,$user);
570             break;
571           }
572       };
573
574     if(!$ok)
575       {
576         echo '<p>'._('This step can only be handled after everyone finished the last step. '.
577           'Seems like this is not the case, so you need to wait a bit... '.
578           'you will get an email once that is the case, please use the link in '.
579           'that email to continue the game.').'</p></div>';
580
581         /* display cards, if player was just at the init-phase he will still see the cards from there
582          * we can put this one here, since the last player to finish the init state won't get here and
583          * will still see his card anyway from the init-phase
584          */
585         if($mystatus=='check')
586           {
587             /* show cards */
588             echo '<div class="mycards">'._('Your cards are').": <br />\n";
589             foreach($mycards as $card)
590               display_card($card,$PREF['cardset']);
591             echo "</div>\n";
592           }
593         break;
594       }
595     else
596       {
597         /* Ok, everyone finished the init-phase, time to figure out what game we
598          * are playing, in case there are any solos this already
599          * will have the correct information in it */
600
601         echo '<p>'._('Ok, everyone is done... figuring out what kind of game we are playing.').'</p>';
602
603         $gametype    = DB_get_gametype_by_gameid($gameid);
604         $startplayer = DB_get_startplayer_by_gameid($gameid);
605
606         /* check for sickness */
607         $cancel  = 0;
608         $poverty = 0;
609         $wedding = 0;
610         $solo    = 0;
611         foreach($userids as $user)
612           {
613             $name     = DB_get_name('userid',$user);
614             $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
615             if($usersick == 'nines' || ($RULES['lowtrump']=='cancel' && $usersick=='lowtrump') )
616               {
617                 $cancel     = $user;
618                 $cancelsick = $usersick;
619                 break; /* no need to check for other poverties, since only solo can win and that is already set */
620               }
621             else if($usersick == 'poverty' || ($RULES['lowtrump']=='poverty' && $usersick=='lowtrump'))
622               $poverty++;
623             else if($usersick == 'wedding')
624               $wedding=$user;
625             else if($usersick == 'solo')
626               $solo++;
627           }
628
629         /* now check which sickness comes first and set the gametype to it */
630         if($gametype == 'solo')
631           {
632             /* do nothing */
633           }
634         else if($cancel)
635           {
636             /* cancel game */
637             if($cancelsick == 'nines')
638               {
639                 $message = "The game has been canceled because ".DB_get_name('userid',$cancel).
640                   " has five or more nines and nobody is playing solo.\n\n".
641                   "To redeal either start a new game or, in case the game was part of a tournament,\n".
642                   "go to the last game and use the link at the bottom of the page to redeal.\n\n";
643
644                 /* update game status */
645                 cancel_game('nines',$gameid);
646
647                 echo "<p>The game has been canceled because ".DB_get_name('userid',$cancel).
648                   " has five or more nines and nobody is playing solo.</p>\n";
649               }
650             else if ($cancelsick == 'lowtrump')
651               {
652                 $message = "The game has been canceled because ".DB_get_name('userid',$cancel).
653                   " has low trump and nobody is playing solo.\n\n".
654                   "To redeal either start a new game or, in case the game was part of a tournament,\n".
655                   "go to the last game and use the link at the bottom of the page to redeal.\n\n";
656
657                 /* update game status */
658                 cancel_game('lowtrump',$gameid);
659
660                 echo "<p>The game has been canceled because ".DB_get_name('userid',$cancel).
661                   " has low trump and nobody is playing solo.</p>\n";
662               };
663
664             $userids = DB_get_all_userid_by_gameid($gameid);
665             foreach($userids as $user)
666               {
667                 mymail($user,$gameid, GAME_CANCELED, $message);
668               }
669
670             echo "</div>\n"; /* end div message */
671             break;
672           }
673         else if($poverty==1) /* one person has poverty */
674           {
675             DB_set_gametype_by_gameid($gameid,'poverty');
676             $gametype = 'poverty';
677             $who      = DB_get_sickness_by_gameid($gameid);
678             if(!$who)
679               {
680                 $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
681                 if($firstsick == 'poverty' || ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
682                   DB_set_sickness_by_gameid($gameid,2); /* who needs to be asked first */
683                 else
684                   DB_set_sickness_by_gameid($gameid,1); /* who needs to be asked first */
685               }
686           }
687         else if($poverty==2) /* two people have poverty */
688           {
689             DB_set_gametype_by_gameid($gameid,'dpoverty');
690             $gametype = 'dpoverty';
691             $who      = DB_get_sickness_by_gameid($gameid);
692             if(!$who)
693               {
694                 $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
695                 if($firstsick == 'poverty' || ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
696                   {
697                     $secondsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
698                     if($secondsick == 'poverty'  || ($RULES['lowtrump']=='poverty' && $secondsick=='lowtrump'))
699                       DB_set_sickness_by_gameid($gameid,30); /* who needs to be asked first */
700                     else
701                       DB_set_sickness_by_gameid($gameid,20); /* who needs to be asked first */
702                   }
703                 else
704                   DB_set_sickness_by_gameid($gameid,10); /* who needs to be asked first */
705               }
706           }
707         else if($wedding> 0)
708           {
709             DB_set_gametype_by_gameid($gameid,'wedding');
710             DB_set_sickness_by_gameid($gameid,'-1'); /* wedding not resolved yet */
711             $gametype = 'wedding';
712           };
713         /* now the gametype is set correctly in the database */
714         echo '<p>'._('Got it').' :)</p>';
715
716         /* loop over all players, set re/contra if possible and start the game if possible */
717         $userids = DB_get_all_userid_by_gameid($gameid);
718         foreach($userids as $userid)
719           {
720             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$userid);
721
722             switch($gametype)
723               {
724               case 'solo':
725                 /* are we the solo player? set us to re, else set us to contra */
726                 $pos = DB_get_pos_by_hash($userhash);
727                 if($pos == $startplayer)
728                   DB_set_party_by_hash($userhash,'re');
729                 else
730                   DB_set_party_by_hash($userhash,'contra');
731                 DB_set_hand_status_by_hash($userhash,'play');
732                 break;
733
734               case 'wedding':
735                 /* set person with the wedding to re, do the rest during the game */
736                 $usersick = DB_get_sickness_by_userid_and_gameid($userid,$gameid);
737                 if($usersick == 'wedding')
738                   DB_set_party_by_hash($userhash,'re');
739                 else
740                   DB_set_party_by_hash($userhash,'contra');
741
742                 DB_set_hand_status_by_hash($userhash,'play');
743                 break;
744
745               case 'normal':
746                 $hand = DB_get_all_hand($userhash);
747
748                 if(in_array('3',$hand)||in_array('4',$hand))
749                   DB_set_party_by_hash($userhash,'re');
750                 else
751                   DB_set_party_by_hash($userhash,'contra');
752                 DB_set_hand_status_by_hash($userhash,'play');
753                 break;
754               case 'poverty':
755               case 'dpoverty':
756                 /* set person with poverty to play status */
757                 $usersick = DB_get_sickness_by_userid_and_gameid($userid,$gameid);
758                 if($usersick == 'poverty'  || ($RULES['lowtrump']=='poverty' && $usersick=='lowtrump'))
759                   DB_set_hand_status_by_hash($userhash,'play');
760
761                 /* set status of first player to be asked to poverty */
762                 $who = DB_get_sickness_by_gameid($gameid);
763                 if($who > 6) $who= $who/10; /* in case we have dpoverty */
764                 $whoid = DB_get_userid('gameid-position',$gameid,$who);
765                 if($whoid==$userid)
766                   DB_set_hand_status_by_hash($userhash,'poverty');
767               }
768           }
769         /* check for silent solo, set game type to solo in this case */
770         $gametype = DB_get_gametype_by_gameid($gameid);
771         $userids  = DB_get_all_userid_by_gameid($gameid);
772         foreach($userids as $userid)
773           {
774             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$userid);
775
776             if($gametype=='normal')
777               {
778                 $userhand = DB_get_all_hand($userhash);
779                 if(check_wedding($userhand))
780                   {
781                     /* normal game type and player has both queens -> silent solo */
782                     /* keep startplayer, just set gametype to silent solo */
783                     DB_set_gametype_by_gameid($gameid,'solo');
784                     DB_set_solo_by_gameid($gameid,'silent');
785                   }
786               }
787           }
788
789         /* send out email to first player or poverty person*/
790         if($gametype!='poverty' && $gametype!='dpoverty')
791           {
792             $startplayer = DB_get_startplayer_by_gameid($gameid);
793             $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
794             $who         = DB_get_userid('hash',$hash);
795             DB_set_player_by_gameid($gameid,$who);
796
797             if($hash!=$me)
798               {
799                 if(DB_get_email_pref_by_hash($hash)!='emailaddict')
800                   {
801                     /* email startplayer */
802                     $message = "It's your turn now in game ".DB_format_gameid($gameid).".\n".
803                       "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$hash."\n\n" ;
804                     mymail($who,$gameid,GAME_READY,$message);
805                   }
806               }
807             else
808               echo "Please, <a href=\"$INDEX?action=game&amp;me=$me\">start</a> the game.<br />\n";
809           }
810         else
811           {
812             /* set status of first player to be asked to poverty */
813             $who   = DB_get_sickness_by_gameid($gameid);
814             if($who > 6) $who= $who/10; /* in case we have dpoverty */
815
816             $whoid = DB_get_userid('gameid-position',$gameid,$who);
817             if($whoid==$myid)
818               echo "Please, <a href=\"$INDEX?action=game&amp;me=$me\">start</a> the game.<br /\n";
819             else
820               {
821                 $whohash = DB_get_hash_from_game_and_pos($gameid,$who);
822                 DB_set_player_by_gameid($gameid,$whoid);
823
824                 if(DB_get_email_pref_by_hash($hash)!='emailaddict')
825                   {
826                     /* email player for poverty */
827                     $message = "Poverty: It's your turn now in game ".DB_format_gameid($gameid).".\n".
828                       "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$whohash."\n\n" ;
829                     mymail($whoid,$gameid,GAME_POVERTY,$message);
830                   }
831               }
832           }
833         echo "</div>\n";
834         /* show cards */
835         echo '<div class="mycards">'._('Your cards are').": <br />\n";
836         foreach($mycards as $card)
837           display_card($card,$PREF['cardset']);
838         echo "</div>\n";
839
840         break;
841       }
842
843   case 'poverty':
844     /* user only gets here in a poverty game, several things have to be handled here:
845      * A) ask, if user wants to take trump
846      *      yes-> take trump,
847      *            poverty: set re/contra
848      *            dpoverty: first time: set re, send email to second player
849      *                      second time: set contra
850      *            poverty: set status of other players to 'play'
851      *            set status to play in case 0 trump
852      *      no -> set status to play,
853      *            ask next player or cancle the game if no more players
854      * B) user took trump and has too many cards (e.g. count(cards)>12 and re/contra set)
855      *         ask to give cards back, set status to play, once player has 12 cards
856      *
857      * it is easier to check B) first
858      */
859
860     set_gametype($gametype); /* this sets the $CARDS variable */
861     $myparty = DB_get_party_by_hash($me);
862
863     /* the following is part B) of whats needs to be done)
864     /*    check if user wants to give cards back */
865     if(myisset('exchange'))
866       {
867         $exchange    = $_REQUEST['exchange'];
868         $partnerhash = DB_get_partner_hash_by_hash($me);
869         $partnerid   = DB_get_userid('hash',$partnerhash);
870         $partnerhand = DB_get_handid('gameid-userid',$gameid,$partnerid);
871
872         /* if exchange is set to a value>0, exchange that card back to the partner */
873         if($exchange >0)
874           {
875             $result = DB_query("UPDATE Hand_Card SET hand_id='$partnerhand'".
876                                " WHERE hand_id='$myhand' AND card_id=".DB_quote_smart($exchange));
877             DB_add_exchanged_card(DB_quote_smart($exchange),$myhand,$partnerhand);
878           };
879       }
880
881     /* update hand */
882     $mycards = DB_get_hand($me);
883     $mycards = mysort($mycards,$gametype);
884
885     /* output pre-game trick in case user reloads,
886      * only needs to be done when a team has been formed */
887     if($myparty=='re' || $myparty=='contra')
888       {
889         echo "\n<ul class=\"tricks\">\n";
890
891         $mygametype =  DB_get_gametype_by_gameid($gameid);
892
893         echo "  <li onclick=\"hl('0');\" class=\"current\"><a href=\"#\">Pre</a>\n".
894           "    <div class=\"trick\" id=\"trick0\">\n";
895
896         /* get information so show the cards that have been handed over in a poverty game */
897         output_exchanged_cards();
898
899         echo "    </div>\n  </li>\n</ul>\n\n";  /* end div trick, end li trick , end ul tricks */
900       }
901     /* end output pre-game trick */
902
903     /* check if user need to give more cards back */
904     if( ($myparty=='re' || $myparty=='contra') && count($mycards)>12)
905       {
906         echo '<div class="poverty"> '._('You need to get rid of a few cards')."</div>\n";
907
908         $type='exchange';
909         echo '<div class="mycards">'._('Your cards are').": <br />\n";
910         foreach($mycards as $card)
911           display_link_card($card,$PREF['cardset'],$type);
912         echo "  <input type=\"submit\" class=\"submitbutton\" value=\"select card to give back\" />\n";
913         echo "</div>\n";
914       }
915     else if( ($myparty=='re' || $myparty=='contra') && count($mycards)==12)
916       {
917         /* user is done, ready to play */
918         DB_set_hand_status_by_hash($me,'play');
919
920         /* email start player */
921         $startplayer = DB_get_startplayer_by_gameid($gameid);
922         $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
923         $who         = DB_get_userid('hash',$hash);
924         DB_set_player_by_gameid($gameid,$who);
925
926         if($hash!=$me)
927           {
928             if(DB_get_email_pref_by_hash($hash)!='emailaddict')
929               {
930                 /* email startplayer */
931                 $message = "It's your turn now in game ".DB_format_gameid($gameid).".\n".
932                   "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$hash."\n\n" ;
933                 mymail($who,$gameid,GAME_READY,$message);
934               }
935           }
936         else
937           echo "<div class=\"message\">Please, <a href=\"$INDEX?action=game&amp;me=$me\">start</a> the game.</div>\n";
938         echo '<div class="mycards"></div>'."\n"; /* needed to make sure the message area is in the right position */
939       }
940
941     /* the following is part A) of what needs to be done */
942     if(!myisset('trump'))
943       {
944         if(!$myparty)
945           {
946             echo "<div class=\"poverty\">\n";
947             $userids = DB_get_all_userid_by_gameid($gameid);
948             foreach($userids as $user)
949               {
950                 $name      = DB_get_name('userid',$user);
951                 $usersick  = DB_get_sickness_by_userid_and_gameid($user,$gameid);
952                 $userhash  = DB_get_hash_from_gameid_and_userid($gameid,$user);
953                 $userparty = DB_get_party_by_hash($userhash);
954
955                 if(($usersick=='poverty'|| ($RULES['lowtrump']=='poverty' && $usersick=='lowtrump')) && !$userparty)
956                   {
957                     $hash    = DB_get_hash_from_gameid_and_userid($gameid,$user);
958                     $cards   = DB_get_hand($hash);
959                     /* count trump */
960                     $nrtrump = 0;
961                     foreach($cards as $card)
962                       if($card<27) $nrtrump++;
963                     $low='';
964                     if($usersick=='lowtrump')
965                       $low='low';
966                     echo "Player $name has $nrtrump $low trump. Do you want to take them?".
967                       "<a href=\"index.php?action=game&amp;me=$me&amp;trump=$user\">Yes</a> <br />\n";
968                   }
969               }
970             echo "<a href=\"index.php?action=game&amp;me=$me&amp;trump=no\">No way</a> <br />\n";
971             echo "</div><div>\n";
972
973             echo '<div class="mycards">'._('Your cards are').": <br />\n";
974             foreach($mycards as $card)
975               display_card($card,$PREF['cardset']);
976             echo "</div></div>\n";
977           }
978         break;
979       }
980     else
981       {
982         $trump = $_REQUEST['trump'];
983
984         if($trump=='no')
985           {
986             /* user doesn't want to take trump */
987             DB_set_hand_status_by_hash($me,'play');
988
989             /* set next player who needs to be asked and email him*/
990             $firstsick  = (string) DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
991             $secondsick = (string) DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
992
993             /* don't ask people who have poverty */
994             $next=1;
995             if($firstsick=='poverty' || ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
996               {
997                 if($secondsick=='poverty'|| ($RULES['lowtrump']=='poverty' && $secondsick=='lowtrump'))
998                   $next=3;
999                 else
1000                   $next=2;
1001               }
1002             if($gametype=='dpoverty')
1003               {
1004                 $next=999; /* need to cancel for sure, since both would need to take the trump */
1005               }
1006
1007             /* no more people to ask, need to cancel the game */
1008             if($mypos+$next>4)
1009               {
1010                 $message = "Hello, \n\n".
1011                   "Game ".DB_format_gameid($gameid)." has been canceled since nobody wanted to take the trump.\n\n";
1012
1013                 $userids = DB_get_all_userid_by_gameid($gameid);
1014                 foreach($userids as $user)
1015                   {
1016                     mymail($user, $gameid, GAME_CANCELED_POVERTY, $message);
1017                   }
1018
1019                 /* update game status */
1020                 cancel_game('trump',$gameid);
1021
1022                 echo "<p class=\"message\";>Game ".DB_format_gameid($gameid)." has been canceled.<br /><br /></p>";
1023                 break;
1024               }
1025             else
1026               {
1027                 /* email next player, set his status to poverty */
1028                 $userhash = DB_get_hash_from_game_and_pos($gameid,$mypos+$next);
1029                 $userid   = DB_get_userid('hash',$userhash);
1030
1031                 DB_set_player_by_gameid($gameid,$userid);
1032                 DB_set_hand_status_by_hash($userhash,'poverty');
1033
1034                 $message = "Someone has poverty, it's your turn to decide, if you want to take the trump. Please visit:".
1035                   " ".$HOST.$INDEX."?action=game&me=".$userhash."\n\n" ;
1036                 mymail($userid,$gameid, GAME_POVERTY, $message);
1037               }
1038           }
1039         else
1040           {
1041             /* player wants to take trump, change cards */
1042
1043             /* user wants to take trump */
1044             $trump = $_REQUEST['trump'];
1045             $userhand = DB_get_handid('gameid-userid',$gameid,$trump);
1046             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$trump);
1047
1048             /* remember which cards were handed over*/
1049             $partnerhand = DB_get_all_hand($userhash);
1050             foreach ($partnerhand as $card)
1051               if($card<27)
1052                 DB_add_exchanged_card($card,$userhand,$myhand);
1053
1054             /* copy trump from player A to B */
1055             $result = DB_query("UPDATE Hand_Card SET hand_id='$myhand' WHERE hand_id='$userhand' AND card_id<'27'" );
1056
1057             /* reload cards */
1058             $mycards = DB_get_hand($me);
1059
1060             /* set re/contra */
1061             if($gametype=='poverty')
1062               {
1063                 $userids = DB_get_all_userid_by_gameid($gameid);
1064                 foreach($userids as $user)
1065                   {
1066                     $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1067                     if($hash==$userhash||$hash==$me)
1068                       {
1069                         DB_set_party_by_hash($hash,'re');
1070                       }
1071                     else
1072                       {
1073                         DB_set_party_by_hash($hash,'contra');
1074                         DB_set_hand_status_by_hash($hash,'play'); /* the contra party is ready to play */
1075                       }
1076                   }
1077                 /* check if we are done (in case of no trump handed over), if so, go to 'play' phase right away*/
1078                 if(count($mycards)==12)
1079                   {
1080                     DB_set_hand_status_by_hash($me,'play');
1081                   }
1082               }
1083             else /*dpoverty*/
1084               {
1085                 /* has the re party already been set?*/
1086                 $re_set=0;
1087                 $userids = DB_get_all_userid_by_gameid($gameid);
1088                 foreach($userids as $user)
1089                   {
1090                     $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1091                     $party = DB_get_party_by_hash($hash);
1092                     if($party=='re')
1093                       $re_set=1;
1094                   }
1095                 if($re_set)
1096                   {
1097                     DB_set_party_by_hash($me,'contra');
1098                     DB_set_party_by_hash($userhash,'contra');
1099                   }
1100                 else
1101                   {
1102                     DB_set_party_by_hash($me,'re');
1103                     DB_set_party_by_hash($userhash,'re');
1104
1105                     /* send out email to second non-poverty player */
1106                     $firstsick  = (string) DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
1107                     $secondsick = (string) DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
1108
1109                     $next=1;
1110                     if($firstsick=='poverty'|| ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
1111                       if($secondsick=='poverty'|| ($RULES['lowtrump']=='poverty' && $secondsick=='lowtrump'))
1112                         $next=3;
1113                       else
1114                         $next=2;
1115
1116                     if($mypos+$next>4)
1117                       echo "<div class=\"message\">Error in poverty, please contact the Admin</div>\n";
1118
1119                     $userhash = DB_get_hash_from_game_and_pos($gameid,$mypos+$next);
1120                     $userid   = DB_get_userid('hash',$userhash);
1121
1122                     DB_set_player_by_gameid($gameid,$userid);
1123                     DB_set_hand_status_by_hash($userhash,'poverty');
1124
1125                     $message = "Two people have poverty, it's your turn to decide, if you want to take the trump. Please visit:".
1126                       " ".$HOST.$INDEX."?action=game&me=".$userhash."\n\n" ;
1127                     mymail($userid,$gameid, GAME_DPOVERTY, $message);
1128                   }
1129               }
1130             echo "<div class=\"message\">Please, <a href=\"$INDEX?action=game&amp;me=$me\">continue</a> here.</div>\n";
1131           }
1132       }
1133     echo "</div>\n";
1134     break;
1135
1136   case 'play':
1137   case 'gameover':
1138     /* both entries here,  so that the tricks are visible for both.
1139      * in case of 'play' there is a break later that skips the last part
1140      */
1141
1142     /* first check if the game has been canceled and display */
1143     switch($gamestatus)
1144       {
1145       case 'cancel-noplay':
1146         echo "<div class=\"message\"><p>The game has been canceled due to the request of one player.</p><p>If this was a mistake all 4 players need to send an Email to $ADMIN_NAME at $ADMIN_EMAIL requesting that the game should be restarted.</p></div>";
1147         break;
1148       case 'cancel-timedout':
1149         echo "<div class=\"message\"><p>The game has been canceled because one player wasn't responding.</p><p>If this was a mistake all 4 players need to send an Email to $ADMIN_NAME at $ADMIN_EMAIL requesting that the game should be restarted.</p></div>";
1150         break;
1151       case 'cancel-nines':
1152         echo "<div class=\"message\"><p>The game has been canceled because one player had too many nines.</p></div>";
1153         break;
1154       case 'cancel-lowtrump':
1155         echo "<div class=\"message\"><p>The game has been canceled because one player had low trump.</p></div>";
1156         break;
1157       case 'cancel-trump':
1158         echo "<div class=\"message\"><p>The game has been canceled because nobody wanted to take the trump.</p></div>";
1159         break;
1160       }
1161     /* for these two types, we shouldn't show the cards, since we might want to restart the game */
1162     if (in_array($gamestatus,array('cancel-noplay','cancel-timedout')))
1163       break;
1164
1165     /* check if all players are ready to play,
1166      * if so, send out email to the startplayer
1167      * only need to do this if the game hasn't started yet
1168      */
1169     $gamestatus = DB_get_game_status_by_gameid($gameid);
1170     if($gamestatus == 'pre')
1171       {
1172         $ok = 1;
1173         $userids = DB_get_all_userid_by_gameid($gameid);
1174         foreach($userids as $user)
1175           {
1176             $userstatus = DB_get_hand_status_by_userid_and_gameid($user,$gameid);
1177             if($userstatus !='play' && $userstatus!='gameover')
1178               {
1179                 $ok = 0;
1180                 DB_set_player_by_gameid($gameid,$user);
1181                 break;
1182               }
1183           }
1184         if($ok)
1185           {
1186             /* only set this after all poverty, etc. are handled*/
1187             DB_set_game_status_by_gameid($gameid,'play');
1188
1189             /* email startplayer */
1190             $startplayer = DB_get_startplayer_by_gameid($gameid);
1191             $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
1192             $who         = DB_get_userid('hash',$hash);
1193             DB_set_player_by_gameid($gameid,$who);
1194
1195             if($hash!=$me && DB_get_email_pref_by_hash($hash)!='emailaddict')
1196               {
1197                 /* email startplayer) */
1198                 $message = "It's your turn now in game ".DB_format_gameid($gameid).".\n".
1199                   "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$hash."\n\n" ;
1200                 mymail($who,$gameid, GAME_READY, $message);
1201               }
1202           }
1203       }
1204     /* figure out what kind of game we are playing,
1205      * set the global variables $CARDS['trump'],$CARDS['diamonds'],$CARDS['hearts'],
1206      * $CARDS['clubs'],$CARDS['spades'],$CARDS['foxes']
1207      * accordingly
1208      */
1209
1210     $gametype = DB_get_gametype_by_gameid($gameid);
1211     $GT       = $gametype;
1212     if($gametype=='solo')
1213       {
1214         $gametype = DB_get_solo_by_gameid($gameid);
1215         if($gametype=='silent')
1216           $GT = 'normal';
1217         else
1218           $GT = $gametype.' '.$GT;
1219       }
1220     else
1221       $gametype = 'normal';
1222
1223     set_gametype($gametype); /* this sets the $CARDS variable */
1224
1225     /* get some infos about the game, need to reset this, since it might have changed */
1226     $gamestatus = DB_get_game_status_by_gameid($gameid);
1227
1228     /* has the game started? No, then just wait here...*/
1229     if($gamestatus == 'pre')
1230       {
1231         echo '<p class="message"> '._('You finished the setup, but not everyone else finished it... '.
1232           'You need to wait for the others. Just wait for an email.').' </p>';
1233
1234         $mycards = DB_get_hand($me);
1235         $mycards = mysort($mycards,$gametype);
1236
1237         echo '<div class="mycards">'._('Your cards are').": <br />\n";
1238         foreach($mycards as $card)
1239           display_card($card,$PREF['cardset']);
1240         echo "</div>\n";
1241
1242         break; /* not sure this works... the idea is that you can
1243                 * only  play a card after everyone is ready to play */
1244       }
1245
1246
1247     /* get time from the last action of the game */
1248     $r = DB_query_array("SELECT mod_date from Game WHERE id='$gameid' " );
1249     $gameend = time() - strtotime($r[0]);
1250
1251     /* handle comments in case player didn't play a card, allow comments a week after the end of the game */
1252     if( (!myisset('card') && $mystatus=='play') || ($mystatus=='gameover' && ($gameend < 60*60*24*7)) )
1253       if(myisset('comment'))
1254         {
1255           $comment = $_REQUEST['comment'];
1256           $playid = DB_get_current_playid($gameid);
1257
1258           if($comment != '')
1259             DB_insert_comment($comment,$playid,$myid);
1260         };
1261
1262     /* get everything relevant to display the tricks */
1263     $result = DB_query("SELECT Hand_Card.card_id as card,".
1264                        "       Hand.position as position,".
1265                        "       Play.sequence as sequence, ".
1266                        "       Trick.id, ".
1267                        "       GROUP_CONCAT(CONCAT('<span>',User.fullname,': ',Comment.comment,'</span>')".
1268                        "                    SEPARATOR '\n' ), ".
1269                        "       Play.create_date, ".
1270                        "       Hand.user_id ".
1271                        "FROM Trick ".
1272                        "LEFT JOIN Play ON Trick.id=Play.trick_id ".
1273                        "LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id ".
1274                        "LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id ".
1275                        "LEFT JOIN Comment ON Play.id=Comment.play_id ".
1276                        "LEFT JOIN User On User.id=Comment.user_id ".
1277                        "WHERE Trick.game_id='".$gameid."' ".
1278                        "GROUP BY Trick.id, sequence ".
1279                        "ORDER BY Trick.id, sequence  ASC");
1280     $trickNR   = 0;
1281     $lasttrick = DB_get_max_trickid($gameid);
1282
1283     $play = array(); /* needed to calculate winner later  */
1284     $seq  = 1;
1285     $pos  = DB_get_startplayer_by_gameid($gameid)-1;
1286     $firstcard = ''; /* first card in a trick */
1287
1288     echo "\n<ul class=\"tricks\">\n";
1289
1290     /* output vorbehalte */
1291     $mygametype = DB_get_gametype_by_gameid($gameid);
1292     $mygamesolo = DB_get_solo_by_gameid($gameid);
1293     if($mygametype != 'normal') /* only show when needed */
1294       if(!( $mygametype == 'solo' && $mygamesolo == 'silent') )
1295         {
1296           echo "  <li onclick=\"hl('0');\" class=\"current\"><a href=\"#\">Pre</a>\n".
1297             "    <div class=\"trick\" id=\"trick0\">\n";
1298
1299           /* get information so show the cards that have been handed over in a poverty game */
1300           output_exchanged_cards();
1301
1302           echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1303         }
1304
1305     /* output tricks */
1306     while($r = DB_fetch_array($result))
1307       {
1308         $pos     = $r[1];
1309         $seq     = $r[2];
1310         $trick   = $r[3];
1311         $comment = $r[4];
1312         $user    = $r[6];
1313
1314         /* count number of tricks */
1315         if($seq==1)
1316           $trickNR++;
1317
1318         /* check if first schweinchen has been played */
1319         if( $GAME['schweinchen-who'] && ($r[0] == 19 || $r[0] == 20) )
1320           if(!$GAME['schweinchen-first'])
1321             $GAME['schweinchen-first'] = 1; /* playing the first fox */
1322           else
1323             $GAME['schweinchen-second'] = 1; /* this must be the second fox */
1324
1325         /* save card to be able to find the winner of the trick later */
1326         $play[$seq] = array('card'=>$r[0],'pos'=>$pos);
1327
1328         if($seq==1)
1329           {
1330             /* first card in a trick, output some html */
1331             if($trick!=$lasttrick)
1332               {
1333                 /* start of an old trick? */
1334                 echo "  <li onclick=\"hl('$trickNR');\" class=\"old\"><a href=\"#\">"._('Trick')." $trickNR</a>\n".
1335                   "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1336                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1337               }
1338             else if($trick==$lasttrick)
1339               {
1340                 /* start of a last trick? */
1341                 echo "  <li onclick=\"hl('$trickNR');\" class=\"current\"><a href=\"#\">"._('Trick')." $trickNR</a>\n".
1342                   "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1343                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1344               };
1345
1346             /* remember first card, so that we are able to check, what cards can be played */
1347             $firstcard = $r[0];
1348           };
1349
1350         /* display card */
1351         echo "      <div class=\"card".($pos-1)."\">\n";
1352
1353         /* display comments */
1354         if($comment!='')
1355           echo "        <span class=\"comment\">".$comment."</span>\n";
1356
1357         echo '        ';
1358         display_card($r[0],$PREF['cardset']);
1359
1360         echo "      </div>\n"; /* end div card */
1361
1362         /* end of trick? */
1363         if($seq==4)
1364           {
1365             $winner    = get_winner($play,$gametype); /* returns the position */
1366             echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1367           }
1368       }
1369
1370     /* whos turn is it? */
1371     if($seq==4)
1372       {
1373         $winner    = get_winner($play,$gametype); /* returns the position */
1374         $next      = $winner;
1375         $firstcard = ''; /* new trick, no first card */
1376       }
1377     else
1378       {
1379         $next = $pos+1;
1380         if($next==5) $next = 1;
1381       }
1382
1383     /* my turn?, display cards as links, ask for comments*/
1384     if(DB_get_pos_by_hash($me) == $next)
1385       $myturn = 1;
1386     else
1387       $myturn = 0;
1388
1389     /* do we want to play a card? */
1390     if(myisset('card') && $myturn)
1391       {
1392         $card   = $_REQUEST['card'];
1393         $handid = DB_get_handid('hash',$me);
1394         $commentSchweinchen =''; /* used to add a comment when Schweinchen is being played */
1395
1396         /* check if we have card and that we haven't played it yet*/
1397         /* set played in hand_card to true where hand_id and card_id*/
1398         $r = DB_query_array("SELECT id FROM Hand_Card WHERE played='false' and ".
1399                               "hand_id='$handid' AND card_id=".DB_quote_smart($card));
1400         $handcardid = $r[0];
1401
1402         if($handcardid) /* everything ok, play card  */
1403           {
1404             /* update Game timestamp */
1405             DB_update_game_timestamp($gameid);
1406
1407             /* mark card as played */
1408             DB_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
1409                      DB_quote_smart($card));
1410
1411             /* get trick id or start new trick */
1412             $a = DB_get_current_trickid($gameid);
1413             $trickid  = $a[0];
1414             $sequence = $a[1];
1415             $tricknr  = $a[2];
1416
1417             $playid = DB_play_card($trickid,$handcardid,$sequence);
1418
1419             /* check special output for schweinchen in case in case a fox is being played
1420              * check for correct rules, etc. has already been done
1421              */
1422             if( $GAME['schweinchen-who'] && ($card == 19 || $card == 20) )
1423               {
1424                 if(!$GAME['schweinchen-first'])
1425                   $GAME['schweinchen-first'] = 1; /* playing the first fox */
1426                 else
1427                   $GAME['schweinchen-second'] = 1; /* this must be the second fox */
1428
1429                 if( $RULES['schweinchen']=='both' ||
1430                     ($RULES['schweinchen']=='second' && $GAME['schweinchen-second']==1 )||
1431                     ($RULES['schweinchen']=='secondaftercall' && $GAME['schweinchen-second']==1 &&
1432                      (DB_get_call_by_hash($GAME['schweinchen-who']) || DB_get_partner_call_by_hash($GAME['schweinchen-who']) ))
1433                   )
1434                   {
1435                     DB_insert_comment('Schweinchen! ',$playid,$myid);
1436                     $commentSchweinchen = 'Schweinchen! ';
1437                   }
1438                 if ($debug)
1439                   echo 'schweinchen = '.$GAME['schweinchen-who'].' ---<br />';
1440               }
1441
1442             /* if sequence == 4 check who one in case of wedding */
1443             if($sequence == 4 && $GT == 'wedding')
1444               {
1445                 /* is wedding resolve */
1446                 $resolved = DB_get_sickness_by_gameid($gameid);
1447                 if($resolved<0)
1448                   {
1449                     /* who has wedding */
1450                     $userids = DB_get_all_userid_by_gameid($gameid);
1451                     foreach($userids as $user)
1452                       {
1453                         $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
1454                         if($usersick == 'wedding')
1455                           $whosick = $user;
1456                       }
1457                     /* who won the trick */
1458                     $play     = DB_get_cards_by_trick($trickid);
1459                     $winner   = get_winner($play,$gametype); /* returns the position */
1460                     $winnerid = DB_get_userid('gameid-position',$gameid,$winner);
1461                     /* is tricknr <=3 */
1462                     if($tricknr <=3 && $winnerid!=$whosick)
1463                       {
1464                         /* set resolved at tricknr*/
1465                         $resolved = DB_set_sickness_by_gameid($gameid,$tricknr);
1466                         /* set partner */
1467                         $whash = DB_get_hash_from_gameid_and_userid($gameid,$winnerid);
1468                         DB_set_party_by_hash($whash,'re');
1469                       }
1470                     if($tricknr == 3 && $winnerid==$whosick)
1471                       {
1472                         /* set resolved at tricknr*/
1473                         $resolved = DB_set_sickness_by_gameid($gameid,'3');
1474                       }
1475                   }
1476               }
1477
1478             /* if sequence == 4, set winner of the trick, count points and set the next player */
1479             if($sequence==4)
1480               {
1481                 $play   = DB_get_cards_by_trick($trickid);
1482                 $winner = get_winner($play,$gametype); /* returns the position */
1483
1484                 /*
1485                  * check if someone caught a fox
1486                  *******************************/
1487
1488                 /* first check if we should account for solos at all,
1489                  * since it doesn't make sense in some games
1490                  */
1491                 $ok = 0; /* fox shouldn't be counted */
1492                 if(DB_get_gametype_by_gameid($gameid)=='solo')
1493                   {
1494                     $solo = DB_get_solo_by_gameid($gameid);
1495                     if($solo == 'trump' || $solo == 'silent')
1496                       $ok = 1; /* for trump solos and silent solos, foxes are ok */
1497                   }
1498                 else
1499                   $ok = 1; /* for all other games (not solos) foxes are ok too */
1500
1501                 if($ok==1)
1502                   foreach($play as $played)
1503                     {
1504                       if ( $played['card']==19 || $played['card']==20 )
1505                         if ($played['pos']!= $winner )
1506                           {
1507                             /* possible caught a fox, check party */
1508                             $uid1 = DB_get_userid('gameid-position',$gameid,$winner);
1509                             $uid2 = DB_get_userid('gameid-position',$gameid,$played['pos']);
1510
1511                             $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1512                             $party2 = DB_get_party_by_gameid_and_userid($gameid,$uid2);
1513
1514                             if($party1 != $party2)
1515                               DB_query("INSERT INTO Score".
1516                                        " VALUES( NULL,NULL,$gameid,'$party1',$uid1,$uid2,'fox')");
1517                           }
1518                     }
1519
1520                 /*
1521                  * check for karlchen (jack of clubs in the last trick)
1522                  ******************************************************/
1523
1524                 /* same as for foxes, karlchen doesn't always make sense
1525                  * check what kind of game it is and set karlchen accordingly */
1526
1527                 if($tricknr == 12 ) /* Karlchen works only in the last trick */
1528                   {
1529                     /* check for solo */
1530                     $solo = 'none';
1531                     if(DB_get_gametype_by_gameid($gameid)=='solo' )
1532                       $solo = DB_get_solo_by_gameid($gameid);
1533
1534                     /* no Karlchen in these solos */
1535                     if($solo != 'trumpless' && $solo != 'jack' && $solo != 'queen' )
1536                       {
1537                         foreach($play as $played)
1538                           if ( $played['card']==11 || $played['card']==12 )
1539                             if ($played['pos'] == $winner )
1540                               {
1541                                 /* save Karlchen */
1542                                 $uid1   = DB_get_userid('gameid-position',$gameid,$winner);
1543                                 $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1544
1545                                 DB_query("INSERT INTO Score".
1546                                          " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'karlchen')");
1547                               };
1548                       };
1549                   }; /* end scoring Karlchen */
1550
1551                 /*
1552                  * check for doppelopf (>40 points)
1553                  ***********************************/
1554
1555                 $points = 0;
1556                 foreach($play as $played)
1557                   {
1558                     $points += DB_get_card_value_by_cardid($played['card']);
1559                   }
1560                 if($points > 39)
1561                   {
1562                     $uid1   = DB_get_userid('gameid-position',$gameid,$winner);
1563                     $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1564
1565                     DB_query("INSERT INTO Score".
1566                              " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'doko')");
1567                   }
1568
1569                 /*
1570                  * set winner (for this trick)
1571                  */
1572
1573                 if($winner>0)
1574                   DB_query("UPDATE Trick SET winner='$winner' WHERE id='$trickid'");
1575                 else
1576                   echo "ERROR during scoring";
1577
1578                 if($debug)
1579                   echo "DEBUG: position $winner won the trick <br />";
1580
1581                 /* who is the next player? */
1582                 $next = $winner;
1583               }
1584             else
1585               {
1586                 $next = DB_get_pos_by_hash($me)+1;
1587               }
1588             if($next==5) $next=1;
1589
1590             /* check for coment */
1591             if(myisset('comment'))
1592               {
1593                 $comment = $_REQUEST['comment'];
1594                 if($comment != '')
1595                   DB_insert_comment($comment,$playid,$myid);
1596                 if($commentSchweinchen)
1597                   $comment = $commentSchweinchen . $comment;
1598               };
1599
1600             /* display played card */
1601             $pos = DB_get_pos_by_hash($me);
1602             if($sequence==1)
1603               {
1604                 echo "  <li onclick=\"hl('".($tricknr)."');\" class=\"current\"><a href=\"#\">"._('Trick').' '.($tricknr)."</a>\n".
1605                   "    <div class=\"trick\" id=\"trick".($tricknr)."\">\n".
1606                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1607               }
1608
1609             echo "      <div class=\"card".($pos-1)."\">\n        ";
1610
1611             /* display comments */
1612             display_card($card,$PREF['cardset']);
1613             if($comment!='')
1614               echo "\n        <span class=\"comment\"> ".$comment."</span>\n";
1615             echo "      </div>\n";
1616
1617             echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1618
1619             /*check if we still have cards left, else set status to gameover */
1620             if(sizeof(DB_get_hand($me))==0)
1621               {
1622                 DB_set_hand_status_by_hash($me,'gameover');
1623                 $mystatus = 'gameover';
1624               }
1625
1626             /* if all players are done, set game status to game over,
1627              * get the points of the last trick and send out an email
1628              * to all players
1629              */
1630             $userids = DB_get_all_userid_by_gameid($gameid);
1631
1632             $done=1;
1633             foreach($userids as $user)
1634               if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
1635                 $done=0;
1636
1637             if($done)
1638               DB_set_game_status_by_gameid($gameid,'gameover');
1639
1640             /* email next player, if game is still running */
1641             if(DB_get_game_status_by_gameid($gameid)=='play')
1642               {
1643                 $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
1644                 $who       = DB_get_userid('hash',$next_hash);
1645                 DB_set_player_by_gameid($gameid,$who);
1646
1647                 $message = "A card has been played in game ".DB_format_gameid($gameid).".\n\n".
1648                   "It's your turn  now.\n".
1649                   "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$next_hash."\n\n" ;
1650                 if( DB_get_email_pref_by_uid($who)!='emailaddict' )
1651                   {
1652                     mymail($who,$gameid, GAME_YOUR_TURN, $message);
1653                   }
1654               }
1655             else /* send out final email */
1656               {
1657                 /* individual score */
1658                 $result = DB_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party FROM Hand".
1659                                    " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1660                                    " LEFT JOIN User ON User.id=Hand.user_id".
1661                                    " LEFT JOIN Play ON Trick.id=Play.trick_id".
1662                                    " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1663                                    " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1664                                    " WHERE Hand.game_id='$gameid'".
1665                                    " GROUP BY User.fullname" );
1666                 $message  = "The game is over. Thanks for playing :)\n";
1667                 $message .= "Final score:\n";
1668                 while( $r = DB_fetch_array($result) )
1669                   $message .= "   ".$r[0]."(".$r[2].") ".$r[1]."\n";
1670
1671                 $result = DB_query("SELECT  Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1672                                    " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1673                                    " LEFT JOIN User ON User.id=Hand.user_id".
1674                                    " LEFT JOIN Play ON Trick.id=Play.trick_id".
1675                                    " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1676                                    " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1677                                    " WHERE Hand.game_id='$gameid'".
1678                                    " GROUP BY Hand.party" );
1679                 $message .= "\nTotals:\n";
1680                 $re     = 0;
1681                 $contra = 0;
1682                 while( $r = DB_fetch_array($result) )
1683                   {
1684                     $message .= "    ".$r[0]." ".$r[1]."\n";
1685                     if($r[0] == 're')
1686                       $re = $r[1];
1687                     else if($r[0] == 'contra')
1688                       $contra = $r[1];
1689                   }
1690
1691                 /*
1692                  * save score in database
1693                  *
1694                  */
1695
1696                 /* get calls from re/contra */
1697                 $call_re     = -1;
1698                 $call_contra = -1;
1699                 foreach($userids as $user)
1700                   {
1701                     $hash  = DB_get_hash_from_gameid_and_userid($gameid,$user);
1702                     $call  = DB_get_call_by_hash($hash);
1703                     $party = DB_get_party_by_hash($hash);
1704
1705                     if($call!=NULL)
1706                       {
1707                         $call = (int) $call;
1708
1709                         if($party=='re')
1710                           {
1711                             if($call_re== -1)
1712                               $call_re = $call;
1713                             else if( $call < $call_re)
1714                               $call_re = $call;
1715                           }
1716                         else if($party=='contra')
1717                           {
1718                             if($call_contra== -1)
1719                               $call_contra = $call;
1720                             else if( $call < $call_contra)
1721                               $call_contra = $call;
1722                           }
1723                       }
1724                   }
1725
1726                 /* figure out who one */
1727                 $winning_party = NULL;
1728
1729                 if($call_re == -1 && $call_contra == -1)
1730                   {
1731                     /* nobody made a call, so it's easy to figure out who won */
1732                     if($re>120)
1733                       $winning_party='re';
1734                     else
1735                       $winning_party='contra';
1736                   }
1737                 else
1738                   {
1739                     /* if one party makes a call, they only win, iff they make enough points
1740                      * if only one party made a call, the other one wins,
1741                      * if the first one didn't make it
1742                      */
1743                     if($call_re != -1)
1744                       {
1745                         $offset = 120 - $call_re;
1746                         if($call_re == 0)
1747                           $offset--; /* since we use a > in the next equation */
1748
1749                         if($re > 120+$offset)
1750                           $winning_party='re';
1751                         else if ($call_contra == -1 )
1752                           $winning_party='contra';
1753                       }
1754
1755                     if($call_contra != -1)
1756                       {
1757                         $offset = 120 - $call_contra;
1758                         if($call_contra == 0)
1759                           $offset--; /* since we use a > in the next equation */
1760
1761                         if($contra > 120+$offset)
1762                           $winning_party='contra';
1763                         else if ($call_re == -1 )
1764                           $winning_party='re';
1765                       }
1766                   }
1767
1768                 /* one point for each call of the other party in case the other party didn't win
1769                  * and one point each in case the party made more than points than one of the calls
1770                  */
1771                 if($winning_party!='contra' && $call_contra!= -1)
1772                   {
1773                     for( $p=$call_contra;$p<=120; $p+=30 )
1774                       {
1775                           DB_query("INSERT INTO Score".
1776                                    " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'against$p')");
1777                         }
1778
1779                       for( $p=$call_contra; $p<120; $p+=30)
1780                         {
1781                           if( $re >= $p )
1782                             DB_query("INSERT INTO Score".
1783                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'made$p')");
1784                         }
1785                     }
1786                   if($winning_party!='re' and $call_re!= -1)
1787                     {
1788                       for( $p=$call_re;$p<=120; $p+=30 )
1789                         {
1790                           DB_query("INSERT INTO Score".
1791                                    " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'against$p')");
1792                         }
1793
1794                       for( $p=$call_re; $p<120; $p+=30)
1795                         {
1796                           if( $contra>=$p )
1797                             DB_query("INSERT INTO Score".
1798                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'made$p')");
1799                         }
1800                     }
1801
1802                   /* point in case contra won */
1803                   if($winning_party=='contra')
1804                     {
1805                       DB_query("INSERT INTO Score".
1806                                " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'againstqueens')");
1807                     }
1808
1809                   /* one point each for winning and each 30 points + calls */
1810                   if($winning_party=='re')
1811                     {
1812                       foreach(array(120,150,180,210,240) as $p)
1813                         {
1814                           $offset = 0;
1815                           if($p==240 || $call_contra != -1)
1816                             $offset = 1;
1817
1818                           if($re>$p-$offset)
1819                             DB_query("INSERT INTO Score".
1820                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'".(240-$p)."')");
1821                         }
1822                       /* re called something and won */
1823                       foreach(array(0,30,60,90,120) as $p)
1824                         {
1825                           if($call_re!= -1 && $call_re<$p+1)
1826                             DB_query("INSERT INTO Score".
1827                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'call$p')");
1828                         }
1829                     }
1830                   else if( $winning_party=='contra')
1831                     {
1832                       foreach(array(120,150,180,210,240) as $p)
1833                         {
1834                           $offset = 0;
1835                           if($p==240 || $call_re != -1)
1836                             $offset = 1;
1837
1838                           if($contra>$p-$offset)
1839                             DB_query("INSERT INTO Score".
1840                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'".(240-$p)."')");
1841                         }
1842                       /* re called something and won */
1843                       foreach(array(0,30,60,90,120) as $p)
1844                         {
1845                           if($call_contra != -1 && $call_contra<$p+1)
1846                             DB_query("INSERT INTO Score".
1847                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'call$p')");
1848                         }
1849                     }
1850
1851
1852                   /* add score points to email */
1853                   $message .= "\n";
1854                   $Tpoint = 0;
1855                   $message .= " Points Re: \n";
1856                   $queryresult = DB_query("SELECT score FROM Score ".
1857                                           "  WHERE game_id=$gameid AND party='re'".
1858                                           " ");
1859                   while($r = DB_fetch_array($queryresult) )
1860                     {
1861                       $message .= "   ".$r[0]."\n";
1862                       $Tpoint ++;
1863                     }
1864                   $message .= " Points Contra: \n";
1865                   $queryresult = DB_query("SELECT score FROM Score ".
1866                                           "  WHERE game_id=$gameid AND party='contra'".
1867                                           " ");
1868                   while($r = DB_fetch_array($queryresult) )
1869                     {
1870                       $message .= "   ".$r[0]."\n";
1871                       $Tpoint --;
1872                     }
1873                   $message .= " Total Points (from the Re point of view): $Tpoint\n";
1874                   $message .= "\n";
1875
1876                   $session = DB_get_session_by_gameid($gameid);
1877                   $score = generate_score_table($session);
1878
1879                   $message .= "Score Table:\n";
1880                   $message .= format_score_table_ascii($score);
1881                   $message .= "\nUse these links to have a look at game ".DB_format_gameid($gameid).": \n";
1882
1883                   /* send out final email */
1884                   foreach($userids as $user)
1885                     {
1886                       /* add links for all players */
1887                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1888                       $name = DB_get_name('userid',$user);
1889
1890                       $link = "$name: ".$HOST.$INDEX."?action=game&me=".$hash."\n" ;
1891                       $message .= $link;
1892                     }
1893                   $message .= "\n\n (you can use reply all on this email to reach all the players.)\n\n";
1894                   mymail($userids,$gameid, GAME_OVER, $message);
1895               }
1896           }
1897         else
1898           {
1899             echo "can't find that card?! <br />\n";
1900           }
1901       }
1902     else if(myisset('card') && !$myturn )
1903       {
1904         echo _("please wait until it's your turn!")."<br />\n";
1905       }
1906
1907     if($seq!=4 && $trickNR>=1 && !(myisset('card') && $myturn) )
1908       echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1909
1910     /* display points in case game is over */
1911     if($mystatus=='gameover' && DB_get_game_status_by_gameid($gameid)=='gameover' )
1912       {
1913         echo "  <li onclick=\"hl('13');\" class=\"current\"><a href=\"#\">"._('Score')."</a>\n".
1914           "    <div class=\"trick\" id=\"trick13\">\n";
1915         /* add pic for re/contra
1916          "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";*/
1917
1918         $result = DB_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party,Hand.position FROM Hand".
1919                            " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1920                            " LEFT JOIN User ON User.id=Hand.user_id".
1921                            " LEFT JOIN Play ON Trick.id=Play.trick_id".
1922                            " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1923                            " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1924                            " WHERE Hand.game_id='$gameid'".
1925                            " GROUP BY User.fullname" );
1926         while( $r = DB_fetch_array($result))
1927           echo "      <div class=\"card".($r[3]-1)."\">\n".
1928             "        <div class=\"score\">".$r[2]."<br /> ".$r[1]."</div>\n".
1929             "      </div>\n";
1930
1931         /* display totals */
1932         $result = DB_query("SELECT Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1933                            " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1934                            " LEFT JOIN User ON User.id=Hand.user_id".
1935                            " LEFT JOIN Play ON Trick.id=Play.trick_id".
1936                            " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1937                            " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1938                            " WHERE Hand.game_id='$gameid'".
1939                            " GROUP BY Hand.party" );
1940         echo "<div class=\"total\">\n  Totals:<br />\n";
1941         while( $r = DB_fetch_array($result))
1942           echo "  ".$r[0]." ".$r[1]."<br />\n";
1943
1944         $queryresult = DB_query("SELECT timediff(mod_date,create_date) ".
1945                                 " FROM Game WHERE id='$gameid'");
1946         $r = DB_fetch_array($queryresult);
1947         echo "  <p>This game took ".$r[0]." hours.</p>\n";
1948
1949         echo "  <div class=\"re\">\n   Points Re: <br />\n";
1950         $queryresult = DB_query("SELECT score FROM Score ".
1951                                 "  WHERE game_id=$gameid AND party='re'".
1952                                 " ");
1953         while($r = DB_fetch_array($queryresult) )
1954           echo "   ".$r[0]."<br />\n";
1955         echo "  </div>\n";
1956
1957         echo "  <div class=\"contra\">\n   Points Contra: <br />\n";
1958         $queryresult = DB_query("SELECT score FROM Score ".
1959                                 "  WHERE game_id=$gameid AND party='contra'".
1960                                 " ");
1961         while($r = DB_fetch_array($queryresult) )
1962           echo "   ".$r[0]."<br />\n";
1963         echo "  </div>\n";
1964
1965         echo "</div>\n";
1966
1967         echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1968       }
1969
1970     echo "  <li onclick=\"hl_prev();\" class=\"old\"><a href=\"#\">"._('prev')."</a></li>\n";
1971     echo "  <li onclick=\"hl_next();\" class=\"old\"><a href=\"#\">"._('next')."</a></li>\n";
1972     echo "</ul>\n"; /* end ul tricks*/
1973
1974     $mycards = DB_get_hand($me);
1975     $mycards = mysort($mycards,$gametype);
1976     echo "<div class=\"mycards\">\n";
1977
1978     if($myturn && !myisset('card') && $mystatus=='play' )
1979       {
1980         echo "Hello ".$myname.", it's your turn!  <br />\n";
1981         echo _('Your cards are').": <br />\n";
1982
1983         /* do we have to follow suite? */
1984         $followsuit = 0;
1985         if(have_suit($mycards,$firstcard))
1986           $followsuit = 1;
1987
1988         /* count how many cards we can play, so that we can pre-select it if there is only one */
1989         $howmanycards = 0;
1990         foreach($mycards as $card)
1991           {
1992             if($howmanycards>1)
1993               break;
1994
1995             /* display only cards that the player is allowed to play as links, the rest just display normal
1996              * also check if we have both schweinchen, in that case only display on of them as playable
1997              */
1998             if( ($followsuit && !same_type($card,$firstcard)) ||
1999                 ( (int)($card)==19 &&
2000                   !$GAME['schweinchen-first'] &&
2001                   ( $RULES['schweinchen']=='second' ||
2002                     ( $RULES['schweinchen']=='secondaftercall' &&
2003                      (DB_get_call_by_hash($GAME['schweinchen-who']) ||
2004                       DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
2005                     )
2006                   ) &&
2007                   $GAME['schweinchen-who']==$me &&
2008                   in_array($gametype,array('normal','wedding','trump','silent'))
2009                   )
2010                 )
2011               continue;
2012             else
2013               $howmanycards++;
2014           }
2015
2016         if($howmanycards==1)
2017           $howmanycards=1;
2018         else
2019           $howmanycards=0;
2020
2021         foreach($mycards as $card)
2022           {
2023             /* display only cards that the player is allowed to play as links, the rest just display normal
2024              * also check if we have both schweinchen, in that case only display on of them as playable
2025              */
2026             if( ($followsuit && !same_type($card,$firstcard)) ||
2027                 ( (int)($card)==19 &&
2028                   !$GAME['schweinchen-first'] &&
2029                   ( $RULES['schweinchen']=='second' ||
2030                     ( $RULES['schweinchen']=='secondaftercall' &&
2031                      (DB_get_call_by_hash($GAME['schweinchen-who']) ||
2032                       DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
2033                     )
2034                   ) &&
2035                   $GAME['schweinchen-who']==$me &&
2036                   in_array($gametype,array('normal','wedding','trump','silent'))
2037                   )
2038                 )
2039               display_card($card,$PREF['cardset']);
2040             else
2041               display_link_card($card,$PREF['cardset'],$type='card',$selected=$howmanycards);
2042           }
2043       }
2044     else if($mystatus=='play' )
2045       {
2046         echo _('Your cards are').": <br />\n";
2047         foreach($mycards as $card)
2048           display_card($card,$PREF['cardset']);
2049       }
2050     else if($mystatus=='gameover')
2051       {
2052         $oldcards = DB_get_all_hand($me);
2053         $oldcards = mysort($oldcards,$gametype);
2054
2055         if(isset($_SESSION['id']) && $myid==$_SESSION['id'])
2056           echo _('Your cards were').": <br />\n";
2057         else
2058           {
2059             $name = DB_get_name('userid',$myid);
2060             echo "$name's were: <br />\n";
2061           }
2062
2063         foreach($oldcards as $card)
2064           display_card($card,$PREF['cardset']);
2065
2066         $userids = DB_get_all_userid_by_gameid($gameid);
2067         foreach($userids as $user)
2068           {
2069             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
2070
2071             if($userhash!=$me)
2072               {
2073                 echo "<br />";
2074
2075                 $name = DB_get_name('userid',$user);
2076                 $oldcards = DB_get_all_hand($userhash);
2077                 $oldcards = mysort($oldcards,$gametype);
2078                 echo "$name's cards were: <br />\n";
2079                 foreach($oldcards as $card)
2080                   display_card($card,$PREF['cardset']);
2081               }
2082           };
2083       }
2084     echo "</div>\n";
2085
2086     /* if the game is over do some extra stuff, therefore exit the swtich statement if we are still playing*/
2087     if($mystatus=='play')
2088       break;
2089
2090     /* the following happens only when the gamestatus is 'gameover' */
2091     /* check if game is over, display results */
2092     if(DB_get_game_status_by_gameid($gameid)=='play')
2093       {
2094         echo _('The game is over for you... other people still need to play though');
2095       }
2096     break;
2097   default:
2098     myerror("error in testing the status");
2099   }
2100
2101 /* output other games where it is the users turn
2102  * make sure that the people looking at old games don't see the wrong games here
2103  */
2104 if( $gamestatus != 'gameover' )
2105   {
2106     /* game isn't over, only valid user can get here, so show menu */
2107     display_user_menu($myid);
2108   }
2109 else if(  $origmystatus != 'gameover' )
2110   {
2111     /* user just played the very last card, game is now over, it's still ok to show the menu though */
2112     display_user_menu($myid);
2113   }
2114 else if(  $mystatus == 'gameover' &&
2115           isset($_SESSION['id']) )
2116   {
2117     /* user is looking at someone else's game, show the menu for the correct user */
2118     display_user_menu($_SESSION['id']);
2119   }
2120 else
2121   {
2122     echo "<div class=\"usermenu\">\n";
2123     echo "It's your turn in these games:<br />\n";
2124     echo "Please log in to see this information.\n";
2125     echo "</div>\n";
2126   }
2127
2128 /*
2129  * display gameinfo: re/contra, comment-box, play-card button, games played by others
2130  */
2131
2132 echo "<div class=\"gameinfo\">\n";
2133
2134 /* get time from the last action of the game */
2135 $r = DB_query_array("SELECT mod_date from Game WHERE id='$gameid' " );
2136 $gameend = time() - strtotime($r[0]);
2137
2138 /* comment box */
2139 if($gamestatus == 'play' || $gameend < 60*60*24*7)
2140   {
2141     echo '  '._('A short comment').":<input name=\"comment\" type=\"text\" size=\"20\" maxlength=\"100\" />\n";
2142   }
2143
2144 /* re-contra */
2145 if($gamestatus == 'play' )
2146   {
2147     $myparty = DB_get_party_by_hash($me);
2148     output_form_calls($me,$myparty);
2149   }
2150
2151 /* play-card button */
2152 if($gamestatus == 'play' || $gameend < 60*60*24*7)
2153   {
2154     echo "  <input type=\"submit\" value=\""._('submit')."\" />\n";
2155   }
2156
2157 /* has this hand been played by others? */
2158 $other_game_ids = DB_played_by_others($gameid);
2159 if(sizeof($other_game_ids)>0 && $mystatus=='gameover')
2160   {
2161     $mypos = DB_get_pos_by_hash($me);
2162     echo "  <p>See how other played the same hand: \n";
2163     foreach($other_game_ids as $id)
2164       {
2165         $otherhash = DB_get_hash_from_game_and_pos($id,$mypos);
2166         $othername = DB_get_name('hash',$otherhash);
2167         echo "    <a href=\"$INDEX?action=game&amp;me=$otherhash\">$othername</a> ";
2168       }
2169     echo "  </p>\n";
2170   }
2171
2172 echo "</div>\n"; /* end gameinfo */
2173
2174 /* make sure that we don't show the notes to the wrong person
2175  * (e.g. other people looking at an old game)
2176  */
2177 if( $mystatus != 'gameover' ||
2178     (  $mystatus == 'gameover' &&
2179        isset($_SESSION['id'])  &&
2180        $myid == $_SESSION['id']))
2181   output_user_notes($myid,$gameid,$mystatus);
2182
2183 echo "</form>\n";
2184
2185 $gamestatus = DB_get_game_status_by_gameid($gameid);
2186 if($mystatus=='gameover' &&
2187    ($gamestatus =='gameover' || $gamestatus =='cancel-nines' || $gamestatus =='cancel-trump') &&
2188    isset($_SESSION['id']) && $_SESSION['id']==$myid)
2189   {
2190     $session = DB_get_session_by_gameid($gameid);
2191     $result  = DB_query("SELECT id,create_date FROM Game".
2192                         " WHERE session=$session".
2193                         " ORDER BY create_date DESC".
2194                         " LIMIT 1");
2195     $r = -1;
2196     if($result)
2197       $r = DB_fetch_array($result);
2198
2199     if(!$session || $gameid==$r[0])
2200       {
2201         /* suggest a new game with the same people in it, just rotated once (unless last game was solo) */
2202         $names = DB_get_all_names_by_gameid($gameid);
2203         $type  = DB_get_gametype_by_gameid($gameid);
2204
2205         if($type=='solo')
2206           {
2207             $solo = DB_get_solo_by_gameid($gameid);
2208
2209             if($solo!='silent') /* repeat game with same first player */
2210               output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
2211             else /* rotate normally */
2212               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
2213           }
2214         else if($gamestatus == 'cancel-nines' || $gamestatus == 'cancel-trump')
2215           output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
2216         else /* rotate normally */
2217           output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
2218       }
2219   }
2220 ?>