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