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