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