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