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