]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into testing
[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         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, false);
506     }
507
508     function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
509     {
510         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, true);
511     }
512
513     function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
514     {
515         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, false);
516     }
517
518     function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0, $since=null)
519     {
520         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, $since, true);
521     }
522
523     function blowFavesCache()
524     {
525         $cache = common_memcache();
526         if ($cache) {
527             // Faves don't happen chronologically, so we need to blow
528             // ;last cache, too
529             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id));
530             $cache->delete(common_cache_key('fave:ids_by_user:'.$this->id.';last'));
531             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id));
532             $cache->delete(common_cache_key('fave:ids_by_user_own:'.$this->id.';last'));
533         }
534         $profile = $this->getProfile();
535         $profile->blowFaveCount();
536     }
537
538     function getSelfTags()
539     {
540         return Profile_tag::getTags($this->id, $this->id);
541     }
542
543     function setSelfTags($newtags)
544     {
545         return Profile_tag::setTags($this->id, $this->id, $newtags);
546     }
547
548     function block($other)
549     {
550         // Add a new block record
551
552         // no blocking (and thus unsubbing from) yourself
553
554         if ($this->id == $other->id) {
555             common_log(LOG_WARNING,
556                 sprintf(
557                     "Profile ID %d (%s) tried to block his or herself.",
558                     $profile->id,
559                     $profile->nickname
560                 )
561             );
562             return false;
563         }
564
565         $block = new Profile_block();
566
567         // Begin a transaction
568
569         $block->query('BEGIN');
570
571         $block->blocker = $this->id;
572         $block->blocked = $other->id;
573
574         $result = $block->insert();
575
576         if (!$result) {
577             common_log_db_error($block, 'INSERT', __FILE__);
578             return false;
579         }
580
581         // Cancel their subscription, if it exists
582
583         $otherUser = User::staticGet('id', $other->id);
584
585         if (!empty($otherUser)) {
586             subs_unsubscribe_to($otherUser, $this->getProfile());
587         }
588
589         $block->query('COMMIT');
590
591         return true;
592     }
593
594     function unblock($other)
595     {
596         // Get the block record
597
598         $block = Profile_block::get($this->id, $other->id);
599
600         if (!$block) {
601             return false;
602         }
603
604         $result = $block->delete();
605
606         if (!$result) {
607             common_log_db_error($block, 'DELETE', __FILE__);
608             return false;
609         }
610
611         return true;
612     }
613
614     function isMember($group)
615     {
616         $profile = $this->getProfile();
617         return $profile->isMember($group);
618     }
619
620     function isAdmin($group)
621     {
622         $profile = $this->getProfile();
623         return $profile->isAdmin($group);
624     }
625
626     function getGroups($offset=0, $limit=null)
627     {
628         $qry =
629           'SELECT user_group.* ' .
630           'FROM user_group JOIN group_member '.
631           'ON user_group.id = group_member.group_id ' .
632           'WHERE group_member.profile_id = %d ' .
633           'ORDER BY group_member.created DESC ';
634
635         if ($offset>0 && !is_null($limit)) {
636             if ($offset) {
637                 if (common_config('db','type') == 'pgsql') {
638                     $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
639                 } else {
640                     $qry .= ' LIMIT ' . $offset . ', ' . $limit;
641                 }
642             }
643         }
644
645         $groups = new User_group();
646
647         $cnt = $groups->query(sprintf($qry, $this->id));
648
649         return $groups;
650     }
651
652     function getSubscriptions($offset=0, $limit=null)
653     {
654         $profile = $this->getProfile();
655         assert(!empty($profile));
656         return $profile->getSubscriptions($offset, $limit);
657     }
658
659     function getSubscribers($offset=0, $limit=null)
660     {
661         $profile = $this->getProfile();
662         assert(!empty($profile));
663         return $profile->getSubscribers($offset, $limit);
664     }
665
666     function getTaggedSubscribers($tag, $offset=0, $limit=null)
667     {
668         $qry =
669           'SELECT profile.* ' .
670           'FROM profile JOIN subscription ' .
671           'ON profile.id = subscription.subscriber ' .
672           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
673           'AND profile_tag.tagger = subscription.subscribed) ' .
674           'WHERE subscription.subscribed = %d ' .
675           "AND profile_tag.tag = '%s' " .
676           'AND subscription.subscribed != subscription.subscriber ' .
677           'ORDER BY subscription.created DESC ';
678
679         if ($offset) {
680             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
681         }
682
683         $profile = new Profile();
684
685         $cnt = $profile->query(sprintf($qry, $this->id, $tag));
686
687         return $profile;
688     }
689
690     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
691     {
692         $qry =
693           'SELECT profile.* ' .
694           'FROM profile JOIN subscription ' .
695           'ON profile.id = subscription.subscribed ' .
696           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
697           'AND profile_tag.tagger = subscription.subscriber) ' .
698           'WHERE subscription.subscriber = %d ' .
699           "AND profile_tag.tag = '%s' " .
700           'AND subscription.subscribed != subscription.subscriber ' .
701           'ORDER BY subscription.created DESC ';
702
703         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
704
705         $profile = new Profile();
706
707         $profile->query(sprintf($qry, $this->id, $tag));
708
709         return $profile;
710     }
711
712     function getDesign()
713     {
714         return Design::staticGet('id', $this->design_id);
715     }
716
717     function hasRight($right)
718     {
719         $profile = $this->getProfile();
720         return $profile->hasRight($right);
721     }
722
723     function delete()
724     {
725         $profile = $this->getProfile();
726         if ($profile) {
727             $profile->delete();
728         }
729
730         $related = array('Fave',
731                          'Confirm_address',
732                          'Remember_me',
733                          'Foreign_link',
734                          'Invitation',
735                          );
736         Event::handle('UserDeleteRelated', array($this, &$related));
737
738         foreach ($related as $cls) {
739             $inst = new $cls();
740             $inst->user_id = $this->id;
741             $inst->delete();
742         }
743
744         $this->_deleteTags();
745         $this->_deleteBlocks();
746
747         parent::delete();
748     }
749
750     function _deleteTags()
751     {
752         $tag = new Profile_tag();
753         $tag->tagger = $this->id;
754         $tag->delete();
755     }
756
757     function _deleteBlocks()
758     {
759         $block = new Profile_block();
760         $block->blocker = $this->id;
761         $block->delete();
762         // XXX delete group block? Reset blocker?
763     }
764
765     function hasRole($name)
766     {
767         $profile = $this->getProfile();
768         return $profile->hasRole($name);
769     }
770
771     function grantRole($name)
772     {
773         $profile = $this->getProfile();
774         return $profile->grantRole($name);
775     }
776
777     function revokeRole($name)
778     {
779         $profile = $this->getProfile();
780         return $profile->revokeRole($name);
781     }
782
783     function isSandboxed()
784     {
785         $profile = $this->getProfile();
786         return $profile->isSandboxed();
787     }
788
789     function isSilenced()
790     {
791         $profile = $this->getProfile();
792         return $profile->isSilenced();
793     }
794
795     function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
796     {
797         $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
798                               array(),
799                               'user:repeated_by_me:'.$this->id,
800                               $offset, $limit, $since_id, $max_id, null);
801
802         return Notice::getStreamByIds($ids);
803     }
804
805     function _repeatedByMeDirect($offset, $limit, $since_id, $max_id, $since)
806     {
807         $notice = new Notice();
808
809         $notice->selectAdd(); // clears it
810         $notice->selectAdd('id');
811
812         $notice->profile_id = $this->id;
813         $notice->whereAdd('repeat_of IS NOT NULL');
814
815         $notice->orderBy('id DESC');
816
817         if (!is_null($offset)) {
818             $notice->limit($offset, $limit);
819         }
820
821         if ($since_id != 0) {
822             $notice->whereAdd('id > ' . $since_id);
823         }
824
825         if ($max_id != 0) {
826             $notice->whereAdd('id <= ' . $max_id);
827         }
828
829         if (!is_null($since)) {
830             $notice->whereAdd('created > \'' . date('Y-m-d H:i:s', $since) . '\'');
831         }
832
833         $ids = array();
834
835         if ($notice->find()) {
836             while ($notice->fetch()) {
837                 $ids[] = $notice->id;
838             }
839         }
840
841         $notice->free();
842         $notice = NULL;
843
844         return $ids;
845     }
846
847     function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
848     {
849         $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
850                               array(),
851                               'user:repeats_of_me:'.$this->id,
852                               $offset, $limit, $since_id, $max_id, null);
853
854         return Notice::getStreamByIds($ids);
855     }
856
857     function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id, $since)
858     {
859         $qry =
860           'SELECT DISTINCT original.id AS id ' .
861           'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
862           'WHERE original.profile_id = ' . $this->id . ' ';
863
864         if ($since_id != 0) {
865             $qry .= 'AND original.id > ' . $since_id . ' ';
866         }
867
868         if ($max_id != 0) {
869             $qry .= 'AND original.id <= ' . $max_id . ' ';
870         }
871
872         if (!is_null($since)) {
873             $qry .= 'AND original.modified > \'' . date('Y-m-d H:i:s', $since) . '\' ';
874         }
875
876         // NOTE: we sort by fave time, not by notice time!
877
878         $qry .= 'ORDER BY original.id DESC ';
879
880         if (!is_null($offset)) {
881             $qry .= "LIMIT $limit OFFSET $offset";
882         }
883
884         $ids = array();
885
886         $notice = new Notice();
887
888         $notice->query($qry);
889
890         while ($notice->fetch()) {
891             $ids[] = $notice->id;
892         }
893
894         $notice->free();
895         $notice = NULL;
896
897         return $ids;
898     }
899
900     function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
901     {
902         throw new Exception("Not implemented since inbox change.");
903     }
904
905     function shareLocation()
906     {
907         $cfg = common_config('location', 'share');
908
909         if ($cfg == 'always') {
910             return true;
911         } else if ($cfg == 'never') {
912             return false;
913         } else { // user
914             $share = true;
915
916             $prefs = User_location_prefs::staticGet('user_id', $this->id);
917
918             if (empty($prefs)) {
919                 $share = common_config('location', 'sharedefault');
920             } else {
921                 $share = $prefs->share_location;
922                 $prefs->free();
923             }
924
925             return $share;
926         }
927     }
928
929     static function siteOwner()
930     {
931         $owner = self::cacheGet('user:site_owner');
932
933         if ($owner === false) { // cache miss
934
935             $pr = new Profile_role();
936
937             $pr->role = Profile_role::OWNER;
938
939             $pr->orderBy('created');
940
941             $pr->limit(1);
942
943             if ($pr->find(true)) {
944                 $owner = User::staticGet('id', $pr->profile_id);
945             } else {
946                 $owner = null;
947             }
948
949             self::cacheSet('user:site_owner', $owner);
950         }
951
952         return $owner;
953     }
954 }