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