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