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