]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
Merge remote-tracking branch 'mainline/1.0.x' into people_tags_rebase
[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 $sms;                             // varchar(64)  unique_key
52     public $carrier;                         // int(4)
53     public $smsnotify;                       // tinyint(1)
54     public $smsreplies;                      // tinyint(1)
55     public $smsemail;                        // varchar(255)
56     public $uri;                             // varchar(255)  unique_key
57     public $autosubscribe;                   // tinyint(1)
58     public $urlshorteningservice;            // varchar(50)   default_ur1.ca
59     public $inboxed;                         // tinyint(1)
60     public $design_id;                       // int(4)
61     public $viewdesigns;                     // tinyint(1)   default_1
62     public $created;                         // datetime()   not_null
63     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
64
65     /* Static get */
66     function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('User',$k,$v); }
67
68     /* the code above is auto generated do not remove the tag below */
69     ###END_AUTOCODE
70
71     /**
72      * @return Profile
73      */
74     function getProfile()
75     {
76         $profile = Profile::staticGet('id', $this->id);
77         if (empty($profile)) {
78             throw new UserNoProfileException($this);
79         }
80         return $profile;
81     }
82
83     function isSubscribed($other)
84     {
85         $profile = $this->getProfile();
86         return $profile->isSubscribed($other);
87     }
88
89     // 'update' won't write key columns, so we have to do it ourselves.
90
91     function updateKeys(&$orig)
92     {
93         $this->_connect();
94         $parts = array();
95         foreach (array('nickname', 'email', '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     /**
118      * Check whether the given nickname is potentially usable, or if it's
119      * excluded by any blacklists on this system.
120      *
121      * WARNING: INPUT IS NOT VALIDATED OR NORMALIZED. NON-NORMALIZED INPUT
122      * OR INVALID INPUT MAY LEAD TO FALSE RESULTS.
123      *
124      * @param string $nickname
125      * @return boolean true if clear, false if blacklisted
126      */
127     static function allowed_nickname($nickname)
128     {
129         // XXX: should already be validated for size, content, etc.
130         $blacklist = common_config('nickname', 'blacklist');
131
132         //all directory and file names should be blacklisted
133         $d = dir(INSTALLDIR);
134         while (false !== ($entry = $d->read())) {
135             $blacklist[]=$entry;
136         }
137         $d->close();
138
139         //all top level names in the router should be blacklisted
140         $router = Router::get();
141         foreach(array_keys($router->m->getPaths()) as $path){
142             if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
143                 $blacklist[]=$matches[1];
144             }
145         }
146         return !in_array($nickname, $blacklist);
147     }
148
149     /**
150      * Get the most recent notice posted by this user, if any.
151      *
152      * @return mixed Notice or null
153      */
154     function getCurrentNotice()
155     {
156         $profile = $this->getProfile();
157         return $profile->getCurrentNotice();
158     }
159
160     function getCarrier()
161     {
162         return Sms_carrier::staticGet('id', $this->carrier);
163     }
164
165     /**
166      * @deprecated use Subscription::start($sub, $other);
167      */
168     function subscribeTo($other)
169     {
170         return Subscription::start($this->getProfile(), $other);
171     }
172
173     function hasBlocked($other)
174     {
175         $profile = $this->getProfile();
176         return $profile->hasBlocked($other);
177     }
178
179     /**
180      * Register a new user account and profile and set up default subscriptions.
181      * If a new-user welcome message is configured, this will be sent.
182      *
183      * @param array $fields associative array of optional properties
184      *              string 'bio'
185      *              string 'email'
186      *              bool 'email_confirmed' pass true to mark email as pre-confirmed
187      *              string 'fullname'
188      *              string 'homepage'
189      *              string 'location' informal string description of geolocation
190      *              float 'lat' decimal latitude for geolocation
191      *              float 'lon' decimal longitude for geolocation
192      *              int 'location_id' geoname identifier
193      *              int 'location_ns' geoname namespace to interpret location_id
194      *              string 'nickname' REQUIRED
195      *              string 'password' (may be missing for eg OpenID registrations)
196      *              string 'code' invite code
197      *              ?string 'uri' permalink to notice; defaults to local notice URL
198      * @return mixed User object or false on failure
199      */
200     static function register($fields) {
201
202         // MAGICALLY put fields into current scope
203
204         extract($fields);
205
206         $profile = new Profile();
207
208         if(!empty($email))
209         {
210             $email = common_canonical_email($email);
211         }
212
213         $nickname = common_canonical_nickname($nickname);
214         $profile->nickname = $nickname;
215         if(! User::allowed_nickname($nickname)){
216             common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
217                        __FILE__);
218             return false;
219         }
220         $profile->profileurl = common_profile_url($nickname);
221
222         if (!empty($fullname)) {
223             $profile->fullname = $fullname;
224         }
225         if (!empty($homepage)) {
226             $profile->homepage = $homepage;
227         }
228         if (!empty($bio)) {
229             $profile->bio = $bio;
230         }
231         if (!empty($location)) {
232             $profile->location = $location;
233
234             $loc = Location::fromName($location);
235
236             if (!empty($loc)) {
237                 $profile->lat         = $loc->lat;
238                 $profile->lon         = $loc->lon;
239                 $profile->location_id = $loc->location_id;
240                 $profile->location_ns = $loc->location_ns;
241             }
242         }
243
244         $profile->created = common_sql_now();
245
246         $user = new User();
247
248         $user->nickname = $nickname;
249
250         // Users who respond to invite email have proven their ownership of that address
251
252         if (!empty($code)) {
253             $invite = Invitation::staticGet($code);
254             if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
255                 $user->email = $invite->address;
256             }
257         }
258
259         if(isset($email_confirmed) && $email_confirmed) {
260             $user->email = $email;
261         }
262
263         // This flag is ignored but still set to 1
264
265         $user->inboxed = 1;
266
267         // Set default-on options here, otherwise they'll be disabled
268         // initially for sites using caching, since the initial encache
269         // doesn't know about the defaults in the database.
270         $user->emailnotifysub = 1;
271         $user->emailnotifyfav = 1;
272         $user->emailnotifynudge = 1;
273         $user->emailnotifymsg = 1;
274         $user->emailnotifyattn = 1;
275         $user->emailmicroid = 1;
276         $user->emailpost = 1;
277         $user->jabbermicroid = 1;
278         $user->viewdesigns = 1;
279
280         $user->created = common_sql_now();
281
282         if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
283
284             $profile->query('BEGIN');
285
286             $id = $profile->insert();
287
288             if (empty($id)) {
289                 common_log_db_error($profile, 'INSERT', __FILE__);
290                 return false;
291             }
292
293             $user->id = $id;
294
295             if (!empty($uri)) {
296                 $user->uri = $uri;
297             } else {
298                 $user->uri = common_user_uri($user);
299             }
300
301             if (!empty($password)) { // may not have a password for OpenID users
302                 $user->password = common_munge_password($password, $id);
303             }
304
305             $result = $user->insert();
306
307             if (!$result) {
308                 common_log_db_error($user, 'INSERT', __FILE__);
309                 return false;
310             }
311
312             // Everyone gets an inbox
313
314             $inbox = new Inbox();
315
316             $inbox->user_id = $user->id;
317             $inbox->notice_ids = '';
318
319             $result = $inbox->insert();
320
321             if (!$result) {
322                 common_log_db_error($inbox, 'INSERT', __FILE__);
323                 return false;
324             }
325
326             // Everyone is subscribed to themself
327
328             $subscription = new Subscription();
329             $subscription->subscriber = $user->id;
330             $subscription->subscribed = $user->id;
331             $subscription->created = $user->created;
332
333             $result = $subscription->insert();
334
335             if (!$result) {
336                 common_log_db_error($subscription, 'INSERT', __FILE__);
337                 return false;
338             }
339
340             if (!empty($email) && !$user->email) {
341
342                 $confirm = new Confirm_address();
343                 $confirm->code = common_confirmation_code(128);
344                 $confirm->user_id = $user->id;
345                 $confirm->address = $email;
346                 $confirm->address_type = 'email';
347
348                 $result = $confirm->insert();
349
350                 if (!$result) {
351                     common_log_db_error($confirm, 'INSERT', __FILE__);
352                     return false;
353                 }
354             }
355
356             if (!empty($code) && $user->email) {
357                 $user->emailChanged();
358             }
359
360             // Default system subscription
361
362             $defnick = common_config('newuser', 'default');
363
364             if (!empty($defnick)) {
365                 $defuser = User::staticGet('nickname', $defnick);
366                 if (empty($defuser)) {
367                     common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
368                                __FILE__);
369                 } else {
370                     Subscription::start($user, $defuser);
371                 }
372             }
373
374             $profile->query('COMMIT');
375
376             if (!empty($email) && !$user->email) {
377                 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
378             }
379
380             // Welcome message
381
382             $welcome = common_config('newuser', 'welcome');
383
384             if (!empty($welcome)) {
385                 $welcomeuser = User::staticGet('nickname', $welcome);
386                 if (empty($welcomeuser)) {
387                     common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
388                                __FILE__);
389                 } else {
390                     $notice = Notice::saveNew($welcomeuser->id,
391                                               // TRANS: Notice given on user registration.
392                                               // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
393                                               sprintf(_('Welcome to %1$s, @%2$s!'),
394                                                       common_config('site', 'name'),
395                                                       $user->nickname),
396                                               'system');
397                 }
398             }
399
400             Event::handle('EndUserRegister', array(&$profile, &$user));
401         }
402
403         return $user;
404     }
405
406     // Things we do when the email changes
407     function emailChanged()
408     {
409
410         $invites = new Invitation();
411         $invites->address = $this->email;
412         $invites->address_type = 'email';
413
414         if ($invites->find()) {
415             while ($invites->fetch()) {
416                 $other = User::staticGet($invites->user_id);
417                 subs_subscribe_to($other, $this);
418             }
419         }
420     }
421
422     function hasFave($notice)
423     {
424         $profile = $this->getProfile();
425         return $profile->hasFave($notice);
426     }
427
428     function mutuallySubscribed($other)
429     {
430         $profile = $this->getProfile();
431         return $profile->mutuallySubscribed($other);
432     }
433
434     function mutuallySubscribedUsers()
435     {
436         // 3-way join; probably should get cached
437         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
438         $qry = "SELECT $UT.* " .
439           "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
440           "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
441           'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
442           "ORDER BY $UT.nickname";
443         $user = new User();
444         $user->query(sprintf($qry, $this->id, $this->id));
445
446         return $user;
447     }
448
449     function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
450     {
451         $ids = Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
452         return Notice::getStreamByIds($ids);
453     }
454
455     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
456         $profile = $this->getProfile();
457         return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
458     }
459
460     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
461     {
462         $profile = $this->getProfile();
463         return $profile->getNotices($offset, $limit, $since_id, $before_id);
464     }
465
466     function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
467     {
468         $ids = Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
469         return Notice::getStreamByIds($ids);
470     }
471
472     function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
473     {
474         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
475     }
476
477     function noticesWithFriendsThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
478     {
479         return Inbox::streamNoticesThreaded($this->id, $offset, $limit, $since_id, $before_id, false);
480     }
481
482     function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
483     {
484         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
485     }
486
487     function noticeInboxThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
488     {
489         return Inbox::streamNoticesThreaded($this->id, $offset, $limit, $since_id, $before_id, true);
490     }
491
492     function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
493     {
494         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
495     }
496
497     function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
498     {
499         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
500     }
501
502     function blowFavesCache()
503     {
504         $profile = $this->getProfile();
505         $profile->blowFavesCache();
506     }
507
508     function getSelfTags()
509     {
510         return Profile_tag::getTagsArray($this->id, $this->id, $this->id);
511     }
512
513     function setSelfTags($newtags, $privacy)
514     {
515         return Profile_tag::setTags($this->id, $this->id, $newtags, $privacy);
516     }
517
518     function block($other)
519     {
520         // Add a new block record
521
522         // no blocking (and thus unsubbing from) yourself
523
524         if ($this->id == $other->id) {
525             common_log(LOG_WARNING,
526                 sprintf(
527                     "Profile ID %d (%s) tried to block themself.",
528                     $this->id,
529                     $this->nickname
530                 )
531             );
532             return false;
533         }
534
535         $block = new Profile_block();
536
537         // Begin a transaction
538
539         $block->query('BEGIN');
540
541         $block->blocker = $this->id;
542         $block->blocked = $other->id;
543
544         $result = $block->insert();
545
546         if (!$result) {
547             common_log_db_error($block, 'INSERT', __FILE__);
548             return false;
549         }
550
551         $self = $this->getProfile();
552         if (Subscription::exists($other, $self)) {
553             Subscription::cancel($other, $self);
554         }
555         if (Subscription::exists($self, $other)) {
556             Subscription::cancel($self, $other);
557         }
558
559         $block->query('COMMIT');
560
561         return true;
562     }
563
564     function unblock($other)
565     {
566         // Get the block record
567
568         $block = Profile_block::get($this->id, $other->id);
569
570         if (!$block) {
571             return false;
572         }
573
574         $result = $block->delete();
575
576         if (!$result) {
577             common_log_db_error($block, 'DELETE', __FILE__);
578             return false;
579         }
580
581         return true;
582     }
583
584     function isMember($group)
585     {
586         $profile = $this->getProfile();
587         return $profile->isMember($group);
588     }
589
590     function isAdmin($group)
591     {
592         $profile = $this->getProfile();
593         return $profile->isAdmin($group);
594     }
595
596     function getGroups($offset=0, $limit=null)
597     {
598         $profile = $this->getProfile();
599         return $profile->getGroups($offset, $limit);
600     }
601
602     /**
603      * Request to join the given group.
604      * May throw exceptions on failure.
605      *
606      * @param User_group $group
607      * @return Group_member
608      */
609     function joinGroup(User_group $group)
610     {
611         $profile = $this->getProfile();
612         return $profile->joinGroup($group);
613     }
614
615     /**
616      * Leave a group that this user is a member of.
617      *
618      * @param User_group $group
619      */
620     function leaveGroup(User_group $group)
621     {
622         $profile = $this->getProfile();
623         return $profile->leaveGroup($group);
624     }
625
626     function getSubscriptions($offset=0, $limit=null)
627     {
628         $profile = $this->getProfile();
629         return $profile->getSubscriptions($offset, $limit);
630     }
631
632     function getSubscribers($offset=0, $limit=null)
633     {
634         $profile = $this->getProfile();
635         return $profile->getSubscribers($offset, $limit);
636     }
637
638     function getTaggedSubscribers($tag, $offset=0, $limit=null)
639     {
640         $qry =
641           'SELECT profile.* ' .
642           'FROM profile JOIN subscription ' .
643           'ON profile.id = subscription.subscriber ' .
644           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
645           'AND profile_tag.tagger = subscription.subscribed) ' .
646           'WHERE subscription.subscribed = %d ' .
647           "AND profile_tag.tag = '%s' " .
648           'AND subscription.subscribed != subscription.subscriber ' .
649           'ORDER BY subscription.created DESC ';
650
651         if ($offset) {
652             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
653         }
654
655         $profile = new Profile();
656
657         $cnt = $profile->query(sprintf($qry, $this->id, $tag));
658
659         return $profile;
660     }
661
662     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
663     {
664         $qry =
665           'SELECT profile.* ' .
666           'FROM profile JOIN subscription ' .
667           'ON profile.id = subscription.subscribed ' .
668           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
669           'AND profile_tag.tagger = subscription.subscriber) ' .
670           'WHERE subscription.subscriber = %d ' .
671           "AND profile_tag.tag = '%s' " .
672           'AND subscription.subscribed != subscription.subscriber ' .
673           'ORDER BY subscription.created DESC ';
674
675         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
676
677         $profile = new Profile();
678
679         $profile->query(sprintf($qry, $this->id, $tag));
680
681         return $profile;
682     }
683
684     function getDesign()
685     {
686         return Design::staticGet('id', $this->design_id);
687     }
688
689     function hasRight($right)
690     {
691         $profile = $this->getProfile();
692         return $profile->hasRight($right);
693     }
694
695     function delete()
696     {
697         try {
698             $profile = $this->getProfile();
699             $profile->delete();
700         } catch (UserNoProfileException $unp) {
701             common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
702         }
703
704         $related = array('Fave',
705                          'Confirm_address',
706                          'Remember_me',
707                          'Foreign_link',
708                          'Invitation',
709                          );
710
711         Event::handle('UserDeleteRelated', array($this, &$related));
712
713         foreach ($related as $cls) {
714             $inst = new $cls();
715             $inst->user_id = $this->id;
716             $inst->delete();
717         }
718
719         $this->_deleteTags();
720         $this->_deleteBlocks();
721
722         parent::delete();
723     }
724
725     function _deleteTags()
726     {
727         $tag = new Profile_tag();
728         $tag->tagger = $this->id;
729         $tag->delete();
730     }
731
732     function _deleteBlocks()
733     {
734         $block = new Profile_block();
735         $block->blocker = $this->id;
736         $block->delete();
737         // XXX delete group block? Reset blocker?
738     }
739
740     function hasRole($name)
741     {
742         $profile = $this->getProfile();
743         return $profile->hasRole($name);
744     }
745
746     function grantRole($name)
747     {
748         $profile = $this->getProfile();
749         return $profile->grantRole($name);
750     }
751
752     function revokeRole($name)
753     {
754         $profile = $this->getProfile();
755         return $profile->revokeRole($name);
756     }
757
758     function isSandboxed()
759     {
760         $profile = $this->getProfile();
761         return $profile->isSandboxed();
762     }
763
764     function isSilenced()
765     {
766         $profile = $this->getProfile();
767         return $profile->isSilenced();
768     }
769
770     function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
771     {
772         $ids = Notice::stream(array($this, '_repeatedByMeDirect'),
773                               array(),
774                               'user:repeated_by_me:'.$this->id,
775                               $offset, $limit, $since_id, $max_id, null);
776
777         return Notice::getStreamByIds($ids);
778     }
779
780     function _repeatedByMeDirect($offset, $limit, $since_id, $max_id)
781     {
782         $notice = new Notice();
783
784         $notice->selectAdd(); // clears it
785         $notice->selectAdd('id');
786
787         $notice->profile_id = $this->id;
788         $notice->whereAdd('repeat_of IS NOT NULL');
789
790         $notice->orderBy('created DESC, id DESC');
791
792         if (!is_null($offset)) {
793             $notice->limit($offset, $limit);
794         }
795
796         Notice::addWhereSinceId($notice, $since_id);
797         Notice::addWhereMaxId($notice, $max_id);
798
799         $ids = array();
800
801         if ($notice->find()) {
802             while ($notice->fetch()) {
803                 $ids[] = $notice->id;
804             }
805         }
806
807         $notice->free();
808         $notice = NULL;
809
810         return $ids;
811     }
812
813     function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
814     {
815         $ids = Notice::stream(array($this, '_repeatsOfMeDirect'),
816                               array(),
817                               'user:repeats_of_me:'.$this->id,
818                               $offset, $limit, $since_id, $max_id);
819
820         return Notice::getStreamByIds($ids);
821     }
822
823     function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id)
824     {
825         $qry =
826           'SELECT DISTINCT original.id AS id ' .
827           'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
828           'WHERE original.profile_id = ' . $this->id . ' ';
829
830         $since = Notice::whereSinceId($since_id, 'original.id', 'original.created');
831         if ($since) {
832             $qry .= "AND ($since) ";
833         }
834
835         $max = Notice::whereMaxId($max_id, 'original.id', 'original.created');
836         if ($max) {
837             $qry .= "AND ($max) ";
838         }
839
840         $qry .= 'ORDER BY original.created, original.id DESC ';
841
842         if (!is_null($offset)) {
843             $qry .= "LIMIT $limit OFFSET $offset";
844         }
845
846         $ids = array();
847
848         $notice = new Notice();
849
850         $notice->query($qry);
851
852         while ($notice->fetch()) {
853             $ids[] = $notice->id;
854         }
855
856         $notice->free();
857         $notice = NULL;
858
859         return $ids;
860     }
861
862     function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
863     {
864         throw new Exception("Not implemented since inbox change.");
865     }
866
867     function shareLocation()
868     {
869         $cfg = common_config('location', 'share');
870
871         if ($cfg == 'always') {
872             return true;
873         } else if ($cfg == 'never') {
874             return false;
875         } else { // user
876             $share = true;
877
878             $prefs = User_location_prefs::staticGet('user_id', $this->id);
879
880             if (empty($prefs)) {
881                 $share = common_config('location', 'sharedefault');
882             } else {
883                 $share = $prefs->share_location;
884                 $prefs->free();
885             }
886
887             return $share;
888         }
889     }
890
891     static function siteOwner()
892     {
893         $owner = self::cacheGet('user:site_owner');
894
895         if ($owner === false) { // cache miss
896
897             $pr = new Profile_role();
898
899             $pr->role = Profile_role::OWNER;
900
901             $pr->orderBy('created');
902
903             $pr->limit(1);
904
905             if ($pr->find(true)) {
906                 $owner = User::staticGet('id', $pr->profile_id);
907             } else {
908                 $owner = null;
909             }
910
911             self::cacheSet('user:site_owner', $owner);
912         }
913
914         return $owner;
915     }
916
917     /**
918      * Pull the primary site account to use in single-user mode.
919      * If a valid user nickname is listed in 'singleuser':'nickname'
920      * in the config, this will be used; otherwise the site owner
921      * account is taken by default.
922      *
923      * @return User
924      * @throws ServerException if no valid single user account is present
925      * @throws ServerException if called when not in single-user mode
926      */
927     static function singleUser()
928     {
929         if (common_config('singleuser', 'enabled')) {
930
931             $user = null;
932
933             $nickname = common_config('singleuser', 'nickname');
934
935             if (!empty($nickname)) {
936                 $user = User::staticGet('nickname', $nickname);
937             }
938
939             // if there was no nickname or no user by that nickname,
940             // try the site owner.
941
942             if (empty($user)) {
943                 $user = User::siteOwner();
944             }
945
946             if (!empty($user)) {
947                 return $user;
948             } else {
949                 // TRANS: Server exception.
950                 throw new ServerException(_('No single user defined for single-user mode.'));
951             }
952         } else {
953             // TRANS: Server exception.
954             throw new ServerException(_('Single-user mode code called when not enabled.'));
955         }
956     }
957
958     /**
959      * This is kind of a hack for using external setup code that's trying to
960      * build single-user sites.
961      *
962      * Will still return a username if the config singleuser/nickname is set
963      * even if the account doesn't exist, which normally indicates that the
964      * site is horribly misconfigured.
965      *
966      * At the moment, we need to let it through so that router setup can
967      * complete, otherwise we won't be able to create the account.
968      *
969      * This will be easier when we can more easily create the account and
970      * *then* switch the site to 1user mode without jumping through hoops.
971      *
972      * @return string
973      * @throws ServerException if no valid single user account is present
974      * @throws ServerException if called when not in single-user mode
975      */
976     static function singleUserNickname()
977     {
978         try {
979             $user = User::singleUser();
980             return $user->nickname;
981         } catch (Exception $e) {
982             if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
983                 common_log(LOG_WARN, "Warning: code attempting to pull single-user nickname when the account does not exist. If this is not setup time, this is probably a bug.");
984                 return common_config('singleuser', 'nickname');
985             }
986             throw $e;
987         }
988     }
989
990     /**
991      * Find and shorten links in the given text using this user's URL shortening
992      * settings.
993      *
994      * By default, links will be left untouched if the text is shorter than the
995      * configured maximum notice length. Pass true for the $always parameter
996      * to force all links to be shortened regardless.
997      *
998      * Side effects: may save file and file_redirection records for referenced URLs.
999      *
1000      * @param string $text
1001      * @param boolean $always
1002      * @return string
1003      */
1004     public function shortenLinks($text, $always=false)
1005     {
1006         return common_shorten_links($text, $always, $this);
1007     }
1008
1009     /*
1010      * Get a list of OAuth client applications that have access to this
1011      * user's account.
1012      */
1013     function getConnectedApps($offset = 0, $limit = null)
1014     {
1015         $qry =
1016           'SELECT u.* ' .
1017           'FROM oauth_application_user u, oauth_application a ' .
1018           'WHERE u.profile_id = %d ' .
1019           'AND a.id = u.application_id ' .
1020           'AND u.access_type > 0 ' .
1021           'ORDER BY u.created DESC ';
1022
1023         if ($offset > 0) {
1024             if (common_config('db','type') == 'pgsql') {
1025                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
1026             } else {
1027                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
1028             }
1029         }
1030
1031         $apps = new Oauth_application_user();
1032
1033         $cnt = $apps->query(sprintf($qry, $this->id));
1034
1035         return $apps;
1036     }
1037
1038 }