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