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