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