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