CLEANUP: make index.php very short and move everything in separate files
[e-DoKo.git] / include / user.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 /* test id and password, should really be done in one step */
9 if(!isset($_SESSION["name"]))
10   {
11     $email     = $_REQUEST["email"];
12     $password  = $_REQUEST["password"];
13   }
14  else
15    {
16      $name = $_SESSION["name"];
17      $email     = DB_get_email('name',$name);
18      $password  = DB_get_passwd_by_name($name);
19    };
20
21 /* user has forgotten his password */
22 if(myisset("forgot"))
23   {
24     /* check if player is in the database */
25     $ok = 1;
26
27     $myid = DB_get_userid('email',$email);
28     if(!$myid)
29       $ok = 0;
30
31     if($ok)
32       {
33         /* check how many entries in recovery table */
34         $number = DB_get_number_of_passwords_recovery($myid);
35
36         /* if less than N recent ones, add a new one and send out email */
37         if( $number < 5 )
38           {
39             echo "Ok, I send you a new password. <br />";
40             if($number >1)
41               echo "N.B. You tried this already $number times during the last day and it will only work ".
42                 " 5 times during a day.<br />";
43             echo "The new password will be valid for one day, make sure you reset it to something else.<br />";
44             echo "Back to the  <a href=\"$INDEX\">main page</a>.";
45
46             /* create temporary password, use the fist 8 letters of a md5 hash */
47             $TIME  = (string) time(); /* to avoid collisions */
48             $hash  = md5("Anewpassword".$email.$TIME);
49             $newpw = substr($hash,1,8);
50
51             $message = "Someone (hopefully you) requested a new password. \n".
52               "You can use this email and the following password: \n".
53               "   $newpw    \n".
54               "to log into the server. The new password is valid for 24h, so make\n".
55               "sure you reset your password to something new. Your old password will\n".
56               " also still be valid until you set a new one\n";
57             mymail($email,$EmailName."recovery ",$message);
58
59             /* we save these in the database */
60             DB_set_recovery_password($myid,md5($newpw));
61           }
62         else
63           {
64             /* make it so that people (or a robot) can request thousands of passwords within a short time
65              * and spam a user this way */
66             echo "Sorry you already tried 5 times during the last 24h.<br />".
67               "You need to use one of those passwords or wait to get a new one.<br />";
68             echo "Back to the <a href=\"$INDEX\">main page</a>.";
69           }
70       }
71     else
72       {/* can't find user id in the database */
73              
74         /* no email given? */
75         if($email=="")
76           echo "You need to give me an email address! <br />".
77             "Please try <a href=\"$INDEX\">again</a>.";
78         else /* default error message */
79           echo "Couldn't find a player with this email! <br />".
80             "Please contact Arun, if you think this is a mistake <br />".
81             "or else try <a href=\"$INDEX\">again</a>.";
82       }
83   }
84  else 
85    { /* normal user page */
86
87
88      /* verify password and email */
89      if(strlen($password)!=32)
90        $password = md5($password);
91
92      $ok  = 1;
93      $myid = DB_get_userid('email-password',$email,$password);
94      if(!$myid)
95        $ok = 0;
96
97      if($ok)
98        {
99          /* user information is ok */
100          $myname = DB_get_name('email',$email);
101          $_SESSION["name"] = $myname;
102          output_status();
103     
104          DB_get_PREF($myid);
105     
106          /* does the user want to change some preferences? */
107          if(myisset("setpref"))
108            {
109              $setpref=$_REQUEST["setpref"];
110              switch($setpref)
111                {
112                case "germancards":
113                case "englishcards":
114                  $result = mysql_query("SELECT * from User_Prefs".
115                                        " WHERE user_id='$myid' AND pref_key='cardset'" );
116                  if( mysql_fetch_array($result,MYSQL_NUM))
117                    $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart($setpref).
118                                          " WHERE user_id='$myid' AND pref_key='cardset'" );
119                  else
120                    $result = mysql_query("INSERT INTO User_Prefs VALUES(NULL,'$myid','cardset',".
121                                          DB_quote_smart($setpref).")");
122                  echo "Ok, changed you preferences for the cards.\n";
123                  break;
124                case "emailaddict":
125                case "emailnonaddict":
126                  $result = mysql_query("SELECT * from User_Prefs".
127                                        " WHERE user_id='$myid' AND pref_key='email'" );
128                  if( mysql_fetch_array($result,MYSQL_NUM))
129                    $result = mysql_query("UPDATE User_Prefs SET value=".DB_quote_smart($setpref).
130                                          " WHERE user_id='$myid' AND pref_key='email'" );
131                  else
132                    $result = mysql_query("INSERT INTO User_Prefs VALUES(NULL,'$myid','email',".
133                                          DB_quote_smart($setpref).")");
134                  echo "Ok, changed you preferences for sending out emails.\n";
135                  break;
136                }
137            }
138          /* user wants to change his password or request a temporary one */
139          else if(myisset("passwd"))
140            {
141              if( $_REQUEST["passwd"]=="ask" )
142                {
143                  /* reset password form*/
144                  output_password_recovery($email,$password);
145                }
146              else if($_REQUEST["passwd"]=="set")
147                {
148                  /* reset password */
149                  $ok = 1;
150
151                  /* check if old password matches */
152                  $oldpasswd = md5($_REQUEST["password0"]);
153                  if(!( ($password == $oldpasswd) || DB_check_recovery_passwords($oldpasswd,$email) ))
154                    $ok = -1;
155                  /* check if new passwords are types the same twice */
156                  if($_REQUEST["password1"] != $_REQUEST["password2"] )
157                    $ok = -2;
158
159                  switch($ok)
160                    {
161                    case '-2':
162                      echo "The new passwords don't match. <br />";
163                      break;
164                    case '-1':
165                      echo "The old password is not correct. <br />";
166                      break;
167                    case '1':
168                      echo "Changed the password.<br />";
169                      mysql_query("UPDATE User SET password='".md5($_REQUEST["password1"]).
170                                  "' WHERE id=".DB_quote_smart($myid));
171                      break;
172                    }
173                  /* set password */
174                }
175            }
176          else /* output default user page */
177            {
178              /* display links to settings */
179              output_user_settings();
180
181              DB_update_user_timestamp($myid);
182
183              display_user_menu();
184
185              /* display all games the user has played */
186              echo "<div class=\"user\">";
187              echo "<h4>These are all your games:</h4>\n";
188              echo "<p>Session: <br />\n";
189              echo "<span class=\"gamestatuspre\"> p </span> =  pre-game phase ";
190              echo "<span class=\"gamestatusplay\">P </span> =  game in progess ";
191              echo "<span class=\"gamestatusover\">F </span> =  game finished <br />";
192              echo "</p>\n";
193
194              $output = array();
195              $result = mysql_query("SELECT Hand.hash,Hand.game_id,Game.mod_date,Game.player,Game.status from Hand".
196                                    " LEFT JOIN Game ON Game.id=Hand.game_id".
197                                    " WHERE user_id='$myid'".
198                                    " ORDER BY Game.session,Game.create_date" );
199              $gamenrold = -1;
200              echo "<table>\n <tr><td>\n";
201              while( $r = mysql_fetch_array($result,MYSQL_NUM))
202                {
203                  $game = DB_format_gameid($r[1]);
204                  $gamenr = (int) $game;
205                  if($gamenrold < $gamenr)
206                    {
207                      if($gamenrold!=-1)
208                        echo "</td></tr>\n <tr> <td>$gamenr:</td><td> ";
209                      else
210                        echo "$gamenr:</td><td> ";
211                      $gamenrold = $gamenr;
212                    }
213                  if($r[4]=='pre')
214                    {
215                      echo "\n   <span class=\"gamestatuspre\"><a href=\"".$INDEX."?me=".$r[0]."\">p </a></span> ";
216
217                    }
218                  else if ($r[4]=='gameover')
219                    echo "\n   <span class=\"gamestatusover\"><a href=\"".$INDEX."?me=".$r[0]."\">F </a></span> ";
220                  else
221                    {
222                      echo "\n   <span class=\"gamestatusplay\"><a href=\"".$INDEX."?me=".$r[0]."\">P </a></span> ";
223                    }
224                  if($r[4] != 'gameover')
225                    {
226                      echo "</td><td>\n    ";
227                      if($r[3]==$myid || !$r[3])
228                        echo "(it's <strong>your</strong> turn)\n";
229                      else
230                        {
231                          $name = DB_get_name('userid',$r[3]);
232                          $gameid = $r[1];
233                          if(DB_get_reminder($r[3],$gameid)==0)
234                            if(time()-strtotime($r[2]) > 60*60*24*7)
235                              echo "".
236                                "<a href=\"$INDEX?remind=1&amp;me=".$r[0]."\">Send a reminder.</a>";
237                          echo "(it's $name's turn)\n";
238                        };
239                      if(time()-strtotime($r[2]) > 60*60*24*30)
240                        echo "".
241                          "<a href=\"$INDEX?cancel=1&amp;me=".$r[0]."\">Cancel?</a>".
242                          " (clicking here is final and can't be restored)";
243
244                    }
245                }
246              echo "</td></tr>\n</table>\n";
247
248              /* display last 5 users that have signed up to e-DoKo */
249              $names = DB_get_names_of_new_logins(5);
250              echo "<h4>New Players:</h4>\n<p>\n";
251              echo implode(", ",$names).",...\n";
252              echo "</p>\n";
253
254              /* display last 5 users that logged on */
255              $names = DB_get_names_of_last_logins(5);
256              echo "<h4>Players last logged in:</h4>\n<p>\n";
257              echo implode(", ",$names).",...\n";
258              echo "</p>\n";
259                
260              echo "</div>\n";
261            }
262        }
263      else
264        {
265          echo "<div class=\"message\">Sorry email and password don't match. Please <a href=\"$INDEX\">try again</a>. </div>";
266        }
267    };
268 output_footer();
269 DB_close();
270 exit();
271
272 ?>