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