]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/User.php
Default to NOT ask for current location for new users
[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('STATUSNET') && !defined('LACONICA')) {
21     exit(1);
22 }
23
24 /**
25  * Table Definition for user
26  */
27
28 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
29 require_once 'Validate.php';
30
31 class User extends Managed_DataObject
32 {
33     const SUBSCRIBE_POLICY_OPEN = 0;
34     const SUBSCRIBE_POLICY_MODERATE = 1;
35
36     ###START_AUTOCODE
37     /* the code below is auto generated do not remove the above tag */
38
39     public $__table = 'user';                            // table name
40     public $id;                              // int(4)  primary_key not_null
41     public $nickname;                        // varchar(64)  unique_key
42     public $password;                        // varchar(255)
43     public $email;                           // varchar(255)  unique_key
44     public $incomingemail;                   // varchar(255)  unique_key
45     public $emailnotifysub;                  // tinyint(1)   default_1
46     public $emailnotifyfav;                  // tinyint(1)   default_1
47     public $emailnotifynudge;                // tinyint(1)   default_1
48     public $emailnotifymsg;                  // tinyint(1)   default_1
49     public $emailnotifyattn;                 // tinyint(1)   default_1
50     public $emailmicroid;                    // tinyint(1)   default_1
51     public $language;                        // varchar(50)
52     public $timezone;                        // varchar(50)
53     public $emailpost;                       // tinyint(1)   default_1
54     public $sms;                             // varchar(64)  unique_key
55     public $carrier;                         // int(4)
56     public $smsnotify;                       // tinyint(1)
57     public $smsreplies;                      // tinyint(1)
58     public $smsemail;                        // varchar(255)
59     public $uri;                             // varchar(255)  unique_key
60     public $autosubscribe;                   // tinyint(1)
61     public $subscribe_policy;                // tinyint(1)
62     public $urlshorteningservice;            // varchar(50)   default_ur1.ca
63     public $inboxed;                         // tinyint(1)
64     public $private_stream;                  // tinyint(1)   default_0
65     public $created;                         // datetime()   not_null
66     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
67
68     /* Static get */
69     function staticGet($k,$v=NULL) { return Memcached_DataObject::staticGet('User',$k,$v); }
70
71     /* the code above is auto generated do not remove the tag below */
72     ###END_AUTOCODE
73
74     public static function schemaDef()
75     {
76         return array(
77             'description' => 'local users',
78             'fields' => array(
79                 'id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
80                 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname or username, duped in profile'),
81                 'password' => array('type' => 'varchar', 'length' => 255, 'description' => 'salted password, can be null for OpenID users'),
82                 'email' => array('type' => 'varchar', 'length' => 255, 'description' => 'email address for password recovery etc.'),
83                 'incomingemail' => array('type' => 'varchar', 'length' => 255, 'description' => 'email address for post-by-email'),
84                 'emailnotifysub' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of subscriptions'),
85                 'emailnotifyfav' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of favorites'),
86                 'emailnotifynudge' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of nudges'),
87                 'emailnotifymsg' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of direct messages'),
88                 'emailnotifyattn' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Notify by email of @-replies'),
89                 'emailmicroid' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'whether to publish email microid'),
90                 'language' => array('type' => 'varchar', 'length' => 50, 'description' => 'preferred language'),
91                 'timezone' => array('type' => 'varchar', 'length' => 50, 'description' => 'timezone'),
92                 'emailpost' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'Post by email'),
93                 'sms' => array('type' => 'varchar', 'length' => 64, 'description' => 'sms phone number'),
94                 'carrier' => array('type' => 'int', 'description' => 'foreign key to sms_carrier'),
95                 'smsnotify' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to send notices to SMS'),
96                 'smsreplies' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to send notices to SMS on replies'),
97                 'smsemail' => array('type' => 'varchar', 'length' => 255, 'description' => 'built from sms and carrier'),
98                 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier, usually a tag URI'),
99                 'autosubscribe' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'automatically subscribe to users who subscribe to us'),
100                 'subscribe_policy' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => '0 = anybody can subscribe; 1 = require approval'),
101                 'urlshorteningservice' => array('type' => 'varchar', 'length' => 50, 'default' => 'internal', 'description' => 'service to use for auto-shortening URLs'),
102                 'inboxed' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'has an inbox been created for this user?'),
103                 'private_stream' => array('type' => 'int', 'size' => 'tiny', 'default' => 0, 'description' => 'whether to limit all notices to followers only'),
104
105                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
106                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
107             ),
108             'primary key' => array('id'),
109             'unique keys' => array(
110                 'user_nickname_key' => array('nickname'),
111                 'user_email_key' => array('email'),
112                 'user_incomingemail_key' => array('incomingemail'),
113                 'user_sms_key' => array('sms'),
114                 'user_uri_key' => array('uri'),
115             ),
116             'foreign keys' => array(
117                 'user_id_fkey' => array('profile', array('id' => 'id')),
118                 'user_carrier_fkey' => array('sms_carrier', array('carrier' => 'id')),
119             ),
120             'indexes' => array(
121                 'user_smsemail_idx' => array('smsemail'),
122             ),
123         );
124     }
125
126     protected $_profile = -1;
127
128     /**
129      * @return Profile
130      */
131     function getProfile()
132     {
133         if (is_int($this->_profile) && $this->_profile == -1) { // invalid but distinct from null
134             $this->_profile = Profile::staticGet('id', $this->id);
135             if (empty($this->_profile)) {
136                 throw new UserNoProfileException($this);
137             }
138         }
139
140         return $this->_profile;
141     }
142
143     function isSubscribed($other)
144     {
145         $profile = $this->getProfile();
146         return $profile->isSubscribed($other);
147     }
148
149     function hasPendingSubscription($other)
150     {
151         $profile = $this->getProfile();
152         return $profile->hasPendingSubscription($other);
153     }
154
155     // 'update' won't write key columns, so we have to do it ourselves.
156
157     function updateKeys(&$orig)
158     {
159         $this->_connect();
160         $parts = array();
161         foreach (array('nickname', 'email', 'incomingemail', 'sms', 'carrier', 'smsemail', 'language', 'timezone') as $k) {
162             if (strcmp($this->$k, $orig->$k) != 0) {
163                 $parts[] = $k . ' = ' . $this->_quote($this->$k);
164             }
165         }
166         if (count($parts) == 0) {
167             // No changes
168             return true;
169         }
170         $toupdate = implode(', ', $parts);
171
172         $table = common_database_tablename($this->tableName());
173         $qry = 'UPDATE ' . $table . ' SET ' . $toupdate .
174           ' WHERE id = ' . $this->id;
175         $orig->decache();
176         $result = $this->query($qry);
177         if ($result) {
178             $this->encache();
179         }
180         return $result;
181     }
182
183     /**
184      * Check whether the given nickname is potentially usable, or if it's
185      * excluded by any blacklists on this system.
186      *
187      * WARNING: INPUT IS NOT VALIDATED OR NORMALIZED. NON-NORMALIZED INPUT
188      * OR INVALID INPUT MAY LEAD TO FALSE RESULTS.
189      *
190      * @param string $nickname
191      * @return boolean true if clear, false if blacklisted
192      */
193     static function allowed_nickname($nickname)
194     {
195         // XXX: should already be validated for size, content, etc.
196         $blacklist = common_config('nickname', 'blacklist');
197
198         //all directory and file names should be blacklisted
199         $d = dir(INSTALLDIR);
200         while (false !== ($entry = $d->read())) {
201             $blacklist[]=$entry;
202         }
203         $d->close();
204
205         //all top level names in the router should be blacklisted
206         $router = Router::get();
207         foreach(array_keys($router->m->getPaths()) as $path){
208             if(preg_match('/^\/(.*?)[\/\?]/',$path,$matches)){
209                 $blacklist[]=$matches[1];
210             }
211         }
212         return !in_array($nickname, $blacklist);
213     }
214
215     /**
216      * Get the most recent notice posted by this user, if any.
217      *
218      * @return mixed Notice or null
219      */
220     function getCurrentNotice()
221     {
222         $profile = $this->getProfile();
223         return $profile->getCurrentNotice();
224     }
225
226     function getCarrier()
227     {
228         return Sms_carrier::staticGet('id', $this->carrier);
229     }
230
231     /**
232      * @deprecated use Subscription::start($sub, $other);
233      */
234     function subscribeTo($other)
235     {
236         return Subscription::start($this->getProfile(), $other);
237     }
238
239     function hasBlocked($other)
240     {
241         $profile = $this->getProfile();
242         return $profile->hasBlocked($other);
243     }
244
245     /**
246      * Register a new user account and profile and set up default subscriptions.
247      * If a new-user welcome message is configured, this will be sent.
248      *
249      * @param array $fields associative array of optional properties
250      *              string 'bio'
251      *              string 'email'
252      *              bool 'email_confirmed' pass true to mark email as pre-confirmed
253      *              string 'fullname'
254      *              string 'homepage'
255      *              string 'location' informal string description of geolocation
256      *              float 'lat' decimal latitude for geolocation
257      *              float 'lon' decimal longitude for geolocation
258      *              int 'location_id' geoname identifier
259      *              int 'location_ns' geoname namespace to interpret location_id
260      *              string 'nickname' REQUIRED
261      *              string 'password' (may be missing for eg OpenID registrations)
262      *              string 'code' invite code
263      *              ?string 'uri' permalink to notice; defaults to local notice URL
264      * @return mixed User object or false on failure
265      */
266     static function register($fields) {
267
268         // MAGICALLY put fields into current scope
269
270         extract($fields);
271
272         $profile = new Profile();
273
274         if(!empty($email))
275         {
276             $email = common_canonical_email($email);
277         }
278
279         $nickname = common_canonical_nickname($nickname);
280         $profile->nickname = $nickname;
281         if(! User::allowed_nickname($nickname)){
282             common_log(LOG_WARNING, sprintf("Attempted to register a nickname that is not allowed: %s", $profile->nickname),
283                        __FILE__);
284             return false;
285         }
286         $profile->profileurl = common_profile_url($nickname);
287
288         if (!empty($fullname)) {
289             $profile->fullname = $fullname;
290         }
291         if (!empty($homepage)) {
292             $profile->homepage = $homepage;
293         }
294         if (!empty($bio)) {
295             $profile->bio = $bio;
296         }
297         if (!empty($location)) {
298             $profile->location = $location;
299
300             $loc = Location::fromName($location);
301
302             if (!empty($loc)) {
303                 $profile->lat         = $loc->lat;
304                 $profile->lon         = $loc->lon;
305                 $profile->location_id = $loc->location_id;
306                 $profile->location_ns = $loc->location_ns;
307             }
308         }
309
310         $profile->created = common_sql_now();
311
312         $user = new User();
313
314         $user->nickname = $nickname;
315
316         $invite = null;
317
318         // Users who respond to invite email have proven their ownership of that address
319
320         if (!empty($code)) {
321             $invite = Invitation::staticGet($code);
322             if ($invite && $invite->address && $invite->address_type == 'email' && $invite->address == $email) {
323                 $user->email = $invite->address;
324             }
325         }
326
327         if(isset($email_confirmed) && $email_confirmed) {
328             $user->email = $email;
329         }
330
331         // This flag is ignored but still set to 1
332
333         $user->inboxed = 1;
334
335         // Set default-on options here, otherwise they'll be disabled
336         // initially for sites using caching, since the initial encache
337         // doesn't know about the defaults in the database.
338         $user->emailnotifysub = 1;
339         $user->emailnotifyfav = 1;
340         $user->emailnotifynudge = 1;
341         $user->emailnotifymsg = 1;
342         $user->emailnotifyattn = 1;
343         $user->emailmicroid = 1;
344         $user->emailpost = 1;
345         $user->jabbermicroid = 1;
346
347         $user->created = common_sql_now();
348
349         if (Event::handle('StartUserRegister', array(&$user, &$profile))) {
350
351             $profile->query('BEGIN');
352
353             $id = $profile->insert();
354
355             if (empty($id)) {
356                 common_log_db_error($profile, 'INSERT', __FILE__);
357                 return false;
358             }
359
360             $user->id = $id;
361
362             if (!empty($uri)) {
363                 $user->uri = $uri;
364             } else {
365                 $user->uri = common_user_uri($user);
366             }
367
368             if (!empty($password)) { // may not have a password for OpenID users
369                 $user->password = common_munge_password($password, $id);
370             }
371
372             $result = $user->insert();
373
374             if (!$result) {
375                 common_log_db_error($user, 'INSERT', __FILE__);
376                 return false;
377             }
378
379             // Everyone gets an inbox
380
381             $inbox = new Inbox();
382
383             $inbox->user_id = $user->id;
384             $inbox->notice_ids = '';
385
386             $result = $inbox->insert();
387
388             if (!$result) {
389                 common_log_db_error($inbox, 'INSERT', __FILE__);
390                 return false;
391             }
392
393             // Everyone is subscribed to themself
394
395             $subscription = new Subscription();
396             $subscription->subscriber = $user->id;
397             $subscription->subscribed = $user->id;
398             $subscription->created = $user->created;
399
400             $result = $subscription->insert();
401
402             if (!$result) {
403                 common_log_db_error($subscription, 'INSERT', __FILE__);
404                 return false;
405             }
406
407             // Mark that this invite was converted
408
409             if (!empty($invite)) {
410                 $invite->convert($user);
411             }
412
413             if (!empty($email) && !$user->email) {
414
415                 $confirm = new Confirm_address();
416                 $confirm->code = common_confirmation_code(128);
417                 $confirm->user_id = $user->id;
418                 $confirm->address = $email;
419                 $confirm->address_type = 'email';
420
421                 $result = $confirm->insert();
422
423                 if (!$result) {
424                     common_log_db_error($confirm, 'INSERT', __FILE__);
425                     return false;
426                 }
427             }
428
429             if (!empty($code) && $user->email) {
430                 $user->emailChanged();
431             }
432
433             // Default system subscription
434
435             $defnick = common_config('newuser', 'default');
436
437             if (!empty($defnick)) {
438                 $defuser = User::staticGet('nickname', $defnick);
439                 if (empty($defuser)) {
440                     common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick),
441                                __FILE__);
442                 } else {
443                     Subscription::start($user, $defuser);
444                 }
445             }
446
447             $profile->query('COMMIT');
448
449             if (!empty($email) && !$user->email) {
450                 mail_confirm_address($user, $confirm->code, $profile->nickname, $email);
451             }
452
453             // Welcome message
454
455             $welcome = common_config('newuser', 'welcome');
456
457             if (!empty($welcome)) {
458                 $welcomeuser = User::staticGet('nickname', $welcome);
459                 if (empty($welcomeuser)) {
460                     common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick),
461                                __FILE__);
462                 } else {
463                     $notice = Notice::saveNew($welcomeuser->id,
464                                               // TRANS: Notice given on user registration.
465                                               // TRANS: %1$s is the sitename, $2$s is the registering user's nickname.
466                                               sprintf(_('Welcome to %1$s, @%2$s!'),
467                                                       common_config('site', 'name'),
468                                                       $user->nickname),
469                                               'system');
470                 }
471             }
472
473             Event::handle('EndUserRegister', array(&$profile, &$user));
474         }
475
476         return $user;
477     }
478
479     // Things we do when the email changes
480     function emailChanged()
481     {
482
483         $invites = new Invitation();
484         $invites->address = $this->email;
485         $invites->address_type = 'email';
486
487         if ($invites->find()) {
488             while ($invites->fetch()) {
489                 $other = User::staticGet($invites->user_id);
490                 subs_subscribe_to($other, $this);
491             }
492         }
493     }
494
495     function hasFave($notice)
496     {
497         $profile = $this->getProfile();
498         return $profile->hasFave($notice);
499     }
500
501     function mutuallySubscribed($other)
502     {
503         $profile = $this->getProfile();
504         return $profile->mutuallySubscribed($other);
505     }
506
507     function mutuallySubscribedUsers()
508     {
509         // 3-way join; probably should get cached
510         $UT = common_config('db','type')=='pgsql'?'"user"':'user';
511         $qry = "SELECT $UT.* " .
512           "FROM subscription sub1 JOIN $UT ON sub1.subscribed = $UT.id " .
513           "JOIN subscription sub2 ON $UT.id = sub2.subscriber " .
514           'WHERE sub1.subscriber = %d and sub2.subscribed = %d ' .
515           "ORDER BY $UT.nickname";
516         $user = new User();
517         $user->query(sprintf($qry, $this->id, $this->id));
518
519         return $user;
520     }
521
522     function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
523     {
524         return Reply::stream($this->id, $offset, $limit, $since_id, $before_id);
525     }
526
527     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0) {
528         $profile = $this->getProfile();
529         return $profile->getTaggedNotices($tag, $offset, $limit, $since_id, $before_id);
530     }
531
532     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
533     {
534         $profile = $this->getProfile();
535         return $profile->getNotices($offset, $limit, $since_id, $before_id);
536     }
537
538     function favoriteNotices($own=false, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
539     {
540         return Fave::stream($this->id, $offset, $limit, $own, $since_id, $max_id);
541     }
542
543     function noticeInbox($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
544     {
545         $stream = new InboxNoticeStream($this);
546         return $stream->getNotices($offset, $limit, $since_id, $before_id);
547     }
548
549     // DEPRECATED, use noticeInbox()
550
551     function noticesWithFriends($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
552     {
553         return $this->noticeInbox($offset, $limit, $since_id, $before_id);
554     }
555
556     // DEPRECATED, use noticeInbox()
557
558     function noticesWithFriendsThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
559     {
560         return $this->noticeInbox($offset, $limit, $since_id, $before_id);
561     }
562
563     // DEPRECATED, use noticeInbox()
564
565     function noticeInboxThreaded($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
566     {
567         return $this->noticeInbox($offset, $limit, $since_id, $before_id);
568     }
569
570     // DEPRECATED, use noticeInbox()
571
572     function friendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
573     {
574         return $this->noticeInbox($offset, $limit, $since_id, $before_id);
575     }
576
577     // DEPRECATED, use noticeInbox()
578
579     function ownFriendsTimeline($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
580     {
581         $this->noticeInbox($offset, $limit, $since_id, $before_id);
582     }
583
584     function blowFavesCache()
585     {
586         $profile = $this->getProfile();
587         $profile->blowFavesCache();
588     }
589
590     function getSelfTags()
591     {
592         return Profile_tag::getTagsArray($this->id, $this->id, $this->id);
593     }
594
595     function setSelfTags($newtags, $privacy)
596     {
597         return Profile_tag::setTags($this->id, $this->id, $newtags, $privacy);
598     }
599
600     function block($other)
601     {
602         // Add a new block record
603
604         // no blocking (and thus unsubbing from) yourself
605
606         if ($this->id == $other->id) {
607             common_log(LOG_WARNING,
608                 sprintf(
609                     "Profile ID %d (%s) tried to block themself.",
610                     $this->id,
611                     $this->nickname
612                 )
613             );
614             return false;
615         }
616
617         $block = new Profile_block();
618
619         // Begin a transaction
620
621         $block->query('BEGIN');
622
623         $block->blocker = $this->id;
624         $block->blocked = $other->id;
625
626         $result = $block->insert();
627
628         if (!$result) {
629             common_log_db_error($block, 'INSERT', __FILE__);
630             return false;
631         }
632
633         $self = $this->getProfile();
634         if (Subscription::exists($other, $self)) {
635             Subscription::cancel($other, $self);
636         }
637         if (Subscription::exists($self, $other)) {
638             Subscription::cancel($self, $other);
639         }
640
641         $block->query('COMMIT');
642
643         return true;
644     }
645
646     function unblock($other)
647     {
648         // Get the block record
649
650         $block = Profile_block::get($this->id, $other->id);
651
652         if (!$block) {
653             return false;
654         }
655
656         $result = $block->delete();
657
658         if (!$result) {
659             common_log_db_error($block, 'DELETE', __FILE__);
660             return false;
661         }
662
663         return true;
664     }
665
666     function isMember($group)
667     {
668         $profile = $this->getProfile();
669         return $profile->isMember($group);
670     }
671
672     function isAdmin($group)
673     {
674         $profile = $this->getProfile();
675         return $profile->isAdmin($group);
676     }
677
678     function getGroups($offset=0, $limit=null)
679     {
680         $profile = $this->getProfile();
681         return $profile->getGroups($offset, $limit);
682     }
683
684     /**
685      * Request to join the given group.
686      * May throw exceptions on failure.
687      *
688      * @param User_group $group
689      * @return Group_member
690      */
691     function joinGroup(User_group $group)
692     {
693         $profile = $this->getProfile();
694         return $profile->joinGroup($group);
695     }
696
697     /**
698      * Leave a group that this user is a member of.
699      *
700      * @param User_group $group
701      */
702     function leaveGroup(User_group $group)
703     {
704         $profile = $this->getProfile();
705         return $profile->leaveGroup($group);
706     }
707
708     function getSubscriptions($offset=0, $limit=null)
709     {
710         $profile = $this->getProfile();
711         return $profile->getSubscriptions($offset, $limit);
712     }
713
714     function getSubscribers($offset=0, $limit=null)
715     {
716         $profile = $this->getProfile();
717         return $profile->getSubscribers($offset, $limit);
718     }
719
720     function getTaggedSubscribers($tag, $offset=0, $limit=null)
721     {
722         $qry =
723           'SELECT profile.* ' .
724           'FROM profile JOIN subscription ' .
725           'ON profile.id = subscription.subscriber ' .
726           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
727           'AND profile_tag.tagger = subscription.subscribed) ' .
728           'WHERE subscription.subscribed = %d ' .
729           "AND profile_tag.tag = '%s' " .
730           'AND subscription.subscribed != subscription.subscriber ' .
731           'ORDER BY subscription.created DESC ';
732
733         if ($offset) {
734             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
735         }
736
737         $profile = new Profile();
738
739         $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
740
741         return $profile;
742     }
743
744     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
745     {
746         $qry =
747           'SELECT profile.* ' .
748           'FROM profile JOIN subscription ' .
749           'ON profile.id = subscription.subscribed ' .
750           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
751           'AND profile_tag.tagger = subscription.subscriber) ' .
752           'WHERE subscription.subscriber = %d ' .
753           "AND profile_tag.tag = '%s' " .
754           'AND subscription.subscribed != subscription.subscriber ' .
755           'ORDER BY subscription.created DESC ';
756
757         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
758
759         $profile = new Profile();
760
761         $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
762
763         return $profile;
764     }
765
766     function hasRight($right)
767     {
768         $profile = $this->getProfile();
769         return $profile->hasRight($right);
770     }
771
772     function delete()
773     {
774         try {
775             $profile = $this->getProfile();
776             $profile->delete();
777         } catch (UserNoProfileException $unp) {
778             common_log(LOG_INFO, "User {$this->nickname} has no profile; continuing deletion.");
779         }
780
781         $related = array('Fave',
782                          'Confirm_address',
783                          'Remember_me',
784                          'Foreign_link',
785                          'Invitation',
786                          );
787
788         Event::handle('UserDeleteRelated', array($this, &$related));
789
790         foreach ($related as $cls) {
791             $inst = new $cls();
792             $inst->user_id = $this->id;
793             $inst->delete();
794         }
795
796         $this->_deleteTags();
797         $this->_deleteBlocks();
798
799         parent::delete();
800     }
801
802     function _deleteTags()
803     {
804         $tag = new Profile_tag();
805         $tag->tagger = $this->id;
806         $tag->delete();
807     }
808
809     function _deleteBlocks()
810     {
811         $block = new Profile_block();
812         $block->blocker = $this->id;
813         $block->delete();
814         // XXX delete group block? Reset blocker?
815     }
816
817     function hasRole($name)
818     {
819         $profile = $this->getProfile();
820         return $profile->hasRole($name);
821     }
822
823     function grantRole($name)
824     {
825         $profile = $this->getProfile();
826         return $profile->grantRole($name);
827     }
828
829     function revokeRole($name)
830     {
831         $profile = $this->getProfile();
832         return $profile->revokeRole($name);
833     }
834
835     function isSandboxed()
836     {
837         $profile = $this->getProfile();
838         return $profile->isSandboxed();
839     }
840
841     function isSilenced()
842     {
843         $profile = $this->getProfile();
844         return $profile->isSilenced();
845     }
846
847     function repeatedByMe($offset=0, $limit=20, $since_id=null, $max_id=null)
848     {
849         $stream = new RepeatedByMeNoticeStream($this);
850         return $stream->getNotices($offset, $limit, $since_id, $max_id);
851     }
852
853
854     function repeatsOfMe($offset=0, $limit=20, $since_id=null, $max_id=null)
855     {
856         $stream = new RepeatsOfMeNoticeStream($this);
857
858         return $stream->getNotices($offset, $limit, $since_id, $max_id);
859     }
860
861
862     function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
863     {
864         // TRANS: Exception thrown when trying view "repeated to me".
865         throw new Exception(_('Not implemented since inbox change.'));
866     }
867
868     function shareLocation()
869     {
870         $cfg = common_config('location', 'share');
871
872         if ($cfg == 'always') {
873             return true;
874         } else if ($cfg == 'never') {
875             return false;
876         } else { // user
877             $share = common_config('location', 'sharedefault');
878
879             // Check if user has a personal setting for this
880             $prefs = User_location_prefs::staticGet('user_id', $this->id);
881
882             if (!empty($prefs)) {
883                 $share = $prefs->share_location;
884                 $prefs->free();
885             }
886
887             return $share;
888         }
889     }
890
891     static function siteOwner()
892     {
893         $owner = self::cacheGet('user:site_owner');
894
895         if ($owner === false) { // cache miss
896
897             $pr = new Profile_role();
898
899             $pr->role = Profile_role::OWNER;
900
901             $pr->orderBy('created');
902
903             $pr->limit(1);
904
905             if ($pr->find(true)) {
906                 $owner = User::staticGet('id', $pr->profile_id);
907             } else {
908                 $owner = null;
909             }
910
911             self::cacheSet('user:site_owner', $owner);
912         }
913
914         return $owner;
915     }
916
917     /**
918      * Pull the primary site account to use in single-user mode.
919      * If a valid user nickname is listed in 'singleuser':'nickname'
920      * in the config, this will be used; otherwise the site owner
921      * account is taken by default.
922      *
923      * @return User
924      * @throws ServerException if no valid single user account is present
925      * @throws ServerException if called when not in single-user mode
926      */
927     static function singleUser()
928     {
929         if (common_config('singleuser', 'enabled')) {
930
931             $user = null;
932
933             $nickname = common_config('singleuser', 'nickname');
934
935             if (!empty($nickname)) {
936                 $user = User::staticGet('nickname', $nickname);
937             }
938
939             // if there was no nickname or no user by that nickname,
940             // try the site owner.
941
942             if (empty($user)) {
943                 $user = User::siteOwner();
944             }
945
946             if (!empty($user)) {
947                 return $user;
948             } else {
949                 // TRANS: Server exception.
950                 throw new ServerException(_('No single user defined for single-user mode.'));
951             }
952         } else {
953             // TRANS: Server exception.
954             throw new ServerException(_('Single-user mode code called when not enabled.'));
955         }
956     }
957
958     /**
959      * This is kind of a hack for using external setup code that's trying to
960      * build single-user sites.
961      *
962      * Will still return a username if the config singleuser/nickname is set
963      * even if the account doesn't exist, which normally indicates that the
964      * site is horribly misconfigured.
965      *
966      * At the moment, we need to let it through so that router setup can
967      * complete, otherwise we won't be able to create the account.
968      *
969      * This will be easier when we can more easily create the account and
970      * *then* switch the site to 1user mode without jumping through hoops.
971      *
972      * @return string
973      * @throws ServerException if no valid single user account is present
974      * @throws ServerException if called when not in single-user mode
975      */
976     static function singleUserNickname()
977     {
978         try {
979             $user = User::singleUser();
980             return $user->nickname;
981         } catch (Exception $e) {
982             if (common_config('singleuser', 'enabled') && common_config('singleuser', 'nickname')) {
983                 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.");
984                 return common_config('singleuser', 'nickname');
985             }
986             throw $e;
987         }
988     }
989
990     /**
991      * Find and shorten links in the given text using this user's URL shortening
992      * settings.
993      *
994      * By default, links will be left untouched if the text is shorter than the
995      * configured maximum notice length. Pass true for the $always parameter
996      * to force all links to be shortened regardless.
997      *
998      * Side effects: may save file and file_redirection records for referenced URLs.
999      *
1000      * @param string $text
1001      * @param boolean $always
1002      * @return string
1003      */
1004     public function shortenLinks($text, $always=false)
1005     {
1006         return common_shorten_links($text, $always, $this);
1007     }
1008
1009     /*
1010      * Get a list of OAuth client applications that have access to this
1011      * user's account.
1012      */
1013     function getConnectedApps($offset = 0, $limit = null)
1014     {
1015         $qry =
1016           'SELECT u.* ' .
1017           'FROM oauth_application_user u, oauth_application a ' .
1018           'WHERE u.profile_id = %d ' .
1019           'AND a.id = u.application_id ' .
1020           'AND u.access_type > 0 ' .
1021           'ORDER BY u.created DESC ';
1022
1023         if ($offset > 0) {
1024             if (common_config('db','type') == 'pgsql') {
1025                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
1026             } else {
1027                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
1028             }
1029         }
1030
1031         $apps = new Oauth_application_user();
1032
1033         $cnt = $apps->query(sprintf($qry, $this->id));
1034
1035         return $apps;
1036     }
1037
1038     /**
1039      * Magic function called at serialize() time.
1040      *
1041      * We use this to drop a couple process-specific references
1042      * from DB_DataObject which can cause trouble in future
1043      * processes.
1044      *
1045      * @return array of variable names to include in serialization.
1046      */
1047
1048     function __sleep()
1049     {
1050         $vars = parent::__sleep();
1051         $skip = array('_profile');
1052         return array_diff($vars, $skip);
1053     }
1054
1055     static function recoverPassword($nore)
1056     {
1057         $user = User::staticGet('email', common_canonical_email($nore));
1058
1059         if (!$user) {
1060             try {
1061                 $user = User::staticGet('nickname', common_canonical_nickname($nore));
1062             } catch (NicknameException $e) {
1063                 // invalid
1064             }
1065         }
1066
1067         // See if it's an unconfirmed email address
1068
1069         if (!$user) {
1070             // Warning: it may actually be legit to have multiple folks
1071             // who have claimed, but not yet confirmed, the same address.
1072             // We'll only send to the first one that comes up.
1073             $confirm_email = new Confirm_address();
1074             $confirm_email->address = common_canonical_email($nore);
1075             $confirm_email->address_type = 'email';
1076             $confirm_email->find();
1077             if ($confirm_email->fetch()) {
1078                 $user = User::staticGet($confirm_email->user_id);
1079             } else {
1080                 $confirm_email = null;
1081             }
1082         } else {
1083             $confirm_email = null;
1084         }
1085
1086         if (!$user) {
1087             // TRANS: Information on password recovery form if no known username or e-mail address was specified.
1088             throw new ClientException(_('No user with that email address or username.'));
1089             return;
1090         }
1091
1092         // Try to get an unconfirmed email address if they used a user name
1093
1094         if (!$user->email && !$confirm_email) {
1095             $confirm_email = new Confirm_address();
1096             $confirm_email->user_id = $user->id;
1097             $confirm_email->address_type = 'email';
1098             $confirm_email->find();
1099             if (!$confirm_email->fetch()) {
1100                 $confirm_email = null;
1101             }
1102         }
1103
1104         if (!$user->email && !$confirm_email) {
1105             // TRANS: Client error displayed on password recovery form if a user does not have a registered e-mail address.
1106             throw new ClientException(_('No registered email address for that user.'));
1107             return;
1108         }
1109
1110         // Success! We have a valid user and a confirmed or unconfirmed email address
1111
1112         $confirm = new Confirm_address();
1113         $confirm->code = common_confirmation_code(128);
1114         $confirm->address_type = 'recover';
1115         $confirm->user_id = $user->id;
1116         $confirm->address = (!empty($user->email)) ? $user->email : $confirm_email->address;
1117
1118         if (!$confirm->insert()) {
1119             common_log_db_error($confirm, 'INSERT', __FILE__);
1120             // TRANS: Server error displayed if e-mail address confirmation fails in the database on the password recovery form.
1121             throw new ServerException(_('Error saving address confirmation.'));
1122             return;
1123         }
1124
1125          // @todo FIXME: needs i18n.
1126         $body = "Hey, $user->nickname.";
1127         $body .= "\n\n";
1128         $body .= 'Someone just asked for a new password ' .
1129                  'for this account on ' . common_config('site', 'name') . '.';
1130         $body .= "\n\n";
1131         $body .= 'If it was you, and you want to confirm, use the URL below:';
1132         $body .= "\n\n";
1133         $body .= "\t".common_local_url('recoverpassword',
1134                                    array('code' => $confirm->code));
1135         $body .= "\n\n";
1136         $body .= 'If not, just ignore this message.';
1137         $body .= "\n\n";
1138         $body .= 'Thanks for your time, ';
1139         $body .= "\n";
1140         $body .= common_config('site', 'name');
1141         $body .= "\n";
1142
1143         $headers = _mail_prepare_headers('recoverpassword', $user->nickname, $user->nickname);
1144         // TRANS: Subject for password recovery e-mail.
1145         mail_to_user($user, _('Password recovery requested'), $body, $headers, $confirm->address);
1146     }
1147
1148     function streamModeOnly()
1149     {
1150         if (common_config('oldschool', 'enabled')) {
1151             $osp = Old_school_prefs::staticGet('user_id', $this->id);
1152             if (!empty($osp)) {
1153                 return $osp->stream_mode_only;
1154             }
1155         }
1156
1157         return false;
1158     }
1159
1160     function conversationTree()
1161     {
1162         if (common_config('oldschool', 'enabled')) {
1163             $osp = Old_school_prefs::staticGet('user_id', $this->id);
1164             if (!empty($osp)) {
1165                 return $osp->conversation_tree;
1166             }
1167         }
1168
1169         return false;
1170     }
1171
1172     function streamNicknames()
1173     {
1174         if (common_config('oldschool', 'enabled')) {
1175             $osp = Old_school_prefs::staticGet('user_id', $this->id);
1176             if (!empty($osp)) {
1177                 return $osp->stream_nicknames;
1178             }
1179         }
1180         return false;
1181     }
1182
1183     function registrationActivity()
1184     {
1185         $profile = $this->getProfile();
1186
1187         $service = new ActivityObject();
1188
1189         $service->type  = ActivityObject::SERVICE;
1190         $service->title = common_config('site', 'name');
1191         $service->link  = common_root_url();
1192         $service->id    = $service->link;
1193
1194         $act = new Activity();
1195
1196         $act->actor = ActivityObject::fromProfile($profile);
1197         $act->verb = ActivityVerb::JOIN;
1198
1199         $act->objects[] = $service;
1200
1201         $act->id = TagURI::mint('user:register:%d',
1202                                 $this->id);
1203
1204         $act->time = strtotime($this->created);
1205
1206         $act->title = _("Register");
1207
1208         $act->content = sprintf(_('%1$s joined %2$s.'),
1209                                 $profile->getBestName(),
1210                                 $service->title);
1211         return $act;
1212     }
1213 }