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