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