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