]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
Merge branch '0.8.x' into 0.9.x
[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         $inboxes = common_config('inboxes', 'enabled');
231
232         if ($inboxes === true || $inboxes == 'transitional') {
233             $user->inboxed = 1;
234         }
235
236         $user->created = common_sql_now();
237         $user->uri = common_user_uri($user);
238
239         $result = $user->insert();
240
241         if (!$result) {
242             common_log_db_error($user, 'INSERT', __FILE__);
243             return false;
244         }
245
246         // Everyone is subscribed to themself
247
248         $subscription = new Subscription();
249         $subscription->subscriber = $user->id;
250         $subscription->subscribed = $user->id;
251         $subscription->created = $user->created;
252
253         $result = $subscription->insert();
254
255         if (!$result) {
256             common_log_db_error($subscription, 'INSERT', __FILE__);
257             return false;
258         }
259
260         if (!empty($email) && !$user->email) {
261
262             $confirm = new Confirm_address();
263             $confirm->code = common_confirmation_code(128);
264             $confirm->user_id = $user->id;
265             $confirm->address = $email;
266             $confirm->address_type = 'email';
267
268             $result = $confirm->insert();
269             if (!$result) {
270                 common_log_db_error($confirm, 'INSERT', __FILE__);
271                 return false;
272             }
273         }
274
275         if (!empty($code) && $user->email) {
276             $user->emailChanged();
277         }
278
279         // Default system subscription
280
281         $defnick = common_config('newuser', 'default');
282
283         if (!empty($defnick)) {
284             $defuser = User::staticGet('nickname', $defnick);
285             if (empty($defuser)) {
286                 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
287                            __FILE__);
288             } else {
289                 $defsub = new Subscription();
290                 $defsub->subscriber = $user->id;
291                 $defsub->subscribed = $defuser->id;
292                 $defsub->created = $user->created;
293
294                 $result = $defsub->insert();
295
296                 if (!$result) {
297                     common_log_db_error($defsub, 'INSERT', __FILE__);
298                     return false;
299                 }
300             }
301         }
302
303         $profile->query('COMMIT');
304
305         if ($email && !$user->email) {
306             mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
307         }
308
309         // Welcome message
310
311         $welcome = common_config('newuser', 'welcome');
312
313         if (!empty($welcome)) {
314             $welcomeuser = User::staticGet('nickname', $welcome);
315             if (empty($welcomeuser)) {
316                 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
317                            __FILE__);
318             } else {
319                 $notice = Notice::saveNew($welcomeuser->id,
320                                           sprintf(_('Welcome to %1$s, @%2$s!'),
321                                                   common_config('site', 'name'),
322                                                   $user->nickname),
323                                           'system');
324             }
325         }
326
327         return $user;
328     }
329
330     // Things we do when the email changes
331
332     function emailChanged()
333     {
334
335         $invites = new Invitation();
336         $invites->address = $this->email;
337         $invites->address_type = 'email';
338
339         if ($invites->find()) {
340             while ($invites->fetch()) {
341                 $other = User::staticGet($invites->user_id);
342                 subs_subscribe_to($other, $this);
343             }
344         }
345     }
346
347     function hasFave($notice)
348     {
349         $cache = common_memcache();
350
351         // XXX: Kind of a hack.
352
353         if ($cache) {
354             // This is the stream of favorite notices, in rev chron
355             // order. This forces it into cache.
356
357             $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
358
359             // If it's in the list, then it's a fave
360
361             if (in_array($notice->id, $ids)) {
362                 return true;
363             }
364
365             // If we're not past the end of the cache window,
366             // then the cache has all available faves, so this one
367             // is not a fave.
368
369             if (count($ids) < NOTICE_CACHE_WINDOW) {
370                 return false;
371             }
372
373             // Otherwise, cache doesn't have all faves;
374             // fall through to the default
375         }
376
377         $fave = Fave::pkeyGet(array('user_id' => $this->id,
378                                     'notice_id' => $notice->id));
379         return ((is_null($fave)) ? false : true);
380     }
381
382     function mutuallySubscribed($other)
383     {
384         return $this->isSubscribed($other) &&
385           $other->isSubscribed($this);
386     }
387
388     function mutuallySubscribedUsers()
389     {
390         // 3-way join; probably should get cached
391         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
392         $qry = "SELECT $UT.* " .
393           "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
394           "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
395           'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
396           "ORDER BY $UT.nickname";
397         $user = new User();
398         $user->query(sprintf($qry, $this->id, $this->id));
399
400         return $user;
401     }
402
403     function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
404     {
405         $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
406         return Notice::getStreamByIds($ids);
407     }
408
409     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
410         $profile = $this->getProfile();
411         if (!$profile) {
412             return null;
413         } else {
414             return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
415         }
416     }
417
418     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
419     {
420         $profile = $this->getProfile();
421         if (!$profile) {
422             return null;
423         } else {
424             return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
425         }
426     }
427
428     function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
429     {
430         $ids = Fave::stream($this->id, $offset, $limit, $own);
431         return Notice::getStreamByIds($ids);
432     }
433
434     function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
435     {
436         $enabled = common_config('inboxes', 'enabled');
437
438         // Complicated code, depending on whether we support inboxes yet
439         // XXX: make this go away when inboxes become mandatory
440
441         if ($enabled === false ||
442             ($enabled == 'transitional' && $this->inboxed == 0)) {
443             $qry =
444               'SELECT notice.* ' .
445               'FROM notice JOIN subscription ON notice.profile_id = subscription.subscribed ' .
446               'WHERE subscription.subscriber = %d ' .
447               'AND notice.is_local != ' . Notice::GATEWAY;
448             return Notice::getStream(sprintf($qry, $this->id),
449                                      'user:notices_with_friends:' . $this->id,
450                                      $offset, $limit, $since_id, $before_id,
451                                      $order, $since);
452         } else if ($enabled === true ||
453                    ($enabled == 'transitional' && $this->inboxed == 1)) {
454
455             $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
456
457             return Notice::getStreamByIds($ids);
458         }
459     }
460
461     function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
462     {
463         $enabled = common_config('inboxes', 'enabled');
464
465         // Complicated code, depending on whether we support inboxes yet
466         // XXX: make this go away when inboxes become mandatory
467
468         if ($enabled === false ||
469             ($enabled == 'transitional' && $this->inboxed == 0)) {
470             $qry =
471               'SELECT notice.* ' .
472               'FROM notice JOIN subscription ON notice.profile_id = subscription.subscribed ' .
473               'WHERE subscription.subscriber = %d ';
474             return Notice::getStream(sprintf($qry, $this->id),
475                                      'user:notices_with_friends:' . $this->id,
476                                      $offset, $limit, $since_id, $before_id,
477                                      $order, $since);
478         } else if ($enabled === true ||
479                    ($enabled == 'transitional' && $this->inboxed == 1)) {
480
481             $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
482
483             return Notice::getStreamByIds($ids);
484         }
485     }
486
487     function blowFavesCache()
488     {
489         $cache = common_memcache();
490         if ($cache) {
491             // Faves don't happen chronologically, so we need to blow
492             // ;last cache, too
493             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
494             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
495             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
496             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
497         }
498         $profile = $this->getProfile();
499         $profile->blowFaveCount();
500     }
501
502     function getSelfTags()
503     {
504         return Profile_tag::getTags($this->id, $this->id);
505     }
506
507     function setSelfTags($newtags)
508     {
509         return Profile_tag::setTags($this->id, $this->id, $newtags);
510     }
511
512     function block($other)
513     {
514         // Add a new block record
515
516         $block = new Profile_block();
517
518         // Begin a transaction
519
520         $block->query('BEGIN');
521
522         $block->blocker = $this->id;
523         $block->blocked = $other->id;
524
525         $result = $block->insert();
526
527         if (!$result) {
528             common_log_db_error($block, 'INSERT', __FILE__);
529             return false;
530         }
531
532         // Cancel their subscription, if it exists
533
534         $sub = Subscription::pkeyGet(array('subscriber' => $other->id,
535                                            'subscribed' => $this->id));
536
537         if ($sub) {
538             $result = $sub->delete();
539             if (!$result) {
540                 common_log_db_error($sub, 'DELETE', __FILE__);
541                 return false;
542             }
543         }
544
545         $block->query('COMMIT');
546
547         return true;
548     }
549
550     function unblock($other)
551     {
552         // Get the block record
553
554         $block = Profile_block::get($this->id, $other->id);
555
556         if (!$block) {
557             return false;
558         }
559
560         $result = $block->delete();
561
562         if (!$result) {
563             common_log_db_error($block, 'DELETE', __FILE__);
564             return false;
565         }
566
567         return true;
568     }
569
570     function isMember($group)
571     {
572         $profile = $this->getProfile();
573         return $profile->isMember($group);
574     }
575
576     function isAdmin($group)
577     {
578         $profile = $this->getProfile();
579         return $profile->isAdmin($group);
580     }
581
582     function getGroups($offset=0, $limit=null)
583     {
584         $qry =
585           'SELECT user_group.* ' .
586           'FROM user_group JOIN group_member '.
587           'ON user_group.id = group_member.group_id ' .
588           'WHERE group_member.profile_id = %d ' .
589           'ORDER BY group_member.created DESC ';
590
591         if ($offset) {
592             if (common_config('db','type') == 'pgsql') {
593                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
594             } else {
595                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
596             }
597         }
598
599         $groups = new User_group();
600
601         $cnt = $groups->query(sprintf($qry, $this->id));
602
603         return $groups;
604     }
605
606     function getSubscriptions($offset=0, $limit=null)
607     {
608         $profile = $this->getProfile();
609         assert(!empty($profile));
610         return $profile->getSubscriptions($offset, $limit);
611     }
612
613     function getSubscribers($offset=0, $limit=null)
614     {
615         $profile = $this->getProfile();
616         assert(!empty($profile));
617         return $profile->getSubscribers($offset, $limit);
618     }
619
620     function getTaggedSubscribers($tag, $offset=0, $limit=null)
621     {
622         $qry =
623           'SELECT profile.* ' .
624           'FROM profile JOIN subscription ' .
625           'ON profile.id = subscription.subscriber ' .
626           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
627           'AND profile_tag.tagger = subscription.subscribed) ' .
628           'WHERE subscription.subscribed = %d ' .
629           "AND profile_tag.tag = '%s' " .
630           'AND subscription.subscribed != subscription.subscriber ' .
631           'ORDER BY subscription.created DESC ';
632
633         if ($offset) {
634             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
635         }
636
637         $profile = new Profile();
638
639         $cnt = $profile->query(sprintf($qry, $this->id, $tag));
640
641         return $profile;
642     }
643
644     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
645     {
646         $qry =
647           'SELECT profile.* ' .
648           'FROM profile JOIN subscription ' .
649           'ON profile.id = subscription.subscribed ' .
650           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
651           'AND profile_tag.tagger = subscription.subscriber) ' .
652           'WHERE subscription.subscriber = %d ' .
653           "AND profile_tag.tag = '%s' " .
654           'AND subscription.subscribed != subscription.subscriber ' .
655           'ORDER BY subscription.created DESC ';
656
657         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
658
659         $profile = new Profile();
660
661         $profile->query(sprintf($qry, $this->id, $tag));
662
663         return $profile;
664     }
665
666     function getDesign()
667     {
668         return Design::staticGet('id', $this->design_id);
669     }
670
671     function hasRole($name)
672     {
673         $role = User_role::pkeyGet(array('user_id' => $this->id,
674                                          'role' => $name));
675         return (!empty($role));
676     }
677
678     function grantRole($name)
679     {
680         $role = new User_role();
681
682         $role->user_id = $this->id;
683         $role->role    = $name;
684         $role->created = common_sql_now();
685
686         $result = $role->insert();
687
688         if (!$result) {
689             common_log_db_error($role, 'INSERT', __FILE__);
690             return false;
691         }
692
693         return true;
694     }
695
696     function revokeRole($name)
697     {
698         $role = User_role::pkeyGet(array('user_id' => $this->id,
699                                          'role' => $name));
700
701         if (empty($role)) {
702             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; does not exist.');
703         }
704
705         $result = $role->delete();
706
707         if (!$result) {
708             common_log_db_error($role, 'DELETE', __FILE__);
709             throw new Exception('Cannot revoke role "'.$name.'" for user #'.$this->id.'; database error.');
710         }
711
712         return true;
713     }
714
715     /**
716      * Does this user have the right to do X?
717      *
718      * With our role-based authorization, this is merely a lookup for whether the user
719      * has a particular role. The implementation currently uses a switch statement
720      * to determine if the user has the pre-defined role to exercise the right. Future
721      * implementations may allow per-site roles, and different mappings of roles to rights.
722      *
723      * @param $right string Name of the right, usually a constant in class Right
724      * @return boolean whether the user has the right in question
725      */
726
727     function hasRight($right)
728     {
729         $result = false;
730         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
731             switch ($right)
732             {
733              case Right::deleteOthersNotice:
734                 $result = $this->hasRole('moderator');
735                 break;
736              default:
737                 $result = false;
738                 break;
739             }
740         }
741         return $result;
742     }
743
744     function delete()
745     {
746         $profile = $this->getProfile();
747         $profile->delete();
748
749         $related = array('Fave',
750                          'User_openid',
751                          'Confirm_address',
752                          'Remember_me',
753                          'Foreign_link',
754                          'Invitation',
755                          );
756
757         if (common_config('inboxes', 'enabled')) {
758             $related[] = 'Notice_inbox';
759         }
760
761         foreach ($related as $cls) {
762             $inst = new $cls();
763             $inst->user_id = $this->id;
764             $inst->delete();
765         }
766
767         $this->_deleteTags();
768         $this->_deleteBlocks();
769
770         parent::delete();
771     }
772
773     function _deleteTags()
774     {
775         $tag = new Profile_tag();
776         $tag->tagger = $this->id;
777         $tag->delete();
778     }
779
780     function _deleteBlocks()
781     {
782         $block = new Profile_block();
783         $block->blocker = $this->id;
784         $block->delete();
785         // XXX delete group block? Reset blocker?
786     }
787 }