278a52c60a2c86e52babfe278f070fd4bd5b643a
[e-DoKo.git] / include / game.php
1 <?php
2 /* Copyright 2006, 2007, 2008, 2009, 2010, 2011, 2012 Arun Persaud <arun@nubati.net>
3  *
4  *   This file is part of e-DoKo.
5  *
6  *   e-DoKo is free software: you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation, either version 3 of the License, or
9  *   (at your option) any later version.
10  *
11  *   e-DoKo is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with e-DoKo.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  */
20
21 /* make sure that we are not called from outside the scripts,
22  * use a variable defined in config.php to check this
23  */
24 if(!isset($HOST))
25   exit;
26
27 /* calling game.php only makes sense when we give it a hash for a game */
28 if(!myisset('me'))
29   {
30     echo "Hmm, you really shouldn't mess with the urls.<br />\n";
31     return;
32   }
33 $me = $_REQUEST['me'];
34
35 /* Ok, got a hash, but is it valid? */
36 $myid = DB_get_userid('hash',$me);
37 if(!$myid)
38   {
39     echo "Can't find you in the database, please check the url.<br />\n";
40     echo "perhaps the game has been canceled, check by login in <a href=\"$INDEX\">here</a>.";
41     return;
42   }
43
44 global $GAME,$RULES,$CARDS;
45
46 /**************************************
47  * get some information from the DB
48  **************************************/
49 $gameid   = DB_get_gameid_by_hash($me);
50 $myname   = DB_get_name('hash',$me);
51 $mystatus = DB_get_status_by_hash($me);
52 $mypos    = DB_get_pos_by_hash($me);
53 $myhand   = DB_get_handid('hash',$me);
54 $myparty  = DB_get_party_by_hash($me);
55 $session  = DB_get_session_by_gameid($gameid);
56 $playid   = DB_get_current_playid($gameid); /* might be -1 at beginning of the game */
57
58 /* get prefs and save them in a variable*/
59 $PREF = DB_get_PREF(isset($_SESSION['id'])?$_SESSION['id']:$myid);
60
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                 $firstcard = ''; /* unset firstcard, so followsuit doesn't trigger with the last trick */
1685               }
1686             else
1687               {
1688                 $next = DB_get_pos_by_hash($me)+1;
1689               }
1690             if($next==5) $next=1;
1691
1692             /* check for coment */
1693             if(myisset('comment'))
1694               {
1695                 $comment = $_REQUEST['comment'];
1696                 if($comment != '')
1697                   DB_insert_comment($comment,$playid,$gameid,$myid);
1698                 if($commentSchweinchen)
1699                   $comment = $commentSchweinchen . $comment;
1700                 if($commentCall != '')
1701                   $comment = $commentCall . $comment;
1702               };
1703
1704             /* display played card */
1705             $pos = DB_get_pos_by_hash($me);
1706             if($sequence==1)
1707               {
1708                 echo "    <div class=\"trick\" id=\"trick".($tricknr)."\">\n".
1709                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1710               }
1711
1712             echo "      <div class=\"card".($pos-1)."\">\n        ";
1713
1714             /* display comments */
1715             display_card($card,$PREF['cardset']);
1716             if($comment!='')
1717               echo "\n        <span class=\"comment\"> ".$comment."</span>\n";
1718             echo "      </div>\n";
1719
1720             echo "    </div>\n";  /* end div trick, end li trick */
1721
1722             /*check if we still have cards left, else set status to gameover */
1723             if(sizeof(DB_get_hand($me))==0)
1724               {
1725                 DB_set_hand_status_by_hash($me,'gameover');
1726                 $mystatus = 'gameover';
1727               }
1728
1729             /* if all players are done, set game status to game over,
1730              * get the points of the last trick and send out an email
1731              * to all players
1732              */
1733             $userids = DB_get_all_userid_by_gameid($gameid);
1734
1735             $done=1;
1736             foreach($userids as $user)
1737               if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
1738                 $done=0;
1739
1740             if($done)
1741               DB_set_game_status_by_gameid($gameid,'gameover');
1742
1743             /* email next player, if game is still running */
1744             if(DB_get_game_status_by_gameid($gameid)=='play')
1745               {
1746                 $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
1747                 $who       = DB_get_userid('hash',$next_hash);
1748                 DB_set_player_by_gameid($gameid,$who);
1749
1750                 $email_message = "A card has been played in game ".DB_format_gameid($gameid).".\n\n".
1751                   "It's your turn  now.\n".
1752                   "Use this link to play a card: ".$HOST.$INDEX."?action=game&me=".$next_hash."\n\n" ;
1753                 if( DB_get_email_pref_by_uid($who)!='emailaddict' )
1754                   {
1755                     mymail($who,$gameid, GAME_YOUR_TURN, $email_message);
1756                   }
1757               }
1758             else /* send out final email */
1759               {
1760                 /* individual score */
1761                 $result = DB_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party FROM Hand".
1762                                    " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1763                                    " LEFT JOIN User ON User.id=Hand.user_id".
1764                                    " LEFT JOIN Play ON Trick.id=Play.trick_id".
1765                                    " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1766                                    " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1767                                    " WHERE Hand.game_id='$gameid'".
1768                                    " GROUP BY User.fullname" );
1769                 $email_message  = "The game is over. Thanks for playing :)\n";
1770                 $email_message .= "Final score:\n";
1771                 while( $r = DB_fetch_array($result) )
1772                   $email_message .= "   ".$r[0]."(".$r[2].") ".$r[1]."\n";
1773
1774                 $result = DB_query("SELECT  Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
1775                                    " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
1776                                    " LEFT JOIN User ON User.id=Hand.user_id".
1777                                    " LEFT JOIN Play ON Trick.id=Play.trick_id".
1778                                    " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
1779                                    " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
1780                                    " WHERE Hand.game_id='$gameid'".
1781                                    " GROUP BY Hand.party" );
1782                 $email_message .= "\nTotals:\n";
1783                 $re     = 0;
1784                 $contra = 0;
1785                 while( $r = DB_fetch_array($result) )
1786                   {
1787                     $email_message .= "    ".$r[0]." ".$r[1]."\n";
1788                     if($r[0] == 're')
1789                       $re = $r[1];
1790                     else if($r[0] == 'contra')
1791                       $contra = $r[1];
1792                   }
1793
1794                 /*
1795                  * save score in database
1796                  *
1797                  */
1798
1799                 /* get calls from re/contra */
1800                 $call_re     = -1;
1801                 $call_contra = -1;
1802                 foreach($userids as $user)
1803                   {
1804                     $hash  = DB_get_hash_from_gameid_and_userid($gameid,$user);
1805                     $call  = DB_get_call_by_hash($hash);
1806                     $party = DB_get_party_by_hash($hash);
1807
1808                     if($call!=NULL)
1809                       {
1810                         $call = (int) $call;
1811
1812                         if($party=='re')
1813                           {
1814                             if($call_re== -1)
1815                               $call_re = $call;
1816                             else if( $call < $call_re)
1817                               $call_re = $call;
1818                           }
1819                         else if($party=='contra')
1820                           {
1821                             if($call_contra== -1)
1822                               $call_contra = $call;
1823                             else if( $call < $call_contra)
1824                               $call_contra = $call;
1825                           }
1826                       }
1827                   }
1828
1829                 /* figure out who one */
1830                 $winning_party = NULL;
1831
1832                 if($call_re == -1 && $call_contra == -1)
1833                   {
1834                     /* nobody made a call, so it's easy to figure out who won */
1835                     if($re>120)
1836                       $winning_party='re';
1837                     else
1838                       $winning_party='contra';
1839                   }
1840                 else
1841                   {
1842                     /* if one party makes a call, they only win, iff they make enough points
1843                      * if only one party made a call, the other one wins,
1844                      * if the first one didn't make it
1845                      */
1846                     if($call_re != -1)
1847                       {
1848                         $offset = 120 - $call_re;
1849                         if($call_re == 0)
1850                           $offset--; /* since we use a > in the next equation */
1851
1852                         if($re > 120+$offset)
1853                           $winning_party='re';
1854                         else if ($call_contra == -1 )
1855                           $winning_party='contra';
1856                       }
1857
1858                     if($call_contra != -1)
1859                       {
1860                         $offset = 120 - $call_contra;
1861                         if($call_contra == 0)
1862                           $offset--; /* since we use a > in the next equation */
1863
1864                         if($contra > 120+$offset)
1865                           $winning_party='contra';
1866                         else if ($call_re == -1 )
1867                           $winning_party='re';
1868                       }
1869                   }
1870
1871                 /* one point for each call of the other party in case the other party didn't win
1872                  * and one point each in case the party made more than points than one of the calls
1873                  */
1874                 if($winning_party!='contra' && $call_contra!= -1)
1875                   {
1876                     for( $p=$call_contra;$p<=120; $p+=30 )
1877                       {
1878                           DB_query("INSERT INTO Score".
1879                                    " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'against$p')");
1880                         }
1881
1882                       for( $p=$call_contra; $p<120; $p+=30)
1883                         {
1884                           if( $re >= $p )
1885                             DB_query("INSERT INTO Score".
1886                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'made$p')");
1887                         }
1888                     }
1889                   if($winning_party!='re' and $call_re!= -1)
1890                     {
1891                       for( $p=$call_re;$p<=120; $p+=30 )
1892                         {
1893                           DB_query("INSERT INTO Score".
1894                                    " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'against$p')");
1895                         }
1896
1897                       for( $p=$call_re; $p<120; $p+=30)
1898                         {
1899                           if( $contra>=$p )
1900                             DB_query("INSERT INTO Score".
1901                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'made$p')");
1902                         }
1903                     }
1904
1905                   /* point in case contra won */
1906                   if($winning_party=='contra')
1907                     {
1908                       DB_query("INSERT INTO Score".
1909                                " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'againstqueens')");
1910                     }
1911
1912                   /* one point each for winning and each 30 points + calls */
1913                   if($winning_party=='re')
1914                     {
1915                       foreach(array(120,150,180,210,240) as $p)
1916                         {
1917                           $offset = 0;
1918                           if($p==240 || $call_contra != -1)
1919                             $offset = 1;
1920
1921                           if($re>$p-$offset)
1922                             DB_query("INSERT INTO Score".
1923                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'".(240-$p)."')");
1924                         }
1925                       /* re called something and won */
1926                       foreach(array(0,30,60,90,120) as $p)
1927                         {
1928                           if($call_re!= -1 && $call_re<$p+1)
1929                             DB_query("INSERT INTO Score".
1930                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'call$p')");
1931                         }
1932                     }
1933                   else if( $winning_party=='contra')
1934                     {
1935                       foreach(array(120,150,180,210,240) as $p)
1936                         {
1937                           $offset = 0;
1938                           if($p==240 || $call_re != -1)
1939                             $offset = 1;
1940
1941                           if($contra>$p-$offset)
1942                             DB_query("INSERT INTO Score".
1943                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'".(240-$p)."')");
1944                         }
1945                       /* re called something and won */
1946                       foreach(array(0,30,60,90,120) as $p)
1947                         {
1948                           if($call_contra != -1 && $call_contra<$p+1)
1949                             DB_query("INSERT INTO Score".
1950                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'call$p')");
1951                         }
1952                     }
1953
1954
1955                   /* add score points to email */
1956                   $email_message .= "\n";
1957                   $Tpoint = 0;
1958                   $email_message .= " Points Re: \n";
1959                   $queryresult = DB_query("SELECT score FROM Score ".
1960                                           "  WHERE game_id=$gameid AND party='re'".
1961                                           " ");
1962                   while($r = DB_fetch_array($queryresult) )
1963                     {
1964                       $email_message .= "   ".$r[0]."\n";
1965                       $Tpoint ++;
1966                     }
1967                   $email_message .= " Points Contra: \n";
1968                   $queryresult = DB_query("SELECT score FROM Score ".
1969                                           "  WHERE game_id=$gameid AND party='contra'".
1970                                           " ");
1971                   while($r = DB_fetch_array($queryresult) )
1972                     {
1973                       $email_message .= "   ".$r[0]."\n";
1974                       $Tpoint --;
1975                     }
1976                   $email_message .= " Total Points (from the Re point of view): $Tpoint\n";
1977                   $email_message .= "\n";
1978
1979                   $session = DB_get_session_by_gameid($gameid);
1980                   $score = generate_score_table($session);
1981
1982                   $email_message .= "Score Table:\n";
1983                   $email_message .= format_score_table_ascii($score);
1984                   $email_message .= "\nUse these links to have a look at game ".DB_format_gameid($gameid).": \n";
1985
1986                   /* send out final email */
1987                   foreach($userids as $user)
1988                     {
1989                       /* add links for all players */
1990                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1991                       $name = DB_get_name('userid',$user);
1992
1993                       $link = "$name: ".$HOST.$INDEX."?action=game&me=".$hash."\n" ;
1994                       $email_message .= $link;
1995                     }
1996                   $email_message .= "\n\n (you can use reply all on this email to reach all the players.)\n\n";
1997                   mymail($userids,$gameid, GAME_OVER, $email_message);
1998               }
1999           }
2000         else
2001           {
2002             $messages[] = "can't find that card?!";
2003           }
2004       }
2005     else if(myisset('card') && !$myturn )
2006       {
2007         $messages[] = _("please wait until it's your turn!");
2008       }
2009
2010     if($seq!=4 && $trickNR>=1 && !(myisset('card') && $myturn) )
2011       echo "    </div>\n";  /* end div trick, end li trick */
2012
2013     /* display points in case game is over */
2014     if($mystatus=='gameover' && DB_get_game_status_by_gameid($gameid)=='gameover' )
2015       {
2016         echo "    <div class=\"trick\" id=\"trick13\">\n";
2017         /* add pic for re/contra
2018          "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";*/
2019
2020         $result = DB_query("SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party,Hand.position FROM Hand".
2021                            " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
2022                            " LEFT JOIN User ON User.id=Hand.user_id".
2023                            " LEFT JOIN Play ON Trick.id=Play.trick_id".
2024                            " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
2025                            " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
2026                            " WHERE Hand.game_id='$gameid'".
2027                            " GROUP BY User.fullname" );
2028         while( $r = DB_fetch_array($result))
2029           echo "      <div class=\"card".($r[3]-1)."\">\n".
2030             "        <div class=\"score\">".$r[2]."<br /> ".$r[1]."</div>\n".
2031             "      </div>\n";
2032
2033         /* display totals */
2034         $result = DB_query("SELECT Hand.party, IFNULL(SUM(Card.points),0) FROM Hand".
2035                            " LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id".
2036                            " LEFT JOIN User ON User.id=Hand.user_id".
2037                            " LEFT JOIN Play ON Trick.id=Play.trick_id".
2038                            " LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id".
2039                            " LEFT JOIN Card ON Card.id=Hand_Card.card_id".
2040                            " WHERE Hand.game_id='$gameid'".
2041                            " GROUP BY Hand.party" );
2042         echo "    <div class=\"total\">\n  Totals:<br />\n";
2043         while( $r = DB_fetch_array($result))
2044           echo "      ".$r[0]." ".$r[1]."<br />\n";
2045
2046         $queryresult = DB_query("SELECT timediff(mod_date,create_date) ".
2047                                 " FROM Game WHERE id='$gameid'");
2048         $r = DB_fetch_array($queryresult);
2049         echo "      <p>This game took ".$r[0]." hours.</p>\n";
2050
2051         echo "      <div class=\"re\">\n   Points Re: <br />\n";
2052         $queryresult = DB_query("SELECT score FROM Score ".
2053                                 "  WHERE game_id=$gameid AND party='re'".
2054                                 " ");
2055         while($r = DB_fetch_array($queryresult) )
2056           echo "       ".$r[0]."<br />\n";
2057         echo "      </div>\n";
2058
2059         echo "      <div class=\"contra\">\n   Points Contra: <br />\n";
2060         $queryresult = DB_query("SELECT score FROM Score ".
2061                                 "  WHERE game_id=$gameid AND party='contra'".
2062                                 " ");
2063         while($r = DB_fetch_array($queryresult) )
2064           echo "       ".$r[0]."<br />\n";
2065         echo "      </div>\n";
2066
2067         echo "    </div>\n";
2068
2069         echo "    </div>\n";  /* end div trick, end li trick */
2070       }
2071
2072     echo "</div>\n"; /* end ul tricks*/
2073
2074     if(   ($myturn && !myisset('card') && $mystatus=='play') /* it's my turn*/
2075           || ($myturn && myisset('card') && $next==$mypos && $mystatus=='play')  /* a card has been played and player won the trick*/)
2076       {
2077         $card_status = CARDS_MYTURN;
2078       }
2079     else if($mystatus=='play' )
2080       {
2081         $card_status = CARDS_SHOW;
2082       }
2083     else if($mystatus=='gameover')
2084       {
2085         if(isset($_SESSION['id']) && $myid==$_SESSION['id'])
2086           $card_status = CARDS_GAMEOVER_ME;
2087         else
2088           $card_status = CARDS_GAMEOVER;
2089       }
2090
2091     /* if the game is over do some extra stuff, therefore exit the swtich statement if we are still playing*/
2092     if($mystatus=='play')
2093       break;
2094
2095     /* the following happens only when the gamestatus is 'gameover' */
2096     /* check if game is over, display results */
2097     if(DB_get_game_status_by_gameid($gameid)=='play')
2098       {
2099         echo _('The game is over for you... other people still need to play though');
2100       }
2101     break;
2102   default:
2103     myerror("error in testing the status");
2104   } /*end of output: tricks, table, messages, card */
2105
2106 /* display the 2nd half of table and the names */
2107 display_table_end();
2108
2109 /**************
2110  * show cards *
2111  **************/
2112
2113 $mycards = DB_get_hand($me);
2114 $mycards = mysort($mycards,$gametype);
2115
2116 echo "\n";
2117 echo '<div class="mycards">';
2118 switch ($card_status) {
2119  case CARDS_SHOW:
2120    echo _('Your cards are').": <br />\n";
2121    foreach($mycards as $card)
2122      display_card($card,$PREF['cardset']);
2123    break;
2124  case CARDS_EXCHANGE:
2125    echo '<div class="poverty"> '._('You need to get rid of a few cards')."</div>\n";
2126
2127    echo _('Your cards are').": <br />\n";
2128    $type='exchange';
2129    foreach($mycards as $card)
2130      display_link_card($card,$PREF['cardset'],$type);
2131    echo '  <input type="submit" class="submitbutton" value="select card to give back" />'."\n";
2132    break;
2133  case CARDS_MYTURN:
2134    echo 'Hello '.$myname.", it's your turn!  <br />\n";
2135    echo _('Your cards are').": <br />\n";
2136
2137    /* do we have to follow suite? */
2138    $followsuit = 0;
2139    if(have_suit($mycards,$firstcard))
2140      $followsuit = 1;
2141
2142    /* count how many cards we can play, so that we can pre-select it if there is only one */
2143    $howmanycards = 0;
2144    foreach($mycards as $card)
2145      {
2146        if($howmanycards>1)
2147          break;
2148
2149        /* display only cards that the player is allowed to play as links, the rest just display normal
2150         * also check if we have both schweinchen, in that case only display on of them as playable
2151         */
2152        if( ($followsuit && !same_type($card,$firstcard)) ||
2153            ( (int)($card)==19 &&
2154              !$GAME['schweinchen-first'] &&
2155              ( $RULES['schweinchen']=='second' ||
2156                ( $RULES['schweinchen']=='secondaftercall' &&
2157                  (DB_get_call_by_hash($GAME['schweinchen-who']) ||
2158                   DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
2159                  )
2160                ) &&
2161              $GAME['schweinchen-who']==$me &&
2162              in_array($gametype,array('normal','wedding','trump','silent'))
2163              )
2164            )
2165          continue;
2166        else
2167          $howmanycards++;
2168      }
2169
2170    /* make it boolean, so that we can pass it later to display_link_card */
2171    if($howmanycards!=1)
2172      $howmanycards=0;
2173
2174    foreach($mycards as $card)
2175      {
2176        /* display only cards that the player is allowed to play as links, the rest just display normal
2177         * also check if we have both schweinchen, in that case only display on of them as playable
2178         */
2179        if( ($followsuit && !same_type($card,$firstcard)) ||
2180            ( (int)($card)==19 &&
2181              !$GAME['schweinchen-first'] &&
2182              ( $RULES['schweinchen']=='second' ||
2183                ( $RULES['schweinchen']=='secondaftercall' &&
2184                  (DB_get_call_by_hash($GAME['schweinchen-who']) ||
2185                   DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
2186                  )
2187                ) &&
2188              $GAME['schweinchen-who']==$me &&
2189              in_array($gametype,array('normal','wedding','trump','silent'))
2190              )
2191            )
2192          display_card($card,$PREF['cardset']);
2193        else
2194          display_link_card($card,$PREF['cardset'],$type='card',$selected=$howmanycards);
2195      }
2196    break;
2197  case CARDS_GAMEOVER_ME:
2198  case CARDS_GAMEOVER:
2199    if($card_status == CARDS_GAMEOVER_ME)
2200      echo _('Your cards were').": <br />\n";
2201    else
2202      {
2203        $name = DB_get_name('userid',$myid);
2204        echo "$name's were: <br />\n";
2205      }
2206    $oldcards = DB_get_all_hand($me);
2207    $oldcards = mysort($oldcards,$gametype);
2208
2209    foreach($oldcards as $card)
2210      display_card($card,$PREF['cardset']);
2211
2212    /* display hands of everyone else */
2213    $userids = DB_get_all_userid_by_gameid($gameid);
2214    foreach($userids as $user)
2215      {
2216        $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
2217
2218        if($userhash!=$me)
2219          {
2220            echo "<br />";
2221
2222            $name = DB_get_name('userid',$user);
2223            $oldcards = DB_get_all_hand($userhash);
2224            $oldcards = mysort($oldcards,$gametype);
2225            echo "$name's cards were: <br />\n";
2226            foreach($oldcards as $card)
2227              display_card($card,$PREF['cardset']);
2228          }
2229      };
2230    break;
2231  case CARDS_EMPTY:
2232  default:
2233    break;
2234  }
2235 echo "</div>\n";
2236
2237 /*****************
2238  * show messages *
2239  *****************/
2240
2241 if( sizeof($messages) )
2242   {
2243     echo "\n<div class=\"message\">\n";
2244     foreach($messages as $message)
2245       {
2246         echo "  <div>$message <div>close</div> </div>\n";
2247       }
2248     echo "</div>\n\n";
2249   }
2250
2251 /****************************
2252  * commit commentCall to DB *
2253  ****************************/
2254
2255 if($commentCall != '')
2256   {
2257     /* treat before game calls special, so that we can show them on the first trick and not the pre-phase */
2258     if($playid == -1)
2259       $playid = -2;
2260
2261     DB_insert_comment($commentCall,$playid,$gameid,$myid);
2262   }
2263 /***********************************************
2264  * Comments, re/contra calls, user menu
2265  ***********************************************/
2266
2267 /*
2268  * display gameinfo: re/contra, comment-box, play-card button, games played by others
2269  */
2270
2271 echo "<div class=\"gameinfo\">\n";
2272
2273 /* get time from the last action of the game */
2274 $r = DB_query_array("SELECT mod_date from Game WHERE id='$gameid' " );
2275 $gameend = time() - strtotime($r[0]);
2276
2277 /* comment box */
2278 if($gamestatus == 'play' || $gamestatus == 'pre' || $gameend < 60*60*24*7)
2279   {
2280     echo '  '._('A short comment').":<input name=\"comment\" type=\"text\" size=\"20\" maxlength=\"100\" />\n";
2281   }
2282
2283 /* re-contra */
2284 if($gamestatus == 'play' )
2285   {
2286     $myparty = DB_get_party_by_hash($me);
2287     output_form_calls($me,$myparty);
2288   }
2289
2290 /* play-card button */
2291 if($gamestatus == 'play' || $gamestatus == 'pre' || $gameend < 60*60*24*7)
2292   {
2293     echo "  <input type=\"submit\" value=\""._('submit')."\" />\n";
2294   }
2295
2296 /* has this hand been played by others? */
2297 $other_game_ids = DB_played_by_others($gameid);
2298 if(sizeof($other_game_ids)>0 && $mystatus=='gameover')
2299   {
2300     $mypos = DB_get_pos_by_hash($me);
2301     echo "  <p>See how other played the same hand: \n";
2302     foreach($other_game_ids as $id)
2303       {
2304         $otherhash = DB_get_hash_from_game_and_pos($id,$mypos);
2305         $othername = DB_get_name('hash',$otherhash);
2306         echo "    <a href=\"$INDEX?action=game&amp;me=$otherhash\">$othername</a> ";
2307       }
2308     echo "  </p>\n";
2309   }
2310
2311 echo "</div>\n\n"; /* end gameinfo */
2312
2313 /* make sure that we don't show the notes to the wrong person
2314  * (e.g. other people looking at an old game)
2315  */
2316 if( $mystatus != 'gameover' ||
2317     (  $mystatus == 'gameover' &&
2318        isset($_SESSION['id'])  &&
2319        $myid == $_SESSION['id']))
2320   output_user_notes($myid,$gameid,$mystatus);
2321
2322 echo "</form>\n";
2323
2324 /*********************************
2325  * suggest next game
2326  *********************************/
2327
2328 $gamestatus = DB_get_game_status_by_gameid($gameid);
2329 if($mystatus=='gameover' &&
2330    ($gamestatus =='gameover' || $gamestatus =='cancel-nines' || $gamestatus =='cancel-trump') &&
2331    isset($_SESSION['id']) && $_SESSION['id']==$myid)
2332   {
2333     $session = DB_get_session_by_gameid($gameid);
2334     $result  = DB_query("SELECT id,create_date FROM Game".
2335                         " WHERE session=$session".
2336                         " ORDER BY create_date DESC".
2337                         " LIMIT 1");
2338     $r = -1;
2339     if($result)
2340       $r = DB_fetch_array($result);
2341
2342     if(!$session || $gameid==$r[0])
2343       {
2344         /* suggest a new game with the same people in it, just rotated once (unless last game was solo) */
2345         $names = DB_get_all_names_by_gameid($gameid);
2346         $type  = DB_get_gametype_by_gameid($gameid);
2347
2348         if($type=='solo')
2349           {
2350             $solo = DB_get_solo_by_gameid($gameid);
2351
2352             if($solo!='silent') /* repeat game with same first player */
2353               output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
2354             else /* rotate normally */
2355               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
2356           }
2357         else if($gamestatus == 'cancel-nines' || $gamestatus == 'cancel-trump')
2358           output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
2359         else /* rotate normally */
2360           output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
2361       }
2362   }
2363 ?>