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