]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Profile.php
upgrade script makes sure all notices have rendered copies
[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     /**
765      * Check if a pending subscription request is outstanding for this...
766      *
767      * @param Profile $other
768      * @return boolean
769      */
770     function hasPendingSubscription(Profile $other)
771     {
772         return Subscription_queue::exists($this, $other);
773     }
774
775     /**
776      * Are these two profiles subscribed to each other?
777      *
778      * @param Profile $other
779      * @return boolean
780      */
781     function mutuallySubscribed(Profile $other)
782     {
783         return $this->isSubscribed($other) &&
784           $other->isSubscribed($this);
785     }
786
787     function noticeCount()
788     {
789         $c = Cache::instance();
790
791         if (!empty($c)) {
792             $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
793             if (is_integer($cnt)) {
794                 return (int) $cnt;
795             }
796         }
797
798         $notices = new Notice();
799         $notices->profile_id = $this->id;
800         $cnt = (int) $notices->count('distinct id');
801
802         if (!empty($c)) {
803             $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
804         }
805
806         return $cnt;
807     }
808
809     function blowSubscriberCount()
810     {
811         $c = Cache::instance();
812         if (!empty($c)) {
813             $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
814         }
815     }
816
817     function blowSubscriptionCount()
818     {
819         $c = Cache::instance();
820         if (!empty($c)) {
821             $c->delete(Cache::key('profile:subscription_count:'.$this->id));
822         }
823     }
824
825     function blowNoticeCount()
826     {
827         $c = Cache::instance();
828         if (!empty($c)) {
829             $c->delete(Cache::key('profile:notice_count:'.$this->id));
830         }
831     }
832
833     static function maxBio()
834     {
835         $biolimit = common_config('profile', 'biolimit');
836         // null => use global limit (distinct from 0!)
837         if (is_null($biolimit)) {
838             $biolimit = common_config('site', 'textlimit');
839         }
840         return $biolimit;
841     }
842
843     static function bioTooLong($bio)
844     {
845         $biolimit = self::maxBio();
846         return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
847     }
848
849     function update($dataObject=false)
850     {
851         if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
852             try {
853                 $local = $this->getUser();
854                 common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
855                 $origuser = clone($local);
856                 $local->nickname = $this->nickname;
857                 // updateWithKeys throws exception on failure.
858                 $local->updateWithKeys($origuser);
859
860                 // Clear the site owner, in case nickname changed
861                 if ($local->hasRole(Profile_role::OWNER)) {
862                     User::blow('user:site_owner');
863                 }
864             } catch (NoSuchUserException $e) {
865                 // Nevermind...
866             }
867         }
868
869         return parent::update($dataObject);
870     }
871
872     function delete($useWhere=false)
873     {
874         // just in case it hadn't been done before... (usually set before adding deluser to queue handling!)
875         if (!$this->hasRole(Profile_role::DELETED)) {
876             $this->grantRole(Profile_role::DELETED);
877         }
878
879         $this->_deleteNotices();
880         $this->_deleteSubscriptions();
881         $this->_deleteTags();
882         $this->_deleteBlocks();
883         $this->_deleteAttentions();
884         Avatar::deleteFromProfile($this, true);
885
886         // Warning: delete() will run on the batch objects,
887         // not on individual objects.
888         $related = array('Reply',
889                          'Group_member',
890                          );
891         Event::handle('ProfileDeleteRelated', array($this, &$related));
892
893         foreach ($related as $cls) {
894             $inst = new $cls();
895             $inst->profile_id = $this->id;
896             $inst->delete();
897         }
898
899         $localuser = User::getKV('id', $this->id);
900         if ($localuser instanceof User) {
901             $localuser->delete();
902         }
903
904         return parent::delete($useWhere);
905     }
906
907     function _deleteNotices()
908     {
909         $notice = new Notice();
910         $notice->profile_id = $this->id;
911
912         if ($notice->find()) {
913             while ($notice->fetch()) {
914                 $other = clone($notice);
915                 $other->delete();
916             }
917         }
918     }
919
920     function _deleteSubscriptions()
921     {
922         $sub = new Subscription();
923         $sub->subscriber = $this->id;
924
925         $sub->find();
926
927         while ($sub->fetch()) {
928             $other = Profile::getKV('id', $sub->subscribed);
929             if (empty($other)) {
930                 continue;
931             }
932             if ($other->id == $this->id) {
933                 continue;
934             }
935             Subscription::cancel($this, $other);
936         }
937
938         $subd = new Subscription();
939         $subd->subscribed = $this->id;
940         $subd->find();
941
942         while ($subd->fetch()) {
943             $other = Profile::getKV('id', $subd->subscriber);
944             if (empty($other)) {
945                 continue;
946             }
947             if ($other->id == $this->id) {
948                 continue;
949             }
950             Subscription::cancel($other, $this);
951         }
952
953         $self = new Subscription();
954
955         $self->subscriber = $this->id;
956         $self->subscribed = $this->id;
957
958         $self->delete();
959     }
960
961     function _deleteTags()
962     {
963         $tag = new Profile_tag();
964         $tag->tagged = $this->id;
965         $tag->delete();
966     }
967
968     function _deleteBlocks()
969     {
970         $block = new Profile_block();
971         $block->blocked = $this->id;
972         $block->delete();
973
974         $block = new Group_block();
975         $block->blocked = $this->id;
976         $block->delete();
977     }
978
979     function _deleteAttentions()
980     {
981         $att = new Attention();
982         $att->profile_id = $this->getID();
983
984         if ($att->find()) {
985             while ($att->fetch()) {
986                 // Can't do delete() on the object directly since it won't remove all of it
987                 $other = clone($att);
988                 $other->delete();
989             }
990         }
991     }
992
993     // XXX: identical to Notice::getLocation.
994
995     public function getLocation()
996     {
997         $location = null;
998
999         if (!empty($this->location_id) && !empty($this->location_ns)) {
1000             $location = Location::fromId($this->location_id, $this->location_ns);
1001         }
1002
1003         if (is_null($location)) { // no ID, or Location::fromId() failed
1004             if (!empty($this->lat) && !empty($this->lon)) {
1005                 $location = Location::fromLatLon($this->lat, $this->lon);
1006             }
1007         }
1008
1009         if (is_null($location)) { // still haven't found it!
1010             if (!empty($this->location)) {
1011                 $location = Location::fromName($this->location);
1012             }
1013         }
1014
1015         return $location;
1016     }
1017
1018     public function shareLocation()
1019     {
1020         $cfg = common_config('location', 'share');
1021
1022         if ($cfg == 'always') {
1023             return true;
1024         } else if ($cfg == 'never') {
1025             return false;
1026         } else { // user
1027             $share = common_config('location', 'sharedefault');
1028
1029             // Check if user has a personal setting for this
1030             $prefs = User_location_prefs::getKV('user_id', $this->id);
1031
1032             if (!empty($prefs)) {
1033                 $share = $prefs->share_location;
1034                 $prefs->free();
1035             }
1036
1037             return $share;
1038         }
1039     }
1040
1041     function hasRole($name)
1042     {
1043         $has_role = false;
1044         if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1045             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1046                                                 'role' => $name));
1047             $has_role = !empty($role);
1048             Event::handle('EndHasRole', array($this, $name, $has_role));
1049         }
1050         return $has_role;
1051     }
1052
1053     function grantRole($name)
1054     {
1055         if (Event::handle('StartGrantRole', array($this, $name))) {
1056
1057             $role = new Profile_role();
1058
1059             $role->profile_id = $this->id;
1060             $role->role       = $name;
1061             $role->created    = common_sql_now();
1062
1063             $result = $role->insert();
1064
1065             if (!$result) {
1066                 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1067             }
1068
1069             if ($name == 'owner') {
1070                 User::blow('user:site_owner');
1071             }
1072
1073             Event::handle('EndGrantRole', array($this, $name));
1074         }
1075
1076         return $result;
1077     }
1078
1079     function revokeRole($name)
1080     {
1081         if (Event::handle('StartRevokeRole', array($this, $name))) {
1082
1083             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1084                                                 'role' => $name));
1085
1086             if (empty($role)) {
1087                 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1088                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1089                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1090             }
1091
1092             $result = $role->delete();
1093
1094             if (!$result) {
1095                 common_log_db_error($role, 'DELETE', __FILE__);
1096                 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1097                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1098                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1099             }
1100
1101             if ($name == 'owner') {
1102                 User::blow('user:site_owner');
1103             }
1104
1105             Event::handle('EndRevokeRole', array($this, $name));
1106
1107             return true;
1108         }
1109     }
1110
1111     function isSandboxed()
1112     {
1113         return $this->hasRole(Profile_role::SANDBOXED);
1114     }
1115
1116     function isSilenced()
1117     {
1118         return $this->hasRole(Profile_role::SILENCED);
1119     }
1120
1121     function sandbox()
1122     {
1123         $this->grantRole(Profile_role::SANDBOXED);
1124     }
1125
1126     function unsandbox()
1127     {
1128         $this->revokeRole(Profile_role::SANDBOXED);
1129     }
1130
1131     function silence()
1132     {
1133         $this->grantRole(Profile_role::SILENCED);
1134         if (common_config('notice', 'hidespam')) {
1135             $this->flushVisibility();
1136         }
1137     }
1138
1139     function unsilence()
1140     {
1141         $this->revokeRole(Profile_role::SILENCED);
1142         if (common_config('notice', 'hidespam')) {
1143             $this->flushVisibility();
1144         }
1145     }
1146
1147     function flushVisibility()
1148     {
1149         // Get all notices
1150         $stream = new ProfileNoticeStream($this, $this);
1151         $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1152         foreach ($ids as $id) {
1153             self::blow('notice:in-scope-for:%d:null', $id);
1154         }
1155     }
1156
1157     /**
1158      * Does this user have the right to do X?
1159      *
1160      * With our role-based authorization, this is merely a lookup for whether the user
1161      * has a particular role. The implementation currently uses a switch statement
1162      * to determine if the user has the pre-defined role to exercise the right. Future
1163      * implementations may allow per-site roles, and different mappings of roles to rights.
1164      *
1165      * @param $right string Name of the right, usually a constant in class Right
1166      * @return boolean whether the user has the right in question
1167      */
1168     public function hasRight($right)
1169     {
1170         $result = false;
1171
1172         if ($this->hasRole(Profile_role::DELETED)) {
1173             return false;
1174         }
1175
1176         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1177             switch ($right)
1178             {
1179             case Right::DELETEOTHERSNOTICE:
1180             case Right::MAKEGROUPADMIN:
1181             case Right::SANDBOXUSER:
1182             case Right::SILENCEUSER:
1183             case Right::DELETEUSER:
1184             case Right::DELETEGROUP:
1185             case Right::TRAINSPAM:
1186             case Right::REVIEWSPAM:
1187                 $result = $this->hasRole(Profile_role::MODERATOR);
1188                 break;
1189             case Right::CONFIGURESITE:
1190                 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1191                 break;
1192             case Right::GRANTROLE:
1193             case Right::REVOKEROLE:
1194                 $result = $this->hasRole(Profile_role::OWNER);
1195                 break;
1196             case Right::NEWNOTICE:
1197             case Right::NEWMESSAGE:
1198             case Right::SUBSCRIBE:
1199             case Right::CREATEGROUP:
1200                 $result = !$this->isSilenced();
1201                 break;
1202             case Right::PUBLICNOTICE:
1203             case Right::EMAILONREPLY:
1204             case Right::EMAILONSUBSCRIBE:
1205             case Right::EMAILONFAVE:
1206                 $result = !$this->isSandboxed();
1207                 break;
1208             case Right::WEBLOGIN:
1209                 $result = !$this->isSilenced();
1210                 break;
1211             case Right::API:
1212                 $result = !$this->isSilenced();
1213                 break;
1214             case Right::BACKUPACCOUNT:
1215                 $result = common_config('profile', 'backup');
1216                 break;
1217             case Right::RESTOREACCOUNT:
1218                 $result = common_config('profile', 'restore');
1219                 break;
1220             case Right::DELETEACCOUNT:
1221                 $result = common_config('profile', 'delete');
1222                 break;
1223             case Right::MOVEACCOUNT:
1224                 $result = common_config('profile', 'move');
1225                 break;
1226             default:
1227                 $result = false;
1228                 break;
1229             }
1230         }
1231         return $result;
1232     }
1233
1234     // FIXME: Can't put Notice typing here due to ArrayWrapper
1235     public function hasRepeated($notice)
1236     {
1237         // XXX: not really a pkey, but should work
1238
1239         $notice = Notice::pkeyGet(array('profile_id' => $this->getID(),
1240                                         'repeat_of' => $notice->getID(),
1241                                         'verb' => ActivityVerb::SHARE));
1242
1243         return !empty($notice);
1244     }
1245
1246     /**
1247      * Returns an XML string fragment with limited profile information
1248      * as an Atom <author> element.
1249      *
1250      * Assumes that Atom has been previously set up as the base namespace.
1251      *
1252      * @param Profile $cur the current authenticated user
1253      *
1254      * @return string
1255      */
1256     function asAtomAuthor($cur = null)
1257     {
1258         $xs = new XMLStringer(true);
1259
1260         $xs->elementStart('author');
1261         $xs->element('name', null, $this->nickname);
1262         $xs->element('uri', null, $this->getUri());
1263         if ($cur != null) {
1264             $attrs = Array();
1265             $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1266             $attrs['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
1267             $xs->element('statusnet:profile_info', $attrs, null);
1268         }
1269         $xs->elementEnd('author');
1270
1271         return $xs->getString();
1272     }
1273
1274     /**
1275      * Extra profile info for atom entries
1276      *
1277      * Clients use some extra profile info in the atom stream.
1278      * This gives it to them.
1279      *
1280      * @param Profile $scoped The currently logged in/scoped profile
1281      *
1282      * @return array representation of <statusnet:profile_info> element or null
1283      */
1284
1285     function profileInfo(Profile $scoped=null)
1286     {
1287         $profileInfoAttr = array('local_id' => $this->id);
1288
1289         if ($scoped instanceof Profile) {
1290             // Whether the current user is a subscribed to this profile
1291             $profileInfoAttr['following'] = $scoped->isSubscribed($this) ? 'true' : 'false';
1292             // Whether the current user is has blocked this profile
1293             $profileInfoAttr['blocking']  = $scoped->hasBlocked($this) ? 'true' : 'false';
1294         }
1295
1296         return array('statusnet:profile_info', $profileInfoAttr, null);
1297     }
1298
1299     /**
1300      * Returns an XML string fragment with profile information as an
1301      * Activity Streams <activity:actor> element.
1302      *
1303      * Assumes that 'activity' namespace has been previously defined.
1304      *
1305      * @return string
1306      */
1307     function asActivityActor()
1308     {
1309         return $this->asActivityNoun('actor');
1310     }
1311
1312     /**
1313      * Returns an XML string fragment with profile information as an
1314      * Activity Streams noun object with the given element type.
1315      *
1316      * Assumes that 'activity', 'georss', and 'poco' namespace has been
1317      * previously defined.
1318      *
1319      * @param string $element one of 'actor', 'subject', 'object', 'target'
1320      *
1321      * @return string
1322      */
1323     function asActivityNoun($element)
1324     {
1325         $noun = $this->asActivityObject();
1326         return $noun->asString('activity:' . $element);
1327     }
1328
1329     public function asActivityObject()
1330     {
1331         $object = new ActivityObject();
1332
1333         if (Event::handle('StartActivityObjectFromProfile', array($this, &$object))) {
1334             $object->type   = $this->getObjectType();
1335             $object->id     = $this->getUri();
1336             $object->title  = $this->getBestName();
1337             $object->link   = $this->getUrl();
1338             $object->summary = $this->getDescription();
1339
1340             try {
1341                 $avatar = Avatar::getUploaded($this);
1342                 $object->avatarLinks[] = AvatarLink::fromAvatar($avatar);
1343             } catch (NoAvatarException $e) {
1344                 // Could not find an original avatar to link
1345             }
1346
1347             $sizes = array(
1348                 AVATAR_PROFILE_SIZE,
1349                 AVATAR_STREAM_SIZE,
1350                 AVATAR_MINI_SIZE
1351             );
1352
1353             foreach ($sizes as $size) {
1354                 $alink  = null;
1355                 try {
1356                     $avatar = Avatar::byProfile($this, $size);
1357                     $alink = AvatarLink::fromAvatar($avatar);
1358                 } catch (NoAvatarException $e) {
1359                     $alink = new AvatarLink();
1360                     $alink->type   = 'image/png';
1361                     $alink->height = $size;
1362                     $alink->width  = $size;
1363                     $alink->url    = Avatar::defaultImage($size);
1364                 }
1365
1366                 $object->avatarLinks[] = $alink;
1367             }
1368
1369             if (isset($this->lat) && isset($this->lon)) {
1370                 $object->geopoint = (float)$this->lat
1371                     . ' ' . (float)$this->lon;
1372             }
1373
1374             $object->poco = PoCo::fromProfile($this);
1375
1376             if ($this->isLocal()) {
1377                 $object->extra[] = array('followers', array('url' => common_local_url('subscribers', array('nickname' => $this->getNickname()))));
1378             }
1379
1380             Event::handle('EndActivityObjectFromProfile', array($this, &$object));
1381         }
1382
1383         return $object;
1384     }
1385
1386     /**
1387      * Returns the profile's canonical url, not necessarily a uri/unique id
1388      *
1389      * @return string $profileurl
1390      */
1391     public function getUrl()
1392     {
1393         if (empty($this->profileurl) ||
1394                 !filter_var($this->profileurl, FILTER_VALIDATE_URL)) {
1395             throw new InvalidUrlException($this->profileurl);
1396         }
1397         return $this->profileurl;
1398     }
1399
1400     public function getNickname()
1401     {
1402         return $this->nickname;
1403     }
1404
1405     public function getFullname()
1406     {
1407         return $this->fullname;
1408     }
1409
1410     public function getHomepage()
1411     {
1412         return $this->homepage;
1413     }
1414
1415     public function getDescription()
1416     {
1417         return $this->bio;
1418     }
1419
1420     /**
1421      * Returns the best URI for a profile. Plugins may override.
1422      *
1423      * @return string $uri
1424      */
1425     public function getUri()
1426     {
1427         $uri = null;
1428
1429         // give plugins a chance to set the URI
1430         if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1431
1432             // check for a local user first
1433             $user = User::getKV('id', $this->id);
1434             if ($user instanceof User) {
1435                 $uri = $user->getUri();
1436             } else {
1437                 $group = User_group::getKV('profile_id', $this->id);
1438                 if ($group instanceof User_group) {
1439                     $uri = $group->getUri();
1440                 }
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 }