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