]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
New NoticeStream class to reify streams of notices
[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         return Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
452     }
453
454     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
455         $profile = $this->getProfile();
456         return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
457     }
458
459     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
460     {
461         $profile = $this->getProfile();
462         return $profile->getNotices($offset, $limit, $since_id, $before_id);
463     }
464
465     function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
466     {
467         return Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
468     }
469
470     function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
471     {
472         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
473     }
474
475     function noticesWithFriendsThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
476     {
477         return Inbox::streamNoticesThreaded($this->id, $offset, $limit, $since_id, $before_id, false);
478     }
479
480     function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
481     {
482         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
483     }
484
485     function noticeInboxThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
486     {
487         return Inbox::streamNoticesThreaded($this->id, $offset, $limit, $since_id, $before_id, true);
488     }
489
490     function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
491     {
492         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, false);
493     }
494
495     function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
496     {
497         return Inbox::streamNotices($this->id, $offset, $limit, $since_id, $before_id, true);
498     }
499
500     function blowFavesCache()
501     {
502         $profile = $this->getProfile();
503         $profile->blowFavesCache();
504     }
505
506     function getSelfTags()
507     {
508         return Profile_tag::getTags($this->id, $this->id);
509     }
510
511     function setSelfTags($newtags)
512     {
513         return Profile_tag::setTags($this->id, $this->id, $newtags);
514     }
515
516     function block($other)
517     {
518         // Add a new block record
519
520         // no blocking (and thus unsubbing from) yourself
521
522         if ($this->id == $other->id) {
523             common_log(LOG_WARNING,
524                 sprintf(
525                     "Profile ID %d (%s) tried to block themself.",
526                     $this->id,
527                     $this->nickname
528                 )
529             );
530             return false;
531         }
532
533         $block = new Profile_block();
534
535         // Begin a transaction
536
537         $block->query('BEGIN');
538
539         $block->blocker = $this->id;
540         $block->blocked = $other->id;
541
542         $result = $block->insert();
543
544         if (!$result) {
545             common_log_db_error($block, 'INSERT', __FILE__);
546             return false;
547         }
548
549         $self = $this->getProfile();
550         if (Subscription::exists($other, $self)) {
551             Subscription::cancel($other, $self);
552         }
553         if (Subscription::exists($self, $other)) {
554             Subscription::cancel($self, $other);
555         }
556
557         $block->query('COMMIT');
558
559         return true;
560     }
561
562     function unblock($other)
563     {
564         // Get the block record
565
566         $block = Profile_block::get($this->id, $other->id);
567
568         if (!$block) {
569             return false;
570         }
571
572         $result = $block->delete();
573
574         if (!$result) {
575             common_log_db_error($block, 'DELETE', __FILE__);
576             return false;
577         }
578
579         return true;
580     }
581
582     function isMember($group)
583     {
584         $profile = $this->getProfile();
585         return $profile->isMember($group);
586     }
587
588     function isAdmin($group)
589     {
590         $profile = $this->getProfile();
591         return $profile->isAdmin($group);
592     }
593
594     function getGroups($offset=0, $limit=null)
595     {
596         $profile = $this->getProfile();
597         return $profile->getGroups($offset, $limit);
598     }
599
600     /**
601      * Request to join the given group.
602      * May throw exceptions on failure.
603      *
604      * @param User_group $group
605      * @return Group_member
606      */
607     function joinGroup(User_group $group)
608     {
609         $profile = $this->getProfile();
610         return $profile->joinGroup($group);
611     }
612
613     /**
614      * Leave a group that this user is a member of.
615      *
616      * @param User_group $group
617      */
618     function leaveGroup(User_group $group)
619     {
620         $profile = $this->getProfile();
621         return $profile->leaveGroup($group);
622     }
623
624     function getSubscriptions($offset=0, $limit=null)
625     {
626         $profile = $this->getProfile();
627         return $profile->getSubscriptions($offset, $limit);
628     }
629
630     function getSubscribers($offset=0, $limit=null)
631     {
632         $profile = $this->getProfile();
633         return $profile->getSubscribers($offset, $limit);
634     }
635
636     function getTaggedSubscribers($tag, $offset=0, $limit=null)
637     {
638         $qry =
639           'SELECT profile.* ' .
640           'FROM profile JOIN subscription ' .
641           'ON profile.id = subscription.subscriber ' .
642           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
643           'AND profile_tag.tagger = subscription.subscribed) ' .
644           'WHERE subscription.subscribed = %d ' .
645           "AND profile_tag.tag = '%s' " .
646           'AND subscription.subscribed != subscription.subscriber ' .
647           'ORDER BY subscription.created DESC ';
648
649         if ($offset) {
650             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
651         }
652
653         $profile = new Profile();
654
655         $cnt = $profile->query(sprintf($qry, $this->id, $tag));
656
657         return $profile;
658     }
659
660     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
661     {
662         $qry =
663           'SELECT profile.* ' .
664           'FROM profile JOIN subscription ' .
665           'ON profile.id = subscription.subscribed ' .
666           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
667           'AND profile_tag.tagger = subscription.subscriber) ' .
668           'WHERE subscription.subscriber = %d ' .
669           "AND profile_tag.tag = '%s' " .
670           'AND subscription.subscribed != subscription.subscriber ' .
671           'ORDER BY subscription.created DESC ';
672
673         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
674
675         $profile = new Profile();
676
677         $profile->query(sprintf($qry, $this->id, $tag));
678
679         return $profile;
680     }
681
682     function getDesign()
683     {
684         return Design::staticGet('id', $this->design_id);
685     }
686
687     function hasRight($right)
688     {
689         $profile = $this->getProfile();
690         return $profile->hasRight($right);
691     }
692
693     function delete()
694     {
695         try {
696             $profile = $this->getProfile();
697             $profile->delete();
698         } catch (UserNoProfileException $unp) {
699             common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
700         }
701
702         $related = array('Fave',
703                          'Confirm_address',
704                          'Remember_me',
705                          'Foreign_link',
706                          'Invitation',
707                          );
708
709         Event::handle('UserDeleteRelated', array($this, &$related));
710
711         foreach ($related as $cls) {
712             $inst = new $cls();
713             $inst->user_id = $this->id;
714             $inst->delete();
715         }
716
717         $this->_deleteTags();
718         $this->_deleteBlocks();
719
720         parent::delete();
721     }
722
723     function _deleteTags()
724     {
725         $tag = new Profile_tag();
726         $tag->tagger = $this->id;
727         $tag->delete();
728     }
729
730     function _deleteBlocks()
731     {
732         $block = new Profile_block();
733         $block->blocker = $this->id;
734         $block->delete();
735         // XXX delete group block? Reset blocker?
736     }
737
738     function hasRole($name)
739     {
740         $profile = $this->getProfile();
741         return $profile->hasRole($name);
742     }
743
744     function grantRole($name)
745     {
746         $profile = $this->getProfile();
747         return $profile->grantRole($name);
748     }
749
750     function revokeRole($name)
751     {
752         $profile = $this->getProfile();
753         return $profile->revokeRole($name);
754     }
755
756     function isSandboxed()
757     {
758         $profile = $this->getProfile();
759         return $profile->isSandboxed();
760     }
761
762     function isSilenced()
763     {
764         $profile = $this->getProfile();
765         return $profile->isSilenced();
766     }
767
768     function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
769     {
770         $stream = new NoticeStream(array($this, '_repeatedByMeDirect'),
771                                    array(),
772                                    'user:repeated_by_me:'.$this->id);
773
774         return $stream->getNotices($offset, $limit, $since_id, $max_id);
775     }
776
777     function _repeatedByMeDirect($offset, $limit, $since_id, $max_id)
778     {
779         $notice = new Notice();
780
781         $notice->selectAdd(); // clears it
782         $notice->selectAdd('id');
783
784         $notice->profile_id = $this->id;
785         $notice->whereAdd('repeat_of IS NOT NULL');
786
787         $notice->orderBy('created DESC, id DESC');
788
789         if (!is_null($offset)) {
790             $notice->limit($offset, $limit);
791         }
792
793         Notice::addWhereSinceId($notice, $since_id);
794         Notice::addWhereMaxId($notice, $max_id);
795
796         $ids = array();
797
798         if ($notice->find()) {
799             while ($notice->fetch()) {
800                 $ids[] = $notice->id;
801             }
802         }
803
804         $notice->free();
805         $notice = NULL;
806
807         return $ids;
808     }
809
810     function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
811     {
812         $stream = new NoticeStream(array($this, '_repeatsOfMeDirect'),
813                                    array(),
814                                    'user:repeats_of_me:'.$this->id);
815
816         return $stream->getNotices($offset, $limit, $since_id, $max_id);
817     }
818
819     function _repeatsOfMeDirect($offset, $limit, $since_id, $max_id)
820     {
821         $qry =
822           'SELECT DISTINCT original.id AS id ' .
823           'FROM notice original JOIN notice rept ON original.id = rept.repeat_of ' .
824           'WHERE original.profile_id = ' . $this->id . ' ';
825
826         $since = Notice::whereSinceId($since_id, 'original.id', 'original.created');
827         if ($since) {
828             $qry .= "AND ($since) ";
829         }
830
831         $max = Notice::whereMaxId($max_id, 'original.id', 'original.created');
832         if ($max) {
833             $qry .= "AND ($max) ";
834         }
835
836         $qry .= 'ORDER BY original.created, original.id DESC ';
837
838         if (!is_null($offset)) {
839             $qry .= "LIMIT $limit OFFSET $offset";
840         }
841
842         $ids = array();
843
844         $notice = new Notice();
845
846         $notice->query($qry);
847
848         while ($notice->fetch()) {
849             $ids[] = $notice->id;
850         }
851
852         $notice->free();
853         $notice = NULL;
854
855         return $ids;
856     }
857
858     function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
859     {
860         throw new Exception("Not implemented since inbox change.");
861     }
862
863     function shareLocation()
864     {
865         $cfg = common_config('location', 'share');
866
867         if ($cfg == 'always') {
868             return true;
869         } else if ($cfg == 'never') {
870             return false;
871         } else { // user
872             $share = true;
873
874             $prefs = User_location_prefs::staticGet('user_id', $this->id);
875
876             if (empty($prefs)) {
877                 $share = common_config('location', 'sharedefault');
878             } else {
879                 $share = $prefs->share_location;
880                 $prefs->free();
881             }
882
883             return $share;
884         }
885     }
886
887     static function siteOwner()
888     {
889         $owner = self::cacheGet('user:site_owner');
890
891         if ($owner === false) { // cache miss
892
893             $pr = new Profile_role();
894
895             $pr->role = Profile_role::OWNER;
896
897             $pr->orderBy('created');
898
899             $pr->limit(1);
900
901             if ($pr->find(true)) {
902                 $owner = User::staticGet('id', $pr->profile_id);
903             } else {
904                 $owner = null;
905             }
906
907             self::cacheSet('user:site_owner', $owner);
908         }
909
910         return $owner;
911     }
912
913     /**
914      * Pull the primary site account to use in single-user mode.
915      * If a valid user nickname is listed in 'singleuser':'nickname'
916      * in the config, this will be used; otherwise the site owner
917      * account is taken by default.
918      *
919      * @return User
920      * @throws ServerException if no valid single user account is present
921      * @throws ServerException if called when not in single-user mode
922      */
923     static function singleUser()
924     {
925         if (common_config('singleuser', 'enabled')) {
926
927             $user = null;
928
929             $nickname = common_config('singleuser', 'nickname');
930
931             if (!empty($nickname)) {
932                 $user = User::staticGet('nickname', $nickname);
933             }
934
935             // if there was no nickname or no user by that nickname,
936             // try the site owner.
937
938             if (empty($user)) {
939                 $user = User::siteOwner();
940             }
941
942             if (!empty($user)) {
943                 return $user;
944             } else {
945                 // TRANS: Server exception.
946                 throw new ServerException(_('No single user defined for single-user mode.'));
947             }
948         } else {
949             // TRANS: Server exception.
950             throw new ServerException(_('Single-user mode code called when not enabled.'));
951         }
952     }
953
954     /**
955      * This is kind of a hack for using external setup code that's trying to
956      * build single-user sites.
957      *
958      * Will still return a username if the config singleuser/nickname is set
959      * even if the account doesn't exist, which normally indicates that the
960      * site is horribly misconfigured.
961      *
962      * At the moment, we need to let it through so that router setup can
963      * complete, otherwise we won't be able to create the account.
964      *
965      * This will be easier when we can more easily create the account and
966      * *then* switch the site to 1user mode without jumping through hoops.
967      *
968      * @return string
969      * @throws ServerException if no valid single user account is present
970      * @throws ServerException if called when not in single-user mode
971      */
972     static function singleUserNickname()
973     {
974         try {
975             $user = User::singleUser();
976             return $user->nickname;
977         } catch (Exception $e) {
978             if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
979                 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.");
980                 return common_config('singleuser', 'nickname');
981             }
982             throw $e;
983         }
984     }
985
986     /**
987      * Find and shorten links in the given text using this user's URL shortening
988      * settings.
989      *
990      * By default, links will be left untouched if the text is shorter than the
991      * configured maximum notice length. Pass true for the $always parameter
992      * to force all links to be shortened regardless.
993      *
994      * Side effects: may save file and file_redirection records for referenced URLs.
995      *
996      * @param string $text
997      * @param boolean $always
998      * @return string
999      */
1000     public function shortenLinks($text, $always=false)
1001     {
1002         return common_shorten_links($text, $always, $this);
1003     }
1004
1005     /*
1006      * Get a list of OAuth client applications that have access to this
1007      * user's account.
1008      */
1009     function getConnectedApps($offset = 0, $limit = null)
1010     {
1011         $qry =
1012           'SELECT u.* ' .
1013           'FROM oauth_application_user u, oauth_application a ' .
1014           'WHERE u.profile_id = %d ' .
1015           'AND a.id = u.application_id ' .
1016           'AND u.access_type > 0 ' .
1017           'ORDER BY u.created DESC ';
1018
1019         if ($offset > 0) {
1020             if (common_config('db','type') == 'pgsql') {
1021                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
1022             } else {
1023                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
1024             }
1025         }
1026
1027         $apps = new Oauth_application_user();
1028
1029         $cnt = $apps->query(sprintf($qry, $this->id));
1030
1031         return $apps;
1032     }
1033
1034 }