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