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