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