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