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