in some cases the user has to reload the page to get to the next pre-game phase....
[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     /* in case the user can go do the next stage, we want to skip the break statement at the
640      * end. We keep track of these cases using this variable
641      */
642     $nobreak=0;
643
644     /* check if everyone has reached this stage */
645     $userids = DB_get_all_userid_by_gameid($gameid);
646     $ok = 1;
647     foreach($userids as $userid)
648       {
649         $userstat = DB_get_hand_status_by_userid_and_gameid($userid,$gameid);
650         if($userstat!='check')
651           {
652             $ok = 0;
653             DB_set_player_by_gameid($gameid,$userid);
654             break;
655           }
656       };
657
658     if(!$ok)
659       {
660         $messages[] = _('This step can only be handled after everyone finished the last step. '.
661           'Seems like this is not the case, so you need to wait a bit... '.
662           'you will get an email once that is the case, please use the link in '.
663           'that email to continue the game.');
664       }
665     else
666       {
667         /* Ok, everyone finished the init-phase, time to figure out what game we
668          * are playing, in case there are any solos this already
669          * will have the correct information in it */
670
671         $messages[] = _('Ok, everyone is done... figuring out what kind of game we are playing.');
672
673         /* gametype for displaying it (hides hidden solo)*/
674         $GT          = get_display_gametype($gameid);
675
676         $startplayer = DB_get_startplayer_by_gameid($gameid);
677
678         /* check for sickness */
679         $cancel  = 0;
680         $poverty = 0;
681         $wedding = 0;
682         $solo    = 0;
683         foreach($userids as $user)
684           {
685             $name     = DB_get_name('userid',$user);
686             $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
687             if($usersick == 'nines' || ($RULES['lowtrump']=='cancel' && $usersick=='lowtrump') )
688               {
689                 $cancel     = $user;
690                 $cancelsick = $usersick;
691                 break; /* no need to check for other poverties, since only solo can win and that is already set */
692               }
693             else if($usersick == 'poverty' || ($RULES['lowtrump']=='poverty' && $usersick=='lowtrump'))
694               $poverty++;
695             else if($usersick == 'wedding')
696               $wedding=$user;
697             else if($usersick == 'solo')
698               $solo++;
699           }
700
701         /* now check which sickness comes first and set the gametype to it */
702         if($gametype_raw == 'solo')
703           {
704             /* do nothing */
705           }
706         else if($cancel)
707           {
708             /* cancel game */
709             if($cancelsick == 'nines')
710               {
711                 /* update game status */
712                 cancel_game('nines',$gameid);
713
714                 $messages[] = sprintf(_('The game has been canceled because %s'.
715                   ' has five or more nines and nobody is playing solo.'),DB_get_name('userid',$cancel) );
716               }
717             else if ($cancelsick == 'lowtrump')
718               {
719                 /* update game status */
720                 cancel_game('lowtrump',$gameid);
721
722                 $messages[] = sprintf(_('The game has been canceled because %s'.
723                   ' has low trump and nobody is playing solo.'),DB_get_name('userid',$cancel));
724               };
725
726             $userids = DB_get_all_userid_by_gameid($gameid);
727             foreach($userids as $user)
728               {
729                 set_language($user,'uid');
730                 if($cancelsick == 'nines')
731                 {
732                   $email_message = sprintf(_('The game has been canceled because %s'.
733                     ' has five or more nines and nobody is playing solo.'),DB_get_name('userid',$cancel) ).
734                     "\n\n".
735                     _("To redeal either start a new game or, in case the game was part of a tournament,\n".
736                     "go to the last game and use the link at the bottom of the page to redeal.").
737                     "\n\n";
738                 }
739                 else if ($cancelsick == 'lowtrump')
740                 {
741                   $email_message = sprintf(_('The game has been canceled because %s'.
742                     " has low trump and nobody is playing solo."),DB_get_name('userid',$cancel)).
743                     "\n\n".
744                     _("To redeal either start a new game or, in case the game was part of a tournament,\n".
745                     "go to the last game and use the link at the bottom of the page to redeal.").
746                     "\n\n";
747                 };
748
749                 mymail($user,$gameid, GAME_CANCELED, $email_message);
750               }
751               set_language($myid,'uid');
752
753             break;
754           }
755         else if($poverty==1) /* one person has poverty */
756           {
757             DB_set_gametype_by_gameid($gameid,'poverty');
758             $gametype_raw = 'poverty';
759             $gametype     = 'poverty';
760             $who      = DB_get_sickness_by_gameid($gameid);
761             if(!$who)
762               {
763                 $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
764                 if($firstsick == 'poverty' || ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
765                   DB_set_sickness_by_gameid($gameid,2); /* who needs to be asked first */
766                 else
767                   DB_set_sickness_by_gameid($gameid,1); /* who needs to be asked first */
768               }
769           }
770         else if($poverty==2) /* two people have poverty */
771           {
772             DB_set_gametype_by_gameid($gameid,'dpoverty');
773             $gametype_raw = 'dpoverty';
774             $gametype     = 'dpoverty';
775             $who      = DB_get_sickness_by_gameid($gameid);
776             if(!$who)
777               {
778                 $firstsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
779                 if($firstsick == 'poverty' || ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
780                   {
781                     $secondsick = DB_get_sickness_by_pos_and_gameid(1,$gameid);
782                     if($secondsick == 'poverty'  || ($RULES['lowtrump']=='poverty' && $secondsick=='lowtrump'))
783                       DB_set_sickness_by_gameid($gameid,30); /* who needs to be asked first */
784                     else
785                       DB_set_sickness_by_gameid($gameid,20); /* who needs to be asked first */
786                   }
787                 else
788                   DB_set_sickness_by_gameid($gameid,10); /* who needs to be asked first */
789               }
790           }
791         else if($wedding> 0)
792           {
793             DB_set_gametype_by_gameid($gameid,'wedding');
794             DB_set_sickness_by_gameid($gameid,'-1'); /* wedding not resolved yet */
795             $gametype_raw = 'wedding';
796             $gametype     = 'wedding';
797           };
798         /* now the gametype is set correctly in the database */
799         $messages[] = _('Got it').' :)';
800
801         /* loop over all players, set re/contra if possible and start the game if possible */
802         $userids = DB_get_all_userid_by_gameid($gameid);
803         foreach($userids as $userid)
804           {
805             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$userid);
806
807             switch($gametype_raw)
808               {
809               case 'solo':
810                 /* are we the solo player? set us to re, else set us to contra */
811                 $pos = DB_get_pos_by_hash($userhash);
812                 if($pos == $startplayer)
813                   DB_set_party_by_hash($userhash,'re');
814                 else
815                   DB_set_party_by_hash($userhash,'contra');
816                 DB_set_hand_status_by_hash($userhash,'play');
817                 break;
818
819               case 'wedding':
820                 /* set person with the wedding to re, do the rest during the game */
821                 $usersick = DB_get_sickness_by_userid_and_gameid($userid,$gameid);
822                 if($usersick == 'wedding')
823                   DB_set_party_by_hash($userhash,'re');
824                 else
825                   DB_set_party_by_hash($userhash,'contra');
826
827                 DB_set_hand_status_by_hash($userhash,'play');
828                 break;
829
830               case 'normal':
831                 $hand = DB_get_all_hand($userhash);
832
833                 if(in_array('3',$hand)||in_array('4',$hand))
834                   DB_set_party_by_hash($userhash,'re');
835                 else
836                   DB_set_party_by_hash($userhash,'contra');
837                 DB_set_hand_status_by_hash($userhash,'play');
838                 break;
839               case 'poverty':
840               case 'dpoverty':
841                 /* set person with poverty to play status */
842                 $usersick = DB_get_sickness_by_userid_and_gameid($userid,$gameid);
843                 if($usersick == 'poverty'  || ($RULES['lowtrump']=='poverty' && $usersick=='lowtrump'))
844                   DB_set_hand_status_by_hash($userhash,'play');
845
846                 /* set status of first player to be asked to poverty */
847                 $who = DB_get_sickness_by_gameid($gameid);
848                 if($who > 6) $who= $who/10; /* in case we have dpoverty */
849                 $whoid = DB_get_userid('gameid-position',$gameid,$who);
850                 if($whoid==$userid)
851                   DB_set_hand_status_by_hash($userhash,'poverty');
852               }
853           }
854         /* check for silent solo, set game type to solo in this case */
855         $userids  = DB_get_all_userid_by_gameid($gameid);
856         foreach($userids as $userid)
857           {
858             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$userid);
859
860             if($gametype_raw=='normal')
861               {
862                 $userhand = DB_get_all_hand($userhash);
863                 if(check_wedding($userhand))
864                   {
865                     /* normal game type and player has both queens -> silent solo */
866                     /* keep startplayer, just set gametype to silent solo */
867                     DB_set_gametype_by_gameid($gameid,'solo');
868                     DB_set_solo_by_gameid($gameid,'silent');
869                     $gametype_raw  = 'solo';
870                     $gametype_solo = 'silent';
871                     $gametype      = 'normal';
872                   }
873               }
874           }
875
876         /* send out email to first player or poverty person*/
877         if($gametype!='poverty' && $gametype!='dpoverty')
878           {
879             $startplayer = DB_get_startplayer_by_gameid($gameid);
880             $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
881             $userid      = DB_get_userid('hash',$hash);
882             DB_set_player_by_gameid($gameid,$userid);
883
884             if($hash!=$me)
885               {
886                 if(DB_get_email_pref_by_hash($hash)!='emailaddict')
887                   {
888                     /* email startplayer */
889                     set_language($userid,'uid');
890                     $email_message = sprintf(_("It's your turn now in game %s.\n".
891                       "Use this link to play a card:"),DB_format_gameid($gameid))." ".$HOST.$INDEX."?action=game&me=".$hash."\n\n" ;
892                     mymail($userid,$gameid,GAME_READY,$email_message);
893                     set_language($myid,'uid');
894                   }
895               }
896             else
897               {
898                 $messages[] = sprintf(_('Please, <a href="%s">start</a> the game.'),$INDEX."?action=game&amp;me=$me").
899                   "<br />\n";
900                 $nobreak=1;
901               }
902           }
903         else
904           {
905             /* set status of first player to be asked to poverty */
906             $who   = DB_get_sickness_by_gameid($gameid);
907             if($who > 6) $who= $who/10; /* in case we have dpoverty */
908
909             $whoid = DB_get_userid('gameid-position',$gameid,$who);
910             if($whoid==$myid)
911               {
912                 $messages[] = sprintf(_('Please, <a href="%s">start</a> the game.'),$INDEX."?action=game&amp;me=$me").
913                   "<br /\n";
914                 $nobreak=1;
915               }
916             else
917               {
918                 $whohash = DB_get_hash_from_game_and_pos($gameid,$who);
919                 DB_set_player_by_gameid($gameid,$whoid);
920
921                 if(DB_get_email_pref_by_hash($hash)!='emailaddict')
922                   {
923                     /* email player for poverty */
924                     set_language($whoid,'uid');
925                     $email_message = sprintf(_("Poverty: It's your turn now in game %s.\n".
926                       'Use this link to play a card: '),DB_format_gameid($gameid)).$HOST.$INDEX."?action=game&me=".$whohash."\n\n" ;
927                     mymail($whoid,$gameid,GAME_POVERTY,$email_message);
928                     set_language($myid,'uid');
929                   }
930               }
931           }
932       }
933     if(!$nobreak)
934       break;
935
936   case 'poverty':
937     /* user only gets here in a poverty game, several things have to be handled here:
938      * A) ask, if user wants to take trump
939      *      yes-> take trump,
940      *            poverty: set re/contra
941      *            dpoverty: first time: set re, send email to second player
942      *                      second time: set contra
943      *            poverty: set status of other players to 'play'
944      *            set status to play in case 0 trump
945      *      no -> set status to play,
946      *            ask next player or cancle the game if no more players
947      * B) user took trump and has too many cards (e.g. count(cards)>12 and re/contra set)
948      *         ask to give cards back, set status to play, once player has 12 cards
949      *
950      * it is easier to check B) first
951      */
952
953     /* in case the user can go do the next stage, we want to skip the break statement at the
954      * end. We keep track of these cases using this variable
955      */
956     $nobreak=0;
957
958     set_gametype($gametype); /* this sets the $CARDS variable */
959     $myparty = DB_get_party_by_hash($me);
960
961     /* the following is part B) of whats needs to be done)
962     /*    check if user wants to give cards back */
963     if(myisset('exchange'))
964       {
965         $exchange    = $_REQUEST['exchange'];
966         $partnerhash = DB_get_partner_hash_by_hash($me);
967         $partnerid   = DB_get_userid('hash',$partnerhash);
968         $partnerhand = DB_get_handid('gameid-userid',$gameid,$partnerid);
969
970         /* if exchange is set to a value>0, exchange that card back to the partner */
971         if($exchange >0)
972           {
973             $result = DB_query("UPDATE Hand_Card SET hand_id='$partnerhand'".
974                                " WHERE hand_id=".DB_quote_smart($myhand)." AND card_id=".DB_quote_smart($exchange));
975             DB_add_exchanged_card(DB_quote_smart($exchange),$myhand,$partnerhand);
976           };
977       }
978
979     /* get hand */
980     $mycards = DB_get_hand($me);
981
982     /* check if user need to give more cards back */
983     if( ($myparty=='re' || $myparty=='contra') && count($mycards)>12)
984       {
985         $card_status = CARDS_EXCHANGE;
986       }
987     else if( ($myparty=='re' || $myparty=='contra') && count($mycards)==12)
988       {
989         /* user is done, ready to play */
990         DB_set_hand_status_by_hash($me,'play');
991
992         /* email start player */
993         $startplayer = DB_get_startplayer_by_gameid($gameid);
994         $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
995         $userid      = DB_get_userid('hash',$hash);
996         DB_set_player_by_gameid($gameid,$userid);
997
998         if($hash!=$me)
999           {
1000             if(DB_get_email_pref_by_hash($hash)!='emailaddict')
1001               {
1002                 /* email startplayer */
1003                 set_language($userid,'uid');
1004                 $email_message = sprintf(_("It's your turn now in game %s.\n".
1005                   'Use this link to play a card: '),DB_format_gameid($gameid)).$HOST.$INDEX."?action=game&me=".$hash."\n\n" ;
1006                 mymail($userid,$gameid,GAME_READY,$email_message);
1007                 set_language($myid,'uid');
1008               }
1009           }
1010         else
1011           $messages[]= sprintf(_('Please, <a href="%s">start</a> the game.'),$INDEX."?action=game&amp;me=$me");
1012       }
1013
1014     /* the following is part A) of what needs to be done */
1015     if(!myisset('trump'))
1016       {
1017         if(!$myparty)
1018           {
1019             echo "<div class=\"poverty\">\n";
1020             $userids = DB_get_all_userid_by_gameid($gameid);
1021             foreach($userids as $user)
1022               {
1023                 $name      = DB_get_name('userid',$user);
1024                 $usersick  = DB_get_sickness_by_userid_and_gameid($user,$gameid);
1025                 $userhash  = DB_get_hash_from_gameid_and_userid($gameid,$user);
1026                 $userparty = DB_get_party_by_hash($userhash);
1027
1028                 if(($usersick=='poverty'|| ($RULES['lowtrump']=='poverty' && $usersick=='lowtrump')) && !$userparty)
1029                   {
1030                     $hash    = DB_get_hash_from_gameid_and_userid($gameid,$user);
1031                     $cards   = DB_get_hand($hash);
1032                     /* count trump */
1033                     $nrtrump = 0;
1034                     foreach($cards as $card)
1035                       if($card<27) $nrtrump++;
1036                     $low='';
1037                     if($usersick=='lowtrump')
1038                       $low=_('low');
1039                     /// TRANSLATORS: first %s=name, %d=number of trump, second %s= '' or 'low' for trumpfarmut
1040                     printf(_('Player %s has %d %s trump. Do you want to take them?'.
1041                              '<a href="%s">Yes</a>')."<br />\n",
1042                            $name,$nrtrump,$low,"index.php?action=game&amp;me=$me&amp;trump=$user");
1043                   }
1044               }
1045             /// TRANSLATORS: answer to question about taking trump in poverty game
1046             echo "<a href=\"index.php?action=game&amp;me=$me&amp;trump=no\">"._("No way")."</a> <br />\n";
1047             echo "</div>\n";
1048           }
1049         break;
1050       }
1051     else
1052       {
1053         $trump = $_REQUEST['trump'];
1054
1055         if($trump=='no')
1056           {
1057             /* user doesn't want to take trump */
1058             DB_set_hand_status_by_hash($me,'play');
1059
1060             /* set next player who needs to be asked and email him*/
1061             $firstsick  = (string) DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
1062             $secondsick = (string) DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
1063
1064             /* don't ask people who have poverty */
1065             $next=1;
1066             if($firstsick=='poverty' || ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
1067               {
1068                 if($secondsick=='poverty'|| ($RULES['lowtrump']=='poverty' && $secondsick=='lowtrump'))
1069                   $next=3;
1070                 else
1071                   $next=2;
1072               }
1073             if($gametype=='dpoverty')
1074               {
1075                 $next=999; /* need to cancel for sure, since both would need to take the trump */
1076               }
1077
1078             /* no more people to ask, need to cancel the game */
1079             if($mypos+$next>4)
1080               {
1081                 $userids = DB_get_all_userid_by_gameid($gameid);
1082                 foreach($userids as $user)
1083                   {
1084                     set_language($user,'uid');
1085                     $email_message = sprintf("Hello, \n\n".
1086                       'Game %s has been canceled since nobody wanted to take the trump.',DB_format_gameid($gameid)).
1087                       "\n\n";
1088                     mymail($user, $gameid, GAME_CANCELED_POVERTY, $email_message);
1089                   }
1090                 set_language($myid,'uid');
1091
1092                 /* update game status */
1093                 cancel_game('trump',$gameid);
1094
1095                 $messages[] = sprintf(_('Game %s has been canceled.'),DB_format_gameid($gameid));
1096                 break;
1097               }
1098             else
1099               {
1100                 /* email next player, set his status to poverty */
1101                 $userhash = DB_get_hash_from_game_and_pos($gameid,$mypos+$next);
1102                 $userid   = DB_get_userid('hash',$userhash);
1103
1104                 DB_set_player_by_gameid($gameid,$userid);
1105                 DB_set_hand_status_by_hash($userhash,'poverty');
1106
1107                 set_language($userid,'uid');
1108                 $email_message = _("Someone has poverty, it's your turn to decide, if you want to take the trump. Please visit:").
1109                   " ".$HOST.$INDEX."?action=game&me=".$userhash."\n\n" ;
1110                 mymail($userid,$gameid, GAME_POVERTY, $email_message);
1111                 set_language($myid,'uid');
1112               }
1113
1114             $cards_status = CARDS_SHOW;
1115           }
1116         else
1117           {
1118             /* player wants to take trump, change cards */
1119
1120             /* user wants to take trump */
1121             $trump = $_REQUEST['trump'];
1122             $userhand = DB_get_handid('gameid-userid',$gameid,$trump);
1123             $userhash = DB_get_hash_from_gameid_and_userid($gameid,$trump);
1124
1125             /* remember which cards were handed over*/
1126             $partnerhand = DB_get_all_hand($userhash);
1127             foreach ($partnerhand as $card)
1128               if($card<27)
1129                 DB_add_exchanged_card($card,$userhand,$myhand);
1130
1131             /* copy trump from player A to B */
1132             $result = DB_query("UPDATE Hand_Card SET hand_id='$myhand' WHERE hand_id=".DB_quote_smart($userhand)." AND card_id<'27'" );
1133
1134             /* reload cards */
1135             $mycards = DB_get_hand($me);
1136
1137             /* set re/contra */
1138             if($gametype=='poverty')
1139               {
1140                 $userids = DB_get_all_userid_by_gameid($gameid);
1141                 foreach($userids as $user)
1142                   {
1143                     $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1144                     if($hash==$userhash||$hash==$me)
1145                       {
1146                         DB_set_party_by_hash($hash,'re');
1147                       }
1148                     else
1149                       {
1150                         DB_set_party_by_hash($hash,'contra');
1151                         DB_set_hand_status_by_hash($hash,'play'); /* the contra party is ready to play */
1152                       }
1153                   }
1154                 /* check if we are done (in case of no trump handed over), if so, go to 'play' phase right away*/
1155                 if(count($mycards)==12)
1156                   {
1157                     DB_set_hand_status_by_hash($me,'play');
1158                   }
1159               }
1160             else /*dpoverty*/
1161               {
1162                 /* has the re party already been set?*/
1163                 $re_set=0;
1164                 $userids = DB_get_all_userid_by_gameid($gameid);
1165                 foreach($userids as $user)
1166                   {
1167                     $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1168                     $party = DB_get_party_by_hash($hash);
1169                     if($party=='re')
1170                       $re_set=1;
1171                   }
1172                 if($re_set)
1173                   {
1174                     DB_set_party_by_hash($me,'contra');
1175                     DB_set_party_by_hash($userhash,'contra');
1176                   }
1177                 else
1178                   {
1179                     DB_set_party_by_hash($me,'re');
1180                     DB_set_party_by_hash($userhash,'re');
1181
1182                     /* send out email to second non-poverty player */
1183                     $firstsick  = (string) DB_get_sickness_by_pos_and_gameid($mypos+1,$gameid);
1184                     $secondsick = (string) DB_get_sickness_by_pos_and_gameid($mypos+2,$gameid);
1185
1186                     $next=1;
1187                     if($firstsick=='poverty'|| ($RULES['lowtrump']=='poverty' && $firstsick=='lowtrump'))
1188                       if($secondsick=='poverty'|| ($RULES['lowtrump']=='poverty' && $secondsick=='lowtrump'))
1189                         $next=3;
1190                       else
1191                         $next=2;
1192
1193                     if($mypos+$next>4)
1194                       $messages[] = "Error in poverty, please contact the Admin ($ADMIN_NAME at $ADMIN_EMAIL)";
1195
1196                     $userhash = DB_get_hash_from_game_and_pos($gameid,$mypos+$next);
1197                     $userid   = DB_get_userid('hash',$userhash);
1198
1199                     DB_set_player_by_gameid($gameid,$userid);
1200                     DB_set_hand_status_by_hash($userhash,'poverty');
1201
1202                     set_langauge($userid,'uid');
1203                     $email_message = _("Two people have poverty, it's your turn to decide, if you want to take the trump. Please visit:").
1204                       " ".$HOST.$INDEX."?action=game&me=".$userhash."\n\n" ;
1205                     mymail($userid,$gameid, GAME_DPOVERTY, $email_message);
1206                     set_language($myid,'uid');
1207                   }
1208               }
1209             $messages[] = sprintf(_('Please, <a href="%s">continue</a> here'),$INDEX."?action=game&amp;me=$me");
1210             $nobreak = 1;
1211           }
1212       }
1213     if(!$nobreak)
1214       break;
1215
1216   case 'play':
1217   case 'gameover':
1218     /* both entries here,  so that the tricks are visible for both.
1219      * in case of 'play' there is a break later that skips the last part
1220      */
1221
1222     /* first check if the game has been canceled and display */
1223     switch($gamestatus)
1224       {
1225       case 'cancel-noplay':
1226         $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.");
1227         break;
1228       case 'cancel-timedout':
1229         $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.");
1230         break;
1231       case 'cancel-nines':
1232         $messages[] = _('The game has been canceled because one player had too many nines.');
1233         break;
1234       case 'cancel-lowtrump':
1235         $messages[] = _('The game has been canceled because one player had low trump.');
1236         break;
1237       case 'cancel-trump':
1238         $messages[] = _('The game has been canceled because nobody wanted to take the trump.');
1239         break;
1240       }
1241     /* for these two types, we shouldn't show the cards, since we might want to restart the game */
1242     if (in_array($gamestatus,array('cancel-noplay','cancel-timedout')))
1243       break;
1244
1245     /* check if all players are ready to play,
1246      * if so, send out email to the startplayer
1247      * only need to do this if the game hasn't started yet
1248      */
1249     $gamestatus = DB_get_game_status_by_gameid($gameid);
1250     if($gamestatus == 'pre')
1251       {
1252         $ok = 1;
1253         $userids = DB_get_all_userid_by_gameid($gameid);
1254         foreach($userids as $userid)
1255           {
1256             $userstatus = DB_get_hand_status_by_userid_and_gameid($userid,$gameid);
1257             if($userstatus !='play' && $userstatus!='gameover')
1258               {
1259                 $ok = 0;
1260                 DB_set_player_by_gameid($gameid,$userid);
1261                 break;
1262               }
1263           }
1264         if($ok)
1265           {
1266             /* only set this after all poverty, etc. are handled*/
1267             DB_set_game_status_by_gameid($gameid,'play');
1268
1269             /* email startplayer */
1270             $startplayer = DB_get_startplayer_by_gameid($gameid);
1271             $hash        = DB_get_hash_from_game_and_pos($gameid,$startplayer);
1272             $userid      = DB_get_userid('hash',$hash);
1273             DB_set_player_by_gameid($gameid,$userid);
1274
1275             if($hash!=$me && DB_get_email_pref_by_hash($hash)!='emailaddict')
1276               {
1277                 /* email startplayer) */
1278                 set_language($userid,'uid');
1279                 $email_message = sprintf(_("It's your turn now in game %s.\n".
1280                   'Use this link to play a card: '),DB_format_gameid($gameid)).$HOST.$INDEX."?action=game&me=".$hash."\n\n" ;
1281                 mymail($userid,$gameid, GAME_READY, $email_message);
1282                 set_language($myid,'uid');
1283               }
1284           }
1285       }
1286     /* figure out what kind of game we are playing,
1287      * set the global variables $CARDS['trump'],$CARDS['diamonds'],$CARDS['hearts'],
1288      * $CARDS['clubs'],$CARDS['spades'],$CARDS['foxes']
1289      * accordingly
1290      */
1291
1292     set_gametype($gametype); /* this sets the $CARDS variable */
1293
1294     /* get some infos about the game, need to reset this, since it might have changed */
1295     $gamestatus = DB_get_game_status_by_gameid($gameid);
1296
1297     /* has the game started? No, then just wait here...*/
1298     if($gamestatus == 'pre')
1299       {
1300         $messages[] = _('You finished the setup, but not everyone else finished it... '.
1301           'You need to wait for the others. Just wait for an email.');
1302
1303         break; /* not sure this works... the idea is that you can
1304                 * only  play a card after everyone is ready to play */
1305       }
1306
1307     /* get everything relevant to display the tricks */
1308     $result = DB_query('SELECT Hand_Card.card_id as card,'.
1309                        '       Hand.position as position,'.
1310                        '       Play.sequence as sequence, '.
1311                        '       Trick.id,'.
1312                        "       GROUP_CONCAT(CONCAT('<span>',User.fullname,': ',Comment.comment,'</span>')".
1313                        "                    SEPARATOR '\n' ), ".
1314                        '       Play.create_date,'.
1315                        '       Hand.user_id'.
1316                        ' FROM Trick'.
1317                        ' LEFT JOIN Play ON Trick.id=Play.trick_id'.
1318                        ' LEFT JOIN Hand_Card ON Play.hand_card_id=Hand_Card.id'.
1319                        ' LEFT JOIN Hand ON Hand_Card.hand_id=Hand.id'.
1320                        ' LEFT JOIN Comment ON Play.id=Comment.play_id'.
1321                        ' LEFT JOIN User On User.id=Comment.user_id'.
1322                        " WHERE Trick.game_id=".DB_quote_smart($gameid).
1323                        ' GROUP BY Trick.id, sequence'.
1324                        ' ORDER BY Trick.id, sequence ASC');
1325     $trickNR   = 0;
1326     $lasttrick = DB_get_max_trickid($gameid);
1327
1328     $play = array(); /* needed to calculate winner later  */
1329     $seq  = 1;
1330     $pos  = DB_get_startplayer_by_gameid($gameid)-1;
1331     $firstcard = ''; /* first card in a trick */
1332
1333     echo "\n<div class=\"tricks\">\n";
1334
1335     /* output vorbehalte */
1336     $show_pre_game_comments=1;
1337     if($gametype_raw != 'normal') /* only show when needed */
1338       if(!($gametype_raw == 'solo' && $gametype_solo == 'silent') )
1339         {
1340           echo "    <div class=\"trick\" id=\"trick0\">\n";
1341
1342           /* get information so show the cards that have been handed over in a poverty game */
1343           output_exchanged_cards($gametype);
1344           $show_pre_game_comments=0;
1345
1346           echo "    </div>\n";  /* end div trick, end li trick */
1347         }
1348     if($show_pre_game_comments==1)
1349       {
1350         /* display all comments on the top right (card1)*/
1351         $comments = DB_get_pre_comment($gameid);
1352
1353         if(sizeof($comments))
1354           {
1355             echo "    <div class=\"trick\" id=\"trick0\">\n";
1356             /* display card */
1357             echo "      <div class=\"card1\">\n";
1358             /* display comments */
1359             foreach( $comments as $comment )
1360               echo "        <span class=\"comment\">".$comment[1].": ".$comment[0]."</span>\n";
1361             echo "      </div>\n"; /* end div card */
1362
1363             echo "    </div>\n";  /* end div trick, end li trick */
1364           }
1365       }
1366
1367     /* output tricks */
1368     while($r = DB_fetch_array($result))
1369       {
1370         $pos     = $r[1];
1371         $seq     = $r[2];
1372         $trick   = $r[3];
1373         $comment = $r[4];
1374         $user    = $r[6];
1375
1376         /* count number of tricks */
1377         if($seq==1)
1378           $trickNR++;
1379
1380         /* check if first schweinchen has been played */
1381         if( $GAME['schweinchen-who'] && ($r[0] == 19 || $r[0] == 20) )
1382           if(!$GAME['schweinchen-first'])
1383             $GAME['schweinchen-first'] = 1; /* playing the first fox */
1384           else
1385             $GAME['schweinchen-second'] = 1; /* this must be the second fox */
1386
1387         /* save card to be able to find the winner of the trick later */
1388         $play[$seq] = array('card'=>$r[0],'pos'=>$pos);
1389
1390         if($seq==1)
1391           {
1392             /* first card in a trick, output some html */
1393             if($trick!=$lasttrick)
1394               {
1395                 /* start of an old trick? */
1396                 echo  "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1397                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1398               }
1399             else if($trick==$lasttrick)
1400               {
1401                 /* start of a last trick? */
1402                 echo "    <div class=\"trick\" id=\"trick".$trickNR."\">\n".
1403                   "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";
1404               };
1405
1406             /* remember first card, so that we are able to check, what cards can be played */
1407             $firstcard = $r[0];
1408           };
1409
1410         /* display card */
1411         echo "      <div class=\"card".($pos-1)."\">\n";
1412
1413         /* for the first card, we also need to display calls from other players */
1414         if($seq==1 && $trickNR==1)
1415           {
1416             $commentPreCalls=DB_get_pre_comment_call($gameid);
1417             foreach ($commentPreCalls as $pre )
1418               $comment .= $pre[1].": ".$pre[0]."<br/>";
1419           }
1420
1421         /* display comments */
1422         if($comment!='')
1423           echo "        <span class=\"comment\">".$comment."</span>\n";
1424
1425         echo '        ';
1426         display_card($r[0],$PREF['cardset']);
1427
1428         echo "      </div>\n"; /* end div card */
1429
1430         /* end of trick? */
1431         if($seq==4)
1432           {
1433             $winner    = get_winner($play,$gametype); /* returns the position */
1434             echo "    </div>\n";  /* end div trick, end li trick */
1435           }
1436       }
1437
1438     /* whos turn is it? */
1439     if($seq==4)
1440       {
1441         $winner    = get_winner($play,$gametype); /* returns the position */
1442         $next      = $winner;
1443         $firstcard = ''; /* new trick, no first card */
1444       }
1445     else
1446       {
1447         $next = $pos+1;
1448         if($next==5) $next = 1;
1449       }
1450
1451     /* my turn?, display cards as links, ask for comments*/
1452     if(DB_get_pos_by_hash($me) == $next)
1453       $myturn = 1;
1454     else
1455       $myturn = 0;
1456
1457     /* do we want to play a card? */
1458     if(myisset('card') && $myturn)
1459       {
1460         $card   = $_REQUEST['card'];
1461         $handid = DB_get_handid('hash',$me);
1462         $commentSchweinchen =''; /* used to add a comment when Schweinchen is being played */
1463
1464         /* check if we have card and that we haven't played it yet*/
1465         /* set played in hand_card to true where hand_id and card_id*/
1466         $r = DB_query_array("SELECT id FROM Hand_Card WHERE played='false' and ".
1467                               "hand_id='$handid' AND card_id=".DB_quote_smart($card));
1468         $handcardid = $r[0];
1469
1470         if($handcardid) /* everything ok, play card  */
1471           {
1472             /* update Game timestamp */
1473             DB_update_game_timestamp($gameid);
1474
1475             /* mark card as played */
1476             DB_query("UPDATE Hand_Card SET played='true' WHERE hand_id=".DB_quote_smart($handid)." AND card_id=".
1477                      DB_quote_smart($card));
1478
1479             /* get trick id or start new trick */
1480             $a = DB_get_current_trickid($gameid);
1481             $trickid  = $a[0];
1482             $sequence = $a[1];
1483             $tricknr  = $a[2];
1484
1485             $playid = DB_play_card($trickid,$handcardid,$sequence);
1486
1487             /* check special output for schweinchen in case in case a fox is being played
1488              * check for correct rules, etc. has already been done
1489              */
1490             if( $GAME['schweinchen-who'] && ($card == 19 || $card == 20) )
1491               {
1492                 if(!$GAME['schweinchen-first'])
1493                   $GAME['schweinchen-first'] = 1; /* playing the first fox */
1494                 else
1495                   $GAME['schweinchen-second'] = 1; /* this must be the second fox */
1496
1497                 if( $RULES['schweinchen']=='both' ||
1498                     ($RULES['schweinchen']=='second' && $GAME['schweinchen-second']==1 )||
1499                     ($RULES['schweinchen']=='secondaftercall' && $GAME['schweinchen-second']==1 &&
1500                      (DB_get_call_by_hash($GAME['schweinchen-who']) || DB_get_partner_call_by_hash($GAME['schweinchen-who']) ))
1501                   )
1502                   {
1503                     DB_insert_comment('Schweinchen! ',$playid,$gameid,$myid);
1504                     $commentSchweinchen = 'Schweinchen! ';
1505                   }
1506                 if ($debug)
1507                   echo 'schweinchen = '.$GAME['schweinchen-who'].' ---<br />';
1508               }
1509
1510             /* if sequence == 4 check who one in case of wedding */
1511             if($sequence == 4 && $GT == 'wedding')
1512               {
1513                 /* is wedding resolve */
1514                 $resolved = DB_get_sickness_by_gameid($gameid);
1515                 if($resolved<0)
1516                   {
1517                     /* who has wedding */
1518                     $userids = DB_get_all_userid_by_gameid($gameid);
1519                     foreach($userids as $user)
1520                       {
1521                         $usersick = DB_get_sickness_by_userid_and_gameid($user,$gameid);
1522                         if($usersick == 'wedding')
1523                           $whosick = $user;
1524                       }
1525                     /* who won the trick */
1526                     $play     = DB_get_cards_by_trick($trickid);
1527                     $winner   = get_winner($play,$gametype); /* returns the position */
1528                     $winnerid = DB_get_userid('gameid-position',$gameid,$winner);
1529                     /* is tricknr <=3 */
1530                     if($tricknr <=3 && $winnerid!=$whosick)
1531                       {
1532                         /* set resolved at tricknr*/
1533                         $resolved = DB_set_sickness_by_gameid($gameid,$tricknr);
1534                         /* set partner */
1535                         $whash = DB_get_hash_from_gameid_and_userid($gameid,$winnerid);
1536                         DB_set_party_by_hash($whash,'re');
1537                       }
1538                     if($tricknr == 3 && $winnerid==$whosick)
1539                       {
1540                         /* set resolved at tricknr*/
1541                         $resolved = DB_set_sickness_by_gameid($gameid,'3');
1542                       }
1543                   }
1544               }
1545
1546             /* if sequence == 4, set winner of the trick, count points and set the next player */
1547             if($sequence==4)
1548               {
1549                 $play   = DB_get_cards_by_trick($trickid);
1550                 $winner = get_winner($play,$gametype); /* returns the position */
1551
1552                 /*
1553                  * check if someone caught a fox
1554                  *******************************/
1555
1556                 /* first check if we should account for solos at all,
1557                  * since it doesn't make sense in some games
1558                  */
1559                 $ok = 0; /* fox shouldn't be counted */
1560                 if($gametype_raw=='solo')
1561                   {
1562                     $solo = DB_get_solo_by_gameid($gameid);
1563                     if($solo == 'trump' || $solo == 'silent')
1564                       $ok = 1; /* for trump solos and silent solos, foxes are ok */
1565                   }
1566                 else
1567                   $ok = 1; /* for all other games (not solos) foxes are ok too */
1568
1569                 if($ok==1)
1570                   foreach($play as $played)
1571                     {
1572                       if ( $played['card']==19 || $played['card']==20 )
1573                         if ($played['pos']!= $winner )
1574                           {
1575                             /* possible caught a fox, check party */
1576                             $uid1 = DB_get_userid('gameid-position',$gameid,$winner);
1577                             $uid2 = DB_get_userid('gameid-position',$gameid,$played['pos']);
1578
1579                             $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1580                             $party2 = DB_get_party_by_gameid_and_userid($gameid,$uid2);
1581
1582                             if($party1 != $party2)
1583                               DB_query("INSERT INTO Score".
1584                                        " VALUES( NULL,NULL,$gameid,'$party1',$uid1,$uid2,'fox')");
1585                           }
1586                     }
1587
1588                 /*
1589                  * check for karlchen (jack of clubs in the last trick)
1590                  ******************************************************/
1591
1592                 /* same as for foxes, karlchen doesn't always make sense
1593                  * check what kind of game it is and set karlchen accordingly */
1594
1595                 if($tricknr == 12 ) /* Karlchen works only in the last trick */
1596                   {
1597                     /* no Karlchen in these solos */
1598                     if($gametype_solo != 'trumpless' && $gametype_solo != 'jack' && $gametype_solo != 'queen' )
1599                       {
1600                         foreach($play as $played)
1601                           if ( $played['card']==11 || $played['card']==12 )
1602                             if ($played['pos'] == $winner )
1603                               {
1604                                 /* save Karlchen */
1605                                 $uid1   = DB_get_userid('gameid-position',$gameid,$winner);
1606                                 $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1607
1608                                 DB_query("INSERT INTO Score".
1609                                          " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'karlchen')");
1610                               };
1611                       };
1612                   }; /* end scoring Karlchen */
1613
1614                 /*
1615                  * check for doppelopf (>40 points)
1616                  ***********************************/
1617
1618                 $points = 0;
1619                 foreach($play as $played)
1620                   {
1621                     $points += DB_get_card_value_by_cardid($played['card']);
1622                   }
1623                 if($points > 39)
1624                   {
1625                     $uid1   = DB_get_userid('gameid-position',$gameid,$winner);
1626                     $party1 = DB_get_party_by_gameid_and_userid($gameid,$uid1);
1627
1628                     DB_query("INSERT INTO Score".
1629                              " VALUES( NULL,NULL,$gameid,'$party1',$uid1,NULL,'doko')");
1630                   }
1631
1632                 /*
1633                  * set winner (for this trick)
1634                  */
1635
1636                 if($winner>0)
1637                   DB_query("UPDATE Trick SET winner='$winner' WHERE id=".DB_quote_smart($trickid));
1638                 else
1639                   $messages[] = "ERROR during scoring";
1640
1641                 if($debug)
1642                   echo "DEBUG: position $winner won the trick <br />";
1643
1644                 /* who is the next player? */
1645                 $next = $winner;
1646                 $firstcard = ''; /* unset firstcard, so followsuit doesn't trigger with the last trick */
1647               }
1648             else
1649               {
1650                 $next = DB_get_pos_by_hash($me)+1;
1651               }
1652             if($next==5) $next=1;
1653
1654             /* check for coment */
1655             if(myisset('comment'))
1656               {
1657                 $comment = $_REQUEST['comment'];
1658                 if($comment != '')
1659                   DB_insert_comment($comment,$playid,$gameid,$myid);
1660                 if($commentSchweinchen)
1661                   $comment = $commentSchweinchen . $comment;
1662                 if($commentCall != '')
1663                   $comment = $commentCall . $comment;
1664               };
1665
1666             /* display played card */
1667             $pos = DB_get_pos_by_hash($me);
1668             if($sequence==1)
1669               {
1670                 echo '    <div class="trick" id="trick'.($tricknr)."\">\n".
1671                   '      <img class="arrow" src="pics/arrow'.($pos-1).".png\" alt=\"table\" />\n";
1672               }
1673
1674             echo '      <div class="card'.($pos-1)."\">\n        ";
1675
1676             /* display comments */
1677             display_card($card,$PREF['cardset']);
1678             if($comment!='')
1679               echo "\n        <span class=\"comment\"> ".$comment."</span>\n";
1680             echo "      </div>\n";
1681
1682             echo "    </div>\n";  /* end div trick, end li trick */
1683
1684             /*check if we still have cards left, else set status to gameover */
1685             if(sizeof(DB_get_hand($me))==0)
1686               {
1687                 DB_set_hand_status_by_hash($me,'gameover');
1688                 $mystatus = 'gameover';
1689               }
1690
1691             /* if all players are done, set game status to game over,
1692              * get the points of the last trick and send out an email
1693              * to all players
1694              */
1695             $userids = DB_get_all_userid_by_gameid($gameid);
1696
1697             $done=1;
1698             foreach($userids as $user)
1699               if(DB_get_hand_status_by_userid_and_gameid($user,$gameid)!='gameover')
1700                 $done=0;
1701
1702             if($done)
1703               DB_set_game_status_by_gameid($gameid,'gameover');
1704
1705             /* email next player, if game is still running */
1706             if(DB_get_game_status_by_gameid($gameid)=='play')
1707               {
1708                 $next_hash = DB_get_hash_from_game_and_pos($gameid,$next);
1709                 $userid    = DB_get_userid('hash',$next_hash);
1710                 DB_set_player_by_gameid($gameid,$userid);
1711
1712                 if( DB_get_email_pref_by_uid($userid)!='emailaddict' )
1713                   {
1714                     set_language($userid,'uid');
1715                     $email_message = sprintf(_("A card has been played in game %s.\n\n".
1716                       "It's your turn now.\n".
1717                       'Use this link to play a card: '),DB_format_gameid($gameid)).$HOST.$INDEX.'?action=game&me='.$next_hash."\n\n" ;
1718                     mymail($userid,$gameid, GAME_YOUR_TURN, $email_message);
1719                     set_language($myid,'uid');
1720                   }
1721               }
1722             else /* send out final email */
1723               {
1724                 /* individual score */
1725                 $result = DB_query('SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party FROM Hand'.
1726                                    ' LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id'.
1727                                    ' LEFT JOIN User ON User.id=Hand.user_id'.
1728                                    ' LEFT JOIN Play ON Trick.id=Play.trick_id'.
1729                                    ' LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id'.
1730                                    ' LEFT JOIN Card ON Card.id=Hand_Card.card_id'.
1731                                    " WHERE Hand.game_id=".DB_quote_smart($gameid).
1732                                    ' GROUP BY User.fullname' );
1733                 $email_final_score="";
1734                 while( $r = DB_fetch_array($result) )
1735                   $email_final_score .= '   '.$r[0].'('.$r[2].') '.$r[1]."\n";
1736
1737                 $result = DB_query('SELECT  Hand.party, IFNULL(SUM(Card.points),0) FROM Hand'.
1738                                    ' LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id'.
1739                                    ' LEFT JOIN User ON User.id=Hand.user_id'.
1740                                    ' LEFT JOIN Play ON Trick.id=Play.trick_id'.
1741                                    ' LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id'.
1742                                    ' LEFT JOIN Card ON Card.id=Hand_Card.card_id'.
1743                                    " WHERE Hand.game_id=".DB_quote_smart($gameid).
1744                                    ' GROUP BY Hand.party' );
1745                 $email_totals="";
1746                 $re     = 0;
1747                 $contra = 0;
1748                 while( $r = DB_fetch_array($result) )
1749                   {
1750                     $email_totals .= '    '.$r[0].' '.$r[1]."\n";
1751                     if($r[0] == 're')
1752                       $re = $r[1];
1753                     else if($r[0] == 'contra')
1754                       $contra = $r[1];
1755                   }
1756
1757                 /*
1758                  * save score in database
1759                  *
1760                  */
1761
1762                 /* get calls from re/contra */
1763                 $call_re     = -1;
1764                 $call_contra = -1;
1765                 foreach($userids as $user)
1766                   {
1767                     $hash  = DB_get_hash_from_gameid_and_userid($gameid,$user);
1768                     $call  = DB_get_call_by_hash($hash);
1769                     $party = DB_get_party_by_hash($hash);
1770
1771                     if($call!=NULL)
1772                       {
1773                         $call = (int) $call;
1774
1775                         if($party=='re')
1776                           {
1777                             if($call_re== -1)
1778                               $call_re = $call;
1779                             else if( $call < $call_re)
1780                               $call_re = $call;
1781                           }
1782                         else if($party=='contra')
1783                           {
1784                             if($call_contra== -1)
1785                               $call_contra = $call;
1786                             else if( $call < $call_contra)
1787                               $call_contra = $call;
1788                           }
1789                       }
1790                   }
1791
1792                 /* figure out who one */
1793                 $winning_party = NULL;
1794
1795                 if($call_re == -1 && $call_contra == -1)
1796                   {
1797                     /* nobody made a call, so it's easy to figure out who won */
1798                     if($re>120)
1799                       $winning_party='re';
1800                     else
1801                       $winning_party='contra';
1802                   }
1803                 else
1804                   {
1805                     /* if one party makes a call, they only win, iff they make enough points
1806                      * if only one party made a call, the other one wins,
1807                      * if the first one didn't make it
1808                      */
1809                     if($call_re != -1)
1810                       {
1811                         $offset = 120 - $call_re;
1812                         if($call_re == 0)
1813                           $offset--; /* since we use a > in the next equation */
1814
1815                         if($re > 120+$offset)
1816                           $winning_party='re';
1817                         else if ($call_contra == -1 )
1818                           $winning_party='contra';
1819                       }
1820
1821                     if($call_contra != -1)
1822                       {
1823                         $offset = 120 - $call_contra;
1824                         if($call_contra == 0)
1825                           $offset--; /* since we use a > in the next equation */
1826
1827                         if($contra > 120+$offset)
1828                           $winning_party='contra';
1829                         else if ($call_re == -1 )
1830                           $winning_party='re';
1831                       }
1832                   }
1833
1834                 /* one point for each call of the other party in case the other party didn't win
1835                  * and one point each in case the party made more than points than one of the calls
1836                  */
1837                 if($winning_party!='contra' && $call_contra!= -1)
1838                   {
1839                     for( $p=$call_contra;$p<=120; $p+=30 )
1840                       {
1841                           DB_query('INSERT INTO Score'.
1842                                    " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'against$p')");
1843                         }
1844
1845                       for( $p=$call_contra; $p<120; $p+=30)
1846                         {
1847                           if( $re >= $p )
1848                             DB_query('INSERT INTO Score'.
1849                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'made$p')");
1850                         }
1851                     }
1852                   if($winning_party!='re' and $call_re!= -1)
1853                     {
1854                       for( $p=$call_re;$p<=120; $p+=30 )
1855                         {
1856                           DB_query('INSERT INTO Score'.
1857                                    " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'against$p')");
1858                         }
1859
1860                       for( $p=$call_re; $p<120; $p+=30)
1861                         {
1862                           if( $contra>=$p )
1863                             DB_query('INSERT INTO Score'.
1864                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'made$p')");
1865                         }
1866                     }
1867
1868                   /* point in case contra won */
1869                   if($winning_party=='contra')
1870                     {
1871                       DB_query('INSERT INTO Score'.
1872                                " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'againstqueens')");
1873                     }
1874
1875                   /* one point each for winning and each 30 points + calls */
1876                   if($winning_party=='re')
1877                     {
1878                       foreach(array(120,150,180,210,240) as $p)
1879                         {
1880                           $offset = 0;
1881                           if($p==240 || $call_contra != -1)
1882                             $offset = 1;
1883
1884                           if($re>$p-$offset)
1885                             DB_query('INSERT INTO Score'.
1886                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'".(240-$p)."')");
1887                         }
1888                       /* re called something and won */
1889                       foreach(array(0,30,60,90,120) as $p)
1890                         {
1891                           if($call_re!= -1 && $call_re<$p+1)
1892                             DB_query('INSERT INTO Score'.
1893                                      " VALUES( NULL,NULL,$gameid,'re',NULL,NULL,'call$p')");
1894                         }
1895                     }
1896                   else if( $winning_party=='contra')
1897                     {
1898                       foreach(array(120,150,180,210,240) as $p)
1899                         {
1900                           $offset = 0;
1901                           if($p==240 || $call_re != -1)
1902                             $offset = 1;
1903
1904                           if($contra>$p-$offset)
1905                             DB_query('INSERT INTO Score'.
1906                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'".(240-$p)."')");
1907                         }
1908                       /* re called something and won */
1909                       foreach(array(0,30,60,90,120) as $p)
1910                         {
1911                           if($call_contra != -1 && $call_contra<$p+1)
1912                             DB_query('INSERT INTO Score'.
1913                                      " VALUES( NULL,NULL,$gameid,'contra',NULL,NULL,'call$p')");
1914                         }
1915                     };
1916
1917                   /* add score points to email */
1918                   $Tpoint = 0;
1919
1920                   $email_points_re="";
1921                   $queryresult = DB_query('SELECT score FROM Score '.
1922                                           "  WHERE game_id=".DB_quote_smart($gameid)." AND party='re'");
1923                   while($r = DB_fetch_array($queryresult) )
1924                     {
1925                       $email_points_re .= '   '.$r[0]."\n";
1926                       $Tpoint ++;
1927                     }
1928
1929                   $email_points_contra="";
1930                   $queryresult = DB_query('SELECT score FROM Score '.
1931                                           "  WHERE game_id=".DB_quote_smart($gameid)." AND party='contra'");
1932                   while($r = DB_fetch_array($queryresult) )
1933                     {
1934                       $email_points_contra .= '   '.$r[0]."\n";
1935                       $Tpoint --;
1936                     }
1937
1938                   $session = DB_get_session_by_gameid($gameid);
1939                   $score = generate_score_table($session);
1940
1941                   $email_score_table = format_score_table_ascii($score);
1942
1943                   /* add user links */
1944                   $email_user_links="";
1945                   foreach($userids as $user)
1946                     {
1947                       /* add links for all players */
1948                       $hash = DB_get_hash_from_gameid_and_userid($gameid,$user);
1949                       $name = DB_get_name('userid',$user);
1950
1951                       $link = "$name: ".$HOST.$INDEX."?action=game&me=".$hash."\n" ;
1952                       $email_user_links .= $link;
1953                     }
1954
1955                   foreach($userids as $user)
1956                     {
1957                       /* set correct language for this user */
1958                       set_language($user,'uid');
1959
1960                       /* generate message */
1961                       $email_message  = _("The game is over. Thanks for playing :)")."\n";
1962                       $email_message .= _("Final score:")."\n";
1963                       $email_message .= $email_final_score;
1964                       $email_message .= "\n"._("Totals:")."\n";
1965                       $email_message .= $email_totals;
1966                       $email_message .= "\n "._("Points Re:")." \n";
1967                       $email_message .= $email_points_re;
1968                       $email_message .= " "._("Points Contra:")." \n";
1969                       $email_message .= $email_points_contra;
1970                       $email_message .= " "._("Total Points (from the Re point of view):")." $Tpoint\n\n";
1971                       $email_message .= _("Score Table:")."\n";
1972                       $email_message .= $email_score_table;
1973                       $email_message .= "\n"._("Use these links to have a look at game")." ".DB_format_gameid($gameid).": \n";
1974                       $email_message .= $email_user_links;
1975                       $email_message .= "\n\n "._("(use in-game comments to reach all players)")."\n\n";
1976
1977                       /* send email */
1978                       mymail($user,$gameid, GAME_OVER, $email_message);
1979                     }
1980                   /* reset language */
1981                   set_language($myid,'uid');
1982               }
1983           }
1984         else
1985           {
1986             $messages[] = _("can't find that card?!");
1987           }
1988       }
1989     else if(myisset('card') && !$myturn )
1990       {
1991         $messages[] = _("please wait until it's your turn!");
1992       }
1993
1994     if($seq!=4 && $trickNR>=1 && !(myisset('card') && $myturn) )
1995       echo "    </div>\n";  /* end div trick, end li trick */
1996
1997     /* display points in case game is over */
1998     if($mystatus=='gameover' && DB_get_game_status_by_gameid($gameid)=='gameover' )
1999       {
2000         echo "    <div class=\"trick\" id=\"trick13\">\n";
2001         /* add pic for re/contra
2002          "      <img class=\"arrow\" src=\"pics/arrow".($pos-1).".png\" alt=\"table\" />\n";*/
2003
2004         $result = DB_query('SELECT User.fullname, IFNULL(SUM(Card.points),0), Hand.party,Hand.position FROM Hand'.
2005                            ' LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id'.
2006                            ' LEFT JOIN User ON User.id=Hand.user_id'.
2007                            ' LEFT JOIN Play ON Trick.id=Play.trick_id'.
2008                            ' LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id'.
2009                            ' LEFT JOIN Card ON Card.id=Hand_Card.card_id'.
2010                            " WHERE Hand.game_id=".DB_quote_smart($gameid).
2011                            ' GROUP BY User.fullname' );
2012         while( $r = DB_fetch_array($result))
2013           echo '      <div class="card'.($r[3]-1)."\">\n".
2014             '        <div class="score">'.$r[2].'<br /> '.$r[1]."</div>\n".
2015             "      </div>\n";
2016
2017         /* display totals */
2018         $result = DB_query('SELECT Hand.party, IFNULL(SUM(Card.points),0) FROM Hand'.
2019                            ' LEFT JOIN Trick ON Trick.winner=Hand.position AND Trick.game_id=Hand.game_id'.
2020                            ' LEFT JOIN User ON User.id=Hand.user_id'.
2021                            ' LEFT JOIN Play ON Trick.id=Play.trick_id'.
2022                            ' LEFT JOIN Hand_Card ON Hand_Card.id=Play.hand_card_id'.
2023                            ' LEFT JOIN Card ON Card.id=Hand_Card.card_id'.
2024                            " WHERE Hand.game_id=".DB_quote_smart($gameid).
2025                            ' GROUP BY Hand.party' );
2026         echo "    <div class=\"total\">\n  "._("Totals:")."<br />\n";
2027         while( $r = DB_fetch_array($result))
2028           echo '      '.$r[0].' '.$r[1]."<br />\n";
2029
2030         $queryresult = DB_query('SELECT timediff(mod_date,create_date) '.
2031                                 " FROM Game WHERE id=".DB_quote_smart($gameid));
2032         $r = DB_fetch_array($queryresult);
2033         echo '      <p>';
2034         printf(_('This game took %d hours.'), $r[0]);
2035         echo "</p>\n";
2036
2037         echo "      <div class=\"re\">\n   "._("Points Re:")." <br />\n";
2038         $queryresult = DB_query('SELECT score FROM Score '.
2039                                 "  WHERE game_id=".DB_quote_smart($gameid)." AND party='re'");
2040         while($r = DB_fetch_array($queryresult) )
2041           echo '       '.$r[0]."<br />\n";
2042         echo "      </div>\n";
2043
2044         echo "      <div class=\"contra\">\n   "._("Points Contra:")." <br />\n";
2045         $queryresult = DB_query('SELECT score FROM Score '.
2046                                 "  WHERE game_id=".DB_quote_smart($gameid)." AND party='contra'");
2047         while($r = DB_fetch_array($queryresult) )
2048           echo '       '.$r[0]."<br />\n";
2049         echo "      </div>\n";
2050
2051         echo "    </div>\n";
2052
2053         echo "    </div>\n";  /* end div trick, end li trick */
2054       }
2055
2056     echo "</div>\n"; /* end ul tricks*/
2057
2058     if(   ($myturn && !myisset('card') && $mystatus=='play') /* it's my turn*/
2059           || ($myturn && myisset('card') && $next==$mypos && $mystatus=='play')  /* a card has been played and player won the trick*/)
2060       {
2061         $card_status = CARDS_MYTURN;
2062       }
2063     else if($mystatus=='play' )
2064       {
2065         $card_status = CARDS_SHOW;
2066       }
2067     else if($mystatus=='gameover')
2068       {
2069         if(isset($_SESSION['id']) && $myid==$_SESSION['id'])
2070           $card_status = CARDS_GAMEOVER_ME;
2071         else
2072           $card_status = CARDS_GAMEOVER;
2073       }
2074
2075     /* if the game is over do some extra stuff, therefore exit the swtich statement if we are still playing*/
2076     if($mystatus=='play')
2077       break;
2078
2079     /* the following happens only when the gamestatus is 'gameover' */
2080     /* check if game is over, display results */
2081     if(DB_get_game_status_by_gameid($gameid)=='play')
2082       {
2083         $messages[] = _('The game is over for you... other people still need to play though');
2084       }
2085     break;
2086   default:
2087     myerror('error in testing the status');
2088   } /*end of output: tricks, table, messages, card */
2089
2090 /* display the 2nd half of table and the names */
2091
2092 /***********************************
2093  * Output pre-trick if needed      *
2094  * this outputs status of healthy, *
2095  * sick, etc during pre-game phase *
2096  **********************************/
2097 switch($mystatus)
2098   {
2099   case 'start':
2100     break;
2101   case 'init':
2102   case 'check':
2103     /* output sickness of other playes, in case they already selected and are sitting in front of the current player */
2104     echo "\n".'<div class="tricks">'."\n";
2105     echo '    <div class="trick" id="trick0">'."\n";
2106
2107     for($pos=1;$pos<5;$pos++)
2108       {
2109         $usersick   = DB_get_sickness_by_pos_and_gameid($pos,$gameid);
2110         $userid     = DB_get_userid('gameid-position',$gameid,$pos);
2111         $userstatus = DB_get_hand_status_by_userid_and_gameid($userid,$gameid);
2112
2113         if($userstatus=='start' || $userstatus=='init')
2114           echo ' <div class="vorbehalt'.($pos-1).'">'._('still needs <br />to decide')."</div>\n"; /* show this to everyone */
2115         else
2116           if($usersick!=NULL) /* in the init-phase we only showed players with $pos<$mypos, now we can show all */
2117             echo ' <div class="vorbehalt'.($pos-1).'">'._('sick')."</div>\n";
2118           else
2119             echo ' <div class="vorbehalt'.($pos-1).'">'._('healthy')."</div>\n";
2120       }
2121
2122     /* display all comments on the top right (card1)*/
2123     $comments = DB_get_pre_comment($gameid);
2124     /* display card */
2125     echo '      <div class="card1">'."\n";
2126     /* display comments */
2127     foreach( $comments as $comment )
2128       echo '        <span class="comment">'.$comment[1].': '.$comment[0]."</span>\n";
2129     echo "      </div>\n"; /* end div card */
2130
2131
2132     echo "    </div>\n  </div>\n";  /* end div trick, end li trick , end tricks*/
2133     /* end displaying sickness */
2134
2135     break;
2136   case 'poverty':
2137     /* output pre-game trick in case user reloads,
2138      * only needs to be done when a team has been formed */
2139     if($myparty=='re' || $myparty=='contra')
2140       {
2141         echo "\n<div class=\"tricks\">\n";
2142
2143         echo "    <div class=\"trick\" id=\"trick0\">\n";
2144
2145         /* get information so show the cards that have been handed over in a poverty game */
2146         output_exchanged_cards($gametype);
2147
2148         echo "    </div>\n </div>\n\n";  /* end div trick, end li trick , end ul tricks */
2149       }
2150     /* end output pre-game trick */
2151     break;
2152   case 'play':
2153   case 'gameover':
2154
2155     /* already taken care of */
2156     break;
2157   default:
2158   }
2159
2160 display_table_end();
2161
2162 /**************
2163  * show cards *
2164  **************/
2165
2166 $mycards = DB_get_hand($me);
2167 $mycards = mysort($mycards,$gametype);
2168
2169 echo "\n";
2170 echo '<div class="mycards">';
2171 switch ($card_status) {
2172  case CARDS_SHOW:
2173    echo _('Your cards are').": <br />\n";
2174    foreach($mycards as $card)
2175      display_card($card,$PREF['cardset']);
2176    break;
2177  case CARDS_EXCHANGE:
2178    echo '<div class="poverty"> '._('You need to get rid of a few cards')."</div>\n";
2179
2180    echo _('Your cards are').": <br />\n";
2181    $type='exchange';
2182    foreach($mycards as $card)
2183      display_link_card($card,$PREF['cardset'],$type);
2184    echo '  <input type="submit" class="submitbutton" value="'._('select card to give back').'" />'."\n";
2185    break;
2186  case CARDS_MYTURN:
2187    printf (_("Hello %s, it's your turn!"),$myname);
2188    echo "  <br />\n";
2189    echo _('Your cards are').": <br />\n";
2190
2191    /* do we have to follow suite? */
2192    $followsuit = 0;
2193    if(have_suit($mycards,$firstcard))
2194      $followsuit = 1;
2195
2196    /* count how many cards we can play, so that we can pre-select it if there is only one */
2197    $howmanycards = 0;
2198    foreach($mycards as $card)
2199      {
2200        if($howmanycards>1)
2201          break;
2202
2203        /* display only cards that the player is allowed to play as links, the rest just display normal
2204         * also check if we have both schweinchen, in that case only display on of them as playable
2205         */
2206        if( ($followsuit && !same_type($card,$firstcard)) ||
2207            ( (int)($card)==19 &&
2208              !$GAME['schweinchen-first'] &&
2209              ( $RULES['schweinchen']=='second' ||
2210                ( $RULES['schweinchen']=='secondaftercall' &&
2211                  (DB_get_call_by_hash($GAME['schweinchen-who']) ||
2212                   DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
2213                  )
2214                ) &&
2215              $GAME['schweinchen-who']==$me &&
2216              in_array($gametype,array('normal','wedding','trump','silent'))
2217              )
2218            )
2219          continue;
2220        else
2221          $howmanycards++;
2222      }
2223
2224    /* make it boolean, so that we can pass it later to display_link_card */
2225    if($howmanycards!=1)
2226      $howmanycards=0;
2227
2228    foreach($mycards as $card)
2229      {
2230        /* display only cards that the player is allowed to play as links, the rest just display normal
2231         * also check if we have both schweinchen, in that case only display on of them as playable
2232         */
2233        if( ($followsuit && !same_type($card,$firstcard)) ||
2234            ( (int)($card)==19 &&
2235              !$GAME['schweinchen-first'] &&
2236              ( $RULES['schweinchen']=='second' ||
2237                ( $RULES['schweinchen']=='secondaftercall' &&
2238                  (DB_get_call_by_hash($GAME['schweinchen-who']) ||
2239                   DB_get_partner_call_by_hash($GAME['schweinchen-who']) )
2240                  )
2241                ) &&
2242              $GAME['schweinchen-who']==$me &&
2243              in_array($gametype,array('normal','wedding','trump','silent'))
2244              )
2245            )
2246          display_card($card,$PREF['cardset']);
2247        else
2248          display_link_card($card,$PREF['cardset'],$type='card',$selected=$howmanycards);
2249      }
2250    break;
2251  case CARDS_GAMEOVER_ME:
2252  case CARDS_GAMEOVER:
2253    if($card_status == CARDS_GAMEOVER_ME)
2254      echo _('Your cards were').": <br />\n";
2255    else
2256      {
2257        $name = DB_get_name('userid',$myid);
2258        printf (_("%s's were:"),$name);
2259        echo " <br />\n";
2260      }
2261    $oldcards = DB_get_all_hand($me);
2262    $oldcards = mysort($oldcards,$gametype);
2263
2264    foreach($oldcards as $card)
2265      display_card($card,$PREF['cardset']);
2266
2267    /* display hands of everyone else */
2268    $userids = DB_get_all_userid_by_gameid($gameid);
2269    foreach($userids as $user)
2270      {
2271        $userhash = DB_get_hash_from_gameid_and_userid($gameid,$user);
2272
2273        if($userhash!=$me)
2274          {
2275            echo "<br />";
2276
2277            $name = DB_get_name('userid',$user);
2278            $oldcards = DB_get_all_hand($userhash);
2279            $oldcards = mysort($oldcards,$gametype);
2280            printf(_("%s's cards were:"),$name);
2281            echo " <br />\n";
2282            foreach($oldcards as $card)
2283              display_card($card,$PREF['cardset']);
2284          }
2285      };
2286    break;
2287  case CARDS_EMPTY:
2288  default:
2289    break;
2290  }
2291 echo "</div>\n";
2292
2293 /*****************
2294  * show messages *
2295  *****************/
2296
2297 if( sizeof($messages) )
2298   {
2299     echo "\n<div class=\"message\">\n";
2300     foreach($messages as $message)
2301       {
2302         echo "  <div>$message <div>"._("close")."</div> </div>\n";
2303       }
2304     echo "</div>\n\n";
2305   }
2306
2307 /****************************
2308  * commit commentCall to DB *
2309  ****************************/
2310
2311 if($commentCall != '')
2312   {
2313     /* treat before game calls special, so that we can show them on the first trick and not the pre-phase */
2314     if($playid == -1)
2315       $playid = -2;
2316
2317     DB_insert_comment($commentCall,$playid,$gameid,$myid);
2318   }
2319 /***********************************************
2320  * Comments, re/contra calls, user menu
2321  ***********************************************/
2322
2323 /*
2324  * display gameinfo: re/contra, comment-box, play-card button, games played by others
2325  */
2326
2327 echo "<div class=\"gameinfo\">\n";
2328
2329 /* get time from the last action of the game */
2330 $r = DB_query_array("SELECT mod_date from Game WHERE id=".DB_quote_smart($gameid));
2331 $gameend = time() - strtotime($r[0]);
2332
2333 /* comment box */
2334 if($gamestatus == 'play' || $gamestatus == 'pre' || $gameend < 60*60*24*7)
2335   {
2336     echo '  '._('A short comment').":<input name=\"comment\" type=\"text\" size=\"20\" maxlength=\"100\" />\n";
2337   }
2338
2339 /* re-contra */
2340 if($gamestatus == 'play' )
2341   {
2342     $myparty = DB_get_party_by_hash($me);
2343     output_form_calls($me,$myparty);
2344   }
2345
2346 /* play-card button */
2347 if($gamestatus == 'play' || $gamestatus == 'pre' || $gameend < 60*60*24*7)
2348   {
2349     echo '  <input type="submit" value="'._('submit')."\" />\n";
2350   }
2351
2352 /* has this hand been played by others? */
2353 $other_game_ids = DB_played_by_others($gameid);
2354 if(sizeof($other_game_ids)>0 && $mystatus=='gameover')
2355   {
2356     $mypos = DB_get_pos_by_hash($me);
2357     echo '  <p>'._('See how other played the same hand:')." \n";
2358     foreach($other_game_ids as $id)
2359       {
2360         $otherhash = DB_get_hash_from_game_and_pos($id,$mypos);
2361         $othername = DB_get_name('hash',$otherhash);
2362         echo "    <a href=\"$INDEX?action=game&amp;me=$otherhash\">$othername</a> ";
2363       }
2364     echo "  </p>\n";
2365   }
2366
2367 echo "</div>\n\n"; /* end gameinfo */
2368
2369 /* make sure that we don't show the notes to the wrong person
2370  * (e.g. other people looking at an old game)
2371  */
2372 if( $mystatus != 'gameover' ||
2373     (  $mystatus == 'gameover' &&
2374        isset($_SESSION['id'])  &&
2375        $myid == $_SESSION['id']))
2376   output_user_notes($myid,$gameid,$mystatus);
2377
2378 echo "</form>\n";
2379
2380 /*********************************
2381  * suggest next game
2382  *********************************/
2383
2384 $gamestatus = DB_get_game_status_by_gameid($gameid);
2385 if($mystatus=='gameover' &&
2386    ($gamestatus =='gameover' || $gamestatus =='cancel-nines' || $gamestatus =='cancel-trump') &&
2387    isset($_SESSION['id']) && $_SESSION['id']==$myid)
2388   {
2389     $session = DB_get_session_by_gameid($gameid);
2390     $result  = DB_query('SELECT id,create_date FROM Game'.
2391                         " WHERE session=$session".
2392                         ' ORDER BY create_date DESC'.
2393                         ' LIMIT 1');
2394     $r = -1;
2395     if($result)
2396       $r = DB_fetch_array($result);
2397
2398     if(!$session || $gameid==$r[0])
2399       {
2400         /* suggest a new game with the same people in it, just rotated once (unless last game was solo) */
2401         $names = DB_get_all_names_by_gameid($gameid);
2402
2403         if($gametype_raw=='solo')
2404           {
2405             if($gametype_solo!='silent') /* repeat game with same first player */
2406               output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
2407             else /* rotate normally */
2408               output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
2409           }
2410         else if($gamestatus == 'cancel-nines' || $gamestatus == 'cancel-trump')
2411           output_ask_for_new_game($names[0],$names[1],$names[2],$names[3],$gameid);
2412         else /* rotate normally */
2413           output_ask_for_new_game($names[1],$names[2],$names[3],$names[0],$gameid);
2414       }
2415   }
2416 ?>