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