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