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