]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Profile.php
only count post-notices (i.e. don't include activity-notices in statuses_count in...
[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|User) $auth_user  Authorized user (used for privacy)
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($auth_user=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 ($auth_user instanceof User || $auth_user instanceof Profile) {
471             $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
472                             'OR ( profile_list.tagger = %d AND ' .
473                             'profile_list.private = true ) )',
474                             $auth_user->id);
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         $notices->whereAdd("verb = '".ActivityVerb::POST."'");        
828         $cnt = (int) $notices->count('distinct id');
829
830         if (!empty($c)) {
831             $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
832         }
833
834         return $cnt;
835     }
836
837     function blowSubscriberCount()
838     {
839         $c = Cache::instance();
840         if (!empty($c)) {
841             $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
842         }
843     }
844
845     function blowSubscriptionCount()
846     {
847         $c = Cache::instance();
848         if (!empty($c)) {
849             $c->delete(Cache::key('profile:subscription_count:'.$this->id));
850         }
851     }
852
853     function blowNoticeCount()
854     {
855         $c = Cache::instance();
856         if (!empty($c)) {
857             $c->delete(Cache::key('profile:notice_count:'.$this->id));
858         }
859     }
860
861     static function maxBio()
862     {
863         $biolimit = common_config('profile', 'biolimit');
864         // null => use global limit (distinct from 0!)
865         if (is_null($biolimit)) {
866             $biolimit = common_config('site', 'textlimit');
867         }
868         return $biolimit;
869     }
870
871     static function bioTooLong($bio)
872     {
873         $biolimit = self::maxBio();
874         return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
875     }
876
877     function update($dataObject=false)
878     {
879         if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
880             try {
881                 $local = $this->getUser();
882                 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
883                 $origuser = clone($local);
884                 $local->nickname = $this->nickname;
885                 // updateWithKeys throws exception on failure.
886                 $local->updateWithKeys($origuser);
887
888                 // Clear the site owner, in case nickname changed
889                 if ($local->hasRole(Profile_role::OWNER)) {
890                     User::blow('user:site_owner');
891                 }
892             } catch (NoSuchUserException $e) {
893                 // Nevermind...
894             }
895         }
896
897         return parent::update($dataObject);
898     }
899
900     function delete($useWhere=false)
901     {
902         // just in case it hadn't been done before... (usually set before adding deluser to queue handling!)
903         if (!$this->hasRole(Profile_role::DELETED)) {
904             $this->grantRole(Profile_role::DELETED);
905         }
906
907         $this->_deleteNotices();
908         $this->_deleteSubscriptions();
909         $this->_deleteTags();
910         $this->_deleteBlocks();
911         $this->_deleteAttentions();
912         Avatar::deleteFromProfile($this, true);
913
914         // Warning: delete() will run on the batch objects,
915         // not on individual objects.
916         $related = array('Reply',
917                          'Group_member',
918                          );
919         Event::handle('ProfileDeleteRelated', array($this, &$related));
920
921         foreach ($related as $cls) {
922             $inst = new $cls();
923             $inst->profile_id = $this->id;
924             $inst->delete();
925         }
926
927         $localuser = User::getKV('id', $this->id);
928         if ($localuser instanceof User) {
929             $localuser->delete();
930         }
931
932         return parent::delete($useWhere);
933     }
934
935     function _deleteNotices()
936     {
937         $notice = new Notice();
938         $notice->profile_id = $this->id;
939
940         if ($notice->find()) {
941             while ($notice->fetch()) {
942                 $other = clone($notice);
943                 $other->delete();
944             }
945         }
946     }
947
948     function _deleteSubscriptions()
949     {
950         $sub = new Subscription();
951         $sub->subscriber = $this->getID();
952         $sub->find();
953
954         while ($sub->fetch()) {
955             try {
956                 $other = $sub->getSubscribed();
957                 if (!$other->sameAs($this)) {
958                     Subscription::cancel($this, $other);
959                 }
960             } catch (NoResultException $e) {
961                 // Profile not found
962                 common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
963             } catch (ServerException $e) {
964                 // Subscription cancel failed
965                 common_log(LOG_INFO, 'Subscribed profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
966             }
967         }
968
969         $sub = new Subscription();
970         $sub->subscribed = $this->getID();
971         $sub->find();
972
973         while ($sub->fetch()) {
974             try {
975                 $other = $sub->getSubscriber();
976                 common_log(LOG_INFO, 'Subscriber profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
977                 if (!$other->sameAs($this)) {
978                     Subscription::cancel($other, $this);
979                 }
980             } catch (NoResultException $e) {
981                 // Profile not found
982                 common_log(LOG_INFO, 'Subscribed profile id=='.$sub->subscribed.' not found when deleting profile id=='.$this->getID().', ignoring...');
983             } catch (ServerException $e) {
984                 // Subscription cancel failed
985                 common_log(LOG_INFO, 'Subscriber profile id=='.$other->getID().' could not be reached for unsubscription notice when deleting profile id=='.$this->getID().', ignoring...');
986             }
987         }
988
989         // Finally delete self-subscription
990         $self = new Subscription();
991         $self->subscriber = $this->getID();
992         $self->subscribed = $this->getID();
993         $self->delete();
994     }
995
996     function _deleteTags()
997     {
998         $tag = new Profile_tag();
999         $tag->tagged = $this->id;
1000         $tag->delete();
1001     }
1002
1003     function _deleteBlocks()
1004     {
1005         $block = new Profile_block();
1006         $block->blocked = $this->id;
1007         $block->delete();
1008
1009         $block = new Group_block();
1010         $block->blocked = $this->id;
1011         $block->delete();
1012     }
1013
1014     function _deleteAttentions()
1015     {
1016         $att = new Attention();
1017         $att->profile_id = $this->getID();
1018
1019         if ($att->find()) {
1020             while ($att->fetch()) {
1021                 // Can't do delete() on the object directly since it won't remove all of it
1022                 $other = clone($att);
1023                 $other->delete();
1024             }
1025         }
1026     }
1027
1028     // XXX: identical to Notice::getLocation.
1029
1030     public function getLocation()
1031     {
1032         $location = null;
1033
1034         if (!empty($this->location_id) && !empty($this->location_ns)) {
1035             $location = Location::fromId($this->location_id, $this->location_ns);
1036         }
1037
1038         if (is_null($location)) { // no ID, or Location::fromId() failed
1039             if (!empty($this->lat) && !empty($this->lon)) {
1040                 $location = Location::fromLatLon($this->lat, $this->lon);
1041             }
1042         }
1043
1044         if (is_null($location)) { // still haven't found it!
1045             if (!empty($this->location)) {
1046                 $location = Location::fromName($this->location);
1047             }
1048         }
1049
1050         return $location;
1051     }
1052
1053     public function shareLocation()
1054     {
1055         $cfg = common_config('location', 'share');
1056
1057         if ($cfg == 'always') {
1058             return true;
1059         } else if ($cfg == 'never') {
1060             return false;
1061         } else { // user
1062             $share = common_config('location', 'sharedefault');
1063
1064             // Check if user has a personal setting for this
1065             $prefs = User_location_prefs::getKV('user_id', $this->id);
1066
1067             if (!empty($prefs)) {
1068                 $share = $prefs->share_location;
1069                 $prefs->free();
1070             }
1071
1072             return $share;
1073         }
1074     }
1075
1076     function hasRole($name)
1077     {
1078         $has_role = false;
1079         if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1080             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1081                                                 'role' => $name));
1082             $has_role = !empty($role);
1083             Event::handle('EndHasRole', array($this, $name, $has_role));
1084         }
1085         return $has_role;
1086     }
1087
1088     function grantRole($name)
1089     {
1090         if (Event::handle('StartGrantRole', array($this, $name))) {
1091
1092             $role = new Profile_role();
1093
1094             $role->profile_id = $this->id;
1095             $role->role       = $name;
1096             $role->created    = common_sql_now();
1097
1098             $result = $role->insert();
1099
1100             if (!$result) {
1101                 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1102             }
1103
1104             if ($name == 'owner') {
1105                 User::blow('user:site_owner');
1106             }
1107
1108             Event::handle('EndGrantRole', array($this, $name));
1109         }
1110
1111         return $result;
1112     }
1113
1114     function revokeRole($name)
1115     {
1116         if (Event::handle('StartRevokeRole', array($this, $name))) {
1117
1118             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1119                                                 'role' => $name));
1120
1121             if (empty($role)) {
1122                 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1123                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1124                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1125             }
1126
1127             $result = $role->delete();
1128
1129             if (!$result) {
1130                 common_log_db_error($role, 'DELETE', __FILE__);
1131                 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1132                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1133                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1134             }
1135
1136             if ($name == 'owner') {
1137                 User::blow('user:site_owner');
1138             }
1139
1140             Event::handle('EndRevokeRole', array($this, $name));
1141
1142             return true;
1143         }
1144     }
1145
1146     function isSandboxed()
1147     {
1148         return $this->hasRole(Profile_role::SANDBOXED);
1149     }
1150
1151     function isSilenced()
1152     {
1153         return $this->hasRole(Profile_role::SILENCED);
1154     }
1155
1156     function sandbox()
1157     {
1158         $this->grantRole(Profile_role::SANDBOXED);
1159     }
1160
1161     function unsandbox()
1162     {
1163         $this->revokeRole(Profile_role::SANDBOXED);
1164     }
1165
1166     function silence()
1167     {
1168         $this->grantRole(Profile_role::SILENCED);
1169         if (common_config('notice', 'hidespam')) {
1170             $this->flushVisibility();
1171         }
1172     }
1173
1174     function unsilence()
1175     {
1176         $this->revokeRole(Profile_role::SILENCED);
1177         if (common_config('notice', 'hidespam')) {
1178             $this->flushVisibility();
1179         }
1180     }
1181
1182     function flushVisibility()
1183     {
1184         // Get all notices
1185         $stream = new ProfileNoticeStream($this, $this);
1186         $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1187         foreach ($ids as $id) {
1188             self::blow('notice:in-scope-for:%d:null', $id);
1189         }
1190     }
1191
1192     /**
1193      * Does this user have the right to do X?
1194      *
1195      * With our role-based authorization, this is merely a lookup for whether the user
1196      * has a particular role. The implementation currently uses a switch statement
1197      * to determine if the user has the pre-defined role to exercise the right. Future
1198      * implementations may allow per-site roles, and different mappings of roles to rights.
1199      *
1200      * @param $right string Name of the right, usually a constant in class Right
1201      * @return boolean whether the user has the right in question
1202      */
1203     public function hasRight($right)
1204     {
1205         $result = false;
1206
1207         if ($this->hasRole(Profile_role::DELETED)) {
1208             return false;
1209         }
1210
1211         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1212             switch ($right)
1213             {
1214             case Right::DELETEOTHERSNOTICE:
1215             case Right::MAKEGROUPADMIN:
1216             case Right::SANDBOXUSER:
1217             case Right::SILENCEUSER:
1218             case Right::DELETEUSER:
1219             case Right::DELETEGROUP:
1220             case Right::TRAINSPAM:
1221             case Right::REVIEWSPAM:
1222                 $result = $this->hasRole(Profile_role::MODERATOR);
1223                 break;
1224             case Right::CONFIGURESITE:
1225                 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1226                 break;
1227             case Right::GRANTROLE:
1228             case Right::REVOKEROLE:
1229                 $result = $this->hasRole(Profile_role::OWNER);
1230                 break;
1231             case Right::NEWNOTICE:
1232             case Right::NEWMESSAGE:
1233             case Right::SUBSCRIBE:
1234             case Right::CREATEGROUP:
1235                 $result = !$this->isSilenced();
1236                 break;
1237             case Right::PUBLICNOTICE:
1238             case Right::EMAILONREPLY:
1239             case Right::EMAILONSUBSCRIBE:
1240             case Right::EMAILONFAVE:
1241                 $result = !$this->isSandboxed();
1242                 break;
1243             case Right::WEBLOGIN:
1244                 $result = !$this->isSilenced();
1245                 break;
1246             case Right::API:
1247                 $result = !$this->isSilenced();
1248                 break;
1249             case Right::BACKUPACCOUNT:
1250                 $result = common_config('profile', 'backup');
1251                 break;
1252             case Right::RESTOREACCOUNT:
1253                 $result = common_config('profile', 'restore');
1254                 break;
1255             case Right::DELETEACCOUNT:
1256                 $result = common_config('profile', 'delete');
1257                 break;
1258             case Right::MOVEACCOUNT:
1259                 $result = common_config('profile', 'move');
1260                 break;
1261             default:
1262                 $result = false;
1263                 break;
1264             }
1265         }
1266         return $result;
1267     }
1268
1269     // FIXME: Can't put Notice typing here due to ArrayWrapper
1270     public function hasRepeated($notice)
1271     {
1272         // XXX: not really a pkey, but should work
1273
1274         $notice = Notice::pkeyGet(array('profile_id' => $this->getID(),
1275                                         'repeat_of' => $notice->getID(),
1276                                         'verb' => ActivityVerb::SHARE));
1277
1278         return !empty($notice);
1279     }
1280
1281     /**
1282      * Returns an XML string fragment with limited profile information
1283      * as an Atom <author> element.
1284      *
1285      * Assumes that Atom has been previously set up as the base namespace.
1286      *
1287      * @param Profile $cur the current authenticated user
1288      *
1289      * @return string
1290      */
1291     function asAtomAuthor($cur = null)
1292     {
1293         $xs = new XMLStringer(true);
1294
1295         $xs->elementStart('author');
1296         $xs->element('name', null, $this->nickname);
1297         $xs->element('uri', null, $this->getUri());
1298         if ($cur != null) {
1299             $attrs = Array();
1300             $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1301             $attrs['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
1302             $xs->element('statusnet:profile_info', $attrs, null);
1303         }
1304         $xs->elementEnd('author');
1305
1306         return $xs->getString();
1307     }
1308
1309     /**
1310      * Extra profile info for atom entries
1311      *
1312      * Clients use some extra profile info in the atom stream.
1313      * This gives it to them.
1314      *
1315      * @param Profile $scoped The currently logged in/scoped profile
1316      *
1317      * @return array representation of <statusnet:profile_info> element or null
1318      */
1319
1320     function profileInfo(Profile $scoped=null)
1321     {
1322         $profileInfoAttr = array('local_id' => $this->id);
1323
1324         if ($scoped instanceof Profile) {
1325             // Whether the current user is a subscribed to this profile
1326             $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1327             // Whether the current user is has blocked this profile
1328             $profileInfoAttr['blocking']  = $scoped->hasBlocked($this) ? 'true' : 'false';
1329         }
1330
1331         return array('statusnet:profile_info', $profileInfoAttr, null);
1332     }
1333
1334     /**
1335      * Returns an XML string fragment with profile information as an
1336      * Activity Streams <activity:actor> element.
1337      *
1338      * Assumes that 'activity' namespace has been previously defined.
1339      *
1340      * @return string
1341      */
1342     function asActivityActor()
1343     {
1344         return $this->asActivityNoun('actor');
1345     }
1346
1347     /**
1348      * Returns an XML string fragment with profile information as an
1349      * Activity Streams noun object with the given element type.
1350      *
1351      * Assumes that 'activity', 'georss', and 'poco' namespace has been
1352      * previously defined.
1353      *
1354      * @param string $element one of 'actor', 'subject', 'object', 'target'
1355      *
1356      * @return string
1357      */
1358     function asActivityNoun($element)
1359     {
1360         $noun = $this->asActivityObject();
1361         return $noun->asString('activity:' . $element);
1362     }
1363
1364     public function asActivityObject()
1365     {
1366         $object = new ActivityObject();
1367
1368         if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1369             $object->type   = $this->getObjectType();
1370             $object->id     = $this->getUri();
1371             $object->title  = $this->getBestName();
1372             $object->link   = $this->getUrl();
1373             $object->summary = $this->getDescription();
1374
1375             try {
1376                 $avatar = Avatar::getUploaded($this);
1377                 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1378             } catch (NoAvatarException $e) {
1379                 // Could not find an original avatar to link
1380             }
1381
1382             $sizes = array(
1383                 AVATAR_PROFILE_SIZE,
1384                 AVATAR_STREAM_SIZE,
1385                 AVATAR_MINI_SIZE
1386             );
1387
1388             foreach ($sizes as $size) {
1389                 $alink  = null;
1390                 try {
1391                     $avatar = Avatar::byProfile($this, $size);
1392                     $alink = AvatarLink::fromAvatar($avatar);
1393                 } catch (NoAvatarException $e) {
1394                     $alink = new AvatarLink();
1395                     $alink->type   = 'image/png';
1396                     $alink->height = $size;
1397                     $alink->width  = $size;
1398                     $alink->url    = Avatar::defaultImage($size);
1399                 }
1400
1401                 $object->avatarLinks[] = $alink;
1402             }
1403
1404             if (isset($this->lat) && isset($this->lon)) {
1405                 $object->geopoint = (float)$this->lat
1406                     . ' ' . (float)$this->lon;
1407             }
1408
1409             $object->poco = PoCo::fromProfile($this);
1410
1411             if ($this->isLocal()) {
1412                 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1413             }
1414
1415             Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1416         }
1417
1418         return $object;
1419     }
1420
1421     /**
1422      * Returns the profile's canonical url, not necessarily a uri/unique id
1423      *
1424      * @return string $profileurl
1425      */
1426     public function getUrl()
1427     {
1428         if (empty($this->profileurl) ||
1429                 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1430             throw new InvalidUrlException($this->profileurl);
1431         }
1432         return $this->profileurl;
1433     }
1434
1435     public function getNickname()
1436     {
1437         return $this->nickname;
1438     }
1439
1440     public function getFullname()
1441     {
1442         return $this->fullname;
1443     }
1444
1445     public function getHomepage()
1446     {
1447         return $this->homepage;
1448     }
1449
1450     public function getDescription()
1451     {
1452         return $this->bio;
1453     }
1454
1455     /**
1456      * Returns the best URI for a profile. Plugins may override.
1457      *
1458      * @return string $uri
1459      */
1460     public function getUri()
1461     {
1462         $uri = null;
1463
1464         // give plugins a chance to set the URI
1465         if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1466
1467             // check for a local user first
1468             $user = User::getKV('id', $this->id);
1469             if ($user instanceof User) {
1470                 $uri = $user->getUri();
1471             } else {
1472                 $group = User_group::getKV('profile_id', $this->id);
1473                 if ($group instanceof User_group) {
1474                     $uri = $group->getUri();
1475                 }
1476             }
1477
1478             Event::handle('EndGetProfileUri', array($this, &$uri));
1479         }
1480
1481         return $uri;
1482     }
1483
1484     /**
1485      * Returns an assumed acct: URI for a profile. Plugins are required.
1486      *
1487      * @return string $uri
1488      */
1489     public function getAcctUri()
1490     {
1491         $acct = null;
1492
1493         if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1494             Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1495         }
1496
1497         if ($acct === null) {
1498             throw new ProfileNoAcctUriException($this);
1499         }
1500
1501         return $acct;
1502     }
1503
1504     function hasBlocked($other)
1505     {
1506         $block = Profile_block::exists($this, $other);
1507         return !empty($block);
1508     }
1509
1510     function getAtomFeed()
1511     {
1512         $feed = null;
1513
1514         if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1515             $user = User::getKV('id', $this->id);
1516             if (!empty($user)) {
1517                 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1518                                                                   'format' => 'atom'));
1519             }
1520             Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1521         }
1522
1523         return $feed;
1524     }
1525
1526     public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
1527     {
1528         // TRANS: Exception thrown when trying view "repeated to me".
1529         throw new Exception(_('Not implemented since inbox change.'));
1530     }
1531
1532     /*
1533      * Get a Profile object by URI. Will call external plugins for help
1534      * using the event StartGetProfileFromURI.
1535      *
1536      * @param string $uri A unique identifier for a resource (profile/group/whatever)
1537      */
1538     static function fromUri($uri)
1539     {
1540         $profile = null;
1541
1542         if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1543             // Get a local user when plugin lookup (like OStatus) fails
1544             $user = User::getKV('uri', $uri);
1545             if ($user instanceof User) {
1546                 $profile = $user->getProfile();
1547             }
1548             Event::handle('EndGetProfileFromURI', array($uri, $profile));
1549         }
1550
1551         if (!$profile instanceof Profile) {
1552             throw new UnknownUriException($uri);
1553         }
1554
1555         return $profile;
1556     }
1557
1558     function canRead(Notice $notice)
1559     {
1560         if ($notice->scope & Notice::SITE_SCOPE) {
1561             $user = $this->getUser();
1562             if (empty($user)) {
1563                 return false;
1564             }
1565         }
1566
1567         if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1568             $replies = $notice->getReplies();
1569
1570             if (!in_array($this->id, $replies)) {
1571                 $groups = $notice->getGroups();
1572
1573                 $foundOne = false;
1574
1575                 foreach ($groups as $group) {
1576                     if ($this->isMember($group)) {
1577                         $foundOne = true;
1578                         break;
1579                     }
1580                 }
1581
1582                 if (!$foundOne) {
1583                     return false;
1584                 }
1585             }
1586         }
1587
1588         if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1589             $author = $notice->getProfile();
1590             if (!Subscription::exists($this, $author)) {
1591                 return false;
1592             }
1593         }
1594
1595         return true;
1596     }
1597
1598     static function current()
1599     {
1600         $user = common_current_user();
1601         if (empty($user)) {
1602             $profile = null;
1603         } else {
1604             $profile = $user->getProfile();
1605         }
1606         return $profile;
1607     }
1608
1609     /**
1610      * Magic function called at serialize() time.
1611      *
1612      * We use this to drop a couple process-specific references
1613      * from DB_DataObject which can cause trouble in future
1614      * processes.
1615      *
1616      * @return array of variable names to include in serialization.
1617      */
1618
1619     function __sleep()
1620     {
1621         $vars = parent::__sleep();
1622         $skip = array('_user', '_group');
1623         return array_diff($vars, $skip);
1624     }
1625
1626     public function getProfile()
1627     {
1628         return $this;
1629     }
1630
1631     /**
1632      * Test whether the given profile is the same as the current class,
1633      * for testing identities.
1634      *
1635      * @param Profile $other    The other profile, usually from Action's $this->scoped
1636      *
1637      * @return boolean
1638      */
1639     public function sameAs(Profile $other=null)
1640     {
1641         if (is_null($other)) {
1642             // In case $this->scoped is null or something, i.e. not a current/legitimate profile.
1643             return false;
1644         }
1645         return $this->getID() === $other->getID();
1646     }
1647
1648     /**
1649      * This will perform shortenLinks with the connected User object.
1650      *
1651      * Won't work on remote profiles or groups, so expect a
1652      * NoSuchUserException if you don't know it's a local User.
1653      *
1654      * @param string $text      String to shorten
1655      * @param boolean $always   Disrespect minimum length etc.
1656      *
1657      * @return string link-shortened $text
1658      */
1659     public function shortenLinks($text, $always=false)
1660     {
1661         return $this->getUser()->shortenLinks($text, $always);
1662     }
1663
1664     public function isPrivateStream()
1665     {
1666         // We only know of public remote users as of yet...
1667         if (!$this->isLocal()) {
1668             return false;
1669         }
1670         return $this->getUser()->private_stream ? true : false;
1671     }
1672
1673     public function delPref($namespace, $topic) {
1674         return Profile_prefs::setData($this, $namespace, $topic, null);
1675     }
1676
1677     public function getPref($namespace, $topic, $default=null) {
1678         // If you want an exception to be thrown, call Profile_prefs::getData directly
1679         try {
1680             return Profile_prefs::getData($this, $namespace, $topic, $default);
1681         } catch (NoResultException $e) {
1682             return null;
1683         }
1684     }
1685
1686     // The same as getPref but will fall back to common_config value for the same namespace/topic
1687     public function getConfigPref($namespace, $topic)
1688     {
1689         return Profile_prefs::getConfigData($this, $namespace, $topic);
1690     }
1691
1692     public function setPref($namespace, $topic, $data) {
1693         return Profile_prefs::setData($this, $namespace, $topic, $data);
1694     }
1695
1696     public function getConnectedApps($offset=0, $limit=null)
1697     {
1698         return $this->getUser()->getConnectedApps($offset, $limit);
1699     }
1700 }