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