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