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