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