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