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