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