]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
d0eba7f75b4d8c21b816d8452f1b1a3a6ecd1726
[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' => 1, '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 = null;
117
118     /**
119      * @return Profile
120      *
121      * @throws UserNoProfileException if user has no profile
122      */
123     public function getProfile()
124     {
125         if (!($this->_profile instanceof Profile)) {
126             $this->_profile = Profile::getKV('id', $this->id);
127             if (!($this->_profile instanceof Profile)) {
128                 throw new UserNoProfileException($this);
129             }
130         }
131
132         return $this->_profile;
133     }
134
135     function isSubscribed(Profile $other)
136     {
137         return $this->getProfile()->isSubscribed($other);
138     }
139
140     function hasPendingSubscription($other)
141     {
142         return $this->getProfile()->hasPendingSubscription($other);
143     }
144
145     // 'update' won't write key columns, so we have to do it ourselves.
146
147     function updateKeys(&$orig)
148     {
149         $this->_connect();
150         $parts = array();
151         foreach (array('nickname', 'email', 'incomingemail', 'sms', 'carrier', 'smsemail') as $k) {
152             if (strcmp($this->$k, $orig->$k) != 0) {
153                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
154             }
155         }
156         if (count($parts) == 0) {
157             // No changes
158             return true;
159         }
160         $toupdate = implode(', ', $parts);
161
162         $table = common_database_tablename($this->tableName());
163         $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
164           ' WHERE id = ' . $this->id;
165         $orig->decache();
166         $result = $this->query($qry);
167         if ($result) {
168             $this->encache();
169         }
170         return $result;
171     }
172
173     /**
174      * Get the most recent notice posted by this user, if any.
175      *
176      * @return mixed Notice or null
177      */
178     function getCurrentNotice()
179     {
180         return $this->getProfile()->getCurrentNotice();
181     }
182
183     function getCarrier()
184     {
185         return Sms_carrier::getKV('id', $this->carrier);
186     }
187
188     function hasBlocked($other)
189     {
190         return $this->getProfile()->hasBlocked($other);
191     }
192
193     /**
194      * Register a new user account and profile and set up default subscriptions.
195      * If a new-user welcome message is configured, this will be sent.
196      *
197      * @param array $fields associative array of optional properties
198      *              string 'bio'
199      *              string 'email'
200      *              bool 'email_confirmed' pass true to mark email as pre-confirmed
201      *              string 'fullname'
202      *              string 'homepage'
203      *              string 'location' informal string description of geolocation
204      *              float 'lat' decimal latitude for geolocation
205      *              float 'lon' decimal longitude for geolocation
206      *              int 'location_id' geoname identifier
207      *              int 'location_ns' geoname namespace to interpret location_id
208      *              string 'nickname' REQUIRED
209      *              string 'password' (may be missing for eg OpenID registrations)
210      *              string 'code' invite code
211      *              ?string 'uri' permalink to notice; defaults to local notice URL
212      * @return mixed User object or false on failure
213      */
214     static function register(array $fields) {
215
216         // MAGICALLY put fields into current scope
217
218         extract($fields);
219
220         $profile = new Profile();
221
222         if (!empty($email)) {
223             $email = common_canonical_email($email);
224         }
225
226         try {
227             $profile->nickname = Nickname::normalize($nickname, true);
228         } catch (NicknameException $e) {
229             common_log(LOG_WARNING, sprintf('Bad nickname during User registration for %s: %s', $nickname, $e->getMessage()), __FILE__);
230             return false;
231         }
232
233         $profile->profileurl = common_profile_url($profile->nickname);
234
235         if (!empty($fullname)) {
236             $profile->fullname = $fullname;
237         }
238         if (!empty($homepage)) {
239             $profile->homepage = $homepage;
240         }
241         if (!empty($bio)) {
242             $profile->bio = $bio;
243         }
244         if (!empty($location)) {
245             $profile->location = $location;
246
247             $loc = Location::fromName($location);
248
249             if (!empty($loc)) {
250                 $profile->lat         = $loc->lat;
251                 $profile->lon         = $loc->lon;
252                 $profile->location_id = $loc->location_id;
253                 $profile->location_ns = $loc->location_ns;
254             }
255         }
256
257         $profile->created = common_sql_now();
258
259         $user = new User();
260
261         $user->nickname = $profile->nickname;
262
263         $invite = null;
264
265         // Users who respond to invite email have proven their ownership of that address
266
267         if (!empty($code)) {
268             $invite = Invitation::getKV($code);
269             if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
270                 $user->email = $invite->address;
271             }
272         }
273
274         if(isset($email_confirmed) && $email_confirmed) {
275             $user->email = $email;
276         }
277
278         // Set default-on options here, otherwise they'll be disabled
279         // initially for sites using caching, since the initial encache
280         // doesn't know about the defaults in the database.
281         $user->emailnotifysub = 1;
282         $user->emailnotifyfav = 1;
283         $user->emailnotifynudge = 1;
284         $user->emailnotifymsg = 1;
285         $user->emailnotifyattn = 1;
286         $user->emailmicroid = 1;
287         $user->emailpost = 1;
288         $user->jabbermicroid = 1;
289
290         $user->created = common_sql_now();
291
292         if (Event::handle('StartUserRegister', array($profile))) {
293
294             $profile->query('BEGIN');
295
296             $id = $profile->insert();
297             if ($id === false) {
298                 common_log_db_error($profile, 'INSERT', __FILE__);
299                 return false;
300             }
301
302             $user->id = $id;
303
304             if (!empty($uri)) {
305                 $user->uri = $uri;
306             } else {
307                 $user->uri = common_user_uri($user);
308             }
309
310             if (!empty($password)) { // may not have a password for OpenID users
311                 $user->password = common_munge_password($password, $id);
312             }
313
314             $result = $user->insert();
315
316             if ($result === false) {
317                 common_log_db_error($user, 'INSERT', __FILE__);
318                 $profile->query('ROLLBACK');
319                 return false;
320             }
321
322             // Everyone is subscribed to themself
323
324             $subscription = new Subscription();
325             $subscription->subscriber = $user->id;
326             $subscription->subscribed = $user->id;
327             $subscription->created = $user->created;
328
329             $result = $subscription->insert();
330
331             if (!$result) {
332                 common_log_db_error($subscription, 'INSERT', __FILE__);
333                 $profile->query('ROLLBACK');
334                 return false;
335             }
336
337             // Mark that this invite was converted
338
339             if (!empty($invite)) {
340                 $invite->convert($user);
341             }
342
343             if (!empty($email) && !$user->email) {
344
345                 $confirm = new Confirm_address();
346                 $confirm->code = common_confirmation_code(128);
347                 $confirm->user_id = $user->id;
348                 $confirm->address = $email;
349                 $confirm->address_type = 'email';
350
351                 $result = $confirm->insert();
352
353                 if (!$result) {
354                     common_log_db_error($confirm, 'INSERT', __FILE__);
355                     $profile->query('ROLLBACK');
356                     return false;
357                 }
358             }
359
360             if (!empty($code) && $user->email) {
361                 $user->emailChanged();
362             }
363
364             // Default system subscription
365
366             $defnick = common_config('newuser', 'default');
367
368             if (!empty($defnick)) {
369                 $defuser = User::getKV('nickname', $defnick);
370                 if (empty($defuser)) {
371                     common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
372                                __FILE__);
373                 } else {
374                     Subscription::start($profile, $defuser->getProfile());
375                 }
376             }
377
378             $profile->query('COMMIT');
379
380             if (!empty($email) && !$user->email) {
381                 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
382             }
383
384             // Welcome message
385
386             $welcome = common_config('newuser', 'welcome');
387
388             if (!empty($welcome)) {
389                 $welcomeuser = User::getKV('nickname', $welcome);
390                 if (empty($welcomeuser)) {
391                     common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
392                                __FILE__);
393                 } else {
394                     $notice = Notice::saveNew($welcomeuser->id,
395                                               // TRANS: Notice given on user registration.
396                                               // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
397                                               sprintf(_('Welcome to %1$s, @%2$s!'),
398                                                       common_config('site', 'name'),
399                                                       $user->nickname),
400                                               'system');
401                 }
402             }
403
404             Event::handle('EndUserRegister', array($profile));
405         }
406
407         return $user;
408     }
409
410     // Things we do when the email changes
411     function emailChanged()
412     {
413
414         $invites = new Invitation();
415         $invites->address = $this->email;
416         $invites->address_type = 'email';
417
418         if ($invites->find()) {
419             while ($invites->fetch()) {
420                 try {
421                     $other = Profile::getKV('id', $invites->user_id);
422                     if (!($other instanceof Profile)) {    // remove when getKV throws exceptions
423                         continue;
424                     }
425                     Subscription::start($other, $this->getProfile());
426                 } catch (Exception $e) {
427                     continue;
428                 }
429             }
430         }
431     }
432
433     function hasFave($notice)
434     {
435         return $this->getProfile()->hasFave($notice);
436     }
437
438     function mutuallySubscribed($other)
439     {
440         return $this->getProfile()->mutuallySubscribed($other);
441     }
442
443     function mutuallySubscribedUsers()
444     {
445         // 3-way join; probably should get cached
446         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
447         $qry = "SELECT $UT.* " .
448           "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
449           "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
450           'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
451           "ORDER BY $UT.nickname";
452         $user = new User();
453         $user->query(sprintf($qry, $this->id, $this->id));
454
455         return $user;
456     }
457
458     function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
459     {
460         return Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
461     }
462
463     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
464         return $this->getProfile()->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
465     }
466
467     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
468     {
469         return $this->getProfile()->getNotices($offset, $limit, $since_id, $before_id);
470     }
471
472     function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
473     {
474         return $this->getProfile()->favoriteNotices($own, $offset, $limit, $since_id, $max_id);
475     }
476
477     function blowFavesCache()
478     {
479         $this->getProfile()->blowFavesCache();
480     }
481
482     function getSelfTags()
483     {
484         return Profile_tag::getTagsArray($this->id, $this->id, $this->id);
485     }
486
487     function setSelfTags($newtags, $privacy)
488     {
489         return Profile_tag::setTags($this->id, $this->id, $newtags, $privacy);
490     }
491
492     function block(Profile $other)
493     {
494         // Add a new block record
495
496         // no blocking (and thus unsubbing from) yourself
497
498         if ($this->id == $other->id) {
499             common_log(LOG_WARNING,
500                 sprintf(
501                     "Profile ID %d (%s) tried to block themself.",
502                     $this->id,
503                     $this->nickname
504                 )
505             );
506             return false;
507         }
508
509         $block = new Profile_block();
510
511         // Begin a transaction
512
513         $block->query('BEGIN');
514
515         $block->blocker = $this->id;
516         $block->blocked = $other->id;
517
518         $result = $block->insert();
519
520         if (!$result) {
521             common_log_db_error($block, 'INSERT', __FILE__);
522             return false;
523         }
524
525         $self = $this->getProfile();
526         if (Subscription::exists($other, $self)) {
527             Subscription::cancel($other, $self);
528         }
529         if (Subscription::exists($self, $other)) {
530             Subscription::cancel($self, $other);
531         }
532
533         $block->query('COMMIT');
534
535         return true;
536     }
537
538     function unblock(Profile $other)
539     {
540         // Get the block record
541
542         $block = Profile_block::exists($this->getProfile(), $other);
543
544         if (!$block) {
545             return false;
546         }
547
548         $result = $block->delete();
549
550         if (!$result) {
551             common_log_db_error($block, 'DELETE', __FILE__);
552             return false;
553         }
554
555         return true;
556     }
557
558     function isMember(User_group $group)
559     {
560         return $this->getProfile()->isMember($group);
561     }
562
563     function isAdmin(User_group $group)
564     {
565         return $this->getProfile()->isAdmin($group);
566     }
567
568     function getGroups($offset=0, $limit=null)
569     {
570         return $this->getProfile()->getGroups($offset, $limit);
571     }
572
573     /**
574      * Request to join the given group.
575      * May throw exceptions on failure.
576      *
577      * @param User_group $group
578      * @return Group_member
579      */
580     function joinGroup(User_group $group)
581     {
582         return $this->getProfile()->joinGroup($group);
583     }
584
585     /**
586      * Leave a group that this user is a member of.
587      *
588      * @param User_group $group
589      */
590     function leaveGroup(User_group $group)
591     {
592         return $this->getProfile()->leaveGroup($group);
593     }
594
595     function getSubscribed($offset=0, $limit=null)
596     {
597         return $this->getProfile()->getSubscribed($offset, $limit);
598     }
599
600     function getSubscribers($offset=0, $limit=null)
601     {
602         return $this->getProfile()->getSubscribers($offset, $limit);
603     }
604
605     function getTaggedSubscribers($tag, $offset=0, $limit=null)
606     {
607         return $this->getProfile()->getTaggedSubscribers($tag, $offset, $limit);
608     }
609
610     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
611     {
612         return $this->getProfile()->getTaggedSubscriptions($tag, $offset, $limit);
613     }
614
615     function hasRight($right)
616     {
617         return $this->getProfile()->hasRight($right);
618     }
619
620     function delete($useWhere=false)
621     {
622         if (empty($this->id)) {
623             common_log(LOG_WARNING, "Ambiguous User->delete(); skipping related tables.");
624             return parent::delete($useWhere);
625         }
626
627         try {
628             $profile = $this->getProfile();
629             $profile->delete();
630         } catch (UserNoProfileException $unp) {
631             common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
632         }
633
634         $related = array('Fave',
635                          'Confirm_address',
636                          'Remember_me',
637                          'Foreign_link',
638                          'Invitation',
639                          );
640
641         Event::handle('UserDeleteRelated', array($this, &$related));
642
643         foreach ($related as $cls) {
644             $inst = new $cls();
645             $inst->user_id = $this->id;
646             $inst->delete();
647         }
648
649         $this->_deleteTags();
650         $this->_deleteBlocks();
651
652         return parent::delete($useWhere);
653     }
654
655     function _deleteTags()
656     {
657         $tag = new Profile_tag();
658         $tag->tagger = $this->id;
659         $tag->delete();
660     }
661
662     function _deleteBlocks()
663     {
664         $block = new Profile_block();
665         $block->blocker = $this->id;
666         $block->delete();
667         // XXX delete group block? Reset blocker?
668     }
669
670     function hasRole($name)
671     {
672         return $this->getProfile()->hasRole($name);
673     }
674
675     function grantRole($name)
676     {
677         return $this->getProfile()->grantRole($name);
678     }
679
680     function revokeRole($name)
681     {
682         return $this->getProfile()->revokeRole($name);
683     }
684
685     function isSandboxed()
686     {
687         return $this->getProfile()->isSandboxed();
688     }
689
690     function isSilenced()
691     {
692         return $this->getProfile()->isSilenced();
693     }
694
695     function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
696     {
697         $stream = new RepeatedByMeNoticeStream($this);
698         return $stream->getNotices($offset, $limit, $since_id, $max_id);
699     }
700
701
702     function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
703     {
704         $stream = new RepeatsOfMeNoticeStream($this);
705
706         return $stream->getNotices($offset, $limit, $since_id, $max_id);
707     }
708
709
710     function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
711     {
712         // TRANS: Exception thrown when trying view "repeated to me".
713         throw new Exception(_('Not implemented since inbox change.'));
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         $user = User::getKV('email', common_canonical_email($nore));
872
873         if (!$user) {
874             try {
875                 $user = User::getKV('nickname', common_canonical_nickname($nore));
876             } catch (NicknameException $e) {
877                 // invalid
878             }
879         }
880
881         // See if it's an unconfirmed email address
882
883         if (!$user) {
884             // Warning: it may actually be legit to have multiple folks
885             // who have claimed, but not yet confirmed, the same address.
886             // We'll only send to the first one that comes up.
887             $confirm_email = new Confirm_address();
888             $confirm_email->address = common_canonical_email($nore);
889             $confirm_email->address_type = 'email';
890             $confirm_email->find();
891             if ($confirm_email->fetch()) {
892                 $user = User::getKV($confirm_email->user_id);
893             } else {
894                 $confirm_email = null;
895             }
896         } else {
897             $confirm_email = null;
898         }
899
900         if (!$user) {
901             // TRANS: Information on password recovery form if no known username or e-mail address was specified.
902             throw new ClientException(_('No user with that email address or username.'));
903             return;
904         }
905
906         // Try to get an unconfirmed email address if they used a user name
907
908         if (!$user->email && !$confirm_email) {
909             $confirm_email = new Confirm_address();
910             $confirm_email->user_id = $user->id;
911             $confirm_email->address_type = 'email';
912             $confirm_email->find();
913             if (!$confirm_email->fetch()) {
914                 $confirm_email = null;
915             }
916         }
917
918         if (!$user->email && !$confirm_email) {
919             // TRANS: Client error displayed on password recovery form if a user does not have a registered e-mail address.
920             throw new ClientException(_('No registered email address for that user.'));
921             return;
922         }
923
924         // Success! We have a valid user and a confirmed or unconfirmed email address
925
926         $confirm = new Confirm_address();
927         $confirm->code = common_confirmation_code(128);
928         $confirm->address_type = 'recover';
929         $confirm->user_id = $user->id;
930         $confirm->address = (!empty($user->email)) ? $user->email : $confirm_email->address;
931
932         if (!$confirm->insert()) {
933             common_log_db_error($confirm, 'INSERT', __FILE__);
934             // TRANS: Server error displayed if e-mail address confirmation fails in the database on the password recovery form.
935             throw new ServerException(_('Error saving address confirmation.'));
936             return;
937         }
938
939          // @todo FIXME: needs i18n.
940         $body = "Hey, $user->nickname.";
941         $body .= "\n\n";
942         $body .= 'Someone just asked for a new password ' .
943                  'for this account on ' . common_config('site', 'name') . '.';
944         $body .= "\n\n";
945         $body .= 'If it was you, and you want to confirm, use the URL below:';
946         $body .= "\n\n";
947         $body .= "\t".common_local_url('recoverpassword',
948                                    array('code' => $confirm->code));
949         $body .= "\n\n";
950         $body .= 'If not, just ignore this message.';
951         $body .= "\n\n";
952         $body .= 'Thanks for your time, ';
953         $body .= "\n";
954         $body .= common_config('site', 'name');
955         $body .= "\n";
956
957         $headers = _mail_prepare_headers('recoverpassword', $user->nickname, $user->nickname);
958         // TRANS: Subject for password recovery e-mail.
959         mail_to_user($user, _('Password recovery requested'), $body, $headers, $confirm->address);
960     }
961
962     function streamModeOnly()
963     {
964         if (common_config('oldschool', 'enabled')) {
965             $osp = Old_school_prefs::getKV('user_id', $this->id);
966             if (!empty($osp)) {
967                 return $osp->stream_mode_only;
968             }
969         }
970
971         return false;
972     }
973
974     function conversationTree()
975     {
976         if (common_config('oldschool', 'enabled')) {
977             $osp = Old_school_prefs::getKV('user_id', $this->id);
978             if (!empty($osp)) {
979                 return $osp->conversation_tree;
980             }
981         }
982
983         return false;
984     }
985
986     function streamNicknames()
987     {
988         if (common_config('oldschool', 'enabled')) {
989             $osp = Old_school_prefs::getKV('user_id', $this->id);
990             if (!empty($osp)) {
991                 return $osp->stream_nicknames;
992             }
993         }
994         return false;
995     }
996
997     function registrationActivity()
998     {
999         $profile = $this->getProfile();
1000
1001         $service = new ActivityObject();
1002
1003         $service->type  = ActivityObject::SERVICE;
1004         $service->title = common_config('site', 'name');
1005         $service->link  = common_root_url();
1006         $service->id    = $service->link;
1007
1008         $act = new Activity();
1009
1010         $act->actor = ActivityObject::fromProfile($profile);
1011         $act->verb = ActivityVerb::JOIN;
1012
1013         $act->objects[] = $service;
1014
1015         $act->id = TagURI::mint('user:register:%d',
1016                                 $this->id);
1017
1018         $act->time = strtotime($this->created);
1019
1020         $act->title = _("Register");
1021
1022         $act->content = sprintf(_('%1$s joined %2$s.'),
1023                                 $profile->getBestName(),
1024                                 $service->title);
1025         return $act;
1026     }
1027 }