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