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