4 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
5 * Copyright (C) 2002-2011 The Nucleus Group
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 * (see nucleus/documentation/index.html#license for more info)
14 * A class representing site members
16 * @license http://nucleuscms.org/license.txt GNU General Public License
17 * @copyright Copyright (C) 2002-2011 The Nucleus Group
19 * $NucleusJP: MEMBER.php,v 1.6 2006/07/17 20:03:44 kimitake Exp $
23 // 1 when authenticated, 0 when not
25 var $password; // not the actual password, but rather a MD5 hash
27 var $cookiekey; // value that should also be in the client cookie to allow authentication
35 var $language = ''; // name of the language file to use (e.g. 'english' -> english.php)
36 var $admin = 0; // (either 0 or 1)
37 var $canlogin = 0; // (either 0 or 1)
39 var $autosave = 1; // if the member use the autosave draft function
42 * Constructor for a member object
49 * Create a member object for a given displayname
53 function &createFromName($displayname) {
55 $mem->readFromName($displayname);
60 * Create a member object for a given ID
64 function &createFromID($id) {
66 $mem->readFromID($id);
70 function readFromName($displayname) {
71 return $this->read("mname='".sql_real_escape_string($displayname)."'");
74 function readFromID($id) {
75 return $this->read("mnumber=" . intval($id));
79 * Tries to login as a given user.
80 * Returns true when succeeded, returns false when failed
81 * 3.40 adds CustomLogin event
83 function login($login, $password) {
88 $manager->notify('CustomLogin', array('login' => &$login, 'password'=>&$password, 'success'=>&$success, 'allowlocal'=>&$allowlocal) );
89 if ($success && $this->readFromName($login)) {
91 return $this->isLoggedIn();
92 } elseif (!$success && $allowlocal) {
93 if (!$this->readFromName($login))
95 if (!$this->checkPassword($password))
98 return $this->isLoggedIn();
105 * Login using cookie key
107 function cookielogin($login, $cookiekey) {
109 if (!$this->readFromName($login))
111 if (!$this->checkCookieKey($cookiekey))
114 return $this->isLoggedIn();
121 function isLoggedIn() {
122 return $this->loggedin;
126 * Read member information from the database
128 function read($where) {
130 $query = 'SELECT * FROM '.sql_table('member') . ' WHERE ' . $where;
132 $res = sql_query($query);
133 $obj = sql_fetch_object($res);
135 $this->setRealName($obj->mrealname);
136 $this->setEmail($obj->memail);
137 $this->password = $obj->mpassword;
138 $this->setCookieKey($obj->mcookiekey);
139 $this->setURL($obj->murl);
140 $this->setDisplayName($obj->mname);
141 $this->setAdmin($obj->madmin);
142 $this->id = $obj->mnumber;
143 $this->setCanLogin($obj->mcanlogin);
144 $this->setNotes($obj->mnotes);
145 $this->setLanguage($obj->deflang);
146 $this->setAutosave($obj->mautosave);
148 return sql_num_rows($res);
153 * Returns true if member is an admin for the given blog
154 * (returns false if not a team member)
156 function isBlogAdmin($blogid) {
157 $query = 'SELECT tadmin FROM '.sql_table('team').' WHERE'
158 . ' tblog=' . intval($blogid)
159 . ' and tmember='. $this->getID();
160 $res = sql_query($query);
161 if (sql_num_rows($res) == 0)
164 return (sql_result($res,0,0) == 1) ;
167 function blogAdminRights($blogid) {
168 return ($this->isAdmin() || $this->isBlogAdmin($blogid));
172 function teamRights($blogid) {
173 return ($this->isAdmin() || $this->isTeamMember($blogid));
177 * Returns true if this member is a team member of the given blog
179 function isTeamMember($blogid) {
180 $query = 'SELECT * FROM '.sql_table('team').' WHERE'
181 . ' tblog=' . intval($blogid)
182 . ' and tmember='. $this->getID();
183 $res = sql_query($query);
184 return (sql_num_rows($res) != 0);
187 function canAddItem($catid) {
190 // if this is a 'newcat' style newcat
191 // no blog admin of destination blog -> NOK
192 // blog admin of destination blog -> OK
193 if (strstr($catid,'newcat')) {
195 list($blogid) = sscanf($catid,"newcat-%d");
196 return $this->blogAdminRights($blogid);
199 // category does not exist -> NOK
200 if (!$manager->existsCategory($catid)) return 0;
202 $blogid = getBlogIDFromCatID($catid);
204 // no team rights for blog -> NOK
205 if (!$this->teamRights($blogid)) return 0;
207 // all other cases: OK
212 * Returns true if this member can edit/delete a commentitem. This can be in the
214 * - member is a super-admin
215 * - member is the author of the comment
216 * - member is admin of the blog associated with the comment
217 * - member is author of the item associated with the comment
219 function canAlterComment($commentid) {
220 if ($this->isAdmin()) return 1;
222 $query = 'SELECT citem as itemid, iblog as blogid, cmember as cauthor, iauthor'
223 . ' FROM '.sql_table('comment') .', '.sql_table('item').', '.sql_table('blog')
224 . ' WHERE citem=inumber and iblog=bnumber and cnumber=' . intval($commentid);
225 $res = sql_query($query);
226 $obj = sql_fetch_object($res);
228 return ($obj->cauthor == $this->getID()) or $this->isBlogAdmin($obj->blogid) or ($obj->iauthor == $this->getID());
232 * Returns true if this member can edit/delete an item. This is true in the following
233 * cases: - member is a super-admin
234 * - member is the author of the item
235 * - member is admin of the the associated blog
237 function canAlterItem($itemid) {
238 if ($this->isAdmin()) return 1;
240 $query = 'SELECT iblog, iauthor FROM '.sql_table('item').' WHERE inumber=' . intval($itemid);
241 $res = sql_query($query);
242 $obj = sql_fetch_object($res);
243 return ($obj->iauthor == $this->getID()) or $this->isBlogAdmin($obj->iblog);
247 * Return true if member can be deleted. This means that there are no items
248 * posted by the member left
250 function canBeDeleted() {
251 $res = sql_query('SELECT * FROM '.sql_table('item').' WHERE iauthor=' . $this->getID());
252 return (sql_num_rows($res) == 0);
256 * returns true if this member can move/update an item to a given category,
257 * false if not (see comments fot the tests that are executed)
260 * @param newcat (can also be of form 'newcat-x' with x=blogid)
262 function canUpdateItem($itemid, $newcat) {
265 // item does not exists -> NOK
266 if (!$manager->existsItem($itemid,1,1)) return 0;
268 // cannot alter item -> NOK
269 if (!$this->canAlterItem($itemid)) return 0;
271 // if this is a 'newcat' style newcat
272 // no blog admin of destination blog -> NOK
273 // blog admin of destination blog -> OK
274 if (strstr($newcat,'newcat')) {
276 list($blogid) = sscanf($newcat,'newcat-%d');
277 return $this->blogAdminRights($blogid);
280 // category does not exist -> NOK
281 if (!$manager->existsCategory($newcat)) return 0;
285 $item =& $manager->getItem($itemid,1,1);
287 // old catid = new catid -> OK
288 if ($item['catid'] == $newcat) return 1;
290 // not a valid category -> NOK
291 $validCat = quickQuery('SELECT COUNT(*) AS result FROM '.sql_table('category').' WHERE catid='.intval($newcat));
292 if (!$validCat) return 0;
294 // get destination blog
295 $source_blogid = getBlogIDFromItemID($itemid);
296 $dest_blogid = getBlogIDFromCatID($newcat);
298 // not a team member of destination blog -> NOK
299 if (!$this->teamRights($dest_blogid)) return 0;
301 // if member is author of item -> OK
302 if ($item['authorid'] == $this->getID()) return 1;
304 // if member has admin rights on both blogs: OK
305 if (($this->blogAdminRights($dest_blogid)) && ($this->blogAdminRights($source_blogid))) return 1;
307 // all other cases: NOK
313 * Sets the cookies for the member
316 * set this to 1 when using a shared computer. Cookies will expire
317 * at the end of the session in this case.
319 function setCookies($shared = 0) {
322 if ($CONF['SessionCookie'] || $shared)
325 $lifetime = (time()+2592000);
327 setcookie($CONF['CookiePrefix'] .'user',$this->getDisplayName(),$lifetime,$CONF['CookiePath'],$CONF['CookieDomain'],$CONF['CookieSecure']);
328 setcookie($CONF['CookiePrefix'] .'loginkey', $this->getCookieKey(),$lifetime,$CONF['CookiePath'],$CONF['CookieDomain'],$CONF['CookieSecure']);
330 // make sure cookies on shared pcs don't get renewed
332 setcookie($CONF['CookiePrefix'] .'sharedpc', '1',$lifetime,$CONF['CookiePath'],$CONF['CookieDomain'],$CONF['CookieSecure']);
335 function sendActivationLink($type, $extra='')
339 if (!isset($CONF['ActivationDays'])) $CONF['ActivationDays'] = 2;
341 // generate key and URL
342 $key = $this->generateActivationEntry($type, $extra);
343 $url = $CONF['AdminURL'] . 'index.php?action=activate&key=' . $key;
345 // choose text to use in mail
349 $message = _ACTIVATE_REGISTER_MAIL;
350 $title = _ACTIVATE_REGISTER_MAILTITLE;
353 $message = _ACTIVATE_FORGOT_MAIL;
354 $title = _ACTIVATE_FORGOT_MAILTITLE;
356 case 'addresschange':
357 $message = _ACTIVATE_CHANGE_MAIL;
358 $title = _ACTIVATE_CHANGE_MAILTITLE;
363 // fill out variables in text
366 'siteName' => $CONF['SiteName'],
367 'siteUrl' => $CONF['IndexURL'],
368 'memberName' => $this->getDisplayName(),
369 'activationUrl' => $url,
370 'activationDays' => $CONF['ActivationDays']
373 $message = TEMPLATE::fill($message, $aVars);
374 $title = TEMPLATE::fill($title, $aVars);
379 mb_internal_encoding(_CHARSET);
380 @mb_send_mail($this->getEmail(), $title ,$message,'From: ' . $CONF['AdminEmail']);
382 ACTIONLOG::add(INFO, _ACTIONLOG_ACTIVATIONLINK . ' (' . $this->getDisplayName() . ' / type: ' . $type . ')');
388 * Returns an array of all blogids for which member has admin rights
390 function getAdminBlogs() {
393 if ($this->isAdmin())
394 $query = 'SELECT bnumber as blogid from '.sql_table('blog');
396 $query = 'SELECT tblog as blogid from '.sql_table('team').' where tadmin=1 and tmember=' . $this->getID();
398 $res = sql_query($query);
399 if (sql_num_rows($res) > 0) {
400 while ($obj = sql_fetch_object($res)) {
401 array_push($blogs, $obj->blogid);
409 * Returns an array of all blogids for which member has team rights
411 function getTeamBlogs($incAdmin = 1) {
412 $incAdmin = intval($incAdmin);
415 if ($this->isAdmin() && $incAdmin)
416 $query = 'SELECT bnumber as blogid from '.sql_table('blog');
418 $query = 'SELECT tblog as blogid from '.sql_table('team').' where tmember=' . $this->getID();
420 $res = sql_query($query);
421 if (sql_num_rows($res) > 0) {
422 while ($obj = sql_fetch_object($res)) {
423 array_push($blogs, $obj->blogid);
431 * Returns an email address from which notification of commenting/karma voting can
432 * be sent. A suggestion can be given for when the member is not logged in
434 function getNotifyFromMailAddress($suggest = "") {
436 if ($this->isLoggedIn()) {
437 return $this->getDisplayName() . " <" . $this->getEmail() . ">";
438 } else if (isValidMailAddress($suggest)) {
441 return $CONF['AdminEmail'];
446 * Write data to database
450 $query = 'UPDATE '.sql_table('member')
451 . " SET mname='" . sql_real_escape_string($this->getDisplayName()) . "',"
452 . " mrealname='". sql_real_escape_string($this->getRealName()) . "',"
453 . " mpassword='". sql_real_escape_string($this->getPassword()) . "',"
454 . " mcookiekey='". sql_real_escape_string($this->getCookieKey()) . "',"
455 . " murl='" . sql_real_escape_string($this->getURL()) . "',"
456 . " memail='" . sql_real_escape_string($this->getEmail()) . "',"
457 . " madmin=" . $this->isAdmin() . ","
458 . " mnotes='" . sql_real_escape_string($this->getNotes()) . "',"
459 . " mcanlogin=" . $this->canLogin() . ","
460 . " deflang='" . sql_real_escape_string($this->getLanguage()) . "',"
461 . " mautosave=" . intval($this->getAutosave()) . ""
462 . " WHERE mnumber=" . $this->getID();
466 function checkCookieKey($key) {
467 return (($key != '') && ($key == $this->getCookieKey()));
470 function checkPassword($pw) {
471 return (md5($pw) == $this->getPassword());
474 function getRealName() {
475 return $this->realname;
478 function setRealName($name) {
479 $this->realname = $name;
482 function getEmail() {
486 function setEmail($email) {
487 $this->email = $email;
490 function getPassword() {
491 return $this->password;
494 function setPassword($pwd) {
495 $this->password = md5($pwd);
498 function getCookieKey() {
499 return $this->cookiekey;
503 * Generate new cookiekey, save it, and return it
505 function newCookieKey() {
506 mt_srand( (double) microtime() * 1000000);
507 $this->cookiekey = md5(uniqid(mt_rand()));
509 return $this->cookiekey;
512 function setCookieKey($val) {
513 $this->cookiekey = $val;
520 function setURL($site) {
524 function getLanguage() {
525 return $this->language;
528 function setLanguage($lang) {
529 $this->language = $lang;
532 function setDisplayName($nick) {
533 $this->displayname = $nick;
536 function getDisplayName() {
537 return $this->displayname;
544 function setAdmin($val) {
548 function canLogin() {
549 return $this->canlogin;
552 function setCanLogin($val) {
553 $this->canlogin = $val;
556 function getNotes() {
560 function setNotes($val) {
564 function getAutosave() {
565 return $this->autosave;
568 function setAutosave($val) {
569 $this->autosave = $val;
577 * Returns true if there is a member with the given login name
581 function exists($name) {
582 $r = sql_query('select * FROM '.sql_table('member')." WHERE mname='".sql_real_escape_string($name)."'");
583 return (sql_num_rows($r) != 0);
587 * Returns true if there is a member with the given ID
591 function existsID($id) {
592 $r = sql_query('select * FROM '.sql_table('member')." WHERE mnumber='".intval($id)."'");
593 return (sql_num_rows($r) != 0);
597 * Checks if a username is protected.
598 * If so, it can not be used on anonymous comments
600 function isNameProtected($name) {
603 $name = strip_tags($name);
606 return MEMBER::exists($name);
614 function create($name, $realname, $password, $email, $url, $admin, $canlogin, $notes) {
615 if (!isValidMailAddress($email))
617 return _ERROR_BADMAILADDRESS;
619 if (!isValidDisplayName($name))
621 return _ERROR_BADNAME;
623 if (MEMBER::exists($name))
625 return _ERROR_NICKNAMEINUSE;
629 return _ERROR_REALNAMEMISSING;
633 return _ERROR_PASSWORDMISSING;
636 # replaced eregi() below with preg_match(). ereg* functions are deprecated in PHP 5.3.0
637 # original eregi: !eregi("^https?://", $url)
638 // begin if: sometimes user didn't prefix the URL with http:// or https://, this cause a malformed URL. Let's fix it.
639 if (!preg_match('#^https?://#', $url) )
641 $url = 'http://' . $url;
644 $name = sql_real_escape_string($name);
645 $realname = sql_real_escape_string($realname);
646 $password = sql_real_escape_string(md5($password));
647 $email = sql_real_escape_string($email);
648 $url = sql_real_escape_string($url);
649 $admin = intval($admin);
650 $canlogin = intval($canlogin);
651 $notes = sql_real_escape_string($notes);
653 if (($admin) && !($canlogin)) {
657 $query = 'INSERT INTO '.sql_table('member')." (MNAME,MREALNAME,MPASSWORD,MEMAIL,MURL, MADMIN, MCANLOGIN, MNOTES) "
658 . "VALUES ('$name','$realname','$password','$email','$url',$admin, $canlogin, '$notes')";
661 ACTIONLOG::add(INFO, _ACTIONLOG_NEWMEMBER . ' ' . $name);
667 * Returns activation info for a certain key (an object with properties vkey, vmember, ...)
672 function getActivationInfo($key)
674 $query = 'SELECT * FROM ' . sql_table('activation') . ' WHERE vkey=\'' . sql_real_escape_string($key). '\'';
675 $res = sql_query($query);
677 if (!$res || (sql_num_rows($res) == 0))
680 return sql_fetch_object($res);
684 * Creates an account activation key
686 * @param $type one of the following values (determines what to do when activation expires)
687 * 'register' (new member registration)
688 * 'forgot' (forgotton password)
689 * 'addresschange' (member address has changed)
690 * @param $extra extra info (needed when validation link expires)
691 * addresschange -> old email address
694 function generateActivationEntry($type, $extra = '')
696 // clean up old entries
697 $this->cleanupActivationTable();
699 // kill any existing entries for the current member (delete is ok)
700 // (only one outstanding activation key can be present for a member)
701 sql_query('DELETE FROM ' . sql_table('activation') . ' WHERE vmember=' . intval($this->getID()));
703 $canLoginWhileActive = false; // indicates if the member can log in while the link is active
707 $canLoginWhileActive = true;
711 case 'addresschange':
712 $extra = $extra . '/' . ($this->canLogin() ? '1' : '0');
719 // generate a random key
720 srand((double)microtime()*1000000);
721 $key = md5(uniqid(rand(), true));
723 // attempt to add entry in database
724 // add in database as non-active
725 $query = 'INSERT INTO ' . sql_table('activation'). ' (vkey, vtime, vmember, vtype, vextra) ';
726 $query .= 'VALUES (\'' . sql_real_escape_string($key). '\', \'' . date('Y-m-d H:i:s',time()) . '\', \'' . intval($this->getID()). '\', \'' . sql_real_escape_string($type). '\', \'' . sql_real_escape_string($extra). '\')';
727 if (sql_query($query))
731 // mark member as not allowed to log in
732 if (!$canLoginWhileActive)
734 $this->setCanLogin(0);
743 * Inidicates that an activation link has been clicked and any forms displayed
744 * there have been successfully filled out.
747 function activate($key)
750 $info = MEMBER::getActivationInfo($key);
756 switch ($info->vtype)
762 // set canlogin value
764 sql_query('UPDATE ' . sql_table('member') . ' SET mcanlogin=' . intval($CONF['NewMemberCanLogon']). ' WHERE mnumber=' . intval($info->vmember));
766 case 'addresschange':
767 // reset old 'canlogin' value
768 list($oldEmail, $oldCanLogin) = explode('/', $info->vextra);
769 sql_query('UPDATE ' . sql_table('member') . ' SET mcanlogin=' . intval($oldCanLogin). ' WHERE mnumber=' . intval($info->vmember));
773 // delete from activation table
774 sql_query('DELETE FROM ' . sql_table('activation') . ' WHERE vkey=\'' . sql_real_escape_string($key) . '\'');
781 * Cleans up entries in the activation table. All entries older than 2 days are removed.
786 function cleanupActivationTable()
789 if (isset($CONF['ActivationDays']) && intval($CONF['ActivationDays']) > 0) {
790 $actdays = intval($CONF['ActivationDays']);
793 $CONF['ActivationDays'] = 2;
795 $boundary = time() - (60 * 60 * 24 * $actdays);
797 // 1. walk over all entries, and see if special actions need to be performed
798 $res = sql_query('SELECT * FROM ' . sql_table('activation') . ' WHERE vtime < \'' . date('Y-m-d H:i:s',$boundary) . '\'');
800 while ($o = sql_fetch_object($res))
805 // delete all information about this site member. registration is undone because there was
806 // no timely activation
807 include_once($DIR_LIBS . 'ADMIN.php');
808 ADMIN::deleteOneMember(intval($o->vmember));
810 case 'addresschange':
811 // revert the e-mail address of the member back to old address
812 list($oldEmail, $oldCanLogin) = explode('/', $o->vextra);
813 sql_query('UPDATE ' . sql_table('member') . ' SET mcanlogin=' . intval($oldCanLogin). ', memail=\'' . sql_real_escape_string($oldEmail). '\' WHERE mnumber=' . intval($o->vmember));
816 // delete the activation link and ignore. member can request a new password using the
817 // forgot password link
822 // 2. delete activation entries for real
823 sql_query('DELETE FROM ' . sql_table('activation') . ' WHERE vtime < \'' . date('Y-m-d H:i:s',$boundary) . '\'');