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