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