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