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