4 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
5 * Copyright (C) 2002-2010 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-2010 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='".addslashes($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 // generate key and URL
340 $key = $this->generateActivationEntry($type, $extra);
341 $url = $CONF['AdminURL'] . 'index.php?action=activate&key=' . $key;
343 // choose text to use in mail
347 $message = _ACTIVATE_REGISTER_MAIL;
348 $title = _ACTIVATE_REGISTER_MAILTITLE;
351 $message = _ACTIVATE_FORGOT_MAIL;
352 $title = _ACTIVATE_FORGOT_MAILTITLE;
354 case 'addresschange':
355 $message = _ACTIVATE_CHANGE_MAIL;
356 $title = _ACTIVATE_CHANGE_MAILTITLE;
361 // fill out variables in text
364 'siteName' => $CONF['SiteName'],
365 'siteUrl' => $CONF['IndexURL'],
366 'memberName' => $this->getDisplayName(),
367 'activationUrl' => $url
370 $message = TEMPLATE::fill($message, $aVars);
371 $title = TEMPLATE::fill($title, $aVars);
376 mb_internal_encoding(_CHARSET);
377 @mb_send_mail($this->getEmail(), $title ,$message,'From: ' . $CONF['AdminEmail']);
379 ACTIONLOG::add(INFO, _ACTIONLOG_ACTIVATIONLINK . ' (' . $this->getDisplayName() . ' / type: ' . $type . ')');
385 * Returns an array of all blogids for which member has admin rights
387 function getAdminBlogs() {
390 if ($this->isAdmin())
391 $query = 'SELECT bnumber as blogid from '.sql_table('blog');
393 $query = 'SELECT tblog as blogid from '.sql_table('team').' where tadmin=1 and tmember=' . $this->getID();
395 $res = sql_query($query);
396 if (sql_num_rows($res) > 0) {
397 while ($obj = sql_fetch_object($res)) {
398 array_push($blogs, $obj->blogid);
406 * Returns an array of all blogids for which member has team rights
408 function getTeamBlogs($incAdmin = 1) {
409 $incAdmin = intval($incAdmin);
412 if ($this->isAdmin() && $incAdmin)
413 $query = 'SELECT bnumber as blogid from '.sql_table('blog');
415 $query = 'SELECT tblog as blogid from '.sql_table('team').' where tmember=' . $this->getID();
417 $res = sql_query($query);
418 if (sql_num_rows($res) > 0) {
419 while ($obj = sql_fetch_object($res)) {
420 array_push($blogs, $obj->blogid);
428 * Returns an email address from which notification of commenting/karma voting can
429 * be sent. A suggestion can be given for when the member is not logged in
431 function getNotifyFromMailAddress($suggest = "") {
433 if ($this->isLoggedIn()) {
434 return $this->getDisplayName() . " <" . $this->getEmail() . ">";
435 } else if (isValidMailAddress($suggest)) {
438 return $CONF['AdminEmail'];
443 * Write data to database
447 $query = 'UPDATE '.sql_table('member')
448 . " SET mname='" . addslashes($this->getDisplayName()) . "',"
449 . " mrealname='". addslashes($this->getRealName()) . "',"
450 . " mpassword='". addslashes($this->getPassword()) . "',"
451 . " mcookiekey='". addslashes($this->getCookieKey()) . "',"
452 . " murl='" . addslashes($this->getURL()) . "',"
453 . " memail='" . addslashes($this->getEmail()) . "',"
454 . " madmin=" . $this->isAdmin() . ","
455 . " mnotes='" . addslashes($this->getNotes()) . "',"
456 . " mcanlogin=" . $this->canLogin() . ","
457 . " deflang='" . addslashes($this->getLanguage()) . "',"
458 . " mautosave=" . intval($this->getAutosave()) . ""
459 . " WHERE mnumber=" . $this->getID();
463 function checkCookieKey($key) {
464 return (($key != '') && ($key == $this->getCookieKey()));
467 function checkPassword($pw) {
468 return (md5($pw) == $this->getPassword());
471 function getRealName() {
472 return $this->realname;
475 function setRealName($name) {
476 $this->realname = $name;
479 function getEmail() {
483 function setEmail($email) {
484 $this->email = $email;
487 function getPassword() {
488 return $this->password;
491 function setPassword($pwd) {
492 $this->password = md5($pwd);
495 function getCookieKey() {
496 return $this->cookiekey;
500 * Generate new cookiekey, save it, and return it
502 function newCookieKey() {
503 mt_srand( (double) microtime() * 1000000);
504 $this->cookiekey = md5(uniqid(mt_rand()));
506 return $this->cookiekey;
509 function setCookieKey($val) {
510 $this->cookiekey = $val;
517 function setURL($site) {
521 function getLanguage() {
522 return $this->language;
525 function setLanguage($lang) {
526 $this->language = $lang;
529 function setDisplayName($nick) {
530 $this->displayname = $nick;
533 function getDisplayName() {
534 return $this->displayname;
541 function setAdmin($val) {
545 function canLogin() {
546 return $this->canlogin;
549 function setCanLogin($val) {
550 $this->canlogin = $val;
553 function getNotes() {
557 function setNotes($val) {
561 function getAutosave() {
562 return $this->autosave;
565 function setAutosave($val) {
566 $this->autosave = $val;
574 * Returns true if there is a member with the given login name
578 function exists($name) {
579 $r = sql_query('select * FROM '.sql_table('member')." WHERE mname='".addslashes($name)."'");
580 return (sql_num_rows($r) != 0);
584 * Returns true if there is a member with the given ID
588 function existsID($id) {
589 $r = sql_query('select * FROM '.sql_table('member')." WHERE mnumber='".intval($id)."'");
590 return (sql_num_rows($r) != 0);
594 * Checks if a username is protected.
595 * If so, it can not be used on anonymous comments
597 function isNameProtected($name) {
600 $name = strip_tags($name);
603 return MEMBER::exists($name);
611 function create($name, $realname, $password, $email, $url, $admin, $canlogin, $notes) {
612 if (!isValidMailAddress($email))
613 return _ERROR_BADMAILADDRESS;
615 if (!isValidDisplayName($name))
616 return _ERROR_BADNAME;
618 if (MEMBER::exists($name))
619 return _ERROR_NICKNAMEINUSE;
622 return _ERROR_REALNAMEMISSING;
625 return _ERROR_PASSWORDMISSING;
627 // Sometimes user didn't prefix the URL with http://, this cause a malformed URL. Let's fix it.
628 if (!eregi("^https?://", $url))
629 $url = "http://".$url;
631 $name = addslashes($name);
632 $realname = addslashes($realname);
633 $password = addslashes(md5($password));
634 $email = addslashes($email);
635 $url = addslashes($url);
636 $admin = intval($admin);
637 $canlogin = intval($canlogin);
638 $notes = addslashes($notes);
640 if (($admin) && !($canlogin)) {return _ERROR;}
642 $query = 'INSERT INTO '.sql_table('member')." (MNAME,MREALNAME,MPASSWORD,MEMAIL,MURL, MADMIN, MCANLOGIN, MNOTES) "
643 . "VALUES ('$name','$realname','$password','$email','$url',$admin, $canlogin, '$notes')";
646 ACTIONLOG::add(INFO, _ACTIONLOG_NEWMEMBER . ' ' . $name);
652 * Returns activation info for a certain key (an object with properties vkey, vmember, ...)
657 function getActivationInfo($key)
659 $query = 'SELECT * FROM ' . sql_table('activation') . ' WHERE vkey=\'' . addslashes($key). '\'';
660 $res = sql_query($query);
662 if (!$res || (sql_num_rows($res) == 0))
665 return sql_fetch_object($res);
669 * Creates an account activation key
671 * @param $type one of the following values (determines what to do when activation expires)
672 * 'register' (new member registration)
673 * 'forgot' (forgotton password)
674 * 'addresschange' (member address has changed)
675 * @param $extra extra info (needed when validation link expires)
676 * addresschange -> old email address
679 function generateActivationEntry($type, $extra = '')
681 // clean up old entries
682 $this->cleanupActivationTable();
684 // kill any existing entries for the current member (delete is ok)
685 // (only one outstanding activation key can be present for a member)
686 sql_query('DELETE FROM ' . sql_table('activation') . ' WHERE vmember=' . intval($this->getID()));
688 $canLoginWhileActive = false; // indicates if the member can log in while the link is active
692 $canLoginWhileActive = true;
696 case 'addresschange':
697 $extra = $extra . '/' . ($this->canLogin() ? '1' : '0');
704 // generate a random key
705 srand((double)microtime()*1000000);
706 $key = md5(uniqid(rand(), true));
708 // attempt to add entry in database
709 // add in database as non-active
710 $query = 'INSERT INTO ' . sql_table('activation'). ' (vkey, vtime, vmember, vtype, vextra) ';
711 $query .= 'VALUES (\'' . addslashes($key). '\', \'' . date('Y-m-d H:i:s',time()) . '\', \'' . intval($this->getID()). '\', \'' . addslashes($type). '\', \'' . addslashes($extra). '\')';
712 if (sql_query($query))
716 // mark member as not allowed to log in
717 if (!$canLoginWhileActive)
719 $this->setCanLogin(0);
728 * Inidicates that an activation link has been clicked and any forms displayed
729 * there have been successfully filled out.
732 function activate($key)
735 $info = MEMBER::getActivationInfo($key);
741 switch ($info->vtype)
747 // set canlogin value
749 sql_query('UPDATE ' . sql_table('member') . ' SET mcanlogin=' . intval($CONF['NewMemberCanLogon']). ' WHERE mnumber=' . intval($info->vmember));
751 case 'addresschange':
752 // reset old 'canlogin' value
753 list($oldEmail, $oldCanLogin) = explode('/', $info->vextra);
754 sql_query('UPDATE ' . sql_table('member') . ' SET mcanlogin=' . intval($oldCanLogin). ' WHERE mnumber=' . intval($info->vmember));
758 // delete from activation table
759 sql_query('DELETE FROM ' . sql_table('activation') . ' WHERE vkey=\'' . addslashes($key) . '\'');
766 * Cleans up entries in the activation table. All entries older than 2 days are removed.
771 function cleanupActivationTable()
774 if (isset($CONF['ActivationDays']) && intval($CONF['ActivationDays']) > 0) {
775 $actdays = intval($CONF['ActivationDays']);
777 $boundary = time() - (60 * 60 * 24 * $actdays);
779 // 1. walk over all entries, and see if special actions need to be performed
780 $res = sql_query('SELECT * FROM ' . sql_table('activation') . ' WHERE vtime < \'' . date('Y-m-d H:i:s',$boundary) . '\'');
782 while ($o = sql_fetch_object($res))
787 // delete all information about this site member. registration is undone because there was
788 // no timely activation
789 include_once($DIR_LIBS . 'ADMIN.php');
790 ADMIN::deleteOneMember(intval($o->vmember));
792 case 'addresschange':
793 // revert the e-mail address of the member back to old address
794 list($oldEmail, $oldCanLogin) = explode('/', $o->vextra);
795 sql_query('UPDATE ' . sql_table('member') . ' SET mcanlogin=' . intval($oldCanLogin). ', memail=\'' . addslashes($oldEmail). '\' WHERE mnumber=' . intval($o->vmember));
798 // delete the activation link and ignore. member can request a new password using the
799 // forgot password link
804 // 2. delete activation entries for real
805 sql_query('DELETE FROM ' . sql_table('activation') . ' WHERE vtime < \'' . date('Y-m-d H:i:s',$boundary) . '\'');