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