YaWK  24.1
Yet another WebKit
user.php
Go to the documentation of this file.
1 <?php
2 namespace YAWK {
3  /**
4  * @details The default user class. Provide all functions to handle the user object.
5  *
6  * All functions that are required to handle a user. Methods are: add, edit, delete, checklogin and many more.
7  * <p><i>Class covers both, backend & frontend functionality.
8  * See Methods Summary for Details!</i></p>
9  *
10  * @author Daniel Retzl <[email protected]>
11  * @copyright 2009-2015 Daniel Retzl
12  * @license https://opensource.org/licenses/MIT
13  * @brief The default user class. Provide all functions to handle the user object.
14  */
15 
16  class user
17  {
18  /** * @param string current user name */
19  public $currentuser;
20  /** * @param string username */
21  public $username;
22  /** * @param int 0|1 if 1, user is blocked and cannot login anymore */
23  public $blocked;
24  /** * @param int user ID */
25  public $id;
26  /** * @param int 0|1 if 1, user is published (active) */
27  public $published;
28  /** * @param int 0|1 if 1, user privacy needs to be respected */
29  public $privacy;
30  /** * @param int 0|1 if 1, user is currently online (or at least: not logged out) */
31  public $online;
32  /** * @param int group ID */
33  public $gid;
34  /** * @param string user password */
35  public $password;
36  /** * @param string datetime when user was created */
37  public $date_created;
38  /** * @param string datetime when user has changed */
39  public $date_changed;
40  /** * @param string datetime when user has last logged in */
42  /** * @param string datetime when user account is about to expire */
43  public $date_expired;
44  /** * @param int how many times the user have logged in */
45  public $login_count;
46  /** * @param string user email address*/
47  public $email;
48  /** * @param string user URL */
49  public $url;
50  /** * @param string user twitter url */
51  public $twitter;
52  /** * @param string user facebook url */
53  public $facebook;
54  /** * @param string user firstname */
55  public $firstname;
56  /** * @param string user lastname */
57  public $lastname;
58  /** * @param string street */
59  public $street;
60  /** * @param string zip code */
61  public $zipcode;
62  /** * @param string city */
63  public $city;
64  /** * @param string country */
65  public $country;
66  /** * @param string job description - can held any string */
67  public $job;
68  /** * @param string datetime when user has last logged in */
69  public $lastlogin;
70  /** * @param int 0|1 1 means the email is public and can be shown on the website */
71  public $public_email;
72  /** * @param int 0|1 user is currently logged in - or at least: not logged out */
73  public $logged_in;
74  /** * @param int how many likes the user has achieved */
75  public $likes;
76  /** * @param int override the current template ID */
78  /** * @param int current template ID */
79  public $templateID;
80  /** * @param int 0|1 indicates, if user has accepted the terms of service */
81  public $terms;
82 
83  /**
84  * @brief user constructor.
85  */
86  function __construct($db)
87  {
88  if (!isset($db)){ $db = new \YAWK\db(); }
89  if (isset($_SESSION['username']))
90  {
91  $this->loadProperties($db, $_SESSION['username']);
92  }
93  }
94 
95 
96  /**
97  * @brief Generate a safe token for password reset
98  * @param string $length the length of your token
99  * @return string $token function returns the token
100  */
101  static function getToken($length)
102  {
103  $token = "";
104  $code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
105  $code.= "abcdefghijklmnopqrstuvwxyz";
106  $code.= "0123456789";
107  $max = strlen($code); // edited
108 
109  for ($i=0; $i < $length; $i++)
110  {
111  $token .= $code[random_int(0, $max-1)];
112  }
113  // check if token is set
114  if (is_string($token))
115  { // ok, return token
116  return $token;
117  }
118  else
119  { // error generating token
120  return false;
121  }
122  }
123 
124 
125  /**
126  * @brief Check if password reset token matches and return uid
127  * @param object $db database obj
128  * @param string $token token that was generated for this user
129  * @return mixed returns the affected user id (or false)
130  */
131  static function checkResetToken($db, $token)
132  {
133  // check if token is set and in valid format
134  if (isset($token) && (is_string($token)))
135  {
136  // strip tags for security reasons
137  $token = strip_tags($token);
138 
139  // compare with stored token in database
140  if ($res = $db->query("SELECT id FROM {users} WHERE hashValue = '".$token."'"))
141  {
142  // token matches, get user ID
143  if ($row = mysqli_fetch_row($res))
144  {
145  // return user ID
146  return $row[0];
147  }
148  else
149  { // no ID found
150  return false;
151  }
152  }
153  else
154  { // no user with this token hash value found
155  return false;
156  }
157  }
158  else
159  { // user token not set or wrong type
160  return false;
161  }
162  }
163 
164  /**
165  * @brief Draw the form where users can reset their password.
166  * @details The password reset email leads to this form.
167  * @param object $db database obj
168  * @param array $lang language array
169  * @param int $uid user ID
170  */
171  static function drawPasswordResetForm($db, $lang, $uid)
172  {
173  echo "<form action=\"index.php?setNewPassword=true\" method=\"POST\" role=\"form\">";
174  echo "<label for=\"newPassword1\">$lang[PASSWORD]</label>";
175  echo "<input type=\"password\" class=\"form-control\" name=\"newPassword1\" id=\"newPassword1\">";
176  echo "<label for=\"newPassword2\">$lang[PASSWORD_REPEAT]</label>";
177  echo "<input type=\"password\" class=\"form-control\" name=\"newPassword2\" id=\"newPassword2\">";
178  echo "<input type=\"hidden\" value=\"$uid\" class=\"form-control\" name=\"uid\" id=\"uid\">";
179  echo "<button type=\"submit\" style=\"margin-top:5px;\" class=\"btn btn-success\">$lang[PASSWORD_SET_NEW]</button>";
180  echo "</form>";
181  }
182 
183  /**
184  * @brief Set a new user password
185  * @param string $newPassword The new password that will be stored in the database
186  * @param int $uid The affected user id
187  * @param object $db database obj
188  */
189  static function setNewPassword($db, $newPassword, $uid)
190  {
191  // check if new password is set and valid
192  if (isset($newPassword) && (!empty($newPassword)) && (is_string($newPassword)))
193  { // check if uid is set and valid
194  if (isset($uid) && (!empty($uid)) && (is_numeric($uid)))
195  {
196  // hash password
197  $newPassword = md5($newPassword);
198 
199  // update database - change password
200  if ($res = $db->query("UPDATE {users} SET password = '".$newPassword."' WHERE id = '".$uid."'"))
201  { // password changed successfully
202  \YAWK\sys::setSyslog($db, 9, 0, "user $uid changed his password", $uid, 0, 0, 0);
203  return true;
204  }
205  else
206  { // password cannot be changed
207  \YAWK\sys::setSyslog($db, 11, 1, "failed to update password of user $uid ", $uid, 0, 0, 0);
208  return false;
209  }
210  }
211  else
212  { // uid not set or not valid
213  \YAWK\sys::setSyslog($db, 11, 1, "uid not set, empty or wrong datatype", $uid, 0, 0, 0);
214  return false;
215  }
216  }
217  else
218  { // new password not set or not valid
219  \YAWK\sys::setSyslog($db, 11, 1, "failed to update user password: new password not set, empty or not valid", $uid, 0, 0, 0);
220  return false;
221  }
222  }
223 
224  /**
225  * @brief Send password change request email
226  * @param object $db database obj
227  * @param string $username username from pwd reset form
228  * @param string $email email from pwd reset from
229  * @param object $lang language obj
230  * @return bool true|false
231  */
233  {
234  // first of all we check if user entered a correct username or email string.
235  // afterwards, we get the UID for this user and store a personal hash value
236  // user will get an email, containing a link with the hash to the form where
237  // he can set his new password. If hash matches, password change is possible.
238  // Until this last step he can still login with his old credentials - password
239  // in database will not be touched until he enters a new one.
240 
241  // get UID from username
242  if (isset($username) && (!empty($username) && (is_string($username)))) {
243  // user wants to reset with his username
244  $username = trim($username);
245  $username = strip_tags($username);
246  // get user id from username
247  $uid = self::getUserIdFromName($db, $username);
248  }
249  // or get UID from email
250  else if (isset($email) && (!empty($email) && (is_string($email))))
251  {
252  // user wants to reset with his email
253  $email = trim($email);
254  $email = strip_tags($email);
255  $uid = self::getUserIdFromEmail($db, $email);
256  }
257  else
258  {
259  \YAWK\alert::draw("warning", $lang['WARNING'], $lang['USERNAME_OR_EMAIL_NOT_SET'], "", 3800);
260  return false;
261  }
262 
263  // check if UID is valid
264  if (empty($uid) || (!is_numeric($uid)))
265  { // throw error - UID is not valid
266  \YAWK\alert::draw("danger", $lang['ERROR'], $lang['PASSWORD_RESET_UID_FAILED'], "", 3800);
267  return false;
268  }
269  else
270  { // uid is valid, go ahead and generate hash value
271  $token = self::getToken(196);
272 
273  // store token in database
274  if ($res = $db->query("UPDATE {users} SET hashValue = '".$token."' WHERE id = '".$uid."'"))
275  {
276  // get user email address
277  if (!isset($email) || (empty($email)))
278  {
279  // get email address of this user
281  }
282  else
283  { // password recipient
284  $to = $email;
285  // get username
286  $username = self::getUserNameFromID($db, $uid);
287  }
288 
289  // get admin email address
290  $from = \YAWK\settings::getSetting($db, "admin_email");
291 
292  // check if $to is a valid email address
293  if (filter_var($to, FILTER_VALIDATE_EMAIL))
294  {
295  // get full url to build the link
297 
298  // append token and generate complete url
299  $firstCharOfUrl = mb_substr($url, 0,-1);
300  if ($firstCharOfUrl === "/")
301  { // url missing trailing slash, append it
302  $tokenLink = $url."/index.php?resetPassword=true&token=$token";
303  }
304  else
305  { // url still got a slash
306  $tokenLink = $url."index.php?resetPassword=true&token=$token";
307  }
308 
309  $mailBody = "$lang[HELLO] $username!\n\r$lang[PASSWORD_RESET_REQUESTED]\n\r$lang[PASSWORD_RESET_MAILBODY]\n\r".$tokenLink."\n\r$lang[PASSWORD_RESET_REQUEST_WARNING].";
310  if (\YAWK\email::sendEmail($from, $to, "", "$lang[PASSWORD_RESET] $url", $mailBody) === true)
311  { // reset password email sent
312  \YAWK\sys::setSyslog($db, 9, 0, "reset password email requested from $username ($to)", $uid, 0, 0, 0);
313  $_SESSION['passwordFail'] = 0;
314  return true;
315  }
316  else
317  { // FAILED to send password reset email
318  \YAWK\alert::draw("warning", $lang['ERROR'], "$lang[EMAIL_NOT_SENT] <br>(from: $from)<br>(to: $to)", "", 3800);
319  \YAWK\sys::setSyslog($db, 11, 1, "failed to send reset password email to $username ($to)", $uid, 0, 0, 0);
320  return false;
321  }
322  }
323  else
324  { // NOT VALID EMAIL ADDRESS (to:)
325  \YAWK\alert::draw("warning", $lang['ERROR'], $lang['EMAIL_ADD_INVALID'], "", 3800);
326  \YAWK\sys::setSyslog($db, 11, 1, "invalid email address $to", $uid, 0, 0, 0);
327  return false;
328  }
329  }
330  else
331  { // error: hash value could not be stored / updated in database
332  \YAWK\sys::setSyslog($db, 11, 1, "failed to update hash value in database", $uid, 0, 0, 0);
333  \YAWK\alert::draw("warning", "Hash Value", "could not be stored.", "", 3800);
334  return false;
335  }
336  }
337  }
338 
339  /**
340  * @brief return current username
341  * @param object $lang language obj
342  * @return string current username
343  */
344  static function getCurrentUserName($lang)
345  {
346  if (isset($_SESSION['username']))
347  {
348  return $_SESSION['username'];
349  }
350  else
351  {
352  return $lang['GUEST'];
353  }
354  }
355 
356  /**
357  * @brief check, if a session username is set and if user is logged in
358  * @param object $db database obj
359  * @return string|bool return current username or false
360  */
361  static function isAnybodyThere($db)
362  {
363  // check if session is set
364  if (isset($_SESSION))
365  {
366  // check if session username + uid is set
367  if (isset($_SESSION['username']) && isset($_SESSION['uid']))
368  { // check if session logged_in status is true
369  if ($_SESSION['logged_in'] == true)
370  { // session username is set, check if its a non-empty string
371  if (!empty($_SESSION['username']) && (is_string($_SESSION['username'])))
372  { // username seems to be valid -
373  return $_SESSION['username'];
374  }
375  else
376  { // username seems not to be valid
377  return false;
378  }
379  }
380  else
381  { // user is there, but not logged in
382  return false;
383  }
384  }
385  else
386  { // session username is not set
387  return false;
388  }
389  }
390  // no session - check if $_GET is set instead
391  else if (isset($_GET))
392  { // check if user param is set
393  if (isset($_GET['user']) && (!empty($_GET['user']) && (is_string($_GET['user']))))
394  { // check if database says user is logged in
395  if (self::isLoggedIn($db, $_GET['user']))
396  { // user is logged in
397  return $_GET['user'];
398  }
399  else
400  { // user is not logged in
401  return false;
402  }
403  }
404  else
405  { // $_GET user is not set, empty or not valid
406  return false;
407  }
408  }
409  else
410  { // no user is there
411  return false;
412  }
413  }
414 
415  /**
416  * @brief template ID for given user ID
417  * @param object $db database
418  * @param int $uid user ID
419  * @return string|bool return template ID to corresponding user ID
420  */
421  static function getUserTemplateID($db, $uid)
422  { /* @param $db \YAWK\db */
423  if (!isset($uid) && (empty($uid)))
424  { // uid is missing
425  return false;
426  }
427  if ($res = $db->query("SELECT templateID FROM {users} WHERE id = $uid"))
428  {
429  if ($row = mysqli_fetch_row($res))
430  { // return $userTemplateID
431  return $row[0];
432  }
433  else
434  {
435  \YAWK\sys::setSyslog($db, 11, 1, "failed to get templateID from user db ", $uid, 0, 0, 0);
436  return false;
437  }
438  }
439  else
440  {
441  \YAWK\sys::setSyslog($db, 11, 1, "failed to query templateID from user db ", $uid, 0, 0, 0);
442  return false;
443  }
444  }
445 
446  /**
447  * @brief check if user ID is allowed to override template
448  * @param object $db database
449  * @param int $uid user ID
450  * @return bool
451  */
453  { /* @param $db \YAWK\db */
454  if ($res = $db->query("SELECT overrideTemplate FROM {users} WHERE id = $uid"))
455  {
456  if ($row = mysqli_fetch_row($res))
457  {
458  if ($row[0] === "1")
459  {
460  return true;
461  }
462  else
463  {
464  return false;
465  }
466  }
467  else
468  {
469  \YAWK\sys::setSyslog($db, 11, 1, "failed to get overrideTemplate status from user db ", 0, 0, 0, 0);
470  return false;
471  }
472  }
473  else
474  {
475  return false;
476  }
477  }
478 
479  /**
480  * @brief set status and override template for this user ID
481  * @param object $db database
482  * @param int $overrideTemplate 0|1 1 if template could be overridden by this user
483  * @param int $userTemplateID the template ID you wish to set for this user
484  * @param int $uid user ID
485  * @return bool
486  */
488  { /* @param $db \YAWK\db */
489  if (!isset($overrideTemplate) && (!is_numeric($overrideTemplate)))
490  { // wrong param
491  return false;
492  }
493  if (!isset($userTemplateID) && (!is_numeric($userTemplateID)))
494  { // wrong param
495  return false;
496  }
497  if (!isset($uid) && (!is_numeric($uid)))
498  { // wrong param
499  return false;
500  }
501 
502  if ($res = $db->query("UPDATE {users} SET overrideTemplate = $overrideTemplate, templateID = $userTemplateID WHERE id = $uid"))
503  {
504  return true;
505  }
506  else
507  {
508  \YAWK\sys::setSyslog($db, 11, 1, "failed to update user template override - template ID: $userTemplateID", $uid, 0, 0, 0);
509  return false;
510  }
511  }
512 
513  /**
514  * @brief check if user template equals selected (active) template
515  * @param object $db Database
516  * @param int $userTemplateID the user template ID
517  * @return bool
518  */
520  {
521  /* @param $db \YAWK\db */
522  // check if userTemplateID param is set
523  if (!isset($userTemplateID) && (empty($userTemplateID))) { // missing templateID - cannot compare,
524  return false;
525  }
526  $selectedTemplate = \YAWK\settings::getSetting($db, "selectedTemplate");
527  if ($selectedTemplate === $userTemplateID) { // user templateID and primary template (selectedTemplate) are equal
528  return true;
529  } else { // user templateID and selected template do not match
530  return false;
531  }
532  }
533 
534  /**
535  * @brief return an array with all login data
536  * @param object $db database
537  * @param object $user
538  * @return array|bool
539  */
540  static function getLoginData($db, $user)
541  { /* @param $db \YAWK\db */
542  if (isset($user) && (!empty($user)))
543  { // check if user is registered
544  if (self::hasLoggedIn($db, $user))
545  { // user is in list, extend sql string
546  $sqlStr = "WHERE username='$user'";
547  \YAWK\alert::draw("success", "showing login data for user: $user", " ", "",2400);
548  }
549  else
550  { // user not found in table, so draw an alert and show all logins...
551  $sqlStr = '';
552  \YAWK\alert::draw("warning", "Error!", "<h4>No login data available.</h4> Could not get data for user <b>$user</b>. Displaying all data instead.", "",5000);
553  }
554  }
555  else
556  { // show all logins
557  $sqlStr = '';
558  }
559  if ($res = $db->query("SELECT * FROM {logins} $sqlStr"))
560  { // fetch data in loop
561  while ($row = $res->fetch_assoc())
562  { // store logins into array
563  $loginsArray[] = $row;
564  }
565  if (isset($loginsArray) && (!empty($loginsArray)))
566  { // if array is set and not empty
567  return $loginsArray;
568  }
569  else
570  { // something went wrong
571  return false;
572  }
573  }
574  else
575  { // could not query login data...
576  \YAWK\sys::setSyslog($db, 11, 1, "failed to query login data of $user ", 0, 0, 0, 0);
577  return false;
578  }
579  }
580 
581  /**
582  * @brief check if username is already registered
583  * @param object $db database
584  * @param string $user username to check
585  * @return bool
586  */
587  static function isRegistered($db, $user)
588  { /** @var $db \YAWK\db */
589  if ($res = $db->query("SELECT username FROM {users} WHERE username='$user'"))
590  {
591  if ($row = $res->fetch_assoc())
592  {
593  return true;
594  }
595  else
596  {
597  return false;
598  }
599  }
600  else
601  {
602  return false;
603  }
604  }
605 
606  /**
607  * @brief check if user already has logged in
608  * @param object $db database
609  * @param string $user username to check
610  * @return bool
611  */
612  static function hasLoggedIn($db, $user)
613  { /** @var $db \YAWK\db */
614  if ($res = $db->query("SELECT username FROM {logins} WHERE username='$user'"))
615  {
616  if ($row = $res->fetch_assoc())
617  {
618  return true;
619  }
620  else
621  {
622  return false;
623  }
624  }
625  else
626  {
627  return false;
628  }
629  }
630 
631 
632  /**
633  * @brief check if backend is allowed for current session user group
634  * @param object $db database
635  * @return bool
636  */
637  static function isAdmin($db)
638  { /** @var $db \YAWK\db */
639  // checks if backend login is allowed for this (logged in) Group ID
640  if (isset($_SESSION))
641  { // check if there is a gid set
642  if (isset($_SESSION['gid']) && (!empty($_SESSION['gid'])))
643  { // only if gid is bigger than zero
644  if ($_SESSION['gid'] > 0)
645  { // check if backend login is allowed for this gid
646  if ($res = $db->query("SELECT backend_allowed FROM {user_groups} WHERE id ='".$_SESSION['gid']."'"))
647  { // get data
648  if ($row = $res->fetch_row())
649  { // if result is
650  if ($row[0] == 1)
651  { // backend login allowed
652  return true;
653  }
654  else
655  { // backend login forbidden
656  return false;
657  }
658  }
659  else
660  { // could not fetch data
661  return false;
662  }
663  }
664  else
665  { // could not query data
666  return false;
667  }
668  }
669  else
670  { // session gid seems to be zero
671  return false;
672  }
673  }
674  else
675  { // gid is not set or empty
676  return false;
677  }
678  }
679  else
680  { // session var is not set, user obviously not logged in
681  return false;
682  }
683  }
684 
685  /**
686  * @brief return user data as an array
687  * @param object $db database
688  * @return array|string
689  */
690  function getUserArray($db)
691  {
692  /* @param $db \YAWK\db */
693  if ($result = $db->query("SELECT cu.*, cg.value as gid FROM {users} as cu
694  JOIN {user_groups} as cg on cu.gid = cg.id ORDER BY id"))
695  {
696  $userDataArray = array();
697  // cycle trough results
698  while ($row = $result->fetch_assoc())
699  {
700  $userDataArray[] = $row;
701  }
702  /* free result */
703  $result->close();
704  }
705  else {
706  $userDataArray = '';
707  echo \YAWK\alert::draw("danger", "Error", "Sorry, database error: fetch getUserArray failed.","page=users","4800");
708  }
709  return $userDataArray;
710  }
711 
712  /**
713  * @brief get latest users and return as array
714  * @param object $db database
715  * @param int $count limit the query
716  * @return array|string
717  */
718  static function getLatestUsers($db, $count)
719  {
720  if (isset($count))
721  { // param
722  $limit = $count;
723  }
724  else
725  { // default value
726  $limit = 8;
727  }
728  /* @param $db \YAWK\db */
729  if ($result = $db->query("SELECT cu.*, cg.value as gid FROM {users} as cu
730  JOIN {user_groups} as cg on cu.gid = cg.id ORDER BY id LIMIT $limit"))
731  {
732  $userDataArray = array();
733  // cycle trough results
734  while ($row = $result->fetch_assoc())
735  {
736  $userDataArray[] = $row;
737  }
738  /* free result */
739  $result->close();
740  }
741  else {
742  $userDataArray = '';
743  \YAWK\sys::setSyslog($db, 11, 1, "failed to fetch user list", 0, 0, 0, 0);
744  echo \YAWK\alert::draw("danger", "Error", "Sorry, database error: fetch getLatestUsers failed.","page=users","4800");
745  }
746  return $userDataArray;
747  }
748 
749  /**
750  * @brief count and return all users
751  * @param object $db database
752  * @return string|bool
753  */
754  static function countUsers($db)
755  {
756  /* @param $db \YAWK\db */
757  if ($result = $db->query("SELECT count(id) FROM {users}"))
758  {
759  $i = mysqli_fetch_row($result);
760  return $i[0];
761  }
762  else
763  {
764  \YAWK\sys::setSyslog($db, 11, 1, "failed to count user db ", 0, 0, 0, 0);
765  return false;
766  }
767  }
768 
769 
770  /**
771  * @brief load user properties into object
772  * @param object $db database
773  * @param string $username username to get the settings for
774  * @return bool
775  */
776  function loadProperties($db, $username)
777  { /** @var $db \YAWK\db */
778  if ($res = $db->query("SELECT * FROM {users}
779  WHERE username = '" . $username . "'"))
780  { // fetch user properties
781  if ($row = $res->fetch_assoc())
782  { // and set obj settings
783  $this->id = $row['id'];
784  $this->blocked = $row['blocked'];
785  $this->privacy = $row['privacy'];
786  $this->online = $row['online'];
787  $this->gid = $row['gid'];
788  $this->terms = $row['terms'];
789  $this->username = $row['username'];
790  $this->password = $row['password'];
791  $this->date_created = $row['date_created'];
792  $this->date_changed = $row['date_changed'];
793  $this->date_expired = $row['date_expired'];
794  $this->date_lastlogin = $row['date_lastlogin'];
795  $this->login_count = $row['login_count'];
796  $this->email = $row['email'];
797  $this->url = $row['url'];
798  $this->twitter = $row['twitter'];
799  $this->facebook = $row['facebook'];
800  $this->firstname = $row['firstname'];
801  $this->lastname = $row['lastname'];
802  $this->street = $row['street'];
803  $this->zipcode = $row['zipcode'];
804  $this->city = $row['city'];
805  $this->country = $row['country'];
806  $this->logged_in = $row['logged_in'];
807  $this->public_email = $row['public_email'];
808  $this->job = $row['job'];
809  $this->likes = $row['likes'];
810  $this->overrideTemplate = $row['overrideTemplate'];
811  $this->templateID = $row['templateID'];
812  }
813  else
814  { // fetch failed
815  \YAWK\sys::setSyslog($db, 11, 1, "failed to load settings of $username", $this->id, 0, 0, 0);
816  // \YAWK\alert::draw("warning","Warning!","Load settings for user <b>$username</b> failed.","","4800");
817  return false;
818  }
819  }
820  else
821  { // q failed
822  \YAWK\sys::setSyslog($db, 11, 1, "failed to query settings of $username", $this->id, 0, 0, 0);
823  // \YAWK\alert::draw("danger","Error!","Could not select data for user <b>$username</b> from database...","","4800");
824  return false;
825  }
826  return true;
827  }
828 
829  /**
830  * @brief get any user property
831  * @param object $db database
832  * @param string $property user property to get
833  * @param int $uid affected user ID
834  * @return string|bool
835  */
836  function getProperty($db, $property, $uid)
837  { /** @var $db \YAWK\db */
838  if ($res = $db->query("SELECT $property FROM {users}
839  WHERE id = '" . $uid . "'"))
840  {
841  $row = $res->fetch_row();
842  return $row[0];
843  }
844  else
845  { // q failed
846  \YAWK\sys::setSyslog($db, 11, 1, "Unable to get property <b>$property</b> of user ID <b>$uid</b> ", 0, 0, 0, 0);
847  // \YAWK\alert::draw("danger","Error!","Could not get property $property","","4800");
848  return false;
849  }
850  }
851 
852  /**
853  * @brief set any user property
854  * @param object $db database
855  * @param int $id affected user ID
856  * @param string $property user property to set
857  * @param string $value user value of this property
858  * @return bool
859  */
860  static function setProperty($db, $id, $property, $value)
861  { /** @var $db \YAWK\db */
862  if (isset($property) && isset($value) && isset($id) && is_numeric($id))
863  { // params are set, now escape strings
864  $property = $db->quote($property);
865  $value = $db->quote($value);
866  $id = $db->quote($id);
867  if ($res = $db->query("UPDATE {users}
868  SET $property = '".$value."'
869  WHERE id = '" . $id . "'"))
870  { // user property update success,
871  \YAWK\alert::draw("success","Success!","".$value." of property ".$property." set.","","4800");
872  return true;
873  }
874  else
875  { // q failed
876  \YAWK\sys::setSyslog($db, 11, 1, "failed to set value <b>$value</b> of property <b>$property</b>", 0, 0, 0, 0);
877  \YAWK\alert::draw("danger","Error!","Could not set value ".$value." of property ".$property.".","","4800");
878  return false;
879  }
880  }
881  else
882  { // params failed or wrong type
883  \YAWK\alert::draw("danger","Error!","Parameters failed or wrong type! You shall not manipulate vars, yoda said!","","4800");
884  return false;
885  }
886  }
887 
888  /**
889  * @brief get group name for given $gid (group ID)
890  * @param object $db database
891  * @param int $gid group ID
892  * @return string|bool
893  */
894  static function getGroupNameFromID($db, $gid)
895  {
896  /** @var $db \YAWK\db */
897  if ($res = $db->query("SELECT value
898  FROM {user_groups}
899  WHERE id = $gid"))
900  {
901  $row = $res->fetch_row();
902  return $row[0];
903  }
904  // q failed
905  return false;
906  }
907 
908  /**
909  * @brief get username from given $uid (user ID)
910  * @param object $db database
911  * @param int $uid user id to get the name for
912  * @return string|bool
913  */
914  static function getUserNameFromID($db, $uid)
915  {
916  /** @var $db \YAWK\db */
917  if ($res = $db->query("SELECT username
918  FROM {users}
919  WHERE id = $uid"))
920  {
921  $row = $res->fetch_row();
922  if (isset($row[0])){
923  return $row[0];
924  }
925  else {
926  return false;
927  }
928  }
929  // q failed
930  return false;
931  }
932 
933  /**
934  * @brief get ID for given user
935  * @param object $db database
936  * @param string $user username to get the ID from
937  * @return string|bool
938  */
939  static function getUserIdFromName($db, $user)
940  {
941  /** @var $db \YAWK\db */
942  if ($res = $db->query("SELECT id
943  FROM {users}
944  WHERE username = '".$user."'"))
945  {
946  $row = $res->fetch_row();
947  if (!empty($row[0])){
948  return $row[0];
949  }
950  else {
951  return false;
952  }
953  }
954  // q failed
955  return false;
956  }
957 
958  /**
959  * @brief get ID for given email address
960  * @param object $db database
961  * @param string $email email to get the ID from
962  * @return string|bool
963  */
964  static function getUserIdFromEmail($db, $email)
965  {
966  /** @var $db \YAWK\db */
967  if ($res = $db->query("SELECT id
968  FROM {users}
969  WHERE email = '".$email."'"))
970  {
971  $row = $res->fetch_row();
972  return $row[0];
973  }
974  // q failed
975  return false;
976  }
977 
978  /**
979  * @brief return all group IDs as an array
980  * @param object $db database
981  * @return array|bool
982  */
983  static function getAllGroupIDs($db)
984  { /** @var $db \YAWK\db */
985  if ($res = $db->query("SELECT id, value FROM {user_groups}"))
986  { // fetch data in loop
987  while ($row = mysqli_fetch_row($res))
988  { // fill array
989  $result[] = $row;
990  }
991  if (isset($result))
992  { // return array
993  return $result;
994  }
995  else
996  { // fetch failed, throw error
997  \YAWK\sys::setSyslog($db, 11, 1, "failed to fetch id from user_groups db", 0, 0, 0, 0);
998  \YAWK\alert::draw("warning","Warning","Could not fetch id and/or value from user groups database.","","4800");
999  return false;
1000  }
1001  }
1002  else
1003  { // q failed, throw error
1004  \YAWK\sys::setSyslog($db, 11, 1, "failed to query id from user_groups db", 0, 0, 0, 0);
1005  \YAWK\alert::draw("warning","Warning","Could not select id and/or value from user groups database.","","4800");
1006  return false;
1007  }
1008  }
1009 
1010  /**
1011  * @brief check if a username is logged in
1012  * @param object $db database
1013  * @param string $username username
1014  * @return bool
1015  */
1016  static function isLoggedIn($db, $username)
1017  { /** @var $db \YAWK\db */
1018  if ($res = $db->query("SELECT id, logged_in FROM {users} WHERE username = '" . $username . "'"))
1019  { // fetch data
1020  $row = mysqli_fetch_row($res);
1021  // user is logged in
1022  if ($row[1] === '1') {
1023  // check if session & db username match
1024  if (isset($_SESSION['username']) == $username)
1025  { // check if session uid + db uid match
1026  if (isset($_SESSION['uid']) == $row[0] && $_SESSION['logged_in'] == true)
1027  { // success
1028  return true;
1029  }
1030  else
1031  { // session var not set and session uid does not match with db
1032  return false;
1033  }
1034  }
1035  else
1036  { // session username does not match with db
1037  return false;
1038  }
1039  }
1040  else
1041  { // user is not logged in
1042  return false;
1043  }
1044  }
1045  else
1046  { // q failed
1047  return false;
1048  }
1049  }
1050 
1051  /**
1052  * @brief get group data for given group ID
1053  * @param object $db database
1054  * @return array|null|string
1055  */
1056  static function getGroup($db)
1057  { /** @var $db \YAWK\db */
1058  if (isset($_SESSION['gid']))
1059  { // prepare vars
1060  $gid = $_SESSION['gid'];
1061  $sql = $db->query("SELECT id,value,signup_allowed,backend_allowed FROM {user_groups} WHERE id = '".$gid."'");
1062  $row = mysqli_fetch_array($sql);
1063  return $row;
1064  }
1065  else {
1066  return "Group ID not set.";
1067  }
1068  }
1069 
1070  /**
1071  * @brief return and output user image
1072  * @param string $location frontend or backend
1073  * @param string $user username
1074  * @param string $cssClass image css class eg. img-circle
1075  * @param int $w width in pixel
1076  * @param int $h height in pixel
1077  * @return string
1078  */
1079  static function getUserImage($location, $user, $cssClass, $w, $h)
1080  {
1081  if (isset($w) && isset($h))
1082  {
1083  if ($w === 0)
1084  {
1085  $width = 0;
1086  }
1087  else
1088  {
1089  $width = "width=\"$w\" ";
1090  }
1091  if ($h === 0)
1092  {
1093  $height = 0;
1094  }
1095  else
1096  {
1097  $height = "height=\"$h\" ";
1098  }
1099  }
1100  else
1101  {
1102  $width = '';
1103  $height = '';
1104  }
1105  if (isset($cssClass))
1106  {
1107  $css = "class=\"$cssClass\"";
1108  }
1109  else
1110  {
1111  $css = '';
1112  }
1113 
1114  if (isset($location))
1115  {
1116  if ($location == "frontend"){
1117  $imageJpg = "media/images/users/".$user.".jpg";
1118  $imagePng = "media/images/users/".$user.".png";
1119  $defaultPic = "<img src=\"media/images/users/avatar.png\" $width $height $css>";
1120 
1121  }
1122  else
1123  {
1124  $imageJpg = '';
1125  $imagePng = '';
1126  $defaultPic = "<img src=\"media/images/users/avatar.png\" $width $height $css>";
1127  }
1128  if ($location == "backend"){
1129  $imageJpg = "../media/images/users/".$user.".jpg";
1130  $imagePng = "../media/images/users/".$user.".png";
1131 
1132  if ($cssClass == "img-circle")
1133  {
1134  $defaultPic = "<img src=\"../media/images/users/avatar.png\" $width $height $css>";
1135  }
1136  elseif ($cssClass == "img-circle sidebar-toggle")
1137  {
1138  $defaultPic = "<img src=\"../media/images/users/avatar-light.png\" $width $height $css>";
1139  }
1140  if ($cssClass == "user-image")
1141  {
1142  $defaultPic = "<img src=\"../media/images/users/avatar.png\" $width $height $css>";
1143  }
1144  if ($cssClass == "profile-user-img img-responsive img-circle")
1145  {
1146  $defaultPic = "<img src=\"../media/images/users/avatar.png\" $width $height $css>";
1147  }
1148  }
1149  else
1150  {
1151  $imageJpg = '';
1152  $imagePng = '';
1153  $defaultPic = "<img src=\"media/images/users/avatar.png\" $width $height $css>";
1154  }
1155  }
1156  else
1157  {
1158  $imageJpg = '';
1159  $imagePng = '';
1160  $defaultPic = "<img src=\"media/images/users/avatar.png\" $width $height $css>";
1161  }
1162 
1163 
1164  if (file_exists($imageJpg)){
1165  return "<img src=\"".$imageJpg."\" $width $height $css>";
1166  }
1167  elseif (file_exists($imagePng)){
1168  return "<img src=\"".$imagePng."\" $width $height $css>";
1169  }
1170  else
1171  {
1172  return $defaultPic;
1173  }
1174  }
1175 
1176  /**
1177  * @brief save object properties
1178  * @param object $db database
1179  * @return bool
1180  */
1181  function save($db)
1182  { /** @var $db \YAWK\db */
1183  $date_changed = date("Y-m-d G:i:s");
1184  // lowercase username
1185  $this->username = mb_strtolower($this->username);
1186  // store sql
1187  if ($res = $db->query("UPDATE {users} SET
1188  blocked = '" . $this->blocked . "',
1189  privacy = '" . $this->privacy . "',
1190  date_changed = '" . $date_changed . "',
1191  username = '" . $this->username . "',
1192  password = '" . $this->password . "',
1193  email = '" . $this->email . "',
1194  url = '" . $this->url . "',
1195  twitter = '" . $this->twitter . "',
1196  facebook = '" . $this->facebook . "',
1197  firstname = '" . $this->firstname . "',
1198  lastname = '" . $this->lastname . "',
1199  street = '" . $this->street . "',
1200  zipcode = '" . $this->zipcode . "',
1201  city = '" . $this->city . "',
1202  country = '" . $this->country . "',
1203  job = '" . $this->job . "',
1204  overrideTemplate = '" . $this->overrideTemplate . "',
1205  templateID = '" . $this->templateID . "',
1206  gid = '" . $this->gid . "'
1207  WHERE id = '" . $this->id . "'"))
1208  {
1209  \YAWK\alert::draw("success", "Success!", "User $this->username updated.","","1200");
1210  return true;
1211  }
1212  else
1213  { // q failed
1214  \YAWK\sys::setSyslog($db, 11, 1, "failed to update status of $this->username", 0, 0, 0, 0);
1215  \YAWK\alert::draw("warning", "Error!", "User status could not be saved, please try again.","","4800");
1216  return false;
1217  }
1218  }
1219 
1220  /**
1221  * @brief block or unblock a user
1222  * @param object $db database
1223  * @param int $id user ID to toggle
1224  * @param int $blocked 0|1 status: 1 is blocked, 0 is not blocked
1225  * @return bool
1226  */
1227  function toggleOffline($db, $id, $blocked)
1228  { /** @var $db \YAWK\db */
1229  // TOGGLE PAGE STATUS
1230  if (isset($blocked)) {
1231  $status = \YAWK\sys::iStatusToString($blocked, "blocked", "unblocked");
1232  } else { $status = "undefined - \$blocked not set"; }
1233  if (!$res = $db->query("UPDATE {users}
1234  SET blocked = '" . $blocked . "'
1235  WHERE id = '" . $id . "'"))
1236  {
1237  // q failed
1238  \YAWK\sys::setSyslog($db, 11, 1, "failed to toggle user ID <b>$id</b> to status <b>$status</b> ", 0, 0, 0, 0);
1239  return false;
1240  }
1241  else
1242  { // toggle successful
1243  \YAWK\sys::setSyslog($db, 9, 0, "toggled user id <b>#$id</b> to status <b>$status</b> ", 0, 0, 0, 0);
1244  return true;
1245  }
1246  }
1247 
1248  /**
1249  * @brief return email address of $user
1250  * @param object $db database
1251  * @param string $user username
1252  * @return bool the emailadress of this $user
1253  */
1254  static function getUserEmail($db, $user)
1255  { /** @param $db \YAWK\db $res */
1256  if ($res = $db->query("SELECT email
1257  FROM {users}
1258  WHERE username = '" . $user. "'"))
1259  { // fetch data
1260  $row = $res->fetch_row();
1261  return $row[0];
1262  }
1263  else
1264  { // q failed
1265  \YAWK\sys::setSyslog($db, 11, 1, "failed to get email address of <b>$user</b> ", 0, 0, 0, 0);
1266  return false;
1267  }
1268  }
1269 
1270  /**
1271  * @brief create a new user
1272  * @param object $db database
1273  * @param string $username username
1274  * @param string $password1 password
1275  * @param string $password2 password (must be same as password1)
1276  * @param string $email email adress
1277  * @param string $url url
1278  * @param string $twitter user twitter url
1279  * @param string $facebook user facebook url
1280  * @param string $firstname user firstname
1281  * @param string $lastname user lastname
1282  * @param string $street street
1283  * @param string $zipcode zip code
1284  * @param string $city city
1285  * @param string $country country
1286  * @param int $blocked 0|1 1 sets user to blocked, 0 is not blocked
1287  * @param int $privacy we need to accept users privacy: do not show email public, do not show on users online list
1288  * @param string $job job description - can held any string
1289  * @param int $gid user group ID
1290  * @return bool
1291  */
1293  { /** @var $db \YAWK\db */
1294  $date_created = date("Y-m-d G:i:s");
1295  // select maxID
1296  if ($res = $db->query("SELECT MAX(id) FROM {users}"))
1297  { // add 1 to ID
1298  $row = mysqli_fetch_row($res);
1299  $id = $row[0] + 1;
1300  }
1301  else
1302  { // if ID could not be determined, set 1 as default
1303  $id = 1;
1304  }
1305  // lowercase username
1306  $username = mb_strtolower($username);
1307 
1308  if ($username === "administrator" xor $username === "admin" or $username === "root")
1309  { // forbidden username, throw error
1310  if ($id > 1)
1311  {
1312  \YAWK\sys::setSyslog($db, 11, 2,"somebody tried to register as <b>$username</b>", 0, 0, 0, 0);
1313  }
1314  }
1315 
1316  // prepare password
1317  $password1 = strip_tags($password1);
1318  $password2 = strip_tags($password2);
1319  // check password
1320  if ($password1 == $password2)
1321  {
1323  $password = md5($password);
1324  // create user
1325  if ($res = $db->query("SELECT username FROM {users} WHERE username='" . $username . "'"))
1326  {
1327  $row = mysqli_fetch_row($res); // username is already taken
1328  if (is_array($row) && !is_null($row[0])) {
1329  if ($row[0] === $username) {
1330  \YAWK\alert::draw("warning", "Warning!", "Please choose another username!", "", "4800");
1331  // exit;
1332  return false;
1333  }
1334  }
1335  }
1336  /* TODO: check if this can be deleted
1337  else {
1338  \YAWK\sys::setSyslog($db, 5, "could not fetch username <b>$username</b> ", 0, 0, 0, 0);
1339  // \YAWK\alert::draw("danger","Warning!","Could not fetch username! Database error?","page=user-new","4800");
1340  // exit;
1341  \YAWK\alert::draw("warning","Warning!","Could not fetch username! Database error?","","4800");
1342  return false;
1343  }
1344  */
1345  // prepare vars
1346  if (isset($_POST['twitter']) && (!empty($_POST['twitter']))) { $twitter = htmlentities($_POST['twitter']); }
1347  if (isset($_POST['facebook']) && (!empty($_POST['facebook']))) { $facebook = htmlentities($_POST['facebook']); }
1348  if (isset($_POST['firstname']) && (!empty($_POST['firstname']))) { $firstname = htmlentities($_POST['firstname']); }
1349  if (isset($_POST['lastname']) && (!empty($_POST['lastname']))) { $lastname = htmlentities($_POST['lastname']); }
1350  if (isset($_POST['street']) && (!empty($_POST['street']))) { $street = htmlentities($_POST['street']); }
1351  if (isset($_POST['zipcode']) && (!empty($_POST['zipcode']))) { $zipcode = htmlentities($_POST['zipcode']); }
1352  if (isset($_POST['city']) && (!empty($_POST['city']))) { $city = htmlentities($_POST['city']); }
1353  if (isset($_POST['country']) && (!empty($_POST['country']))) { $country = htmlentities($_POST['country']); }
1354  if (isset($_POST['job']) && (!empty($_POST['job']))) { $job = htmlentities($_POST['job']); }
1355  // prepare url vars
1356  if ($url === "http://") $url = "";
1357  if ($twitter === "http://www.twitter.com/username") $twitter = "";
1358  if ($facebook === "http://www.facebook.com/username") $facebook = "";
1359 
1360  // do db insert
1361  if ($res = $db->query("INSERT INTO {users}
1362  (id,username,password,date_created,email,url,twitter,facebook,firstname,lastname,street,zipcode,city,country,blocked,privacy,job,gid)
1363  VALUES('" . $id . "',
1364  '" . $username . "',
1365  '" . $password . "',
1366  '" . $date_created . "',
1367  '" . $email . "',
1368  '" . $url . "',
1369  '" . $twitter . "',
1370  '" . $facebook . "',
1371  '" . $firstname . "',
1372  '" . $lastname . "',
1373  '" . $street . "',
1374  '" . $zipcode . "',
1375  '" . $city . "',
1376  '" . $country . "',
1377  '" . $blocked . "',
1378  '" . $privacy . "',
1379  '" . $job . "',
1380  '" . $gid . "')"))
1381  { // all good
1382  return true;
1383  }
1384  else
1385  { // q failed
1386  return false;
1387  }
1388  }
1389  else
1390  { // passwords do not match
1391  // \YAWK\alert::draw("warning", "Warning!", "Passwords do not match!", "page=user-new", "4800");
1392  // exit;
1393  \YAWK\alert::draw("warning", "Warning!", "Passwords do not match!", "", "4000");
1394  return false;
1395  }
1396  }
1397 
1398  /**
1399  * @brief create a user from frontend
1400  * @param object $db database
1401  * @param string $username username
1402  * @param string $password1 password
1403  * @param string $password2 password (must match w password1)
1404  * @param string $email user email address
1405  * @param int $gid user group ID
1406  * @return bool
1407  */
1408  static function createFromFrontend($db, $username, $password1, $password2, $email, $gid)
1409  { /** @var $db \YAWK\db */
1410  if (empty($username) || (empty($password1) || (empty($password2) || (empty($email) || (empty($gid))))))
1411  {
1412  echo \YAWK\alert::draw("danger", "Error!", "Missing Data. Please fill out the complete form.","",4200);
1413  echo \YAWK\PLUGINS\SIGNUP\signup::signUp($db);
1414  echo "</div></div><!-- <div style=\"background-image: url(media/images/bottom.png); height: 150px;\"></div> -->";
1415  exit;
1416  }
1417  $date_created = date("Y-m-d G:i:s");
1418  // select maxID
1419  if ($res = $db->query("SELECT MAX(id) FROM {users}"))
1420  {
1421  $row = mysqli_fetch_row($res);
1422  $id = $row[0] + 1;
1423  }
1424  // prepare password
1425  $password1 = htmlentities($_POST['password1']);
1426  $password2 = htmlentities($_POST['password2']);
1427  $password1 = $db->quote($password1);
1428  $password2 = $db->quote($password2);
1429  // check if passwords match
1430  if ($password1 == $password2)
1431  {
1433  $password = md5($password);
1434  // check if username is already in use
1435  if ($res = $db->query("SELECT username FROM {users} WHERE username='" . $username . "'"))
1436  {
1437  $row = mysqli_fetch_row($res);
1438  if ($row[0])
1439  { // username IS already in use
1440  \YAWK\alert::draw("danger", "Error!", "Please choose another user name!", "","");
1441  echo \YAWK\PLUGINS\SIGNUP\signup::signUp($db);
1442  exit;
1443  }
1444  }
1445  // check if email is already in use
1446  if ($res = $db->query("SELECT email FROM {users} WHERE email='" . $email . "'"))
1447  {
1448  $row = mysqli_fetch_row($res);
1449  if ($row[0])
1450  { // email IS already in use
1451  \YAWK\alert::draw("danger", "Error!", "Email is already in use!", "","");
1452  echo \YAWK\PLUGINS\SIGNUP\signup::signUp($db);
1453  exit;
1454  }
1455  }
1456  // filter forbidden usernames
1457  if ($username === "administrator" xor $username === "admin" or $username === "root") {
1458  \YAWK\alert::draw("danger", "Error!", "Hey c'mon... those kind of names are not allowed! Please choose another username!","","");
1459  echo \YAWK\PLUGINS\SIGNUP\signup::signUp($db);
1460  exit;
1461  }
1462  // default values of blocked and privacy
1463  $blocked = 0; // NOT BLOCKED
1464  $privacy = 0; // NO PRIVACY
1465 
1466  if ($res = $db->query("INSERT INTO {users} (id,username,password,date_created,email,blocked,privacy,gid)
1467  VALUES('" . $id . "',
1468  '" . $username . "',
1469  '" . $password . "',
1470  '" . $date_created . "',
1471  '" . $email . "',
1472  '" . $blocked . "',
1473  '" . $privacy . "',
1474  '" . $gid . "')"))
1475  { // user added,
1476  return true;
1477  }
1478  else
1479  { // q failed
1480  \YAWK\sys::setSyslog($db, 12, 2, "failed to register user from frontend: signup of <b>$username</b> failed", $id, 0, 0, 0);
1481  \YAWK\alert::draw("danger", "Error!", "Error registering username. Exit with empty result.","","");
1482  echo \YAWK\PLUGINS\SIGNUP\signup::signUp($db);
1483  }
1484  }
1485  else
1486  { // passwords do not match
1487  // in that case throw error & draw form again...
1488  \YAWK\sys::setSyslog($db, 11, 1, "failed to signup user: <b>$username</b> - passwords mismatch", 0, 0, 0, 0);
1489  \YAWK\alert::draw("danger", "Error!", "Passwords mismatch! Please try again.","","");
1490  echo \YAWK\PLUGINS\SIGNUP\signup::signUp($db);
1491  exit;
1492  }
1493  echo \YAWK\alert::draw("danger", "Error!", "Something strange has happend. Code (000)","","");
1494  return false;
1495  }
1496 
1497  /**
1498  * @brief delete a user from database
1499  * @param object $db database
1500  * @param string $user username
1501  * @return bool
1502  */
1503  static function delete($db, $user)
1504  { /** @var $db \YAWK\db */
1505  if ($res = $db->query("DELETE FROM {users} WHERE username = '" . $user . "'"))
1506  {
1507  return true;
1508  }
1509  else
1510  {
1511  \YAWK\sys::setSyslog($db, 11, 2,"failed to delete <b>$user</b> ", 0, 0, 0, 0);
1512  return false;
1513  }
1514  }
1515 
1516  /**
1517  * @brief check if password is correct; check also if user is blocked or terminated.
1518  * @param object $db database
1519  * @param string $username username
1520  * @param string $password password
1521  * @return bool
1522  */
1523  static function checkPassword($db, $username, $password)
1524  { /** @var $db \YAWK\db */
1525  $adminEmail = \YAWK\settings::getSetting($db, "admin_email");
1527  $password = $db->quote(trim($password));
1528  $username = $db->quote(trim($username));
1529  $username = mb_strtolower($username);
1530  $sql = $db->query("SELECT blocked, terminatedByUser FROM {users} WHERE
1531  username='" . $username . "' AND password = '" . md5($password) . "'");
1532  $res = mysqli_fetch_assoc($sql);
1533  if (isset($res)){ // if there is a result, username + pwd match.
1534  if(isset($res['blocked'])){ // check if user is blocked.
1535  if ($res['blocked']==='1')
1536  {
1537  // get user id of the blocked user who tried to login
1538  $uid = \YAWK\user::getUserIdFromName($db, $username);
1539  \YAWK\sys::setSyslog($db, 12, 2, "<b>blocked user $username</b> tried to login", $uid, 0, 0, 0);
1540  echo "<div class=\"container bg-danger\"><br><h2>We're Sorry! <small>Your Account is blocked.</h2><b>If you think
1541  this is a mistake, contact the admin via email: </b>(<a class=\"text-danger\" href=\"mailto:$adminEmail\">$adminEmail</a>)
1542  <b>for further information.</b><br><small>You will be redirected to <a class=\"small\" href=\"$host\">$host</a> in 30 seconds.</small><br><br></div>";
1543  \YAWK\sys::setTimeout("index.html", 30000);
1544  return false;
1545  }
1546  }
1547  if(isset($res['terminatedByUser'])){ // is user has canceled his account
1548  if ($res['terminatedByUser']==='1'){ // check if user is
1549  $uid = \YAWK\user::getUserIdFromName($db, $username);
1550  \YAWK\sys::setSyslog($db, 11, 1, "failed to login <b>$username</b> user has deleted his account before - it does not exist anymore", $uid, 0, 0, 0);
1551  echo "<div class=\"container bg-danger\"><br><h2>We're Sorry! <small>This account does not exist.</h2><b>If you think
1552  this is a mistake, contact the admin via email: </b>(<a class=\"text-danger\" href=\"mailto:$adminEmail\">$adminEmail</a>)
1553  <b>.</b><br><small>You will be redirected to <a class=\"small\" href=\"$host\">$host</a> in 30 seconds.</small><br><br></div>";
1554  \YAWK\sys::setTimeout("index.html", 30000);
1555  return false;
1556  }
1557  }
1558  // username + pwd match, user is not blocked, not terminated...
1559  return true;
1560  }
1561  else
1562  {
1563 
1564  \YAWK\sys::setSyslog($db, 11, 1, "login failed due wrong credentials from <b>".$username."</b>", 0, 0, 0, 0);
1565  // checkPassword failed
1566  /* echo "<div class=\"container bg-danger\"><br><h2>Warning! <small>Login failed!</h2>
1567  <b>Please check your login credentials and try again in a few seconds.</b>
1568  <br><small>You will be redirected to <a class=\"small\" href=\"$host\">$host</a>.</small><br><br></div>";
1569  \YAWK\sys::setTimeout("index.html", 10000); */
1570  return false;
1571  }
1572  }
1573 
1574  /**
1575  * @brief check if group ID is allowed to login to backend
1576  * @param object $db database
1577  * @param int $gid group ID who needs to be checked
1578  * @return bool
1579  */
1580  function checkGroupId($db, $gid)
1581  { /** @var $db \YAWK\db */
1582  // query data
1583  $sql = $db->query("SELECT backend_allowed FROM {user_groups} WHERE id='".$gid."'");
1584  $res = mysqli_fetch_row($sql);
1585  if ($res[0] === '1')
1586  { // success
1587  return true;
1588  }
1589  else
1590  { // login not allowed from that user group
1591  \YAWK\sys::setSyslog($db, 11, 1, "user group ID <b>$gid</b> is not allowed to login into backend", 0, 0, 0, 0);
1592  return false;
1593  }
1594  }
1595 
1596  /**
1597  * @brief check if user is allowed to login
1598  * @param object $db password
1599  * @return bool
1600  */
1601  static function checkLogin($db)
1602  { /** @var $db \YAWK\db */
1603  /* check user login */
1604  $user = new \YAWK\user($db);
1605  if(isset($_POST['user']) && isset($_POST['password'])) {
1606  if($user->login($db, $_POST['user'],$_POST['password']))
1607  { // create session var
1608  $user->storeLogin($db, 0, "backend", $_POST['user'], $_POST['password']);
1609  \YAWK\sys::setSyslog($db, 10, 0, "backend login <b>$_POST[user]</b> successful", 0, 0, 0, 0);
1610  return true;
1611  }
1612  else
1613  { // if username or pwd is wrong
1614  $user->storeLogin($db, 1, "backend", $_POST['user'], $_POST['password']);
1615  \YAWK\sys::setSyslog($db, 12, 2, "failed backend login <b>$_POST[user]</b> username or password wrong", 0, 0, 0, 0);
1616  // \YAWK\alert::draw("warning","Warning:","<b>Login failed.</b> Please check login data and try again. Please wait, you will be redirected in 5 Seconds...","index.php","5000");
1617  return false;
1618  }
1619  }
1620  else
1621  { // username or password not set
1622  \YAWK\sys::setSyslog($db, 11, 1, "somebody $_POST[user] tried to login, but username or password was not set.", 0, 0, 0, 0);
1623  return false;
1624  }
1625  }
1626 
1627  public static function ajaxLogin($db, $user, $password)
1628  {
1629  // create new user class object
1630  $userClass = new \YAWK\user($db);
1631 
1632  // check user and password vars
1633  if (isset($user) && (!empty($user) && (is_string($user)
1634  && (isset($password) && (!empty($password) && (is_string($password)))))))
1635  {
1636  // check if user is logged in
1637  if (self::isLoggedIn($db, $user) === false)
1638  {
1639  // login successful
1640  if(self::login($db, $user, $password) === true)
1641  { // login successful
1642  $userClass->storeLogin($db, 0, "frontend", $user, $password);
1643  // \YAWK\sys::setSyslog($db, "3", "ajax login successful", 0, 0, 0, 0);
1644  return true;
1645  }
1646  else
1647  { // login failed
1648  $userClass->storeLogin($db, 1, "frontend", $user, $password);
1649  // \YAWK\sys::setSyslog($db, "5", "ajax login failed", 0, 0, 0, 0);
1650  return false;
1651  }
1652  }
1653  // in any other case
1654  return false;
1655  }
1656  else
1657  { // login data wrong
1658  return false;
1659  }
1660  }
1661 
1662  /**
1663  * @brief login user
1664  * @param object $db database
1665  * @param string $username username
1666  * @param string $password password
1667  * @return bool
1668  */
1669  static function login($db, $username, $password)
1670  {
1671  /** @var $db \YAWK\db */
1672  if (empty($username && $password)){
1673  return false;
1674  }
1675  if (empty($username || $password)){
1676  return false;
1677  }
1678  // remove html tags from username
1679  $username = strip_tags($username);
1680  // remove html tags from password
1681  $password = strip_tags($password);
1682  // quote username
1683  $username = $db->quote(trim($username));
1684  // quote password
1685  $password = $db->quote(trim($password));
1686  // set session username
1687  $_SESSION['username'] = $username;
1688 
1689  // if given username + password are correct
1690  if (self::checkPassword($db, $username, $password))
1691  {
1692  // select login count
1693  $res = $db->query("SELECT id, login_count, gid FROM {users} WHERE username='" . $username . "'");
1694  $row = mysqli_fetch_row($res);
1695  // add session user ID
1696  $_SESSION['uid'] = $row[0];
1697  // add session group ID
1698  $_SESSION['gid'] = $row[2];
1699  // set login counter
1700  $login_count = $row[1] + 1;
1701  // get current datetime
1702  $date_now = date("Y-m-d G:i:s");
1703  // update login counter
1704  if (!$res = $db->query("UPDATE {users} SET
1705  date_lastlogin = '" . $date_now . "',
1706  login_count = '" . $login_count . "',
1707  online = '1',
1708  logged_in = '1'
1709  WHERE username = '" . $username . "'"))
1710  {
1711  \YAWK\sys::setSyslog($db, 11, 1, "failed to update login counter ($login_count) of <b>$username</b> .", $_SESSION['uid'], 0, 0, 0);
1712  return false;
1713  }
1714  else
1715  { // LOGIN SUCCESSFUL
1716  // try to re-new session ID
1717  @session_regenerate_id();
1718  // set session username
1719  $_SESSION['username'] = $username;
1720  // set logged_in session status to true
1721  $_SESSION['logged_in'] = true;
1722  // store successful login
1723  \YAWK\sys::setSyslog($db, 10, 0, "login <b>$username</b> successful", $_SESSION['uid'], 0, 0, 0);
1724  // self::storeLogin($db, 0, "frontend", $username, $password);
1725  return true;
1726  }
1727  }
1728  else
1729  { // check password failed
1730  $uid = \YAWK\user::getUserIdFromName($db, $username);
1731  \YAWK\sys::setSyslog($db, 11, 1, "failed to login <b>$username</b>", $uid, 0, 0, 0);
1732  // return \YAWK\alert::draw("warning", "Login failed...", "Please try to re-login in a few seconds...", "",3000);
1733  return false;
1734  /*
1735  if (!isset($_SESSION['failed'])){
1736  $_SESSION['failed']=1;
1737  $this->storeLogin($db, 1, "frontend", $username, $password);
1738  return false;
1739  }
1740  else {
1741  $_SESSION['failed']++;
1742  $this->storeLogin($db, 1, "frontend", $username, $password);
1743  // return false;
1744  }
1745  if ($_SESSION['failed'] == 2){
1746  echo "<div class=\"well\">";
1747  echo \YAWK\alert::draw("danger", "<h3><i class=\"fa fa-exclamation-triangle\"></i> ACHTUNG!", "2. Fehlversuch!</h3>
1748  <b>Du hast noch einen Versuch um deinen Benutzernamen und das Passwort korrekt einzugeben.</b>","", 6200);
1749  echo "</div>";
1750  $this->storeLogin($db, 1, "frontend", $username, $password);
1751  return false;
1752  }
1753  if ($_SESSION['failed'] == 3){
1754  echo "<div class=\"container\"><div class=\"well\">";
1755  echo \YAWK\alert::draw("danger", "<h3><i class=\"fa fa-exclamation-triangle\"></i> ACHTUNG!", "3. Fehlversuch!</h3>
1756  <b>Beim n&auml;chsten falschen Versuch wird die Prozedur geloggt und der Admin informiert.</b>","",6200);
1757  echo "</div></div>";
1758  $this->storeLogin($db, 1, "frontend", $username, $password);
1759  return false;
1760  }
1761  if ($_SESSION['failed'] >= 10){
1762  echo "<div class=\"container\"><div class=\"well\">";
1763  echo \YAWK\alert::draw("danger", "<h3><i class=\"fa fa-exclamation-triangle\"></i> ACHTUNG!", "$_SESSION[failed]. Fehlversuch!</h3>
1764  <b>Du wurdest gewarnt! Brute Force Attacken sind strafbar. Es wird Anzeige erstattet.</b><br>
1765  <b>Du bist nicht berechtigt Dich einzuloggen. Du wurdest gewarnt. Lass den Schwachsinn.</b><br>
1766  Datum: $date_now<br>
1767  Deine IP: $_SERVER[REMOTE_ADDR]<br>
1768  Agent: $_SERVER[HTTP_USER_AGENT]","",12200);
1769  echo "</div></div>";
1770  $domain = \YAWK\settings::getSetting($db, "domain");
1771  $to = \YAWK\settings::getSetting($db, "admin_email");
1772  $from = "script@".$domain."";
1773  $message = "FAILED LOGIN ATTEMPT!\n\r
1774  Date : $date_now\n
1775  Message : User tried a FrontEnd Login more than $_SESSION[failed] times!!!\n
1776  User : $this->username\n
1777  Password : $this->password\n";
1778  \YAWK\email::sendEmail($from, $to, "","LOGIN WARNING! on $domain", $message);
1779  $this->storeLogin($db, 1, "frontend", $username, $password);
1780  return false;
1781  }
1782  if ($_SESSION['failed'] >= 4){
1783  echo "<div class=\"container\"><div class=\"well\">";
1784  echo \YAWK\alert::draw("danger", "<h3><i class=\"fa fa-exclamation-triangle\"></i> ACHTUNG!", "$_SESSION[failed]. Fehlversuch!</h3>
1785  <b>Offensichtlich bist Du nicht berechtigt, Dich hier einzuloggen.<br>
1786  </b><i>Deine wiederholten Zugriffe wurden aus Sicherheitsgr&uuml;nden geloggt. Admin ist informiert.</i>","",6200);
1787  echo "</div></div>";
1788  $domain = \YAWK\settings::getSetting($db, "domain");
1789  $to = \YAWK\settings::getSetting($db, "admin_email");
1790  $from = "script@".$domain."";
1791  $message = "FAILED LOGIN ATTEMPT!\n\r
1792  Date : $date_now\n
1793  Message : User tried a FrontEnd Login without sufficient right!\n
1794  User : $this->username\n
1795  Password : $this->password\n";
1796  \YAWK\email::sendEmail($from, $to, "","LOGIN WARNING! on $domain", $message);
1797  $this->storeLogin($db, 1, "frontend", $username, $password);
1798  //\YAWK\backend::setTimeout("startseite.html", 6400);
1799  return false;
1800  }
1801 
1802  return false;
1803  */
1804  }
1805  }
1806 
1807  /**
1808  * @brief login user to backend
1809  * @param object $db database
1810  * @param string $username username
1811  * @param string $password password
1812  * @return bool
1813  */
1814  function loginBackEnd($db, $username, $password)
1815  { /** @var $db \YAWK\db */
1816  $password = $db->quote(trim($password));
1817  $this->username = $db->quote(trim($username));
1818  // datum + login count aktualisieren
1819  $date_now = date("Y-m-d G:i:s");
1820 
1821  // Implement rate limiting
1822  $maxAttempts = 5;
1823  $lockoutTime = 30; // In minutes
1824 
1825 
1826  if ($this->checkPassword($db, $this->username, $password)) {
1827  /* select and add login_count */
1828  $res = $db->query("SELECT id, login_count, gid FROM {users} WHERE username='" . $username . "'");
1829  $row = mysqli_fetch_row($res);
1830  $_SESSION['uid'] = $row[0];
1831  $_SESSION['gid'] = $row[2];
1832  $i = $row[1];
1833  $login_count = $i + 1;
1834  $_SESSION['logins'] = $login_count;
1835  $this->username = $username;
1836  // check if user got sufficient rights for backend use
1837  if ($this->checkGroupId($db, $_SESSION['gid'])) {
1838  if(!$res = $db->query("UPDATE {users} SET
1839  date_lastlogin = '" . $date_now . "',
1840  login_count = '" . $login_count . "',
1841  online = '1',
1842  logged_in = '1'
1843  WHERE username = '" . $this->username . "'"))
1844  {
1845  $uid = \YAWK\user::getUserIdFromName($db, $username);
1846  \YAWK\sys::setSyslog($db, 11, 1, "failed to login <b>$username</b>", $uid, 0, 0, 0);
1847  echo \YAWK\alert::draw("warning", "Error!", "Could not log user into database. Expect some errors.","","3800");
1848  }
1849  else
1850  { // avoid fake session ID
1851  @session_regenerate_id();
1852  $_SESSION['logged_in'] = true;
1853  }
1854  return true;
1855  }
1856  else
1857  {
1858  $uid = \YAWK\user::getUserIdFromName($db, $username);
1859  // user aint got the rights to login to backend
1860  \YAWK\sys::setSyslog($db, 12, 2, "failed to login <b>$username</b> user aint got sufficient rights to login. .", $uid, 0, 0, 0);
1861  \YAWK\alert::draw("danger", "Login failed!", "You are not allowed to login here.", "", 10000);
1862  }
1863  } // wrong password given
1864  else { // kick it back
1865  /** LOG FAILED LOGIN ....*/
1866  if (!isset($_SESSION['failed']))
1867  {
1868  $_SESSION['failed'] = 0;
1869  $_SESSION['failed']++;
1870  }
1871  else
1872  {
1873  $_SESSION['failed']++;
1874  // If max attempts reached, set lockout time
1875  if ($_SESSION['failed'] >= $maxAttempts) {
1876  $_SESSION['lockout_until'] = time() + ($lockoutTime * 60);
1877  }
1878 
1879  echo "<script>
1880  function disableButtons(delay)
1881  {
1882  // Disable the buttons
1883  $('#loginButton').removeClass().addClass('btn btn-success disabled').attr('id', 'LOGIN_FORBIDDEN');
1884  $('#resetPasswordButton').removeClass().addClass('btn btn-danger disabled');
1885 
1886  // Enable the buttons after the specified delay
1887  setTimeout(function() {
1888  $('#LOGIN_FORBIDDEN').attr('id', 'loginButton').removeClass().addClass('btn btn-success');
1889  $('#resetPasswordButton').removeClass().addClass('btn btn-danger');
1890  }, delay);
1891  }
1892  // add document ready
1893  $(document).ready(function() {
1894  disableButtons(10000);
1895  });
1896 
1897  // RE-LOGIN TIMER
1898  $('div *').prop('disabled', true);
1899  var count = 10;
1900  var counter = setInterval(timer, 1000); // 1000 will run it every 1 second
1901  function timer()
1902  {
1903  count=count-1;
1904  if (count <= 0)
1905  {
1906  timer = '#timer';
1907  clearInterval(counter);
1908  //counter ended, do something here
1909  $('div *').prop('disabled', false);
1910  // $(timer).empty();
1911  // $(timer).append(\"a few\").fadeIn();
1912  return null;
1913  }
1914  //Do code for showing the number of seconds here
1915  // document.getElementById(\"timer\").innerHTML=count; // watch for spelling
1916  }
1917 
1918  </script>";
1919 
1920  \YAWK\alert::draw("danger", "Login failed!", "Please check your login data and try to re-login in a few seconds!","","3500");
1921  $uid = \YAWK\user::getUserIdFromName($db, $username);
1922  $this->storeLogin($db, 0, "backend", $username, $password);
1923 
1924 
1925  if ($_SESSION['failed'] == 3){
1926  \YAWK\alert::draw("warning", "ATTENTION!", "This is the 3rd failed login tryout. - <b>The next failed login will be logged for security reasons!</b>","","6800");
1927  return false;
1928  }
1929  else if ($_SESSION['failed'] >= 5)
1930  {
1931  $hostname = gethostname();
1932  \YAWK\sys::setSyslog($db, 11, 1, "possible brute force attack: <b>$username</b> : $password", $uid, 0, 0, 0);
1933  \YAWK\alert::draw("danger", "DO NOT BRUTE FORCE HERE!", "failed tryouts: $_SESSION[failed]</h3><br><b>You are not allowed to login here. You have been warned.<br>The Admin is informed. Remember: BruteForce Attacks are against the law. <i style=\"text-decoration: underline\"><br><br>All of your actions will be logged and prosecuted. - <b>The network operation centre was informed.</b></i></b><br><br>Date: $date_now<br>Your IP: $_SERVER[REMOTE_ADDR]<br>Browser: $_SERVER[HTTP_USER_AGENT]</b><br>","","0");
1934  $domain = \YAWK\settings::getSetting($db, "domain");
1935  $to = \YAWK\settings::getSetting($db, "admin_email");
1936  $from = "script@".$domain." ";
1937  $ip = $_SERVER['HTTP_USER_AGENT'];
1938  $userAgent = $_SERVER['HTTP_USER_AGENT'];
1939  $message = "FAILED LOGIN ATTEMPT!\n\r
1940  Date : $date_now\n
1941  Message : User tried a Backend Login more than 5 times!\n
1942  User : $this->username\n
1943  Password : $this->password\n
1944  IP : $ip\n
1945  UserAgent : $userAgent\n";
1946  \YAWK\email::sendEmail($from, $to, "", "LOGIN WARNING! on $domain", $message);
1947  $this->storeLogin($db, 0, "backend", $username, $password);
1948  return false;
1949  }
1950 
1951  return false;
1952 
1953  } // failed login
1954  }
1955  // something else has happened
1956  \YAWK\alert::draw("danger", "Login failed!", "Please check your credentials!", "", 6000);
1957  return false;
1958  }
1959 
1960  /**
1961  * @brief store user login in database
1962  * @param object $db database
1963  * @param int $failed 0|1 failed status: 1 means login failed, 0 means NOT failed
1964  * @param string $location frontend or backend
1965  * @param string $username username
1966  * @param string $password password
1967  * @return bool
1968  */
1969  static function storeLogin($db, $failed, $location, $username, $password)
1970  { /** @var $db \YAWK\db */
1971  if (!isset($location)){
1972  $location = '';
1973  }
1974 
1975  // store failed login
1976  $atm = date("Y-m-d H:i:s");
1977  if (!isset($failed))
1978  { //
1979  $failed = 1;
1980  }
1981  if (!isset($state) || (empty($state)))
1982  {
1983  $state = "login";
1984  }
1985  $ip = $_SERVER['REMOTE_ADDR'];
1986  $useragent = $_SERVER['HTTP_USER_AGENT'];
1987  $res = $db->query("INSERT INTO {logins}
1988  (datetime, location, failed, ip, useragent, username, password)
1989  VALUES ('".$atm."', '".$location."', '".$failed."', '".$ip."', '".$useragent."', '".$username."', '".$password."') ");
1990  if ($res){ return true; }
1991  else { return false; }
1992  }
1993 
1994 
1995  /**
1996  * @brief return the html for a default login box
1997  * @param string $username username, as option
1998  * @param string $password password, as option
1999  * @return string
2000  */
2002  {
2003  $html = "
2004  <form name=\"login\" id=\"loginForm\" role=\"form\" method=\"POST\">
2005  <input type=\"text\" id=\"user\" name=\"user\" value=\"".$username."\" class=\"form-control animated fadeIn\" placeholder=\"Benutzername\">
2006  <input type=\"password\" id=\"password\" name=\"password\" value=\"".$password."\" class=\"form-control animated fadeIn\" placeholder=\"Passwort\">
2007  <input type=\"hidden\" name=\"login\" value=\"login\">
2008  <input type=\"submit\" id=\"submitBtn\" value=\"Login\" style=\"margin-top:5px;\" name=\"Login\" class=\"btn btn-success animated fadeIn\">
2009  <div id=\"captchaNode\"></div>
2010  </form>";
2011  return $html;
2012  }
2013 
2014  /**
2015  * @brief return the html for a menu login box
2016  * @param string $username username, as option
2017  * @param string $password password, as option
2018  * @param string $style menu styling: light or dark
2019  * @return string htmnl that draws the menu login box
2020  */
2021  static function drawMenuLoginBox($username, $password, $style)
2022  {
2023  if (!isset($style) || (empty($style)))
2024  {
2025  $style = "light";
2026  $input_style = '';
2027  }
2028  else
2029  {
2030  if ($style == "light")
2031  {
2032  $input_style = '';
2033  }
2034  elseif ($style == "dark")
2035  {
2036  $input_style = "style=\"color: #ccc; border-color: #000; background-color: #444;\"";
2037  }
2038  else
2039  {
2040  $input_style = '';
2041  }
2042  }
2043 
2044  $html = "<form name=\"login\" id=\"loginForm\" class=\"navbar-form navbar-right\" role=\"form\" action=\"welcome.html\" method=\"POST\">
2045  <div class=\"form-group\">
2046  <input type=\"text\" id=\"user\" name=\"user\" value=\"".$username."\" class=\"form-control\" $input_style placeholder=\"Benutzername\">
2047  <input type=\"password\" id=\"password\" name=\"password\" value=\"".$password."\" class=\"form-control\" $input_style placeholder=\"Passwort\">
2048  <input type=\"hidden\" name=\"login\" value=\"login\">
2049  <input type=\"hidden\" name=\"LOCK\" value=\"1\">
2050  <input type=\"hidden\" name=\"include\" value=\"login\">
2051  <input type=\"submit\" value=\"Login\" name=\"Login\" class=\"btn btn-success\">
2052  </div>
2053  </form>";
2054  return $html;
2055  }
2056 
2057  /**
2058  * @brief logout user
2059  * @param object $db database
2060  * @return bool
2061  */
2062  public function logout($db)
2063  { /** @var $db \YAWK\db */
2064  // set user offline in db
2065  if (isset($_SESSION['username']))
2066  { // if username is set in session var, logout
2067  if (!$res = $db->query("UPDATE {users}
2068  SET online = '0'
2069  WHERE username = '".$_SESSION['username']."'"))
2070  {
2071  \YAWK\sys::setSyslog($db, 11, 1, "failed to logout <b>$_SESSION[username]</b> .", 0, 0, 0, 0);
2072  \YAWK\alert::draw("danger", "Error!", "Could not logout ".$_SESSION['username']." Please try again!","","3800");
2073  // DELETE SESSION
2074  $_SESSION['failed']=0;
2075  $_SESSION['logged_in']=0;
2076  session_destroy();
2077  return false;
2078  }
2079  else
2080  { // username is not set, delete session anyway
2081  $_SESSION['failed']=0;
2082  $_SESSION['logged_in']=0;
2083  session_destroy();
2084  \YAWK\sys::setSyslog($db, 9, 0, "logout <b>".$_SESSION['username']."</b>", 0, 0, 0, 0);
2085  return true;
2086  }
2087  }
2088  else
2089  { // if a username is sent via get param...
2090  if (isset($_GET['user'])
2091  && (!empty($_GET['user'])
2092  && (is_string($_GET['user']))))
2093  {
2094  // logout user
2095  if (!$res = $db->query("UPDATE {users}
2096  SET online = '0'
2097  WHERE username = '".$_GET['username']."'"))
2098  { // unable to logout
2099  \YAWK\sys::setSyslog($db, 11, 1, "unable to logout <b>".$_GET['username']."</b>", 0, 0, 0, 0);
2100  \YAWK\alert::draw("danger", "Error!", "Could not logout ".$_GET['username']." Please try again!","","3800");
2101  // DELETE SESSION
2102  $_SESSION['failed']=0;
2103  $_SESSION['logged_in']=0;
2104  session_destroy();
2105  return false;
2106  }
2107  else
2108  { // user logged out from database, destroy session
2109  $_SESSION['failed']=0;
2110  $_SESSION['logged_in']=0;
2111  session_destroy();
2112  \YAWK\sys::setSyslog($db, 9, 0, "logout <b>".$_GET['username']."</b>", 0, 0, 0, 0);
2113  return true;
2114  }
2115  }
2116  // DELETE SESSION
2117  $_SESSION['failed']=0;
2118  $_SESSION['logged_in']=0;
2119  session_destroy();
2120  return true;
2121  }
2122  }
2123 
2124 
2125  /**
2126  * @brief output a list of all users (who have not activated privacy switch)
2127  * @param object $db database
2128  */
2129  static function getUserList($db)
2130  { /* @param \YAWK\db $db */
2131  // show ALL users
2132  // get all users from db where privacy is set to zero
2133  // & just pick users who are set to online in database
2134  $res = $db->query("SELECT username, email, public_email, online FROM {users} WHERE privacy != 1");
2135  while ($row = mysqli_fetch_assoc($res)){
2136  // first char uppcerase
2137  $username = ucfirst($row['username']);
2138  // check if users email adress is public
2139  if ($row['email'] && $row['public_email'] === '0'){
2140  $email = $row['email'];
2141  } else {
2142  $email = "";
2143  } // if not, build an empty string
2144  if ($row['online'] === '0') {
2145  $color = "text-danger";
2146  }
2147  else {
2148  $color = "text-success";
2149  }
2150  echo "<ul class=\"list-group\">
2151  <li class=\"list-group-item\"><span class=\"".$color."\"><strong>".$username." &nbsp;&nbsp;<small>".$email."</strong></small></span></li>
2152  </ul>";
2153  }
2154  }
2155 
2156 
2157  /**
2158  * @brief check if a user follows another
2159  * @param object $db database
2160  * @param int $uid user ID of the user who wants to know
2161  * @param int $hunted user ID of the other user
2162  * @return bool true, if they follow each other, false if not
2163  */
2164  static function checkFollowStatus($db, $uid, $hunted)
2165  { /** @var $db \YAWK\db */
2166  if ($sql = $db->query("SELECT id FROM {follower} WHERE follower='$uid' AND hunted = '".$hunted."'"))
2167  {
2168  if (mysqli_fetch_row($sql))
2169  {
2170  return true;
2171  }
2172  else
2173  {
2174  return false;
2175  }
2176  }
2177  else
2178  { // q failed
2179  \YAWK\sys::setSyslog($db, 19, 1, "failed to get status from follower db", $uid, 0, 0, 0);
2180  return false;
2181  }
2182  }
2183 
2184  /**
2185  * @brief check if two users are friends
2186  * @param object $db database
2187  * @param int $uid user ID who want to know
2188  * @param int $hunted user ID of the other user
2189  * @return bool
2190  */
2191  static function isFriend($db, $uid, $hunted)
2192  { /** @var $db \YAWK\db */
2193  if ($sql = $db->query("SELECT id FROM {friends}
2194  WHERE confirmed='1' AND friendA='$uid' AND friendB = '".$hunted."'
2195  OR confirmed='1' AND friendA='$hunted' AND friendB = '$uid'"))
2196  {
2197  if (mysqli_fetch_row($sql))
2198  {
2199  return true;
2200  }
2201  else
2202  {
2203  return false;
2204  }
2205  }
2206  else
2207  { // q failed
2208  \YAWK\sys::setSyslog($db, 19, 1, "failed to query friendship status of user ID <b>$uid</b> .", 0, 0, 0, 0);
2209  return false;
2210  }
2211  }
2212 
2213  /**
2214  * @brief check if a friendship request was sent from a user to another
2215  * @param object $db database
2216  * @param int $uid user ID who wants to know
2217  * @param int $hunted user ID of the other user
2218  * @return array|bool
2219  */
2220  static function isFriendRequested($db, $uid, $hunted)
2221  { /** @var $db \YAWK\db */
2222  if ($sql = $db->query("SELECT id, friendA, friendB, confirmed, aborted FROM {friends}
2223  WHERE confirmed='0' AND friendA='$uid' AND friendB = '".$hunted."'
2224  OR confirmed='0' AND friendA='$hunted' AND friendB = '$uid'"))
2225  {
2226  $friends = array();
2227  while ($row = mysqli_fetch_assoc($sql))
2228  {
2229  $friends[] = $row;
2230  }
2231  return $friends;
2232  }
2233  else
2234  { // q failed
2235  \YAWK\sys::setSyslog($db, 19, 1, "failed to query friendship request status of uid <b>#$uid</b> .", 0, 0, 0, 0);
2236  return false;
2237  }
2238  }
2239 
2240  /**
2241  * @brief count and return how many notifications are unseen
2242  * @param object $db database
2243  * @return int|bool the number of notifications or false
2244  */
2245  static function countNotifications($db)
2246  { /** @var $db \YAWK\db */
2247  if ($sql = $db->query("SELECT count(log_id) FROM {syslog}
2248  WHERE seen = '0'"))
2249  { // count + return syslog entries
2250  $row = mysqli_fetch_row($sql);
2251  return $row[0];
2252  }
2253  else
2254  { // q failed
2255  \YAWK\sys::setSyslog($db, 3, 1, "failed to count admin notifications", 0, 0, 0, 0);
2256  return false;
2257  }
2258  }
2259 
2260  /**
2261  * @brief count and return notifications for user ID
2262  * @param object $db database
2263  * @param int $uid user ID
2264  * @return int|bool the number of personal notifications for user ID, or false
2265  */
2266  static function countMyNotifications($db, $uid)
2267  { /** @var $db \YAWK\db */
2268  if ($sql = $db->query("SELECT count(toUID) FROM {notifications}
2269  WHERE toUID = '".$uid."' AND seen = '0'"))
2270  { // count + return syslog entries
2271  $row = mysqli_fetch_row($sql);
2272  return $row[0];
2273  }
2274  else
2275  { // q failed
2276  \YAWK\sys::setSyslog($db, 3, 1, "failed to count personal notifications of UID <b>$uid</b> .", 0, 0, 0, 0);
2277  return false;
2278  }
2279  }
2280 
2281  /**
2282  * @brief return an array with all notifications
2283  * @param object $db database
2284  * @return array|bool
2285  */
2286  static function getAllNotifications($db)
2287  { /** @var $db \YAWK\db */
2288 
2289  if ($sql = $db->query("SELECT * FROM {syslog} AS log
2290  LEFT JOIN {syslog_categories} AS category ON log.log_category=category.id
2291  LEFT JOIN {users} AS u ON log.fromUID=u.id
2292  WHERE log.seen = '0'
2293  GROUP BY log.log_id
2294  ORDER BY log.log_date DESC"))
2295  { // create array
2296  $all_notifications = array();
2297  while ($row = mysqli_fetch_assoc($sql))
2298  { // fill w data in loop
2299  $all_notifications[] = $row;
2300  }
2301  return $all_notifications;
2302  }
2303  else
2304  { // q failed
2305  \YAWK\sys::setSyslog($db, 3, 1, "unable to get syslog entries", 0, 0, 0, 0);
2306  return false;
2307  }
2308  }
2309 
2310  /**
2311  * @brief get all personal notifications for given user ID
2312  * @param object $db database
2313  * @param int $uid affected user ID
2314  * @return array|bool returns an array with all entries or false
2315  */
2316  static function getMyNotifications($db, $uid)
2317  { /** @var $db \YAWK\db */
2318  if ($sql = $db->query("SELECT * FROM {notifications} AS log
2319  LEFT JOIN {syslog_categories} AS category ON log.log_category=category.id
2320  LEFT JOIN {notifications_msg} AS msg ON log.msg_id=msg.id
2321  LEFT JOIN {users} AS u ON log.fromUID=u.id
2322  WHERE log.toUID = '".$uid."'
2323  AND log.seen = '0'
2324  GROUP BY log.log_id
2325  ORDER BY log.log_date DESC"))
2326  { // create array
2327  $my_notifications = array();
2328  while ($row = mysqli_fetch_assoc($sql))
2329  { // fill w data in loop
2330  $my_notifications[] = $row;
2331  }
2332  return $my_notifications;
2333  }
2334  else
2335  { // q failed
2336  \YAWK\sys::setSyslog($db, 3, 1, "failed to get notifications.", $uid, 0, 0, 0);
2337  return false;
2338  }
2339  }
2340 
2341  /**
2342  * @brief count followers of given user ID
2343  * @param object $db database
2344  * @param int $uid affected user ID
2345  * @return int|bool the number of followers for that user ID or false
2346  */
2347  static function countMyFollowers($db, $uid)
2348  { /** @var $db \YAWK\db */
2349  if ($sql = $db->query("SELECT count(id) FROM {follower} WHERE hunted = '".$uid."'"))
2350  { // count + return data
2351  $row = mysqli_fetch_row($sql);
2352  return $row[0];
2353  }
2354  else
2355  { // q failed
2356  \YAWK\sys::setSyslog($db, 19,1, "failed to count followers of user ID<b>$uid</b>", 0, 0, 0, 0);
2357  return false;
2358  }
2359  }
2360 
2361  /**
2362  * @brief count friends of given user ID
2363  * @param object $db database
2364  * @param int $uid affected user ID
2365  * @return int|bool the number of friends for that user ID or false
2366  */
2367  static function countMyFriends($db, $uid)
2368  { /** @var $db \YAWK\db */
2369  if ($sql = $db->query("SELECT count(id) FROM {friends}
2370  WHERE confirmed = '1' AND friendA = '".$uid."'
2371  OR friendB = '".$uid."' AND confirmed = '1'
2372  AND aborted NOT LIKE '1'"))
2373  { // count + return data
2374  $row = mysqli_fetch_row($sql);
2375  return $row[0];
2376  }
2377  else
2378  { // q failed
2379  \YAWK\sys::setSyslog($db, 19, 1, "failed to count friends of user ID <b>$uid</b>", 0, 0, 0, 0);
2380  return false;
2381  }
2382  }
2383 
2384  /**
2385  * @brief return an array with all confirmed friends for given user ID
2386  * @param object $db database
2387  * @param object $lang language
2388  * @param int $uid affected user ID
2389  * @param int $confirmed 0|1 1 is confirmed, 0 is not. therefore you can get all friends, confirmed and outstanding
2390  * @return array|bool
2391  */
2392  static function getMyFriends($db, $uid, $confirmed, $lang)
2393  { /** @var $db \YAWK\db */
2394  // to just friend requests
2395  if (isset($confirmed) && $confirmed === 0)
2396  { // param outstanding
2397  $confirmed = 0;
2398  }
2399  else
2400  {
2401  $confirmed = 1;
2402  }
2403  if ($sql = $db->query("SELECT * FROM {friends} AS friends
2404  WHERE confirmed = '".$confirmed."' AND friendA = '".$uid."'
2405  OR confirmed = '".$confirmed."' AND friendB = '".$uid."'
2406  AND aborted NOT LIKE '1'"))
2407  { // create friends array
2408  $friends = array();
2409  while ($row = mysqli_fetch_assoc($sql))
2410  { // fill w data in loop
2411  $friends[] = $row;
2412  }
2413  return $friends;
2414  }
2415  else
2416  { // q failed
2417  \YAWK\sys::setSyslog($db, 19, 1, "failed to get friends of user ID <b>$uid</b>", 0, 0, 0, 0);
2418  return false;
2419  }
2420  }
2421 
2422  /**
2423  * @brief get an array with all followers for given user ID
2424  * @param object $db database
2425  * @param int $uid user ID
2426  * @return array|bool
2427  */
2428  static function getMyFollower($db, $uid)
2429  { /** @var $db \YAWK\db */
2430  // param UID is set
2431  if (isset($uid))
2432  { //
2433  if ($uid == 0)
2434  { // select followers of logged in user
2435  $currentuser = $_SESSION['uid'];
2436  }
2437  else
2438  { // select followers of given user ID
2439  $currentuser = $uid;
2440  }
2441  }
2442  else
2443  { // default: followers of logged in user
2444  $currentuser = $_SESSION['uid'];
2445  }
2446  if ($sql = $db->query("SELECT * FROM {follower} AS f
2447  LEFT JOIN {users} AS u ON f.follower=u.id
2448  WHERE hunted = '".$currentuser."'"))
2449  { // create friends array
2450  $follower = array();
2451  while ($row = mysqli_fetch_assoc($sql))
2452  { // fill w data in loop
2453  $follower[] = $row;
2454  }
2455  return $follower;
2456  }
2457  else
2458  { // q failed
2459  \YAWK\sys::setSyslog($db, 3, 1, "failed to get followers of user ID <b>$uid</b> .", 0, 0, 0, 0);
2460  return false;
2461  }
2462  }
2463 
2464  /**
2465  * @brief count and return number of messages for given user ID
2466  * @param object $db database
2467  * @param int $uid affected user ID
2468  * @return int|bool number of messages or false
2469  */
2470  static function countNewMessages($db, $uid)
2471  { /** @var $db \YAWK\db */
2472  $i = 0;
2473  if ($sql = $db->query("SELECT msg_id FROM {plugin_msg} WHERE msg_read ='0' AND spam IS NOT NULL AND trash IS NOT NULL AND toUID = '".$uid."'"))
2474  { // fetch data in loop
2475  while ($row = mysqli_fetch_assoc($sql))
2476  { // count +1 for each loop
2477  $i++;
2478  }
2479  return $i;
2480  }
2481  else
2482  { // q failed
2483  \YAWK\sys::setSyslog($db, 3, 1, "failed to count new messages of user ID <b>$uid</b> .", 0, 0, 0, 0);
2484  return false;
2485  }
2486  }
2487 
2488  /**
2489  * @brief return array with all messages for given user ID
2490  * @param object $db database
2491  * @param int $uid affected user ID
2492  * @return array|bool
2493  */
2494  static function getNewMessages($db, $uid)
2495  { /** @var $db \YAWK\db */
2496 
2497  if ($sql = $db->query("SELECT * FROM {plugin_msg} WHERE msg_read ='0' AND toUID = '".$uid."' ORDER by msg_date DESC"))
2498  { // create array
2499  $newMessages = array();
2500  while ($row = mysqli_fetch_assoc($sql))
2501  { // add every message as new entry
2502  $newMessages[] = $row;
2503  }
2504  return $newMessages;
2505  }
2506  else
2507  { // q failed
2508  \YAWK\sys::setSyslog($db, 3, 1, "failed to get new messages of user ID <b>#$uid</b> .", 0, 0, 0, 0);
2509  return false;
2510  }
2511  }
2512 
2513  } // ./ class user
2514 } // ./ namespace
if(!isset($db)) $uid
$ip
Definition: add-comment.php:9
print $lang['FILEMAN_UPLOAD']
$blog gid
Definition: blog-setup.php:139
static draw($type, $title, $text, $redirect, $delay)
Definition: alert.php:30
Email class serve function sendEmail() to send email.
Definition: email.php:20
static sendEmail($email_from, $email_to, $email_cc, $email_subject, $email_message)
send an email
Definition: email.php:31
static getSetting($db, $property)
Get and return value for property from settings database.
Definition: settings.php:470
static setTimeout($location, $wait)
set a timeout and force page reload via JS
Definition: sys.php:864
static getHost($db)
get hostname (url where yawk is installed) from database
Definition: sys.php:1115
static iStatusToString($i, $on, $off)
convert a integer status to string variable (0|1) to online / offline
Definition: sys.php:729
The default user class. Provide all functions to handle the user object.
Definition: user.php:17
$date_lastlogin
Definition: user.php:41
static getUserTemplateID($db, $uid)
template ID for given user ID
Definition: user.php:421
$email
Definition: user.php:47
static getLoginData($db, $user)
return an array with all login data
Definition: user.php:540
static setNewPassword($db, $newPassword, $uid)
Set a new user password.
Definition: user.php:189
setUserTemplate($db, $overrideTemplate, $userTemplateID, $uid)
set status and override template for this user ID
Definition: user.php:487
__construct($db)
user constructor.
Definition: user.php:86
$currentuser
Definition: user.php:19
static drawLoginBox($username, $password)
return the html for a default login box
Definition: user.php:2001
static isAnybodyThere($db)
check, if a session username is set and if user is logged in
Definition: user.php:361
static getUserImage($location, $user, $cssClass, $w, $h)
return and output user image
Definition: user.php:1079
static getToken($length)
Generate a safe token for password reset.
Definition: user.php:101
static countUsers($db)
count and return all users
Definition: user.php:754
$street
Definition: user.php:59
$lastname
Definition: user.php:57
$overrideTemplate
Definition: user.php:77
$date_created
Definition: user.php:37
$blocked
Definition: user.php:23
$public_email
Definition: user.php:71
static drawPasswordResetForm($db, $lang, $uid)
Draw the form where users can reset their password.
Definition: user.php:171
$online
Definition: user.php:31
static getUserList($db)
output a list of all users (who have not activated privacy switch)
Definition: user.php:2129
$country
Definition: user.php:65
$username
Definition: user.php:21
isTemplateEqual($db, $userTemplateID)
check if user template equals selected (active) template
Definition: user.php:519
isAllowedToOverrideTemplate($db, $uid)
check if user ID is allowed to override template
Definition: user.php:452
$facebook
Definition: user.php:53
$login_count
Definition: user.php:45
static getUserEmail($db, $user)
return email address of $user
Definition: user.php:1254
$password
Definition: user.php:35
static getLatestUsers($db, $count)
get latest users and return as array
Definition: user.php:718
$twitter
Definition: user.php:51
static getCurrentUserName($lang)
return current username
Definition: user.php:344
$date_changed
Definition: user.php:39
$logged_in
Definition: user.php:73
$lastlogin
Definition: user.php:69
$published
Definition: user.php:27
static ajaxLogin($db, $user, $password)
Definition: user.php:1627
$templateID
Definition: user.php:79
$date_expired
Definition: user.php:43
getUserArray($db)
return user data as an array
Definition: user.php:690
$privacy
Definition: user.php:29
$likes
Definition: user.php:75
static drawMenuLoginBox($username, $password, $style)
return the html for a menu login box
Definition: user.php:2021
$terms
Definition: user.php:81
static sendResetEmail($db, $username, $email, $lang)
Send password change request email.
Definition: user.php:232
$zipcode
Definition: user.php:61
$firstname
Definition: user.php:55
static checkResetToken($db, $token)
Check if password reset token matches and return uid.
Definition: user.php:131
$result
Definition: email-send.php:137
$hunted
Definition: follow-user.php:23
exit
$sql
Definition: message-new.php:32
This class serves methods to create backup from files.
Definition: AdminLTE.php:2
$host
Definition: page-edit.php:65
print $_GET['id']
Definition: page-edit.php:357
$user overrideTemplate
$userTemplateID
print $tourdates date
$friends
Definition: user-edit.php:331
$password2
Definition: user-new.php:93
$password1
Definition: user-new.php:92
$value
$i
$useragent
Definition: yawk-stats.php:70