]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Profile.php
Pending subscription requests now work as they should
[quix0rs-gnu-social.git] / classes / Profile.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008-2011, 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 profile
24  */
25 class Profile extends Managed_DataObject
26 {
27     public $__table = 'profile';                         // table name
28     public $id;                              // int(4)  primary_key not_null
29     public $nickname;                        // varchar(64)  multiple_key not_null
30     public $fullname;                        // text()
31     public $profileurl;                      // text()
32     public $homepage;                        // text()
33     public $bio;                             // text()  multiple_key
34     public $location;                        // text()
35     public $lat;                             // decimal(10,7)
36     public $lon;                             // decimal(10,7)
37     public $location_id;                     // int(4)
38     public $location_ns;                     // int(4)
39     public $created;                         // datetime()   not_null
40     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
41
42     public static function schemaDef()
43     {
44         $def = array(
45             'description' => 'local and remote users have profiles',
46             'fields' => array(
47                 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
48                 'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8mb4_general_ci'),
49                 'fullname' => array('type' => 'text', 'description' => 'display name', 'collate' => 'utf8mb4_general_ci'),
50                 'profileurl' => array('type' => 'text', 'description' => 'URL, cached so we dont regenerate'),
51                 'homepage' => array('type' => 'text', 'description' => 'identifying URL', 'collate' => 'utf8mb4_general_ci'),
52                 'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8mb4_general_ci'),
53                 'location' => array('type' => 'text', 'description' => 'physical location', 'collate' => 'utf8mb4_general_ci'),
54                 'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
55                 'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
56                 'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
57                 'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),
58
59                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
60                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
61             ),
62             'primary key' => array('id'),
63             'indexes' => array(
64                 'profile_nickname_idx' => array('nickname'),
65             )
66         );
67
68         // Add a fulltext index
69
70         if (common_config('search', 'type') == 'fulltext') {
71             $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
72         }
73
74         return $def;
75     }
76
77     public static function getByEmail($email)
78     {
79         // in the future, profiles should have emails stored...
80         $user = User::getKV('email', $email);
81         if (!($user instanceof User)) {
82             throw new NoSuchUserException(array('email'=>$email));
83         }
84         return $user->getProfile();
85     } 
86
87     protected $_user = array();
88
89     public function getUser()
90     {
91         if (!isset($this->_user[$this->id])) {
92             $user = User::getKV('id', $this->id);
93             if (!$user instanceof User) {
94                 throw new NoSuchUserException(array('id'=>$this->id));
95             }
96             $this->_user[$this->id] = $user;
97         }
98         return $this->_user[$this->id];
99     }
100
101     protected $_group = array();
102
103     public function getGroup()
104     {
105         if (!isset($this->_group[$this->id])) {
106             $group = User_group::getKV('profile_id', $this->id);
107             if (!$group instanceof User_group) {
108                 throw new NoSuchGroupException(array('profile_id'=>$this->id));
109             }
110             $this->_group[$this->id] = $group;
111         }
112         return $this->_group[$this->id];
113     }
114
115     public function isGroup()
116     {
117         try {
118             $this->getGroup();
119             return true;
120         } catch (NoSuchGroupException $e) {
121             return false;
122         }
123     }
124
125     public function isLocal()
126     {
127         try {
128             $this->getUser();
129         } catch (NoSuchUserException $e) {
130             return false;
131         }
132         return true;
133     }
134
135     // Returns false if the user has no password (which will always
136     // be the case for remote users). This can be the case for OpenID
137     // logins or other mechanisms which don't store a password hash.
138     public function hasPassword()
139     {
140         try {
141             return $this->getUser()->hasPassword();
142         } catch (NoSuchUserException $e) {
143             return false;
144         }
145     }
146
147     public function getObjectType()
148     {
149         // FIXME: More types... like peopletags and whatever
150         if ($this->isGroup()) {
151             return ActivityObject::GROUP;
152         } else {
153             return ActivityObject::PERSON;
154         }
155     }
156
157     public function getAvatar($width, $height=null)
158     {
159         return Avatar::byProfile($this, $width, $height);
160     }
161
162     public function setOriginal($filename)
163     {
164         if ($this->isGroup()) {
165             // Until Group avatars are handled just like profile avatars.
166             return $this->getGroup()->setOriginal($filename);
167         }
168
169         $imagefile = new ImageFile(null, Avatar::path($filename));
170
171         $avatar = new Avatar();
172         $avatar->profile_id = $this->id;
173         $avatar->width = $imagefile->width;
174         $avatar->height = $imagefile->height;
175         $avatar->mediatype = image_type_to_mime_type($imagefile->type);
176         $avatar->filename = $filename;
177         $avatar->original = true;
178         $avatar->url = Avatar::url($filename);
179         $avatar->created = common_sql_now();
180
181         // XXX: start a transaction here
182         if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
183             // If we can't delete the old avatars, let's abort right here.
184             @unlink(Avatar::path($filename));
185             return null;
186         }
187
188         return $avatar;
189     }
190
191     /**
192      * Gets either the full name (if filled) or the nickname.
193      *
194      * @return string
195      */
196     function getBestName()
197     {
198         return ($this->fullname) ? $this->fullname : $this->nickname;
199     }
200
201     /**
202      * Takes the currently scoped profile into account to give a name 
203      * to list in notice streams. Preferences may differ between profiles.
204      */
205     function getStreamName()
206     {
207         $user = common_current_user();
208         if ($user instanceof User && $user->streamNicknames()) {
209             return $this->nickname;
210         }
211
212         return $this->getBestName();
213     }
214
215     /**
216      * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
217      * if no fullname is provided.
218      *
219      * @return string
220      */
221     function getFancyName()
222     {
223         if ($this->fullname) {
224             // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
225             return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
226         } else {
227             return $this->nickname;
228         }
229     }
230
231     /**
232      * Get the most recent notice posted by this user, if any.
233      *
234      * @return mixed Notice or null
235      */
236     function getCurrentNotice()
237     {
238         $notice = $this->getNotices(0, 1);
239
240         if ($notice->fetch()) {
241             if ($notice instanceof ArrayWrapper) {
242                 // hack for things trying to work with single notices
243                 return $notice->_items[0];
244             }
245             return $notice;
246         }
247         
248         return null;
249     }
250
251     function getReplies($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $before_id=0)
252     {
253         return Reply::stream($this->getID(), $offset, $limit, $since_id, $before_id);
254     }
255
256     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
257     {
258         $stream = new TaggedProfileNoticeStream($this, $tag);
259
260         return $stream->getNotices($offset, $limit, $since_id, $max_id);
261     }
262
263     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
264     {
265         $stream = new ProfileNoticeStream($this, $scoped);
266
267         return $stream->getNotices($offset, $limit, $since_id, $max_id);
268     }
269
270     function isMember(User_group $group)
271     {
272         $groups = $this->getGroups(0, null);
273         while ($groups instanceof User_group && $groups->fetch()) {
274             if ($groups->id == $group->id) {
275                 return true;
276             }
277         }
278         return false;
279     }
280
281     function isAdmin(User_group $group)
282     {
283         $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
284                                           'group_id' => $group->id));
285         return (!empty($gm) && $gm->is_admin);
286     }
287
288     function isPendingMember($group)
289     {
290         $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
291                                                    'group_id' => $group->id));
292         return !empty($request);
293     }
294
295     function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
296     {
297         $ids = array();
298
299         $keypart = sprintf('profile:groups:%d', $this->id);
300
301         $idstring = self::cacheGet($keypart);
302
303         if ($idstring !== false) {
304             $ids = explode(',', $idstring);
305         } else {
306             $gm = new Group_member();
307
308             $gm->profile_id = $this->id;
309
310             if ($gm->find()) {
311                 while ($gm->fetch()) {
312                     $ids[] = $gm->group_id;
313                 }
314             }
315
316             self::cacheSet($keypart, implode(',', $ids));
317         }
318
319         if (!is_null($offset) && !is_null($limit)) {
320             $ids = array_slice($ids, $offset, $limit);
321         }
322
323         try {
324             return User_group::multiGet('id', $ids);
325         } catch (NoResultException $e) {
326             return null;    // throw exception when we handle it everywhere
327         }
328     }
329
330     function getGroupCount() {
331         $groups = $this->getGroups(0, null);
332         return $groups instanceof User_group
333                 ? $groups->N
334                 : 0;
335     }
336
337     function isTagged($peopletag)
338     {
339         $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
340                                           'tagged' => $this->id,
341                                           'tag'    => $peopletag->tag));
342         return !empty($tag);
343     }
344
345     function canTag($tagged)
346     {
347         if (empty($tagged)) {
348             return false;
349         }
350
351         if ($tagged->id == $this->id) {
352             return true;
353         }
354
355         $all = common_config('peopletag', 'allow_tagging', 'all');
356         $local = common_config('peopletag', 'allow_tagging', 'local');
357         $remote = common_config('peopletag', 'allow_tagging', 'remote');
358         $subs = common_config('peopletag', 'allow_tagging', 'subs');
359
360         if ($all) {
361             return true;
362         }
363
364         $tagged_user = $tagged->getUser();
365         if (!empty($tagged_user)) {
366             if ($local) {
367                 return true;
368             }
369         } else if ($subs) {
370             return (Subscription::exists($this, $tagged) ||
371                     Subscription::exists($tagged, $this));
372         } else if ($remote) {
373             return true;
374         }
375         return false;
376     }
377
378     function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
379     {
380         $ids = array();
381
382         $keypart = sprintf('profile:lists:%d', $this->id);
383
384         $idstr = self::cacheGet($keypart);
385
386         if ($idstr !== false) {
387             $ids = explode(',', $idstr);
388         } else {
389             $list = new Profile_list();
390             $list->selectAdd();
391             $list->selectAdd('id');
392             $list->tagger = $this->id;
393             $list->selectAdd('id as "cursor"');
394
395             if ($since_id>0) {
396                $list->whereAdd('id > '.$since_id);
397             }
398
399             if ($max_id>0) {
400                 $list->whereAdd('id <= '.$max_id);
401             }
402
403             if($offset>=0 && !is_null($limit)) {
404                 $list->limit($offset, $limit);
405             }
406
407             $list->orderBy('id DESC');
408
409             if ($list->find()) {
410                 while ($list->fetch()) {
411                     $ids[] = $list->id;
412                 }
413             }
414
415             self::cacheSet($keypart, implode(',', $ids));
416         }
417
418         $showPrivate = (($auth_user instanceof User ||
419                             $auth_user instanceof Profile) &&
420                         $auth_user->id === $this->id);
421
422         $lists = array();
423
424         foreach ($ids as $id) {
425             $list = Profile_list::getKV('id', $id);
426             if (!empty($list) &&
427                 ($showPrivate || !$list->private)) {
428
429                 if (!isset($list->cursor)) {
430                     $list->cursor = $list->id;
431                 }
432
433                 $lists[] = $list;
434             }
435         }
436
437         return new ArrayWrapper($lists);
438     }
439
440     /**
441      * Get tags that other people put on this profile, in reverse-chron order
442      *
443      * @param (Profile|User) $auth_user  Authorized user (used for privacy)
444      * @param int            $offset     Offset from latest
445      * @param int            $limit      Max number to get
446      * @param datetime       $since_id   max date
447      * @param datetime       $max_id     min date
448      *
449      * @return Profile_list resulting lists
450      */
451
452     function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
453     {
454         $list = new Profile_list();
455
456         $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
457                        'from profile_tag join profile_list '.
458                        'on (profile_tag.tagger = profile_list.tagger ' .
459                        '    and profile_tag.tag = profile_list.tag) ' .
460                        'where profile_tag.tagged = %d ',
461                        $this->id);
462
463
464         if ($auth_user instanceof User || $auth_user instanceof Profile) {
465             $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
466                             'OR ( profile_list.tagger = %d AND ' .
467                             'profile_list.private = true ) )',
468                             $auth_user->id);
469         } else {
470             $qry .= 'AND profile_list.private = 0 ';
471         }
472
473         if ($since_id > 0) {
474             $qry .= sprintf('AND (cursor > %d) ', $since_id);
475         }
476
477         if ($max_id > 0) {
478             $qry .= sprintf('AND (cursor < %d) ', $max_id);
479         }
480
481         $qry .= 'ORDER BY profile_tag.modified DESC ';
482
483         if ($offset >= 0 && !is_null($limit)) {
484             $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
485         }
486
487         $list->query($qry);
488         return $list;
489     }
490
491     function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
492     {
493         $tags = new Profile_list();
494         $tags->private = true;
495         $tags->tagger = $this->id;
496
497         if ($since_id>0) {
498            $tags->whereAdd('id > '.$since_id);
499         }
500
501         if ($max_id>0) {
502             $tags->whereAdd('id <= '.$max_id);
503         }
504
505         if($offset>=0 && !is_null($limit)) {
506             $tags->limit($offset, $limit);
507         }
508
509         $tags->orderBy('id DESC');
510         $tags->find();
511
512         return $tags;
513     }
514
515     function hasLocalTags()
516     {
517         $tags = new Profile_tag();
518
519         $tags->joinAdd(array('tagger', 'user:id'));
520         $tags->whereAdd('tagged  = '.$this->id);
521         $tags->whereAdd('tagger != '.$this->id);
522
523         $tags->limit(0, 1);
524         $tags->fetch();
525
526         return ($tags->N == 0) ? false : true;
527     }
528
529     function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
530     {
531         $lists = new Profile_list();
532         $subs = new Profile_tag_subscription();
533
534         $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
535
536         #@fixme: postgres (round(date_part('epoch', my_date)))
537         $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
538
539         $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
540
541         if ($since_id>0) {
542            $lists->whereAdd('cursor > '.$since_id);
543         }
544
545         if ($max_id>0) {
546             $lists->whereAdd('cursor <= '.$max_id);
547         }
548
549         if($offset>=0 && !is_null($limit)) {
550             $lists->limit($offset, $limit);
551         }
552
553         $lists->orderBy('"cursor" DESC');
554         $lists->find();
555
556         return $lists;
557     }
558
559     /**
560      * Request to join the given group.
561      * May throw exceptions on failure.
562      *
563      * @param User_group $group
564      * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
565      */
566     function joinGroup(User_group $group)
567     {
568         $join = null;
569         if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
570             $join = Group_join_queue::saveNew($this, $group);
571         } else {
572             if (Event::handle('StartJoinGroup', array($group, $this))) {
573                 $join = Group_member::join($group->id, $this->id);
574                 self::blow('profile:groups:%d', $this->id);
575                 self::blow('group:member_ids:%d', $group->id);
576                 self::blow('group:member_count:%d', $group->id);
577                 Event::handle('EndJoinGroup', array($group, $this));
578             }
579         }
580         if ($join) {
581             // Send any applicable notifications...
582             $join->notify();
583         }
584         return $join;
585     }
586
587     /**
588      * Leave a group that this profile is a member of.
589      *
590      * @param User_group $group
591      */
592     function leaveGroup(User_group $group)
593     {
594         if (Event::handle('StartLeaveGroup', array($group, $this))) {
595             Group_member::leave($group->id, $this->id);
596             self::blow('profile:groups:%d', $this->id);
597             self::blow('group:member_ids:%d', $group->id);
598             self::blow('group:member_count:%d', $group->id);
599             Event::handle('EndLeaveGroup', array($group, $this));
600         }
601     }
602
603     function avatarUrl($size=AVATAR_PROFILE_SIZE)
604     {
605         return Avatar::urlByProfile($this, $size);
606     }
607
608     function getSubscribed($offset=0, $limit=null)
609     {
610         $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
611         try {
612             $profiles = Profile::multiGet('id', $subs);
613         } catch (NoResultException $e) {
614             return $e->obj;
615         }
616         return $profiles;
617     }
618
619     function getSubscribers($offset=0, $limit=null)
620     {
621         $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
622         try {
623             $profiles = Profile::multiGet('id', $subs);
624         } catch (NoResultException $e) {
625             return $e->obj;
626         }
627         return $profiles;
628     }
629
630     function getTaggedSubscribers($tag, $offset=0, $limit=null)
631     {
632         $qry =
633           'SELECT profile.* ' .
634           'FROM profile JOIN subscription ' .
635           'ON profile.id = subscription.subscriber ' .
636           'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
637           'AND profile_tag.tagger = subscription.subscribed) ' .
638           'WHERE subscription.subscribed = %d ' .
639           "AND profile_tag.tag = '%s' " .
640           'AND subscription.subscribed != subscription.subscriber ' .
641           'ORDER BY subscription.created DESC ';
642
643         if ($offset) {
644             $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
645         }
646
647         $profile = new Profile();
648
649         $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
650
651         return $profile;
652     }
653
654     function getTaggedSubscriptions($tag, $offset=0, $limit=null)
655     {
656         $qry =
657           'SELECT profile.* ' .
658           'FROM profile JOIN subscription ' .
659           'ON profile.id = subscription.subscribed ' .
660           'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
661           'AND profile_tag.tagger = subscription.subscriber) ' .
662           'WHERE subscription.subscriber = %d ' .
663           "AND profile_tag.tag = '%s' " .
664           'AND subscription.subscribed != subscription.subscriber ' .
665           'ORDER BY subscription.created DESC ';
666
667         $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
668
669         $profile = new Profile();
670
671         $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
672
673         return $profile;
674     }
675
676     /**
677      * Get pending subscribers, who have not yet been approved.
678      *
679      * @param int $offset
680      * @param int $limit
681      * @return Profile
682      */
683     function getRequests($offset=0, $limit=null)
684     {
685         // FIXME: mysql only
686         $subqueue = new Profile();
687         $subqueue->joinAdd(array('id', 'subscription_queue:subscriber'));
688         $subqueue->whereAdd(sprintf('subscription_queue.subscribed = %d', $this->getID()));
689         $subqueue->limit($offset, $limit);
690         $subqueue->orderBy('subscription_queue.created', 'DESC');
691         if (!$subqueue->find()) {
692             throw new NoResultException($subqueue);
693         }
694         return $subqueue;
695     }
696
697     function subscriptionCount()
698     {
699         $c = Cache::instance();
700
701         if (!empty($c)) {
702             $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
703             if (is_integer($cnt)) {
704                 return (int) $cnt;
705             }
706         }
707
708         $sub = new Subscription();
709         $sub->subscriber = $this->id;
710
711         $cnt = (int) $sub->count('distinct subscribed');
712
713         $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
714
715         if (!empty($c)) {
716             $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
717         }
718
719         return $cnt;
720     }
721
722     function subscriberCount()
723     {
724         $c = Cache::instance();
725         if (!empty($c)) {
726             $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
727             if (is_integer($cnt)) {
728                 return (int) $cnt;
729             }
730         }
731
732         $sub = new Subscription();
733         $sub->subscribed = $this->id;
734         $sub->whereAdd('subscriber != subscribed');
735         $cnt = (int) $sub->count('distinct subscriber');
736
737         if (!empty($c)) {
738             $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
739         }
740
741         return $cnt;
742     }
743
744     /**
745      * Is this profile subscribed to another profile?
746      *
747      * @param Profile $other
748      * @return boolean
749      */
750     function isSubscribed(Profile $other)
751     {
752         return Subscription::exists($this, $other);
753     }
754
755     function readableBy(Profile $other=null)
756     {
757         // If it's not a private stream, it's readable by anyone
758         if (!$this->isPrivateStream()) {
759             return true;
760         }
761
762         // If it's a private stream, $other must be a subscriber to $this
763         return is_null($other) ? false : $other->isSubscribed($this);
764     }
765
766     function requiresSubscriptionApproval(Profile $other=null)
767     {
768         if (!$this->isLocal()) {
769             // We don't know for remote users, and we'll always be able to send
770             // the request. Whether it'll work immediately or require moderation
771             // can be determined in another function.
772             return false;
773         }
774
775         // Assume that profiles _we_ subscribe to are permitted. Could be made configurable.
776         if (!is_null($other) && $this->isSubscribed($other)) {
777             return false;
778         }
779
780         // If the local user either has a private stream (implies the following)
781         // or  user has a moderation policy for new subscriptions, return true.
782         return $this->getUser()->private_stream || $this->getUser()->subscribe_policy === User::SUBSCRIBE_POLICY_MODERATE;
783     }
784
785     /**
786      * Check if a pending subscription request is outstanding for this...
787      *
788      * @param Profile $other
789      * @return boolean
790      */
791     function hasPendingSubscription(Profile $other)
792     {
793         return Subscription_queue::exists($this, $other);
794     }
795
796     /**
797      * Are these two profiles subscribed to each other?
798      *
799      * @param Profile $other
800      * @return boolean
801      */
802     function mutuallySubscribed(Profile $other)
803     {
804         return $this->isSubscribed($other) &&
805           $other->isSubscribed($this);
806     }
807
808     function noticeCount()
809     {
810         $c = Cache::instance();
811
812         if (!empty($c)) {
813             $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
814             if (is_integer($cnt)) {
815                 return (int) $cnt;
816             }
817         }
818
819         $notices = new Notice();
820         $notices->profile_id = $this->id;
821         $cnt = (int) $notices->count('distinct id');
822
823         if (!empty($c)) {
824             $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
825         }
826
827         return $cnt;
828     }
829
830     function blowSubscriberCount()
831     {
832         $c = Cache::instance();
833         if (!empty($c)) {
834             $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
835         }
836     }
837
838     function blowSubscriptionCount()
839     {
840         $c = Cache::instance();
841         if (!empty($c)) {
842             $c->delete(Cache::key('profile:subscription_count:'.$this->id));
843         }
844     }
845
846     function blowNoticeCount()
847     {
848         $c = Cache::instance();
849         if (!empty($c)) {
850             $c->delete(Cache::key('profile:notice_count:'.$this->id));
851         }
852     }
853
854     static function maxBio()
855     {
856         $biolimit = common_config('profile', 'biolimit');
857         // null => use global limit (distinct from 0!)
858         if (is_null($biolimit)) {
859             $biolimit = common_config('site', 'textlimit');
860         }
861         return $biolimit;
862     }
863
864     static function bioTooLong($bio)
865     {
866         $biolimit = self::maxBio();
867         return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
868     }
869
870     function update($dataObject=false)
871     {
872         if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
873             try {
874                 $local = $this->getUser();
875                 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
876                 $origuser = clone($local);
877                 $local->nickname = $this->nickname;
878                 // updateWithKeys throws exception on failure.
879                 $local->updateWithKeys($origuser);
880
881                 // Clear the site owner, in case nickname changed
882                 if ($local->hasRole(Profile_role::OWNER)) {
883                     User::blow('user:site_owner');
884                 }
885             } catch (NoSuchUserException $e) {
886                 // Nevermind...
887             }
888         }
889
890         return parent::update($dataObject);
891     }
892
893     function delete($useWhere=false)
894     {
895         // just in case it hadn't been done before... (usually set before adding deluser to queue handling!)
896         if (!$this->hasRole(Profile_role::DELETED)) {
897             $this->grantRole(Profile_role::DELETED);
898         }
899
900         $this->_deleteNotices();
901         $this->_deleteSubscriptions();
902         $this->_deleteTags();
903         $this->_deleteBlocks();
904         $this->_deleteAttentions();
905         Avatar::deleteFromProfile($this, true);
906
907         // Warning: delete() will run on the batch objects,
908         // not on individual objects.
909         $related = array('Reply',
910                          'Group_member',
911                          );
912         Event::handle('ProfileDeleteRelated', array($this, &$related));
913
914         foreach ($related as $cls) {
915             $inst = new $cls();
916             $inst->profile_id = $this->id;
917             $inst->delete();
918         }
919
920         $localuser = User::getKV('id', $this->id);
921         if ($localuser instanceof User) {
922             $localuser->delete();
923         }
924
925         return parent::delete($useWhere);
926     }
927
928     function _deleteNotices()
929     {
930         $notice = new Notice();
931         $notice->profile_id = $this->id;
932
933         if ($notice->find()) {
934             while ($notice->fetch()) {
935                 $other = clone($notice);
936                 $other->delete();
937             }
938         }
939     }
940
941     function _deleteSubscriptions()
942     {
943         $sub = new Subscription();
944         $sub->subscriber = $this->id;
945
946         $sub->find();
947
948         while ($sub->fetch()) {
949             $other = Profile::getKV('id', $sub->subscribed);
950             if (empty($other)) {
951                 continue;
952             }
953             if ($other->id == $this->id) {
954                 continue;
955             }
956             Subscription::cancel($this, $other);
957         }
958
959         $subd = new Subscription();
960         $subd->subscribed = $this->id;
961         $subd->find();
962
963         while ($subd->fetch()) {
964             $other = Profile::getKV('id', $subd->subscriber);
965             if (empty($other)) {
966                 continue;
967             }
968             if ($other->id == $this->id) {
969                 continue;
970             }
971             Subscription::cancel($other, $this);
972         }
973
974         $self = new Subscription();
975
976         $self->subscriber = $this->id;
977         $self->subscribed = $this->id;
978
979         $self->delete();
980     }
981
982     function _deleteTags()
983     {
984         $tag = new Profile_tag();
985         $tag->tagged = $this->id;
986         $tag->delete();
987     }
988
989     function _deleteBlocks()
990     {
991         $block = new Profile_block();
992         $block->blocked = $this->id;
993         $block->delete();
994
995         $block = new Group_block();
996         $block->blocked = $this->id;
997         $block->delete();
998     }
999
1000     function _deleteAttentions()
1001     {
1002         $att = new Attention();
1003         $att->profile_id = $this->getID();
1004
1005         if ($att->find()) {
1006             while ($att->fetch()) {
1007                 // Can't do delete() on the object directly since it won't remove all of it
1008                 $other = clone($att);
1009                 $other->delete();
1010             }
1011         }
1012     }
1013
1014     // XXX: identical to Notice::getLocation.
1015
1016     public function getLocation()
1017     {
1018         $location = null;
1019
1020         if (!empty($this->location_id) && !empty($this->location_ns)) {
1021             $location = Location::fromId($this->location_id, $this->location_ns);
1022         }
1023
1024         if (is_null($location)) { // no ID, or Location::fromId() failed
1025             if (!empty($this->lat) && !empty($this->lon)) {
1026                 $location = Location::fromLatLon($this->lat, $this->lon);
1027             }
1028         }
1029
1030         if (is_null($location)) { // still haven't found it!
1031             if (!empty($this->location)) {
1032                 $location = Location::fromName($this->location);
1033             }
1034         }
1035
1036         return $location;
1037     }
1038
1039     public function shareLocation()
1040     {
1041         $cfg = common_config('location', 'share');
1042
1043         if ($cfg == 'always') {
1044             return true;
1045         } else if ($cfg == 'never') {
1046             return false;
1047         } else { // user
1048             $share = common_config('location', 'sharedefault');
1049
1050             // Check if user has a personal setting for this
1051             $prefs = User_location_prefs::getKV('user_id', $this->id);
1052
1053             if (!empty($prefs)) {
1054                 $share = $prefs->share_location;
1055                 $prefs->free();
1056             }
1057
1058             return $share;
1059         }
1060     }
1061
1062     function hasRole($name)
1063     {
1064         $has_role = false;
1065         if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1066             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1067                                                 'role' => $name));
1068             $has_role = !empty($role);
1069             Event::handle('EndHasRole', array($this, $name, $has_role));
1070         }
1071         return $has_role;
1072     }
1073
1074     function grantRole($name)
1075     {
1076         if (Event::handle('StartGrantRole', array($this, $name))) {
1077
1078             $role = new Profile_role();
1079
1080             $role->profile_id = $this->id;
1081             $role->role       = $name;
1082             $role->created    = common_sql_now();
1083
1084             $result = $role->insert();
1085
1086             if (!$result) {
1087                 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1088             }
1089
1090             if ($name == 'owner') {
1091                 User::blow('user:site_owner');
1092             }
1093
1094             Event::handle('EndGrantRole', array($this, $name));
1095         }
1096
1097         return $result;
1098     }
1099
1100     function revokeRole($name)
1101     {
1102         if (Event::handle('StartRevokeRole', array($this, $name))) {
1103
1104             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1105                                                 'role' => $name));
1106
1107             if (empty($role)) {
1108                 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1109                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1110                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1111             }
1112
1113             $result = $role->delete();
1114
1115             if (!$result) {
1116                 common_log_db_error($role, 'DELETE', __FILE__);
1117                 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1118                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1119                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1120             }
1121
1122             if ($name == 'owner') {
1123                 User::blow('user:site_owner');
1124             }
1125
1126             Event::handle('EndRevokeRole', array($this, $name));
1127
1128             return true;
1129         }
1130     }
1131
1132     function isSandboxed()
1133     {
1134         return $this->hasRole(Profile_role::SANDBOXED);
1135     }
1136
1137     function isSilenced()
1138     {
1139         return $this->hasRole(Profile_role::SILENCED);
1140     }
1141
1142     function sandbox()
1143     {
1144         $this->grantRole(Profile_role::SANDBOXED);
1145     }
1146
1147     function unsandbox()
1148     {
1149         $this->revokeRole(Profile_role::SANDBOXED);
1150     }
1151
1152     function silence()
1153     {
1154         $this->grantRole(Profile_role::SILENCED);
1155         if (common_config('notice', 'hidespam')) {
1156             $this->flushVisibility();
1157         }
1158     }
1159
1160     function unsilence()
1161     {
1162         $this->revokeRole(Profile_role::SILENCED);
1163         if (common_config('notice', 'hidespam')) {
1164             $this->flushVisibility();
1165         }
1166     }
1167
1168     function flushVisibility()
1169     {
1170         // Get all notices
1171         $stream = new ProfileNoticeStream($this, $this);
1172         $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1173         foreach ($ids as $id) {
1174             self::blow('notice:in-scope-for:%d:null', $id);
1175         }
1176     }
1177
1178     /**
1179      * Does this user have the right to do X?
1180      *
1181      * With our role-based authorization, this is merely a lookup for whether the user
1182      * has a particular role. The implementation currently uses a switch statement
1183      * to determine if the user has the pre-defined role to exercise the right. Future
1184      * implementations may allow per-site roles, and different mappings of roles to rights.
1185      *
1186      * @param $right string Name of the right, usually a constant in class Right
1187      * @return boolean whether the user has the right in question
1188      */
1189     public function hasRight($right)
1190     {
1191         $result = false;
1192
1193         if ($this->hasRole(Profile_role::DELETED)) {
1194             return false;
1195         }
1196
1197         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1198             switch ($right)
1199             {
1200             case Right::DELETEOTHERSNOTICE:
1201             case Right::MAKEGROUPADMIN:
1202             case Right::SANDBOXUSER:
1203             case Right::SILENCEUSER:
1204             case Right::DELETEUSER:
1205             case Right::DELETEGROUP:
1206             case Right::TRAINSPAM:
1207             case Right::REVIEWSPAM:
1208                 $result = $this->hasRole(Profile_role::MODERATOR);
1209                 break;
1210             case Right::CONFIGURESITE:
1211                 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1212                 break;
1213             case Right::GRANTROLE:
1214             case Right::REVOKEROLE:
1215                 $result = $this->hasRole(Profile_role::OWNER);
1216                 break;
1217             case Right::NEWNOTICE:
1218             case Right::NEWMESSAGE:
1219             case Right::SUBSCRIBE:
1220             case Right::CREATEGROUP:
1221                 $result = !$this->isSilenced();
1222                 break;
1223             case Right::PUBLICNOTICE:
1224             case Right::EMAILONREPLY:
1225             case Right::EMAILONSUBSCRIBE:
1226             case Right::EMAILONFAVE:
1227                 $result = !$this->isSandboxed();
1228                 break;
1229             case Right::WEBLOGIN:
1230                 $result = !$this->isSilenced();
1231                 break;
1232             case Right::API:
1233                 $result = !$this->isSilenced();
1234                 break;
1235             case Right::BACKUPACCOUNT:
1236                 $result = common_config('profile', 'backup');
1237                 break;
1238             case Right::RESTOREACCOUNT:
1239                 $result = common_config('profile', 'restore');
1240                 break;
1241             case Right::DELETEACCOUNT:
1242                 $result = common_config('profile', 'delete');
1243                 break;
1244             case Right::MOVEACCOUNT:
1245                 $result = common_config('profile', 'move');
1246                 break;
1247             default:
1248                 $result = false;
1249                 break;
1250             }
1251         }
1252         return $result;
1253     }
1254
1255     // FIXME: Can't put Notice typing here due to ArrayWrapper
1256     public function hasRepeated($notice)
1257     {
1258         // XXX: not really a pkey, but should work
1259
1260         $notice = Notice::pkeyGet(array('profile_id' => $this->getID(),
1261                                         'repeat_of' => $notice->getID(),
1262                                         'verb' => ActivityVerb::SHARE));
1263
1264         return !empty($notice);
1265     }
1266
1267     /**
1268      * Returns an XML string fragment with limited profile information
1269      * as an Atom <author> element.
1270      *
1271      * Assumes that Atom has been previously set up as the base namespace.
1272      *
1273      * @param Profile $cur the current authenticated user
1274      *
1275      * @return string
1276      */
1277     function asAtomAuthor($cur = null)
1278     {
1279         $xs = new XMLStringer(true);
1280
1281         $xs->elementStart('author');
1282         $xs->element('name', null, $this->nickname);
1283         $xs->element('uri', null, $this->getUri());
1284         if ($cur != null) {
1285             $attrs = Array();
1286             $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1287             $attrs['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
1288             $xs->element('statusnet:profile_info', $attrs, null);
1289         }
1290         $xs->elementEnd('author');
1291
1292         return $xs->getString();
1293     }
1294
1295     /**
1296      * Extra profile info for atom entries
1297      *
1298      * Clients use some extra profile info in the atom stream.
1299      * This gives it to them.
1300      *
1301      * @param Profile $scoped The currently logged in/scoped profile
1302      *
1303      * @return array representation of <statusnet:profile_info> element or null
1304      */
1305
1306     function profileInfo(Profile $scoped=null)
1307     {
1308         $profileInfoAttr = array('local_id' => $this->id);
1309
1310         if ($scoped instanceof Profile) {
1311             // Whether the current user is a subscribed to this profile
1312             $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1313             // Whether the current user is has blocked this profile
1314             $profileInfoAttr['blocking']  = $scoped->hasBlocked($this) ? 'true' : 'false';
1315         }
1316
1317         return array('statusnet:profile_info', $profileInfoAttr, null);
1318     }
1319
1320     /**
1321      * Returns an XML string fragment with profile information as an
1322      * Activity Streams <activity:actor> element.
1323      *
1324      * Assumes that 'activity' namespace has been previously defined.
1325      *
1326      * @return string
1327      */
1328     function asActivityActor()
1329     {
1330         return $this->asActivityNoun('actor');
1331     }
1332
1333     /**
1334      * Returns an XML string fragment with profile information as an
1335      * Activity Streams noun object with the given element type.
1336      *
1337      * Assumes that 'activity', 'georss', and 'poco' namespace has been
1338      * previously defined.
1339      *
1340      * @param string $element one of 'actor', 'subject', 'object', 'target'
1341      *
1342      * @return string
1343      */
1344     function asActivityNoun($element)
1345     {
1346         $noun = $this->asActivityObject();
1347         return $noun->asString('activity:' . $element);
1348     }
1349
1350     public function asActivityObject()
1351     {
1352         $object = new ActivityObject();
1353
1354         if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1355             $object->type   = $this->getObjectType();
1356             $object->id     = $this->getUri();
1357             $object->title  = $this->getBestName();
1358             $object->link   = $this->getUrl();
1359             $object->summary = $this->getDescription();
1360
1361             try {
1362                 $avatar = Avatar::getUploaded($this);
1363                 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1364             } catch (NoAvatarException $e) {
1365                 // Could not find an original avatar to link
1366             }
1367
1368             $sizes = array(
1369                 AVATAR_PROFILE_SIZE,
1370                 AVATAR_STREAM_SIZE,
1371                 AVATAR_MINI_SIZE
1372             );
1373
1374             foreach ($sizes as $size) {
1375                 $alink  = null;
1376                 try {
1377                     $avatar = Avatar::byProfile($this, $size);
1378                     $alink = AvatarLink::fromAvatar($avatar);
1379                 } catch (NoAvatarException $e) {
1380                     $alink = new AvatarLink();
1381                     $alink->type   = 'image/png';
1382                     $alink->height = $size;
1383                     $alink->width  = $size;
1384                     $alink->url    = Avatar::defaultImage($size);
1385                 }
1386
1387                 $object->avatarLinks[] = $alink;
1388             }
1389
1390             if (isset($this->lat) && isset($this->lon)) {
1391                 $object->geopoint = (float)$this->lat
1392                     . ' ' . (float)$this->lon;
1393             }
1394
1395             $object->poco = PoCo::fromProfile($this);
1396
1397             if ($this->isLocal()) {
1398                 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1399             }
1400
1401             Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1402         }
1403
1404         return $object;
1405     }
1406
1407     /**
1408      * Returns the profile's canonical url, not necessarily a uri/unique id
1409      *
1410      * @return string $profileurl
1411      */
1412     public function getUrl()
1413     {
1414         if (empty($this->profileurl) ||
1415                 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1416             throw new InvalidUrlException($this->profileurl);
1417         }
1418         return $this->profileurl;
1419     }
1420
1421     public function getNickname()
1422     {
1423         return $this->nickname;
1424     }
1425
1426     public function getFullname()
1427     {
1428         return $this->fullname;
1429     }
1430
1431     public function getHomepage()
1432     {
1433         return $this->homepage;
1434     }
1435
1436     public function getDescription()
1437     {
1438         return $this->bio;
1439     }
1440
1441     /**
1442      * Returns the best URI for a profile. Plugins may override.
1443      *
1444      * @return string $uri
1445      */
1446     public function getUri()
1447     {
1448         $uri = null;
1449
1450         // give plugins a chance to set the URI
1451         if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1452
1453             // check for a local user first
1454             $user = User::getKV('id', $this->id);
1455             if ($user instanceof User) {
1456                 $uri = $user->getUri();
1457             } else {
1458                 $group = User_group::getKV('profile_id', $this->id);
1459                 if ($group instanceof User_group) {
1460                     $uri = $group->getUri();
1461                 }
1462             }
1463
1464             Event::handle('EndGetProfileUri', array($this, &$uri));
1465         }
1466
1467         return $uri;
1468     }
1469
1470     /**
1471      * Returns an assumed acct: URI for a profile. Plugins are required.
1472      *
1473      * @return string $uri
1474      */
1475     public function getAcctUri()
1476     {
1477         $acct = null;
1478
1479         if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1480             Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1481         }
1482
1483         if ($acct === null) {
1484             throw new ProfileNoAcctUriException($this);
1485         }
1486
1487         return $acct;
1488     }
1489
1490     function hasBlocked($other)
1491     {
1492         $block = Profile_block::exists($this, $other);
1493         return !empty($block);
1494     }
1495
1496     function getAtomFeed()
1497     {
1498         $feed = null;
1499
1500         if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1501             $user = User::getKV('id', $this->id);
1502             if (!empty($user)) {
1503                 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1504                                                                   'format' => 'atom'));
1505             }
1506             Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1507         }
1508
1509         return $feed;
1510     }
1511
1512     public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
1513     {
1514         // TRANS: Exception thrown when trying view "repeated to me".
1515         throw new Exception(_('Not implemented since inbox change.'));
1516     }
1517
1518     /*
1519      * Get a Profile object by URI. Will call external plugins for help
1520      * using the event StartGetProfileFromURI.
1521      *
1522      * @param string $uri A unique identifier for a resource (profile/group/whatever)
1523      */
1524     static function fromUri($uri)
1525     {
1526         $profile = null;
1527
1528         if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1529             // Get a local user when plugin lookup (like OStatus) fails
1530             $user = User::getKV('uri', $uri);
1531             if ($user instanceof User) {
1532                 $profile = $user->getProfile();
1533             }
1534             Event::handle('EndGetProfileFromURI', array($uri, $profile));
1535         }
1536
1537         if (!$profile instanceof Profile) {
1538             throw new UnknownUriException($uri);
1539         }
1540
1541         return $profile;
1542     }
1543
1544     function canRead(Notice $notice)
1545     {
1546         if ($notice->scope & Notice::SITE_SCOPE) {
1547             $user = $this->getUser();
1548             if (empty($user)) {
1549                 return false;
1550             }
1551         }
1552
1553         if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1554             $replies = $notice->getReplies();
1555
1556             if (!in_array($this->id, $replies)) {
1557                 $groups = $notice->getGroups();
1558
1559                 $foundOne = false;
1560
1561                 foreach ($groups as $group) {
1562                     if ($this->isMember($group)) {
1563                         $foundOne = true;
1564                         break;
1565                     }
1566                 }
1567
1568                 if (!$foundOne) {
1569                     return false;
1570                 }
1571             }
1572         }
1573
1574         if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1575             $author = $notice->getProfile();
1576             if (!Subscription::exists($this, $author)) {
1577                 return false;
1578             }
1579         }
1580
1581         return true;
1582     }
1583
1584     static function current()
1585     {
1586         $user = common_current_user();
1587         if (empty($user)) {
1588             $profile = null;
1589         } else {
1590             $profile = $user->getProfile();
1591         }
1592         return $profile;
1593     }
1594
1595     /**
1596      * Magic function called at serialize() time.
1597      *
1598      * We use this to drop a couple process-specific references
1599      * from DB_DataObject which can cause trouble in future
1600      * processes.
1601      *
1602      * @return array of variable names to include in serialization.
1603      */
1604
1605     function __sleep()
1606     {
1607         $vars = parent::__sleep();
1608         $skip = array('_user', '_group');
1609         return array_diff($vars, $skip);
1610     }
1611
1612     public function getProfile()
1613     {
1614         return $this;
1615     }
1616
1617     /**
1618      * Test whether the given profile is the same as the current class,
1619      * for testing identities.
1620      *
1621      * @param Profile $other    The other profile, usually from Action's $this->scoped
1622      *
1623      * @return boolean
1624      */
1625     public function sameAs(Profile $other=null)
1626     {
1627         if (is_null($other)) {
1628             // In case $this->scoped is null or something, i.e. not a current/legitimate profile.
1629             return false;
1630         }
1631         return $this->getID() === $other->getID();
1632     }
1633
1634     /**
1635      * This will perform shortenLinks with the connected User object.
1636      *
1637      * Won't work on remote profiles or groups, so expect a
1638      * NoSuchUserException if you don't know it's a local User.
1639      *
1640      * @param string $text      String to shorten
1641      * @param boolean $always   Disrespect minimum length etc.
1642      *
1643      * @return string link-shortened $text
1644      */
1645     public function shortenLinks($text, $always=false)
1646     {
1647         return $this->getUser()->shortenLinks($text, $always);
1648     }
1649
1650     public function isPrivateStream()
1651     {
1652         // We only know of public remote users as of yet...
1653         if (!$this->isLocal()) {
1654             return false;
1655         }
1656         return $this->getUser()->private_stream ? true : false;
1657     }
1658
1659     public function delPref($namespace, $topic) {
1660         return Profile_prefs::setData($this, $namespace, $topic, null);
1661     }
1662
1663     public function getPref($namespace, $topic, $default=null) {
1664         // If you want an exception to be thrown, call Profile_prefs::getData directly
1665         try {
1666             return Profile_prefs::getData($this, $namespace, $topic, $default);
1667         } catch (NoResultException $e) {
1668             return null;
1669         }
1670     }
1671
1672     // The same as getPref but will fall back to common_config value for the same namespace/topic
1673     public function getConfigPref($namespace, $topic)
1674     {
1675         return Profile_prefs::getConfigData($this, $namespace, $topic);
1676     }
1677
1678     public function setPref($namespace, $topic, $data) {
1679         return Profile_prefs::setData($this, $namespace, $topic, $data);
1680     }
1681
1682     public function getConnectedApps($offset=0, $limit=null)
1683     {
1684         return $this->getUser()->getConnectedApps($offset, $limit);
1685     }
1686 }