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