]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
0a70c9801402f8038d1dc59bb72bf0204ce1f3c7
[quix0rs-gnu-social.git] / classes / User.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) {
21     exit(1);
22 }
23
24 /**
25  * Table Definition for user
26  */
27
28 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
29 require_once 'Validate.php';
30
31 class User extends Memcached_DataObject
32 {
33     ###START_AUTOCODE
34     /* the code below is auto generated do not remove the above tag */
35
36     public $__table = 'user';                            // table name
37     public $id;                              // int(4)  primary_key not_null
38     public $nickname;                        // varchar(64)  unique_key
39     public $password;                        // varchar(255)
40     public $email;                           // varchar(255)  unique_key
41     public $incomingemail;                   // varchar(255)  unique_key
42     public $emailnotifysub;                  // tinyint(1)   default_1
43     public $emailnotifyfav;                  // tinyint(1)   default_1
44     public $emailnotifynudge;                // tinyint(1)   default_1
45     public $emailnotifymsg;                  // tinyint(1)   default_1
46     public $emailnotifyattn;                 // tinyint(1)   default_1
47     public $emailmicroid;                    // tinyint(1)   default_1
48     public $language;                        // varchar(50)
49     public $timezone;                        // varchar(50)
50     public $emailpost;                       // tinyint(1)   default_1
51     public $jabber;                          // varchar(255)  unique_key
52     public $jabbernotify;                    // tinyint(1)
53     public $jabberreplies;                   // tinyint(1)
54     public $jabbermicroid;                   // tinyint(1)   default_1
55     public $updatefrompresence;              // tinyint(1)
56     public $sms;                             // varchar(64)  unique_key
57     public $carrier;                         // int(4)
58     public $smsnotify;                       // tinyint(1)
59     public $smsreplies;                      // tinyint(1)
60     public $smsemail;                        // varchar(255)
61     public $uri;                             // varchar(255)  unique_key
62     public $autosubscribe;                   // tinyint(1)
63     public $urlshorteningservice;            // varchar(50)   default_ur1.ca
64     public $inboxed;                         // tinyint(1)
65     public $design_id;                       // int(4)
66     public $viewdesigns;                     // tinyint(1)   default_1
67     public $created;                         // datetime()   not_null
68     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
69
70     /* Static get */
71     function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('User',$k,$v); }
72
73     /* the code above is auto generated do not remove the tag below */
74     ###END_AUTOCODE
75
76     function getProfile()
77     {
78         return Profile::staticGet('id', $this->id);
79     }
80
81     function isSubscribed($other)
82     {
83         assert(!is_null($other));
84         // XXX: cache results of this query
85         $sub = Subscription::pkeyGet(array('subscriber' => $this->id,
86                                            'subscribed' => $other->id));
87         return (is_null($sub)) ? false : true;
88     }
89
90     // 'update' won't write key columns, so we have to do it ourselves.
91
92     function updateKeys(&$orig)
93     {
94         $parts = array();
95         foreach (array('nickname', 'email', 'jabber', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
96             if (strcmp($this->$k, $orig->$k) != 0) {
97                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
98             }
99         }
100         if (count($parts) == 0) {
101             // No changes
102             return true;
103         }
104         $toupdate = implode(', ', $parts);
105
106         $table = common_database_tablename($this->tableName());
107         $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
108           ' WHERE id = ' . $this->id;
109         $orig->decache();
110         $result = $this->query($qry);
111         if ($result) {
112             $this->encache();
113         }
114         return $result;
115     }
116
117     function allowed_nickname($nickname)
118     {
119         // XXX: should already be validated for size, content, etc.
120
121         $blacklist = array();
122
123         //all directory and file names should be blacklisted
124         $d = dir(INSTALLDIR);
125         while (false !== ($entry = $d->read())) {
126             $blacklist[]=$entry;
127         }
128         $d->close();
129         $merged = array_merge($blacklist, common_config('nickname', 'blacklist'));
130         return !in_array($nickname, $merged);
131     }
132
133     function getCurrentNotice($dt=null)
134     {
135         $profile = $this->getProfile();
136         if (!$profile) {
137             return null;
138         }
139         return $profile->getCurrentNotice($dt);
140     }
141
142     function getCarrier()
143     {
144         return Sms_carrier::staticGet('id', $this->carrier);
145     }
146
147     function subscribeTo($other)
148     {
149         $sub = new Subscription();
150         $sub->subscriber = $this->id;
151         $sub->subscribed = $other->id;
152
153         $sub->created = common_sql_now(); // current time
154
155         if (!$sub->insert()) {
156             return false;
157         }
158
159         return true;
160     }
161
162     function hasBlocked($other)
163     {
164
165         $block = Profile_block::get($this->id, $other->id);
166
167         if (is_null($block)) {
168             $result = false;
169         } else {
170             $result = true;
171             $block->free();
172         }
173
174         return $result;
175     }
176
177     static function register($fields) {
178
179         // MAGICALLY put fields into current scope
180
181         extract($fields);
182
183         $profile = new Profile();
184
185         $profile->query('BEGIN');
186
187         $profile->nickname = $nickname;
188         $profile->profileurl = common_profile_url($nickname);
189
190         if (!empty($fullname)) {
191             $profile->fullname = $fullname;
192         }
193         if (!empty($homepage)) {
194             $profile->homepage = $homepage;
195         }
196         if (!empty($bio)) {
197             $profile->bio = $bio;
198         }
199         if (!empty($location)) {
200             $profile->location = $location;
201         }
202
203         $profile->created = common_sql_now();
204
205         $id = $profile->insert();
206
207         if (empty($id)) {
208             common_log_db_error($profile, 'INSERT', __FILE__);
209             return false;
210         }
211
212         $user = new User();
213
214         $user->id = $id;
215         $user->nickname = $nickname;
216
217         if (!empty($password)) { // may not have a password for OpenID users
218             $user->password = common_munge_password($password, $id);
219         }
220
221         // Users who respond to invite email have proven their ownership of that address
222
223         if (!empty($code)) {
224             $invite = Invitation::staticGet($code);
225             if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
226                 $user->email = $invite->address;
227             }
228         }
229
230         // This flag is ignored but still set to 1
231
232         $user->inboxed = 1;
233
234         $user->created = common_sql_now();
235         $user->uri = common_user_uri($user);
236
237         $result = $user->insert();
238
239         if (!$result) {
240             common_log_db_error($user, 'INSERT', __FILE__);
241             return false;
242         }
243
244         // Everyone is subscribed to themself
245
246         $subscription = new Subscription();
247         $subscription->subscriber = $user->id;
248         $subscription->subscribed = $user->id;
249         $subscription->created = $user->created;
250
251         $result = $subscription->insert();
252
253         if (!$result) {
254             common_log_db_error($subscription, 'INSERT', __FILE__);
255             return false;
256         }
257
258         if (!empty($email) && !$user->email) {
259
260             $confirm = new Confirm_address();
261             $confirm->code = common_confirmation_code(128);
262             $confirm->user_id = $user->id;
263             $confirm->address = $email;
264             $confirm->address_type = 'email';
265
266             $result = $confirm->insert();
267             if (!$result) {
268                 common_log_db_error($confirm, 'INSERT', __FILE__);
269                 return false;
270             }
271         }
272
273         if (!empty($code) && $user->email) {
274             $user->emailChanged();
275         }
276
277         // Default system subscription
278
279         $defnick = common_config('newuser', 'default');
280
281         if (!empty($defnick)) {
282             $defuser = User::staticGet('nickname', $defnick);
283             if (empty($defuser)) {
284                 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
285                            __FILE__);
286             } else {
287                 $defsub = new Subscription();
288                 $defsub->subscriber = $user->id;
289                 $defsub->subscribed = $defuser->id;
290                 $defsub->created = $user->created;
291
292                 $result = $defsub->insert();
293
294                 if (!$result) {
295                     common_log_db_error($defsub, 'INSERT', __FILE__);
296                     return false;
297                 }
298             }
299         }
300
301         $profile->query('COMMIT');
302
303         if ($email && !$user->email) {
304             mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
305         }
306
307         // Welcome message
308
309         $welcome = common_config('newuser', 'welcome');
310
311         if (!empty($welcome)) {
312             $welcomeuser = User::staticGet('nickname', $welcome);
313             if (empty($welcomeuser)) {
314                 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
315                            __FILE__);
316             } else {
317                 $notice = Notice::saveNew($welcomeuser->id,
318                                           sprintf(_('Welcome to %1$s, @%2$s!'),
319                                                   common_config('site', 'name'),
320                                                   $user->nickname),
321                                           'system');
322             }
323         }
324
325         return $user;
326     }
327
328     // Things we do when the email changes
329
330     function emailChanged()
331     {
332
333         $invites = new Invitation();
334         $invites->address = $this->email;
335         $invites->address_type = 'email';
336
337         if ($invites->find()) {
338             while ($invites->fetch()) {
339                 $other = User::staticGet($invites->user_id);
340                 subs_subscribe_to($other, $this);
341             }
342         }
343     }
344
345     function hasFave($notice)
346     {
347         $cache = common_memcache();
348
349         // XXX: Kind of a hack.
350
351         if ($cache) {
352             // This is the stream of favorite notices, in rev chron
353             // order. This forces it into cache.
354
355             $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
356
357             // If it's in the list, then it's a fave
358
359             if (in_array($notice->id, $ids)) {
360                 return true;
361             }
362
363             // If we're not past the end of the cache window,
364             // then the cache has all available faves, so this one
365             // is not a fave.
366
367             if (count($ids) < NOTICE_CACHE_WINDOW) {
368                 return false;
369             }
370
371             // Otherwise, cache doesn't have all faves;
372             // fall through to the default
373         }
374
375         $fave = Fave::pkeyGet(array('user_id' => $this->id,
376                                     'notice_id' => $notice->id));
377         return ((is_null($fave)) ? false : true);
378     }
379
380     function mutuallySubscribed($other)
381     {
382         return $this->isSubscribed($other) &&
383           $other->isSubscribed($this);
384     }
385
386     function mutuallySubscribedUsers()
387     {
388         // 3-way join; probably should get cached
389         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
390         $qry = "SELECT $UT.* " .
391           "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
392           "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
393           'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
394           "ORDER BY $UT.nickname";
395         $user = new User();
396         $user->query(sprintf($qry, $this->id, $this->id));
397
398         return $user;
399     }
400
401     function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
402     {
403         $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
404         return Notice::getStreamByIds($ids);
405     }
406
407     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
408         $profile = $this->getProfile();
409         if (!$profile) {
410             return null;
411         } else {
412             return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
413         }
414     }
415
416     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
417     {
418         $profile = $this->getProfile();
419         if (!$profile) {
420             return null;
421         } else {
422             return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
423         }
424     }
425
426     function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
427     {
428         $ids = Fave::stream($this->id, $offset, $limit, $own);
429         return Notice::getStreamByIds($ids);
430     }
431
432     function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
433     {
434         $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
435
436         return Notice::getStreamByIds($ids);
437     }
438
439     function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
440     {
441         $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
442
443         return Notice::getStreamByIds($ids);
444     }
445
446     function blowFavesCache()
447     {
448         $cache = common_memcache();
449         if ($cache) {
450             // Faves don't happen chronologically, so we need to blow
451             // ;last cache, too
452             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
453             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
454             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
455             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
456         }
457         $profile = $this->getProfile();
458         $profile->blowFaveCount();
459     }
460
461     function getSelfTags()
462     {
463         return Profile_tag::getTags($this->id, $this->id);
464     }
465
466     function setSelfTags($newtags)
467     {
468         return Profile_tag::setTags($this->id, $this->id, $newtags);
469     }
470
471     function block($other)
472     {
473         // Add a new block record
474
475         $block = new Profile_block();
476
477         // Begin a transaction
478
479         $block->query('BEGIN');
480
481         $block->blocker = $this->id;
482         $block->blocked = $other->id;
483
484         $result = $block->insert();
485
486         if (!$result) {
487             common_log_db_error($block, 'INSERT', __FILE__);
488             return false;
489         }
490
491         // Cancel their subscription, if it exists
492
493         $sub = Subscription::pkeyGet(array('subscriber' => $other->id,
494                                            'subscribed' => $this->id));
495
496         if ($sub) {
497             $result = $sub->delete();
498             if (!$result) {
499                 common_log_db_error($sub, 'DELETE', __FILE__);
500                 return false;
501             }
502         }
503
504         $block->query('COMMIT');
505
506         return true;
507     }
508
509     function unblock($other)
510     {
511         // Get the block record
512
513         $block = Profile_block::get($this->id, $other->id);
514
515         if (!$block) {
516             return false;
517         }
518
519         $result = $block->delete();
520
521         if (!$result) {
522             common_log_db_error($block, 'DELETE', __FILE__);
523             return false;
524         }
525
526         return true;
527     }
528
529     function isMember($group)
530     {
531         $profile = $this->getProfile();
532         return $profile->isMember($group);
533     }
534
535     function isAdmin($group)
536     {
537         $profile = $this->getProfile();
538         return $profile->isAdmin($group);
539     }
540
541     function getGroups($offset=0, $limit=null)
542     {
543         $qry =
544           'SELECT user_group.* ' .
545           'FROM user_group JOIN group_member '.
546           'ON user_group.id = group_member.group_id ' .
547           'WHERE group_member.profile_id = %d ' .
548           'ORDER BY group_member.created DESC ';
549
550         if ($offset) {
551             if (common_config('db','type') == 'pgsql') {
552                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
553             } else {
554                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
555             }
556         }
557
558         $groups = new User_group();
559
560         $cnt = $groups->query(sprintf($qry, $this->id));
561
562         return $groups;
563     }
564
565     function getSubscriptions($offset=0, $limit=null)
566     {
567         $profile = $this->getProfile();
568         assert(!empty($profile));
569         return $profile->getSubscriptions($offset, $limit);
570     }
571
572     function getSubscribers($offset=0, $limit=null)
573     {
574         $profile = $this->getProfile();
575         assert(!empty($profile));
576         return $profile->getSubscribers($offset, $limit);
577     }
578
579     function getTaggedSubscribers($tag, $offset=0, $limit=null)
580     {
581         $qry =
582           'SELECT profile.* ' .
583           'FROM profile JOIN subscription ' .
584           'ON profile.id = subscription.subscriber ' .
585           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
586           'AND profile_tag.tagger = subscription.subscribed) ' .
587           'WHERE subscription.subscribed = %d ' .
588           "AND profile_tag.tag = '%s' " .
589           'AND subscription.subscribed != subscription.subscriber ' .
590           'ORDER BY subscription.created DESC ';
591
592         if ($offset) {
593             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
594         }
595
596         $profile = new Profile();
597
598         $cnt = $profile->query(sprintf($qry, $this->id, $tag));
599
600         return $profile;
601     }
602
603     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
604     {
605         $qry =
606           'SELECT profile.* ' .
607           'FROM profile JOIN subscription ' .
608           'ON profile.id = subscription.subscribed ' .
609           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
610           'AND profile_tag.tagger = subscription.subscriber) ' .
611           'WHERE subscription.subscriber = %d ' .
612           "AND profile_tag.tag = '%s' " .
613           'AND subscription.subscribed != subscription.subscriber ' .
614           'ORDER BY subscription.created DESC ';
615
616         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
617
618         $profile = new Profile();
619
620         $profile->query(sprintf($qry, $this->id, $tag));
621
622         return $profile;
623     }
624
625     function getDesign()
626     {
627         return Design::staticGet('id', $this->design_id);
628     }
629
630     function hasRole($name)
631     {
632         $role = User_role::pkeyGet(array('user_id' => $this->id,
633                                          'role' => $name));
634         return (!empty($role));
635     }
636
637     function grantRole($name)
638     {
639         $role = new User_role();
640
641         $role->user_id = $this->id;
642         $role->role    = $name;
643         $role->created = common_sql_now();
644
645         $result = $role->insert();
646
647         if (!$result) {
648             common_log_db_error($role, 'INSERT', __FILE__);
649             return false;
650         }
651
652         return true;
653     }
654
655     function revokeRole($name)
656     {
657         $role = User_role::pkeyGet(array('user_id' => $this->id,
658                                          'role' => $name));
659
660         if (empty($role)) {
661             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
662         }
663
664         $result = $role->delete();
665
666         if (!$result) {
667             common_log_db_error($role, 'DELETE', __FILE__);
668             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
669         }
670
671         return true;
672     }
673
674     /**
675      * Does this user have the right to do X?
676      *
677      * With our role-based authorization, this is merely a lookup for whether the user
678      * has a particular role. The implementation currently uses a switch statement
679      * to determine if the user has the pre-defined role to exercise the right. Future
680      * implementations may allow per-site roles, and different mappings of roles to rights.
681      *
682      * @param $right string Name of the right, usually a constant in class Right
683      * @return boolean whether the user has the right in question
684      */
685
686     function hasRight($right)
687     {
688         $result = false;
689         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
690             switch ($right)
691             {
692              case Right::deleteOthersNotice:
693                 $result = $this->hasRole('moderator');
694                 break;
695              default:
696                 $result = false;
697                 break;
698             }
699         }
700         return $result;
701     }
702
703     function delete()
704     {
705         $profile = $this->getProfile();
706         $profile->delete();
707
708         $related = array('Fave',
709                          'User_openid',
710                          'Confirm_address',
711                          'Remember_me',
712                          'Foreign_link',
713                          'Invitation',
714                          'Notice_inbox',
715                          );
716
717         foreach ($related as $cls) {
718             $inst = new $cls();
719             $inst->user_id = $this->id;
720             $inst->delete();
721         }
722
723         $this->_deleteTags();
724         $this->_deleteBlocks();
725
726         parent::delete();
727     }
728
729     function _deleteTags()
730     {
731         $tag = new Profile_tag();
732         $tag->tagger = $this->id;
733         $tag->delete();
734     }
735
736     function _deleteBlocks()
737     {
738         $block = new Profile_block();
739         $block->blocker = $this->id;
740         $block->delete();
741         // XXX delete group block? Reset blocker?
742     }
743 }