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