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