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