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