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