added autofocus to login page
[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 they 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     $mygamesolo = DB_get_solo_by_gameid($gameid);
1296     if($mygametype != 'normal') /* only show when needed */
1297       if(!( $mygametype == 'solo' && $mygamesolo == 'silent') )
1298         {
1299           echo "  <li onclick=\"hl('0');\" class=\"current\"><a href=\"#\">Pre</a>\n".
1300             "    <div class=\"trick\" id=\"trick0\">\n";
1301
1302           /* get information so show the cards that have been handed over in a poverty game */
1303           output_exchanged_cards();
1304
1305           echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1306         }
1307
1308     /* output tricks */
1309     while($r = DB_fetch_array($result))
1310       {
1311         $pos     = $r[1];
1312         $seq     = $r[2];
1313         $trick   = $r[3];
1314         $comment = $r[4];
1315         $user    = $r[6];
1316
1317         /* count number of tricks */
1318         if($seq==1)
1319           $trickNR++;
1320
1321         /* check if first schweinchen has been played */
1322         if( $GAME['schweinchen-who'] && ($r[0] == 19 || $r[0] == 20) )
1323           if(!$GAME['schweinchen-first'])
1324             $GAME['schweinchen-first'] = 1; /* playing the first fox */
1325           else
1326             $GAME['schweinchen-second'] = 1; /* this must be the second fox */
1327
1328         /* save card to be able to find the winner of the trick later */
1329         $play[$seq] = array('card'=>$r[0],'pos'=>$pos);
1330
1331         if($seq==1)
1332           {
1333             /* first card in a trick, output some html */
1334             if($trick!=$lasttrick)
1335               {
1336                 /* start of an old trick? */
1337                 echo "  <li onclick=\"hl('$trickNR');\" class=\"old\"><a href=\"#\">"._('Trick')." $trickNR</a>\n".
1338                   "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1339                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1340               }
1341             else if($trick==$lasttrick)
1342               {
1343                 /* start of a last trick? */
1344                 echo "  <li onclick=\"hl('$trickNR');\" class=\"current\"><a href=\"#\">"._('Trick')." $trickNR</a>\n".
1345                   "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1346                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1347               };
1348
1349             /* remember first card, so that we are able to check, what cards can be played */
1350             $firstcard = $r[0];
1351           };
1352
1353         /* display card */
1354         echo "      <div class=\"card".($pos-1)."\">\n";
1355
1356         /* display comments */
1357         if($comment!='')
1358           echo "        <span class=\"comment\">".$comment."</span>\n";
1359
1360         echo '        ';
1361         display_card($r[0],$PREF['cardset']);
1362
1363         echo "      </div>\n"; /* end div card */
1364
1365         /* end of trick? */
1366         if($seq==4)
1367           {
1368             $winner    = get_winner($play,$gametype); /* returns the position */
1369             echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1370           }
1371       }
1372
1373     /* whos turn is it? */
1374     if($seq==4)
1375       {
1376         $winner    = get_winner($play,$gametype); /* returns the position */
1377         $next      = $winner;
1378         $firstcard = ''; /* new trick, no first card */
1379       }
1380     else
1381       {
1382         $next = $pos+1;
1383         if($next==5) $next = 1;
1384       }
1385
1386     /* my turn?, display cards as links, ask for comments*/
1387     if(DB_get_pos_by_hash($me) == $next)
1388       $myturn = 1;
1389     else
1390       $myturn = 0;
1391
1392     /* do we want to play a card? */
1393     if(myisset('card') && $myturn)
1394       {
1395         $card   = $_REQUEST['card'];
1396         $handid = DB_get_handid('hash',$me);
1397         $commentSchweinchen =''; /* used to add a comment when Schweinchen is being played */
1398
1399         /* check if we have card and that we haven't played it yet*/
1400         /* set played in hand_card to true where hand_id and card_id*/
1401         $r = DB_query_array("SELECT id FROM Hand_Card WHERE played='false' and ".
1402                               "hand_id='$handid' AND card_id=".DB_quote_smart($card));
1403         $handcardid = $r[0];
1404
1405         if($handcardid) /* everything ok, play card  */
1406           {
1407             /* update Game timestamp */
1408             DB_update_game_timestamp($gameid);
1409
1410             /* mark card as played */
1411             DB_query("UPDATE Hand_Card SET played='true' WHERE hand_id='$handid' AND card_id=".
1412                      DB_quote_smart($card));
1413
1414             /* get trick id or start new trick */
1415             $a = DB_get_current_trickid($gameid);
1416             $trickid  = $a[0];
1417             $sequence = $a[1];
1418             $tricknr  = $a[2];
1419
1420             $playid = DB_play_card($trickid,$handcardid,$sequence);
1421
1422             /* check special output for schweinchen in case in case a fox is being played
1423              * check for correct rules, etc. has already been done
1424              */
1425             if( $GAME['schweinchen-who'] && ($card == 19 || $card == 20) )
1426               {
1427                 if(!$GAME['schweinchen-first'])
1428                   $GAME['schweinchen-first'] = 1; /* playing the first fox */
1429                 else
1430                   $GAME['schweinchen-second'] = 1; /* this must be the second fox */
1431
1432                 if( $RULES['schweinchen']=='both' ||
1433                     ($RULES['schweinchen']=='second' && $GAME['schweinchen-second']==1 )||
1434                     ($RULES['schweinchen']=='secondaftercall' && $GAME['schweinchen-second']==1 &&
1435                      (DB_get_call_by_hash($GAME['schweinchen-who']) || DB_get_partner_call_by_hash($GAME['schweinchen-who']) ))
1436                   )
1437                   {
1438                     DB_insert_comment('Schweinchen! ',$playid,$myid);
1439                     $commentSchweinchen = 'Schweinchen! ';
1440                   }
1441                 if ($debug)
1442                   echo 'schweinchen = '.$GAME['schweinchen-who'].' ---<br />';
1443               }
1444
1445             /* if sequence == 4 check who one in case of wedding */
1446             if($sequence == 4 && $GT == 'wedding')
1447               {
1448                 /* is wedding resolve */
1449                 $resolved = DB_get_sickness_by_gameid($gameid);
1450                 if($resolved<0)
1451                   {
1452                     /* who has wedding */
1453                     $userids = DB_get_all_userid_by_gameid($gameid);
1454                     foreach($userids as $user)
1455                       {
1456                         $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
1457                         if($usersick == 'wedding')
1458                           $whosick = $user;
1459                       }
1460                     /* who won the trick */
1461                     $play     = DB_get_cards_by_trick($trickid);
1462                     $winner   = get_winner($play,$gametype); /* returns the position */
1463                     $winnerid = DB_get_userid('gameid-position',$gameid,$winner);
1464                     /* is tricknr <=3 */
1465                     if($tricknr <=3 && $winnerid!=$whosick)
1466                       {
1467                         /* set resolved at tricknr*/
1468                         $resolved = DB_set_sickness_by_gameid($gameid,$tricknr);
1469                         /* set partner */
1470                         $whash = DB_get_hash_from_gameid_and_userid($gameid,$winnerid);
1471                         DB_set_party_by_hash($whash,'re');
1472                       }
1473                     if($tricknr == 3 && $winnerid==$whosick)
1474                       {
1475                         /* set resolved at tricknr*/
1476                         $resolved = DB_set_sickness_by_gameid($gameid,'3');
1477                       }
1478                   }
1479               }
1480
1481             /* if sequence == 4, set winner of the trick, count points and set the next player */
1482             if($sequence==4)
1483               {
1484                 $play   = DB_get_cards_by_trick($trickid);
1485                 $winner = get_winner($play,$gametype); /* returns the position */
1486
1487                 /*
1488                  * check if someone caught a fox
1489                  *******************************/
1490
1491                 /* first check if we should account for solos at all,
1492                  * since it doesn't make sense in some games
1493                  */
1494                 $ok = 0; /* fox shouldn't be counted */
1495                 if(DB_get_gametype_by_gameid($gameid)=='solo')
1496                   {
1497                     $solo = DB_get_solo_by_gameid($gameid);
1498                     if($solo == 'trump' || $solo == 'silent')
1499                       $ok = 1; /* for trump solos and silent solos, foxes are ok */
1500                   }
1501                 else
1502                   $ok = 1; /* for all other games (not solos) foxes are ok too */
1503
1504                 if($ok==1)
1505                   foreach($play as $played)
1506                     {
1507                       if ( $played['card']==19 || $played['card']==20 )
1508                         if ($played['pos']!= $winner )
1509                           {
1510                             /* possible caught a fox, check party */
1511                             $uid1 = DB_get_userid('gameid-position',$gameid,$winner);
1512                             $uid2 = DB_get_userid('gameid-position',$gameid,$played['pos']);
1513
1514                             $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1515                             $party2 = DB_get_party_by_gameid_and_userid($gameid,$uid2);
1516
1517                             if($party1 != $party2)
1518                               DB_query("INSERT INTO Score".
1519                                        " VALUES( NULL,NULL,$gameid,'$party1',$uid1,$uid2,'fox')");
1520                           }
1521                     }
1522
1523                 /*
1524                  * check for karlchen (jack of clubs in the last trick)
1525                  ******************************************************/
1526
1527                 /* same as for foxes, karlchen doesn't always make sense
1528                  * check what kind of game it is and set karlchen accordingly */
1529
1530                 if($tricknr == 12 ) /* Karlchen works only in the last trick */
1531                   {
1532                     /* check for solo */
1533                     $solo = 'none';
1534                     if(DB_get_gametype_by_gameid($gameid)=='solo' )
1535                       $solo = DB_get_solo_by_gameid($gameid);
1536
1537                     /* no Karlchen in these solos */
1538                     if($solo != 'trumpless' && $solo != 'jack' && $solo != 'queen' )
1539                       {
1540                         foreach($play as $played)
1541                           if ( $played['card']==11 || $played['card']==12 )
1542                             if ($played['pos'] == $winner )
1543                               {
1544                                 /* save Karlchen */
1545                                 $uid1   = DB_get_userid('gameid-position',$gameid,$winner);
1546                                 $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1547
1548                                 DB_query("INSERT INTO Score".
1549                                          " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'karlchen')");
1550                               };
1551                       };
1552                   }; /* end scoring Karlchen */
1553
1554                 /*
1555                  * check for doppelopf (>40 points)
1556                  ***********************************/
1557
1558                 $points = 0;
1559                 foreach($play as $played)
1560                   {
1561                     $points += DB_get_card_value_by_cardid($played['card']);
1562                   }
1563                 if($points > 39)
1564                   {
1565                     $uid1   = DB_get_userid('gameid-position',$gameid,$winner);
1566                     $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1567
1568                     DB_query("INSERT INTO Score".
1569                              " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'doko')");
1570                   }
1571
1572                 /*
1573                  * set winner (for this trick)
1574                  */
1575
1576                 if($winner>0)
1577                   DB_query("UPDATE Trick SET winner='$winner' WHERE id='$trickid'");
1578                 else
1579                   echo "ERROR during scoring";
1580
1581                 if($debug)
1582                   echo "DEBUG: position $winner won the trick <br />";
1583
1584                 /* who is the next player? */
1585                 $next = $winner;
1586               }
1587             else
1588               {
1589                 $next = DB_get_pos_by_hash($me)+1;
1590               }
1591             if($next==5) $next=1;
1592
1593             /* check for coment */
1594             if(myisset('comment'))
1595               {
1596                 $comment = $_REQUEST['comment'];
1597                 if($comment != '')
1598                   DB_insert_comment($comment,$playid,$myid);
1599                 if($commentSchweinchen)
1600                   $comment = $commentSchweinchen . $comment;
1601               };
1602
1603             /* display played card */
1604             $pos = DB_get_pos_by_hash($me);
1605             if($sequence==1)
1606               {
1607                 echo "  <li onclick=\"hl('".($tricknr)."');\" class=\"current\"><a href=\"#\">"._('Trick').' '.($tricknr)."</a>\n".
1608                   "    <div class=\"trick\" id=\"trick".($tricknr)."\">\n".
1609                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1610               }
1611
1612             echo "      <div class=\"card".($pos-1)."\">\n        ";
1613
1614             /* display comments */
1615             display_card($card,$PREF['cardset']);
1616             if($comment!='')
1617               echo "\n        <span class=\"comment\"> ".$comment."</span>\n";
1618             echo "      </div>\n";
1619
1620             echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1621
1622             /*check if we still have cards left, else set status to gameover */
1623             if(sizeof(DB_get_hand($me))==0)
1624               {
1625                 DB_set_hand_status_by_hash($me,'gameover');
1626                 $mystatus = 'gameover';
1627               }
1628
1629             /* if all players are done, set game status to game over,
1630              * get the points of the last trick and send out an email
1631              * to all players
1632              */
1633             $userids = DB_get_all_userid_by_gameid($gameid);
1634
1635             $done=1;
1636             foreach($userids as $user)
1637               if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
1638                 $done=0;
1639
1640             if($done)
1641               DB_set_game_status_by_gameid($gameid,'gameover');
1642
1643             /* email next player, if game is still running */
1644             if(DB_get_game_status_by_gameid($gameid)=='play')
1645               {
1646                 $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
1647                 $who       = DB_get_userid('hash',$next_hash);
1648                 DB_set_player_by_gameid($gameid,$who);
1649
1650                 $message = "A card has been played in game ".DB_format_gameid($gameid).".\n\n".
1651                   "It's your turn  now.\n".
1652                   "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$next_hash."\n\n" ;
1653                 if( DB_get_email_pref_by_uid($who)!='emailaddict' )
1654                   {
1655                     $subject = 'A card has been played in game '.DB_format_gameid($gameid);
1656                     mymail($who,$subject,$message);
1657                   }
1658               }
1659             else /* send out final email */
1660               {
1661                 /* individual score */
1662                 $result = DB_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party FROM Hand".
1663                                    " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1664                                    " LEFT JOIN User ON User.id=Hand.user_id".
1665                                    " LEFT JOIN Play ON Trick.id=Play.trick_id".
1666                                    " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1667                                    " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1668                                    " WHERE Hand.game_id='$gameid'".
1669                                    " GROUP BY User.fullname" );
1670                 $message  = "The game is over. Thanks for playing :)\n";
1671                 $message .= "Final score:\n";
1672                 while( $r = DB_fetch_array($result) )
1673                   $message .= "   ".$r[0]."(".$r[2].") ".$r[1]."\n";
1674
1675                 $result = DB_query("SELECT  Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1676                                    " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1677                                    " LEFT JOIN User ON User.id=Hand.user_id".
1678                                    " LEFT JOIN Play ON Trick.id=Play.trick_id".
1679                                    " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1680                                    " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1681                                    " WHERE Hand.game_id='$gameid'".
1682                                    " GROUP BY Hand.party" );
1683                 $message .= "\nTotals:\n";
1684                 $re     = 0;
1685                 $contra = 0;
1686                 while( $r = DB_fetch_array($result) )
1687                   {
1688                     $message .= "    ".$r[0]." ".$r[1]."\n";
1689                     if($r[0] == 're')
1690                       $re = $r[1];
1691                     else if($r[0] == 'contra')
1692                       $contra = $r[1];
1693                   }
1694
1695                 /*
1696                  * save score in database
1697                  *
1698                  */
1699
1700                 /* get calls from re/contra */
1701                 $call_re     = NULL;
1702                 $call_contra = NULL;
1703                 foreach($userids as $user)
1704                   {
1705                     $hash  = DB_get_hash_from_gameid_and_userid($gameid,$user);
1706                     $call  = DB_get_call_by_hash($hash);
1707                     $party = DB_get_party_by_hash($hash);
1708
1709                     if($call!=NULL)
1710                       {
1711                         $call = (int) $call;
1712
1713                         if($party=='re')
1714                           {
1715                             if($call_re==NULL)
1716                               $call_re = $call;
1717                             else if( $call < $call_re)
1718                               $call_re = $call;
1719                           }
1720                         else if($party=='contra')
1721                           {
1722                             if($call_contra==NULL)
1723                               $call_contra = $call;
1724                             else if( $call < $call_contra)
1725                               $call_contra = $call;
1726                           }
1727                       }
1728                   }
1729
1730                 /* figure out who one */
1731                 $winning_party = NULL;
1732
1733                 if($call_re == NULL && $call_contra==NULL)
1734                   {
1735                     /* nobody made a call, so it's easy to figure out who won */
1736                     if($re>120)
1737                       $winning_party='re';
1738                     else
1739                       $winning_party='contra';
1740                   }
1741                 else
1742                   {
1743                     /* if one party makes a call, they only win, iff they make enough points
1744                      * if only one party made a call, the other one wins,
1745                      * if the first one didn't make it
1746                      */
1747                     if($call_re)
1748                       {
1749                         $offset = 120 - $call_re;
1750                         if($call_re == 0)
1751                           $offset--; /* since we use a > in the next equation */
1752
1753                         if($re > 120+$offset)
1754                           $winning_party='re';
1755                         else if ($call_contra == NULL )
1756                           $winning_party='contra';
1757                       }
1758
1759                     if($call_contra)
1760                       {
1761                         $offset = 120 - $call_contra;
1762                         if($call_contra == 0)
1763                           $offset--; /* since we use a > in the next equation */
1764
1765                         if($contra > 120+$offset)
1766                           $winning_party='contra';
1767                         else if ($call_re == NULL )
1768                           $winning_party='re';
1769                       }
1770                   }
1771
1772                 /* one point for each call of the other party in case the other party didn't win
1773                  * and one point each in case the party made more than points than one of the calls
1774                  */
1775                 if($winning_party!='contra' && $call_contra!=NULL)
1776                   {
1777                     for( $p=$call_contra;$p<=120; $p+=30 )
1778                       {
1779                           DB_query("INSERT INTO Score".
1780                                    " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'against$p')");
1781                         }
1782
1783                       for( $p=$call_contra; $p<120; $p+=30)
1784                         {
1785                           if( $re >= $p )
1786                             DB_query("INSERT INTO Score".
1787                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'made$p')");
1788                         }
1789                     }
1790                   if($winning_party!='re' and $call_re!=NULL)
1791                     {
1792                       for( $p=$call_re;$p<=120; $p+=30 )
1793                         {
1794                           DB_query("INSERT INTO Score".
1795                                    " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'against$p')");
1796                         }
1797
1798                       for( $p=$call_re; $p<120; $p+=30)
1799                         {
1800                           if( $contra>=$p )
1801                             DB_query("INSERT INTO Score".
1802                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'made$p')");
1803                         }
1804                     }
1805
1806                   /* point in case contra won */
1807                   if($winning_party=='contra')
1808                     {
1809                       DB_query("INSERT INTO Score".
1810                                " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'againstqueens')");
1811                     }
1812
1813                   /* one point each for winning and each 30 points + calls */
1814                   if($winning_party=='re')
1815                     {
1816                       foreach(array(120,150,180,210,240) as $p)
1817                         {
1818                           $offset = 0;
1819                           if($p==240 || $call_contra!=NULL)
1820                             $offset = 1;
1821
1822                           if($re>$p-$offset)
1823                             DB_query("INSERT INTO Score".
1824                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'".(240-$p)."')");
1825                         }
1826                       /* re called something and won */
1827                       foreach(array(0,30,60,90,120) as $p)
1828                         {
1829                           if($call_re!=NULL && $call_re<$p+1)
1830                             DB_query("INSERT INTO Score".
1831                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'call$p')");
1832                         }
1833                     }
1834                   else if( $winning_party=='contra')
1835                     {
1836                       foreach(array(120,150,180,210,240) as $p)
1837                         {
1838                           $offset = 0;
1839                           if($p==240 || $call_re!=NULL)
1840                             $offset = 1;
1841
1842                           if($contra>$p-$offset)
1843                             DB_query("INSERT INTO Score".
1844                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'".(240-$p)."')");
1845                         }
1846                       /* re called something and won */
1847                       foreach(array(0,30,60,90,120) as $p)
1848                         {
1849                           if($call_contra!=NULL && $call_contra<$p+1)
1850                             DB_query("INSERT INTO Score".
1851                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'call$p')");
1852                         }
1853                     }
1854
1855
1856                   /* add score points to email */
1857                   $message .= "\n";
1858                   $Tpoint = 0;
1859                   $message .= " Points Re: \n";
1860                   $queryresult = DB_query("SELECT score FROM Score ".
1861                                           "  WHERE game_id=$gameid AND party='re'".
1862                                           " ");
1863                   while($r = DB_fetch_array($queryresult) )
1864                     {
1865                       $message .= "   ".$r[0]."\n";
1866                       $Tpoint ++;
1867                     }
1868                   $message .= " Points Contra: \n";
1869                   $queryresult = DB_query("SELECT score FROM Score ".
1870                                           "  WHERE game_id=$gameid AND party='contra'".
1871                                           " ");
1872                   while($r = DB_fetch_array($queryresult) )
1873                     {
1874                       $message .= "   ".$r[0]."\n";
1875                       $Tpoint --;
1876                     }
1877                   $message .= " Total Points (from the Re point of view): $Tpoint\n";
1878                   $message .= "\n";
1879
1880                   $session = DB_get_session_by_gameid($gameid);
1881                   $score = generate_score_table($session);
1882
1883                   $message .= "Score Table:\n";
1884                   $message .= format_score_table_ascii($score);
1885                   $message .= "\nUse these links to have a look at game ".DB_format_gameid($gameid).": \n";
1886
1887                   /* send out final email */
1888                   foreach($userids as $user)
1889                     {
1890                       /* add links for all players */
1891                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1892                       $name = DB_get_name('userid',$user);
1893
1894                       $link = "$name: ".$HOST.$INDEX."?action=game&me=".$hash."\n" ;
1895                       $message .= $link;
1896                     }
1897                   $message .= "\n\n (you can use reply all on this email to reach all the players.)\n\n";
1898                   $subject = ' Game over (game '.DB_format_gameid($gameid).') ';
1899                   mymail($userids,$subject,$message);
1900               }
1901           }
1902         else
1903           {
1904             echo "can't find that card?! <br />\n";
1905           }
1906       }
1907     else if(myisset('card') && !$myturn )
1908       {
1909         echo _("please wait until it's your turn!")."<br />\n";
1910       }
1911
1912     if($seq!=4 && $trickNR>=1 && !(myisset('card') && $myturn) )
1913       echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1914
1915     /* display points in case game is over */
1916     if($mystatus=='gameover' && DB_get_game_status_by_gameid($gameid)=='gameover' )
1917       {
1918         echo "  <li onclick=\"hl('13');\" class=\"current\"><a href=\"#\">"._('Score')."</a>\n".
1919           "    <div class=\"trick\" id=\"trick13\">\n";
1920         /* add pic for re/contra
1921          "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";*/
1922
1923         $result = DB_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party,Hand.position FROM Hand".
1924                            " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1925                            " LEFT JOIN User ON User.id=Hand.user_id".
1926                            " LEFT JOIN Play ON Trick.id=Play.trick_id".
1927                            " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1928                            " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1929                            " WHERE Hand.game_id='$gameid'".
1930                            " GROUP BY User.fullname" );
1931         while( $r = DB_fetch_array($result))
1932           echo "      <div class=\"card".($r[3]-1)."\">\n".
1933             "        <div class=\"score\">".$r[2]."<br /> ".$r[1]."</div>\n".
1934             "      </div>\n";
1935
1936         /* display totals */
1937         $result = DB_query("SELECT Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1938                            " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1939                            " LEFT JOIN User ON User.id=Hand.user_id".
1940                            " LEFT JOIN Play ON Trick.id=Play.trick_id".
1941                            " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1942                            " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1943                            " WHERE Hand.game_id='$gameid'".
1944                            " GROUP BY Hand.party" );
1945         echo "<div class=\"total\">\n  Totals:<br />\n";
1946         while( $r = DB_fetch_array($result))
1947           echo "  ".$r[0]." ".$r[1]."<br />\n";
1948
1949         $queryresult = DB_query("SELECT timediff(mod_date,create_date) ".
1950                                 " FROM Game WHERE id='$gameid'");
1951         $r = DB_fetch_array($queryresult);
1952         echo "  <p>This game took ".$r[0]." hours.</p>\n";
1953
1954         echo "  <div class=\"re\">\n   Points Re: <br />\n";
1955         $queryresult = DB_query("SELECT score FROM Score ".
1956                                 "  WHERE game_id=$gameid AND party='re'".
1957                                 " ");
1958         while($r = DB_fetch_array($queryresult) )
1959           echo "   ".$r[0]."<br />\n";
1960         echo "  </div>\n";
1961
1962         echo "  <div class=\"contra\">\n   Points Contra: <br />\n";
1963         $queryresult = DB_query("SELECT score FROM Score ".
1964                                 "  WHERE game_id=$gameid AND party='contra'".
1965                                 " ");
1966         while($r = DB_fetch_array($queryresult) )
1967           echo "   ".$r[0]."<br />\n";
1968         echo "  </div>\n";
1969
1970         echo "</div>\n";
1971
1972         echo "    </div>\n  </li>\n";  /* end div trick, end li trick */
1973       }
1974
1975     echo "  <li onclick=\"hl_prev();\" class=\"old\"><a href=\"#\">"._('prev')."</a></li>\n";
1976     echo "  <li onclick=\"hl_next();\" class=\"old\"><a href=\"#\">"._('next')."</a></li>\n";
1977     echo "</ul>\n"; /* end ul tricks*/
1978
1979     $mycards = DB_get_hand($me);
1980     $mycards = mysort($mycards,$gametype);
1981     echo "<div class=\"mycards\">\n";
1982
1983     if($myturn && !myisset('card') && $mystatus=='play' )
1984       {
1985         echo "Hello ".$myname.", it's your turn!  <br />\n";
1986         echo _('Your cards are').": <br />\n";
1987
1988         /* do we have to follow suite? */
1989         $followsuit = 0;
1990         if(have_suit($mycards,$firstcard))
1991           $followsuit = 1;
1992
1993         /* count how many cards we can play, so that we can pre-select it if there is only one */
1994         $howmanycards = 0;
1995         foreach($mycards as $card)
1996           {
1997             if($howmanycards>1)
1998               break;
1999
2000             /* display only cards that the player is allowed to play as links, the rest just display normal
2001              * also check if we have both schweinchen, in that case only display on of them as playable
2002              */
2003             if( ($followsuit && !same_type($card,$firstcard)) ||
2004                 ( (int)($card)==19 &&
2005                   !$GAME['schweinchen-first'] &&
2006                   ( $RULES['schweinchen']=='second' ||
2007                     ( $RULES['schweinchen']=='secondaftercall' &&
2008                      (DB_get_call_by_hash($GAME['schweinchen-who']) ||
2009                       DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
2010                     )
2011                   ) &&
2012                   $GAME['schweinchen-who']==$me &&
2013                   in_array($gametype,array('normal','wedding','trump','silent'))
2014                   )
2015                 )
2016               continue;
2017             else
2018               $howmanycards++;
2019           }
2020
2021         if($howmanycards==1)
2022           $howmanycards=1;
2023         else
2024           $howmanycards=0;
2025
2026         foreach($mycards as $card)
2027           {
2028             /* display only cards that the player is allowed to play as links, the rest just display normal
2029              * also check if we have both schweinchen, in that case only display on of them as playable
2030              */
2031             if( ($followsuit && !same_type($card,$firstcard)) ||
2032                 ( (int)($card)==19 &&
2033                   !$GAME['schweinchen-first'] &&
2034                   ( $RULES['schweinchen']=='second' ||
2035                     ( $RULES['schweinchen']=='secondaftercall' &&
2036                      (DB_get_call_by_hash($GAME['schweinchen-who']) ||
2037                       DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
2038                     )
2039                   ) &&
2040                   $GAME['schweinchen-who']==$me &&
2041                   in_array($gametype,array('normal','wedding','trump','silent'))
2042                   )
2043                 )
2044               display_card($card,$PREF['cardset']);
2045             else
2046               display_link_card($card,$PREF['cardset'],$type='card',$selected=$howmanycards);
2047           }
2048       }
2049     else if($mystatus=='play' )
2050       {
2051         echo _('Your cards are').": <br />\n";
2052         foreach($mycards as $card)
2053           display_card($card,$PREF['cardset']);
2054       }
2055     else if($mystatus=='gameover')
2056       {
2057         $oldcards = DB_get_all_hand($me);
2058         $oldcards = mysort($oldcards,$gametype);
2059
2060         if(isset($_SESSION['id']) && $myid==$_SESSION['id'])
2061           echo _('Your cards were').": <br />\n";
2062         else
2063           {
2064             $name = DB_get_name('userid',$myid);
2065             echo "$name's were: <br />\n";
2066           }
2067
2068         foreach($oldcards as $card)
2069           display_card($card,$PREF['cardset']);
2070
2071         $userids = DB_get_all_userid_by_gameid($gameid);
2072         foreach($userids as $user)
2073           {
2074             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
2075
2076             if($userhash!=$me)
2077               {
2078                 echo "<br />";
2079
2080                 $name = DB_get_name('userid',$user);
2081                 $oldcards = DB_get_all_hand($userhash);
2082                 $oldcards = mysort($oldcards,$gametype);
2083                 echo "$name's cards were: <br />\n";
2084                 foreach($oldcards as $card)
2085                   display_card($card,$PREF['cardset']);
2086               }
2087           };
2088       }
2089     echo "</div>\n";
2090
2091     /* if the game is over do some extra stuff, therefore exit the swtich statement if we are still playing*/
2092     if($mystatus=='play')
2093       break;
2094
2095     /* the following happens only when the gamestatus is 'gameover' */
2096     /* check if game is over, display results */
2097     if(DB_get_game_status_by_gameid($gameid)=='play')
2098       {
2099         echo _('The game is over for you... other people still need to play though');
2100       }
2101     break;
2102   default:
2103     myerror("error in testing the status");
2104   }
2105
2106 /* output other games where it is the users turn
2107  * make sure that the people looking at old games don't see the wrong games here
2108  */
2109 if( $gamestatus != 'gameover' )
2110   {
2111     /* game isn't over, only valid user can get here, so show menu */
2112     display_user_menu($myid);
2113   }
2114 else if(  $origmystatus != 'gameover' )
2115   {
2116     /* user just played the very last card, game is now over, it's still ok to show the menu though */
2117     display_user_menu($myid);
2118   }
2119 else if(  $mystatus == 'gameover' &&
2120           isset($_SESSION['id']) )
2121   {
2122     /* user is looking at someone else's game, show the menu for the correct user */
2123     display_user_menu($_SESSION['id']);
2124   }
2125 else
2126   {
2127     echo "<div class=\"usermenu\">\n";
2128     echo "It's your turn in these games:<br />\n";
2129     echo "Please log in to see this information.\n";
2130     echo "</div>\n";
2131   }
2132
2133 /*
2134  * display gameinfo: re/contra, comment-box, play-card button, games played by others
2135  */
2136
2137 echo "<div class=\"gameinfo\">\n";
2138
2139 /* get time from the last action of the game */
2140 $r = DB_query_array("SELECT mod_date from Game WHERE id='$gameid' " );
2141 $gameend = time() - strtotime($r[0]);
2142
2143 /* comment box */
2144 if($gamestatus == 'play' || $gameend < 60*60*24*7)
2145   {
2146     echo '  '._('A short comment').":<input name=\"comment\" type=\"text\" size=\"20\" maxlength=\"100\" />\n";
2147   }
2148
2149 /* re-contra */
2150 if($gamestatus == 'play' )
2151   {
2152     $myparty = DB_get_party_by_hash($me);
2153     output_form_calls($me,$myparty);
2154   }
2155
2156 /* play-card button */
2157 if($gamestatus == 'play' || $gameend < 60*60*24*7)
2158   {
2159     echo "  <input type=\"submit\" value=\""._('submit')."\" />\n";
2160   }
2161
2162 /* has this hand been played by others? */
2163 $other_game_ids = DB_played_by_others($gameid);
2164 if(sizeof($other_game_ids)>0 && $mystatus=='gameover')
2165   {
2166     $mypos = DB_get_pos_by_hash($me);
2167     echo "  <p>See how other played the same hand: \n";
2168     foreach($other_game_ids as $id)
2169       {
2170         $otherhash = DB_get_hash_from_game_and_pos($id,$mypos);
2171         $othername = DB_get_name('hash',$otherhash);
2172         echo "    <a href=\"$INDEX?action=game&amp;me=$otherhash\">$othername</a> ";
2173       }
2174     echo "  </p>\n";
2175   }
2176
2177 echo "</div>\n"; /* end gameinfo */
2178
2179 echo "</form>\n";
2180
2181 $gamestatus = DB_get_game_status_by_gameid($gameid);
2182 if($mystatus=='gameover' &&
2183    ($gamestatus =='gameover' || $gamestatus =='cancel-nines' || $gamestatus =='cancel-trump') &&
2184    isset($_SESSION['id']) && $_SESSION['id']==$myid)
2185   {
2186     $session = DB_get_session_by_gameid($gameid);
2187     $result  = DB_query("SELECT id,create_date FROM Game".
2188                         " WHERE session=$session".
2189                         " ORDER BY create_date DESC".
2190                         " LIMIT 1");
2191     $r = -1;
2192     if($result)
2193       $r = DB_fetch_array($result);
2194
2195     if(!$session || $gameid==$r[0])
2196       {
2197         /* suggest a new game with the same people in it, just rotated once (unless last game was solo) */
2198         $names = DB_get_all_names_by_gameid($gameid);
2199         $type  = DB_get_gametype_by_gameid($gameid);
2200
2201         if($type=='solo')
2202           {
2203             $solo = DB_get_solo_by_gameid($gameid);
2204
2205             if($solo!='silent') /* repeat game with same first player */
2206               output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
2207             else /* rotate normally */
2208               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
2209           }
2210         else if($gamestatus == 'cancel-nines' || $gamestatus == 'cancel-trump')
2211           output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
2212         else /* rotate normally */
2213           output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
2214       }
2215   }
2216 ?>