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