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