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