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