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