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