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