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