]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
Merge commit 'origin/0.9.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     static function allowed_nickname($nickname)
118     {
119         // XXX: should already be validated for size, content, etc.
120         $blacklist = common_config('nickname', 'blacklist');
121
122         //all directory and file names should be blacklisted
123         $d = dir(INSTALLDIR);
124         while (false !== ($entry = $d->read())) {
125             $blacklist[]=$entry;
126         }
127         $d->close();
128
129         //all top level names in the router should be blacklisted
130         $router = Router::get();
131         foreach(array_keys($router->m->getPaths()) as $path){
132             if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
133                 $blacklist[]=$matches[1];
134             }
135         }
136         return !in_array($nickname, $blacklist);
137     }
138
139     function getCurrentNotice($dt=null)
140     {
141         $profile = $this->getProfile();
142         if (!$profile) {
143             return null;
144         }
145         return $profile->getCurrentNotice($dt);
146     }
147
148     function getCarrier()
149     {
150         return Sms_carrier::staticGet('id', $this->carrier);
151     }
152
153     function subscribeTo($other)
154     {
155         $sub = new Subscription();
156         $sub->subscriber = $this->id;
157         $sub->subscribed = $other->id;
158
159         $sub->created = common_sql_now(); // current time
160
161         if (!$sub->insert()) {
162             return false;
163         }
164
165         return true;
166     }
167
168     function hasBlocked($other)
169     {
170
171         $block = Profile_block::get($this->id, $other->id);
172
173         if (is_null($block)) {
174             $result = false;
175         } else {
176             $result = true;
177             $block->free();
178         }
179
180         return $result;
181     }
182
183     /**
184      * Register a new user account and profile and set up default subscriptions.
185      * If a new-user welcome message is configured, this will be sent.
186      *
187      * @param array $fields associative array of optional properties
188      *              string 'bio'
189      *              string 'email'
190      *              bool 'email_confirmed' pass true to mark email as pre-confirmed
191      *              string 'fullname'
192      *              string 'homepage'
193      *              string 'location' informal string description of geolocation
194      *              float 'lat' decimal latitude for geolocation
195      *              float 'lon' decimal longitude for geolocation
196      *              int 'location_id' geoname identifier
197      *              int 'location_ns' geoname namespace to interpret location_id
198      *              string 'nickname' REQUIRED
199      *              string 'password' (may be missing for eg OpenID registrations)
200      *              string 'code' invite code
201      *              ?string 'uri' permalink to notice; defaults to local notice URL
202      * @return mixed User object or false on failure
203      */
204     static function register($fields) {
205
206         // MAGICALLY put fields into current scope
207
208         extract($fields);
209
210         $profile = new Profile();
211
212         $profile->query('BEGIN');
213
214         if(!empty($email))
215         {
216             $email = common_canonical_email($email);
217         }
218
219         $nickname = common_canonical_nickname($nickname);
220         $profile->nickname = $nickname;
221         if(! User::allowed_nickname($nickname)){
222             common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
223                            __FILE__);
224         }
225         $profile->profileurl = common_profile_url($nickname);
226
227         if (!empty($fullname)) {
228             $profile->fullname = $fullname;
229         }
230         if (!empty($homepage)) {
231             $profile->homepage = $homepage;
232         }
233         if (!empty($bio)) {
234             $profile->bio = $bio;
235         }
236         if (!empty($location)) {
237             $profile->location = $location;
238
239             $loc = Location::fromName($location);
240
241             if (!empty($loc)) {
242                 $profile->lat         = $loc->lat;
243                 $profile->lon         = $loc->lon;
244                 $profile->location_id = $loc->location_id;
245                 $profile->location_ns = $loc->location_ns;
246             }
247         }
248
249         $profile->created = common_sql_now();
250
251         $id = $profile->insert();
252
253         if (empty($id)) {
254             common_log_db_error($profile, 'INSERT', __FILE__);
255             return false;
256         }
257
258         $user = new User();
259
260         $user->id = $id;
261         $user->nickname = $nickname;
262
263         if (!empty($password)) { // may not have a password for OpenID users
264             $user->password = common_munge_password($password, $id);
265         }
266
267         // Users who respond to invite email have proven their ownership of that address
268
269         if (!empty($code)) {
270             $invite = Invitation::staticGet($code);
271             if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
272                 $user->email = $invite->address;
273             }
274         }
275
276         if(isset($email_confirmed) && $email_confirmed) {
277             $user->email = $email;
278         }
279
280         // This flag is ignored but still set to 1
281
282         $user->inboxed = 1;
283
284         $user->created = common_sql_now();
285         $user->uri = common_user_uri($user);
286
287         $result = $user->insert();
288
289         if (!$result) {
290             common_log_db_error($user, 'INSERT', __FILE__);
291             return false;
292         }
293
294         // Everyone is subscribed to themself
295
296         $subscription = new Subscription();
297         $subscription->subscriber = $user->id;
298         $subscription->subscribed = $user->id;
299         $subscription->created = $user->created;
300
301         $result = $subscription->insert();
302
303         if (!$result) {
304             common_log_db_error($subscription, 'INSERT', __FILE__);
305             return false;
306         }
307
308         if (!empty($email) && !$user->email) {
309
310             $confirm = new Confirm_address();
311             $confirm->code = common_confirmation_code(128);
312             $confirm->user_id = $user->id;
313             $confirm->address = $email;
314             $confirm->address_type = 'email';
315
316             $result = $confirm->insert();
317             if (!$result) {
318                 common_log_db_error($confirm, 'INSERT', __FILE__);
319                 return false;
320             }
321         }
322
323         if (!empty($code) && $user->email) {
324             $user->emailChanged();
325         }
326
327         // Default system subscription
328
329         $defnick = common_config('newuser', 'default');
330
331         if (!empty($defnick)) {
332             $defuser = User::staticGet('nickname', $defnick);
333             if (empty($defuser)) {
334                 common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
335                            __FILE__);
336             } else {
337                 $defsub = new Subscription();
338                 $defsub->subscriber = $user->id;
339                 $defsub->subscribed = $defuser->id;
340                 $defsub->created = $user->created;
341
342                 $result = $defsub->insert();
343
344                 if (!$result) {
345                     common_log_db_error($defsub, 'INSERT', __FILE__);
346                     return false;
347                 }
348             }
349         }
350
351         $profile->query('COMMIT');
352
353         if (!empty($email) && !$user->email) {
354             mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
355         }
356
357         // Welcome message
358
359         $welcome = common_config('newuser', 'welcome');
360
361         if (!empty($welcome)) {
362             $welcomeuser = User::staticGet('nickname', $welcome);
363             if (empty($welcomeuser)) {
364                 common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
365                            __FILE__);
366             } else {
367                 $notice = Notice::saveNew($welcomeuser->id,
368                                           sprintf(_('Welcome to %1$s, @%2$s!'),
369                                                   common_config('site', 'name'),
370                                                   $user->nickname),
371                                           'system');
372                 common_broadcast_notice($notice);
373             }
374         }
375
376         return $user;
377     }
378
379     // Things we do when the email changes
380
381     function emailChanged()
382     {
383
384         $invites = new Invitation();
385         $invites->address = $this->email;
386         $invites->address_type = 'email';
387
388         if ($invites->find()) {
389             while ($invites->fetch()) {
390                 $other = User::staticGet($invites->user_id);
391                 subs_subscribe_to($other, $this);
392             }
393         }
394     }
395
396     function hasFave($notice)
397     {
398         $cache = common_memcache();
399
400         // XXX: Kind of a hack.
401
402         if ($cache) {
403             // This is the stream of favorite notices, in rev chron
404             // order. This forces it into cache.
405
406             $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
407
408             // If it's in the list, then it's a fave
409
410             if (in_array($notice->id, $ids)) {
411                 return true;
412             }
413
414             // If we're not past the end of the cache window,
415             // then the cache has all available faves, so this one
416             // is not a fave.
417
418             if (count($ids) < NOTICE_CACHE_WINDOW) {
419                 return false;
420             }
421
422             // Otherwise, cache doesn't have all faves;
423             // fall through to the default
424         }
425
426         $fave = Fave::pkeyGet(array('user_id' => $this->id,
427                                     'notice_id' => $notice->id));
428         return ((is_null($fave)) ? false : true);
429     }
430
431     function mutuallySubscribed($other)
432     {
433         return $this->isSubscribed($other) &&
434           $other->isSubscribed($this);
435     }
436
437     function mutuallySubscribedUsers()
438     {
439         // 3-way join; probably should get cached
440         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
441         $qry = "SELECT $UT.* " .
442           "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
443           "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
444           'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
445           "ORDER BY $UT.nickname";
446         $user = new User();
447         $user->query(sprintf($qry, $this->id, $this->id));
448
449         return $user;
450     }
451
452     function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
453     {
454         $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id, $since);
455         return Notice::getStreamByIds($ids);
456     }
457
458     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null) {
459         $profile = $this->getProfile();
460         if (!$profile) {
461             return null;
462         } else {
463             return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id, $since);
464         }
465     }
466
467     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
468     {
469         $profile = $this->getProfile();
470         if (!$profile) {
471             return null;
472         } else {
473             return $profile->getNotices($offset, $limit, $since_id, $before_id, $since);
474         }
475     }
476
477     function favoriteNotices($offset=0, $limit=NOTICES_PER_PAGE, $own=false)
478     {
479         $ids = Fave::stream($this->id, $offset, $limit, $own);
480         return Notice::getStreamByIds($ids);
481     }
482
483     function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
484     {
485         $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, false);
486
487         return Notice::getStreamByIds($ids);
488     }
489
490     function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
491     {
492         $ids = Notice_inbox::stream($this->id, $offset, $limit, $since_id, $before_id, $since, true);
493
494         return Notice::getStreamByIds($ids);
495     }
496
497     function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
498     {
499         $ids = Notice::stream(array($this, '_friendsTimelineDirect'),
500                               array(false),
501                               'user:friends_timeline:'.$this->id,
502                               $offset, $limit, $since_id, $before_id, $since);
503
504         return Notice::getStreamByIds($ids);
505     }
506
507     function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
508     {
509         $ids = Notice::stream(array($this, '_friendsTimelineDirect'),
510                               array(true),
511                               'user:friends_timeline_own:'.$this->id,
512                               $offset, $limit, $since_id, $before_id, $since);
513
514         return Notice::getStreamByIds($ids);
515     }
516
517     function _friendsTimelineDirect($own, $offset, $limit, $since_id, $max_id, $since)
518     {
519         $qry =
520           'SELECT notice.id AS id ' .
521           'FROM notice JOIN notice_inbox ON notice.id = notice_inbox.notice_id ' .
522           'WHERE notice_inbox.user_id = ' . $this->id . ' ' .
523           'AND notice.repeat_of IS NULL ';
524
525         if (!$own) {
526             // XXX: autoload notice inbox for constant
527             $inbox = new Notice_inbox();
528
529             $qry .= 'AND notice_inbox.source != ' . NOTICE_INBOX_SOURCE_GATEWAY . ' ';
530         }
531
532         if ($since_id != 0) {
533             $qry .= 'AND notice.id > ' . $since_id . ' ';
534         }
535
536         if ($max_id != 0) {
537             $qry .= 'AND notice.id <= ' . $max_id . ' ';
538         }
539
540         if (!is_null($since)) {
541             $qry .= 'AND notice.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
542         }
543
544         // NOTE: we sort by fave time, not by notice time!
545
546         $qry .= 'ORDER BY notice_id DESC ';
547
548         if (!is_null($offset)) {
549             $qry .= "LIMIT $limit OFFSET $offset";
550         }
551
552         $ids = array();
553
554         $notice = new Notice();
555
556         $notice->query($qry);
557
558         while ($notice->fetch()) {
559             $ids[] = $notice->id;
560         }
561
562         $notice->free();
563         $notice = NULL;
564
565         return $ids;
566     }
567
568     function blowFavesCache()
569     {
570         $cache = common_memcache();
571         if ($cache) {
572             // Faves don't happen chronologically, so we need to blow
573             // ;last cache, too
574             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
575             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
576             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
577             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
578         }
579         $profile = $this->getProfile();
580         $profile->blowFaveCount();
581     }
582
583     function getSelfTags()
584     {
585         return Profile_tag::getTags($this->id, $this->id);
586     }
587
588     function setSelfTags($newtags)
589     {
590         return Profile_tag::setTags($this->id, $this->id, $newtags);
591     }
592
593     function block($other)
594     {
595         // Add a new block record
596
597         // no blocking (and thus unsubbing from) yourself
598
599         if ($this->id == $other->id) {
600             common_log(LOG_WARNING,
601                 sprintf(
602                     "Profile ID %d (%s) tried to block his or herself.",
603                     $profile->id,
604                     $profile->nickname
605                 )
606             );
607             return false;
608         }
609
610         $block = new Profile_block();
611
612         // Begin a transaction
613
614         $block->query('BEGIN');
615
616         $block->blocker = $this->id;
617         $block->blocked = $other->id;
618
619         $result = $block->insert();
620
621         if (!$result) {
622             common_log_db_error($block, 'INSERT', __FILE__);
623             return false;
624         }
625
626         // Cancel their subscription, if it exists
627
628         $otherUser = User::staticGet('id', $other->id);
629
630         if (!empty($otherUser)) {
631             subs_unsubscribe_to($otherUser, $this->getProfile());
632         }
633
634         $block->query('COMMIT');
635
636         return true;
637     }
638
639     function unblock($other)
640     {
641         // Get the block record
642
643         $block = Profile_block::get($this->id, $other->id);
644
645         if (!$block) {
646             return false;
647         }
648
649         $result = $block->delete();
650
651         if (!$result) {
652             common_log_db_error($block, 'DELETE', __FILE__);
653             return false;
654         }
655
656         return true;
657     }
658
659     function isMember($group)
660     {
661         $profile = $this->getProfile();
662         return $profile->isMember($group);
663     }
664
665     function isAdmin($group)
666     {
667         $profile = $this->getProfile();
668         return $profile->isAdmin($group);
669     }
670
671     function getGroups($offset=0, $limit=null)
672     {
673         $qry =
674           'SELECT user_group.* ' .
675           'FROM user_group JOIN group_member '.
676           'ON user_group.id = group_member.group_id ' .
677           'WHERE group_member.profile_id = %d ' .
678           'ORDER BY group_member.created DESC ';
679
680         if ($offset>0 && !is_null($limit)) {
681             if ($offset) {
682                 if (common_config('db','type') == 'pgsql') {
683                     $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
684                 } else {
685                     $qry .= ' LIMIT ' . $offset . ', ' . $limit;
686                 }
687             }
688         }
689
690         $groups = new User_group();
691
692         $cnt = $groups->query(sprintf($qry, $this->id));
693
694         return $groups;
695     }
696
697     function getSubscriptions($offset=0, $limit=null)
698     {
699         $profile = $this->getProfile();
700         assert(!empty($profile));
701         return $profile->getSubscriptions($offset, $limit);
702     }
703
704     function getSubscribers($offset=0, $limit=null)
705     {
706         $profile = $this->getProfile();
707         assert(!empty($profile));
708         return $profile->getSubscribers($offset, $limit);
709     }
710
711     function getTaggedSubscribers($tag, $offset=0, $limit=null)
712     {
713         $qry =
714           'SELECT profile.* ' .
715           'FROM profile JOIN subscription ' .
716           'ON profile.id = subscription.subscriber ' .
717           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
718           'AND profile_tag.tagger = subscription.subscribed) ' .
719           'WHERE subscription.subscribed = %d ' .
720           "AND profile_tag.tag = '%s' " .
721           'AND subscription.subscribed != subscription.subscriber ' .
722           'ORDER BY subscription.created DESC ';
723
724         if ($offset) {
725             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
726         }
727
728         $profile = new Profile();
729
730         $cnt = $profile->query(sprintf($qry, $this->id, $tag));
731
732         return $profile;
733     }
734
735     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
736     {
737         $qry =
738           'SELECT profile.* ' .
739           'FROM profile JOIN subscription ' .
740           'ON profile.id = subscription.subscribed ' .
741           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
742           'AND profile_tag.tagger = subscription.subscriber) ' .
743           'WHERE subscription.subscriber = %d ' .
744           "AND profile_tag.tag = '%s' " .
745           'AND subscription.subscribed != subscription.subscriber ' .
746           'ORDER BY subscription.created DESC ';
747
748         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
749
750         $profile = new Profile();
751
752         $profile->query(sprintf($qry, $this->id, $tag));
753
754         return $profile;
755     }
756
757     function getDesign()
758     {
759         return Design::staticGet('id', $this->design_id);
760     }
761
762     function hasRight($right)
763     {
764         $profile = $this->getProfile();
765         return $profile->hasRight($right);
766     }
767
768     function delete()
769     {
770         $profile = $this->getProfile();
771         if ($profile) {
772             $profile->delete();
773         }
774
775         $related = array('Fave',
776                          'Confirm_address',
777                          'Remember_me',
778                          'Foreign_link',
779                          'Invitation',
780                          'Notice_inbox',
781                          );
782         Event::handle('UserDeleteRelated', array($this, &$related));
783
784         foreach ($related as $cls) {
785             $inst = new $cls();
786             $inst->user_id = $this->id;
787             $inst->delete();
788         }
789
790         $this->_deleteTags();
791         $this->_deleteBlocks();
792
793         parent::delete();
794     }
795
796     function _deleteTags()
797     {
798         $tag = new Profile_tag();
799         $tag->tagger = $this->id;
800         $tag->delete();
801     }
802
803     function _deleteBlocks()
804     {
805         $block = new Profile_block();
806         $block->blocker = $this->id;
807         $block->delete();
808         // XXX delete group block? Reset blocker?
809     }
810
811     function hasRole($name)
812     {
813         $profile = $this->getProfile();
814         return $profile->hasRole($name);
815     }
816
817     function grantRole($name)
818     {
819         $profile = $this->getProfile();
820         return $profile->grantRole($name);
821     }
822
823     function revokeRole($name)
824     {
825         $profile = $this->getProfile();
826         return $profile->revokeRole($name);
827     }
828
829     function isSandboxed()
830     {
831         $profile = $this->getProfile();
832         return $profile->isSandboxed();
833     }
834
835     function isSilenced()
836     {
837         $profile = $this->getProfile();
838         return $profile->isSilenced();
839     }
840
841     function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
842     {
843         $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
844                               array(),
845                               'user:repeated_by_me:'.$this->id,
846                               $offset, $limit, $since_id, $max_id, null);
847
848         return Notice::getStreamByIds($ids);
849     }
850
851     function _repeatedByMeDirect($offset, $limit, $since_id, $max_id, $since)
852     {
853         $notice = new Notice();
854
855         $notice->selectAdd(); // clears it
856         $notice->selectAdd('id');
857
858         $notice->profile_id = $this->id;
859         $notice->whereAdd('repeat_of IS NOT NULL');
860
861         $notice->orderBy('id DESC');
862
863         if (!is_null($offset)) {
864             $notice->limit($offset, $limit);
865         }
866
867         if ($since_id != 0) {
868             $notice->whereAdd('id > ' . $since_id);
869         }
870
871         if ($max_id != 0) {
872             $notice->whereAdd('id <= ' . $max_id);
873         }
874
875         if (!is_null($since)) {
876             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
877         }
878
879         $ids = array();
880
881         if ($notice->find()) {
882             while ($notice->fetch()) {
883                 $ids[] = $notice->id;
884             }
885         }
886
887         $notice->free();
888         $notice = NULL;
889
890         return $ids;
891     }
892
893     function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
894     {
895         $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
896                               array(),
897                               'user:repeats_of_me:'.$this->id,
898                               $offset, $limit, $since_id, $max_id, null);
899
900         return Notice::getStreamByIds($ids);
901     }
902
903     function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id, $since)
904     {
905         $qry =
906           'SELECT DISTINCT original.id AS id ' .
907           'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
908           'WHERE original.profile_id = ' . $this->id . ' ';
909
910         if ($since_id != 0) {
911             $qry .= 'AND original.id > ' . $since_id . ' ';
912         }
913
914         if ($max_id != 0) {
915             $qry .= 'AND original.id <= ' . $max_id . ' ';
916         }
917
918         if (!is_null($since)) {
919             $qry .= 'AND original.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
920         }
921
922         // NOTE: we sort by fave time, not by notice time!
923
924         $qry .= 'ORDER BY original.id DESC ';
925
926         if (!is_null($offset)) {
927             $qry .= "LIMIT $limit OFFSET $offset";
928         }
929
930         $ids = array();
931
932         $notice = new Notice();
933
934         $notice->query($qry);
935
936         while ($notice->fetch()) {
937             $ids[] = $notice->id;
938         }
939
940         $notice->free();
941         $notice = NULL;
942
943         return $ids;
944     }
945
946     function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
947     {
948         $ids = Notice::stream(array($this, '_repeatedToMeDirect'),
949                               array(),
950                               'user:repeated_to_me:'.$this->id,
951                               $offset, $limit, $since_id, $max_id, null);
952
953         return Notice::getStreamByIds($ids);
954     }
955
956     function _repeatedToMeDirect($offset, $limit, $since_id, $max_id, $since)
957     {
958         $qry =
959           'SELECT notice.id AS id ' .
960           'FROM notice JOIN notice_inbox ON notice.id = notice_inbox.notice_id ' .
961           'WHERE notice_inbox.user_id = ' . $this->id . ' ' .
962           'AND notice.repeat_of IS NOT NULL ';
963
964         if ($since_id != 0) {
965             $qry .= 'AND notice.id > ' . $since_id . ' ';
966         }
967
968         if ($max_id != 0) {
969             $qry .= 'AND notice.id <= ' . $max_id . ' ';
970         }
971
972         if (!is_null($since)) {
973             $qry .= 'AND notice.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
974         }
975
976         // NOTE: we sort by fave time, not by notice time!
977
978         $qry .= 'ORDER BY notice.id DESC ';
979
980         if (!is_null($offset)) {
981             $qry .= "LIMIT $limit OFFSET $offset";
982         }
983
984         $ids = array();
985
986         $notice = new Notice();
987
988         $notice->query($qry);
989
990         while ($notice->fetch()) {
991             $ids[] = $notice->id;
992         }
993
994         $notice->free();
995         $notice = NULL;
996
997         return $ids;
998     }
999
1000     function shareLocation()
1001     {
1002         $cfg = common_config('location', 'share');
1003
1004         if ($cfg == 'always') {
1005             return true;
1006         } else if ($cfg == 'never') {
1007             return false;
1008         } else { // user
1009             $share = true;
1010
1011             $prefs = User_location_prefs::staticGet('user_id', $this->id);
1012
1013             if (empty($prefs)) {
1014                 $share = common_config('location', 'sharedefault');
1015             } else {
1016                 $share = $prefs->share_location;
1017                 $prefs->free();
1018             }
1019
1020             return $share;
1021         }
1022     }
1023 }