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