]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Profile.php
5709a15d01060513b7b63b956d63f227edafdf56
[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 !empty($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         $this->_deleteNotices();
881         $this->_deleteSubscriptions();
882         $this->_deleteTags();
883         $this->_deleteBlocks();
884         $this->_deleteAttentions();
885         Avatar::deleteFromProfile($this, true);
886
887         // Warning: delete() will run on the batch objects,
888         // not on individual objects.
889         $related = array('Reply',
890                          'Group_member',
891                          );
892         Event::handle('ProfileDeleteRelated', array($this, &$related));
893
894         foreach ($related as $cls) {
895             $inst = new $cls();
896             $inst->profile_id = $this->id;
897             $inst->delete();
898         }
899
900         $localuser = User::getKV('id', $this->id);
901         if ($localuser instanceof User) {
902             $localuser->delete();
903         }
904
905         return parent::delete($useWhere);
906     }
907
908     function _deleteNotices()
909     {
910         $notice = new Notice();
911         $notice->profile_id = $this->id;
912
913         if ($notice->find()) {
914             while ($notice->fetch()) {
915                 $other = clone($notice);
916                 $other->delete();
917             }
918         }
919     }
920
921     function _deleteSubscriptions()
922     {
923         $sub = new Subscription();
924         $sub->subscriber = $this->id;
925
926         $sub->find();
927
928         while ($sub->fetch()) {
929             $other = Profile::getKV('id', $sub->subscribed);
930             if (empty($other)) {
931                 continue;
932             }
933             if ($other->id == $this->id) {
934                 continue;
935             }
936             Subscription::cancel($this, $other);
937         }
938
939         $subd = new Subscription();
940         $subd->subscribed = $this->id;
941         $subd->find();
942
943         while ($subd->fetch()) {
944             $other = Profile::getKV('id', $subd->subscriber);
945             if (empty($other)) {
946                 continue;
947             }
948             if ($other->id == $this->id) {
949                 continue;
950             }
951             Subscription::cancel($other, $this);
952         }
953
954         $self = new Subscription();
955
956         $self->subscriber = $this->id;
957         $self->subscribed = $this->id;
958
959         $self->delete();
960     }
961
962     function _deleteTags()
963     {
964         $tag = new Profile_tag();
965         $tag->tagged = $this->id;
966         $tag->delete();
967     }
968
969     function _deleteBlocks()
970     {
971         $block = new Profile_block();
972         $block->blocked = $this->id;
973         $block->delete();
974
975         $block = new Group_block();
976         $block->blocked = $this->id;
977         $block->delete();
978     }
979
980     function _deleteAttentions()
981     {
982         $att = new Attention();
983         $att->profile_id = $this->getID();
984
985         if ($att->find()) {
986             while ($att->fetch()) {
987                 // Can't do delete() on the object directly since it won't remove all of it
988                 $other = clone($att);
989                 $other->delete();
990             }
991         }
992     }
993
994     // XXX: identical to Notice::getLocation.
995
996     public function getLocation()
997     {
998         $location = null;
999
1000         if (!empty($this->location_id) && !empty($this->location_ns)) {
1001             $location = Location::fromId($this->location_id, $this->location_ns);
1002         }
1003
1004         if (is_null($location)) { // no ID, or Location::fromId() failed
1005             if (!empty($this->lat) && !empty($this->lon)) {
1006                 $location = Location::fromLatLon($this->lat, $this->lon);
1007             }
1008         }
1009
1010         if (is_null($location)) { // still haven't found it!
1011             if (!empty($this->location)) {
1012                 $location = Location::fromName($this->location);
1013             }
1014         }
1015
1016         return $location;
1017     }
1018
1019     public function shareLocation()
1020     {
1021         $cfg = common_config('location', 'share');
1022
1023         if ($cfg == 'always') {
1024             return true;
1025         } else if ($cfg == 'never') {
1026             return false;
1027         } else { // user
1028             $share = common_config('location', 'sharedefault');
1029
1030             // Check if user has a personal setting for this
1031             $prefs = User_location_prefs::getKV('user_id', $this->id);
1032
1033             if (!empty($prefs)) {
1034                 $share = $prefs->share_location;
1035                 $prefs->free();
1036             }
1037
1038             return $share;
1039         }
1040     }
1041
1042     function hasRole($name)
1043     {
1044         $has_role = false;
1045         if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1046             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1047                                                 'role' => $name));
1048             $has_role = !empty($role);
1049             Event::handle('EndHasRole', array($this, $name, $has_role));
1050         }
1051         return $has_role;
1052     }
1053
1054     function grantRole($name)
1055     {
1056         if (Event::handle('StartGrantRole', array($this, $name))) {
1057
1058             $role = new Profile_role();
1059
1060             $role->profile_id = $this->id;
1061             $role->role       = $name;
1062             $role->created    = common_sql_now();
1063
1064             $result = $role->insert();
1065
1066             if (!$result) {
1067                 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1068             }
1069
1070             if ($name == 'owner') {
1071                 User::blow('user:site_owner');
1072             }
1073
1074             Event::handle('EndGrantRole', array($this, $name));
1075         }
1076
1077         return $result;
1078     }
1079
1080     function revokeRole($name)
1081     {
1082         if (Event::handle('StartRevokeRole', array($this, $name))) {
1083
1084             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1085                                                 'role' => $name));
1086
1087             if (empty($role)) {
1088                 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1089                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1090                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1091             }
1092
1093             $result = $role->delete();
1094
1095             if (!$result) {
1096                 common_log_db_error($role, 'DELETE', __FILE__);
1097                 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1098                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1099                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1100             }
1101
1102             if ($name == 'owner') {
1103                 User::blow('user:site_owner');
1104             }
1105
1106             Event::handle('EndRevokeRole', array($this, $name));
1107
1108             return true;
1109         }
1110     }
1111
1112     function isSandboxed()
1113     {
1114         return $this->hasRole(Profile_role::SANDBOXED);
1115     }
1116
1117     function isSilenced()
1118     {
1119         return $this->hasRole(Profile_role::SILENCED);
1120     }
1121
1122     function sandbox()
1123     {
1124         $this->grantRole(Profile_role::SANDBOXED);
1125     }
1126
1127     function unsandbox()
1128     {
1129         $this->revokeRole(Profile_role::SANDBOXED);
1130     }
1131
1132     function silence()
1133     {
1134         $this->grantRole(Profile_role::SILENCED);
1135         if (common_config('notice', 'hidespam')) {
1136             $this->flushVisibility();
1137         }
1138     }
1139
1140     function unsilence()
1141     {
1142         $this->revokeRole(Profile_role::SILENCED);
1143         if (common_config('notice', 'hidespam')) {
1144             $this->flushVisibility();
1145         }
1146     }
1147
1148     function flushVisibility()
1149     {
1150         // Get all notices
1151         $stream = new ProfileNoticeStream($this, $this);
1152         $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1153         foreach ($ids as $id) {
1154             self::blow('notice:in-scope-for:%d:null', $id);
1155         }
1156     }
1157
1158     /**
1159      * Does this user have the right to do X?
1160      *
1161      * With our role-based authorization, this is merely a lookup for whether the user
1162      * has a particular role. The implementation currently uses a switch statement
1163      * to determine if the user has the pre-defined role to exercise the right. Future
1164      * implementations may allow per-site roles, and different mappings of roles to rights.
1165      *
1166      * @param $right string Name of the right, usually a constant in class Right
1167      * @return boolean whether the user has the right in question
1168      */
1169     public function hasRight($right)
1170     {
1171         $result = false;
1172
1173         if ($this->hasRole(Profile_role::DELETED)) {
1174             return false;
1175         }
1176
1177         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1178             switch ($right)
1179             {
1180             case Right::DELETEOTHERSNOTICE:
1181             case Right::MAKEGROUPADMIN:
1182             case Right::SANDBOXUSER:
1183             case Right::SILENCEUSER:
1184             case Right::DELETEUSER:
1185             case Right::DELETEGROUP:
1186             case Right::TRAINSPAM:
1187             case Right::REVIEWSPAM:
1188                 $result = $this->hasRole(Profile_role::MODERATOR);
1189                 break;
1190             case Right::CONFIGURESITE:
1191                 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1192                 break;
1193             case Right::GRANTROLE:
1194             case Right::REVOKEROLE:
1195                 $result = $this->hasRole(Profile_role::OWNER);
1196                 break;
1197             case Right::NEWNOTICE:
1198             case Right::NEWMESSAGE:
1199             case Right::SUBSCRIBE:
1200             case Right::CREATEGROUP:
1201                 $result = !$this->isSilenced();
1202                 break;
1203             case Right::PUBLICNOTICE:
1204             case Right::EMAILONREPLY:
1205             case Right::EMAILONSUBSCRIBE:
1206             case Right::EMAILONFAVE:
1207                 $result = !$this->isSandboxed();
1208                 break;
1209             case Right::WEBLOGIN:
1210                 $result = !$this->isSilenced();
1211                 break;
1212             case Right::API:
1213                 $result = !$this->isSilenced();
1214                 break;
1215             case Right::BACKUPACCOUNT:
1216                 $result = common_config('profile', 'backup');
1217                 break;
1218             case Right::RESTOREACCOUNT:
1219                 $result = common_config('profile', 'restore');
1220                 break;
1221             case Right::DELETEACCOUNT:
1222                 $result = common_config('profile', 'delete');
1223                 break;
1224             case Right::MOVEACCOUNT:
1225                 $result = common_config('profile', 'move');
1226                 break;
1227             default:
1228                 $result = false;
1229                 break;
1230             }
1231         }
1232         return $result;
1233     }
1234
1235     // FIXME: Can't put Notice typing here due to ArrayWrapper
1236     public function hasRepeated($notice)
1237     {
1238         // XXX: not really a pkey, but should work
1239
1240         $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1241                                         'repeat_of' => $notice->id));
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 getDescription()
1411     {
1412         return $this->bio;
1413     }
1414
1415     /**
1416      * Returns the best URI for a profile. Plugins may override.
1417      *
1418      * @return string $uri
1419      */
1420     public function getUri()
1421     {
1422         $uri = null;
1423
1424         // give plugins a chance to set the URI
1425         if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1426
1427             // check for a local user first
1428             $user = User::getKV('id', $this->id);
1429             if ($user instanceof User) {
1430                 $uri = $user->getUri();
1431             }
1432
1433             Event::handle('EndGetProfileUri', array($this, &$uri));
1434         }
1435
1436         return $uri;
1437     }
1438
1439     /**
1440      * Returns an assumed acct: URI for a profile. Plugins are required.
1441      *
1442      * @return string $uri
1443      */
1444     public function getAcctUri()
1445     {
1446         $acct = null;
1447
1448         if (Event::handle('StartGetProfileAcctUri', array($this, &$acct))) {
1449             Event::handle('EndGetProfileAcctUri', array($this, &$acct));
1450         }
1451
1452         if ($acct === null) {
1453             throw new ProfileNoAcctUriException($this);
1454         }
1455
1456         return $acct;
1457     }
1458
1459     function hasBlocked($other)
1460     {
1461         $block = Profile_block::exists($this, $other);
1462         return !empty($block);
1463     }
1464
1465     function getAtomFeed()
1466     {
1467         $feed = null;
1468
1469         if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1470             $user = User::getKV('id', $this->id);
1471             if (!empty($user)) {
1472                 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1473                                                                   'format' => 'atom'));
1474             }
1475             Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1476         }
1477
1478         return $feed;
1479     }
1480
1481     public function repeatedToMe($offset=0, $limit=20, $since_id=null, $max_id=null)
1482     {
1483         // TRANS: Exception thrown when trying view "repeated to me".
1484         throw new Exception(_('Not implemented since inbox change.'));
1485     }
1486
1487     /*
1488      * Get a Profile object by URI. Will call external plugins for help
1489      * using the event StartGetProfileFromURI.
1490      *
1491      * @param string $uri A unique identifier for a resource (profile/group/whatever)
1492      */
1493     static function fromUri($uri)
1494     {
1495         $profile = null;
1496
1497         if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1498             // Get a local user when plugin lookup (like OStatus) fails
1499             $user = User::getKV('uri', $uri);
1500             if ($user instanceof User) {
1501                 $profile = $user->getProfile();
1502             }
1503             Event::handle('EndGetProfileFromURI', array($uri, $profile));
1504         }
1505
1506         if (!$profile instanceof Profile) {
1507             throw new UnknownUriException($uri);
1508         }
1509
1510         return $profile;
1511     }
1512
1513     function canRead(Notice $notice)
1514     {
1515         if ($notice->scope & Notice::SITE_SCOPE) {
1516             $user = $this->getUser();
1517             if (empty($user)) {
1518                 return false;
1519             }
1520         }
1521
1522         if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1523             $replies = $notice->getReplies();
1524
1525             if (!in_array($this->id, $replies)) {
1526                 $groups = $notice->getGroups();
1527
1528                 $foundOne = false;
1529
1530                 foreach ($groups as $group) {
1531                     if ($this->isMember($group)) {
1532                         $foundOne = true;
1533                         break;
1534                     }
1535                 }
1536
1537                 if (!$foundOne) {
1538                     return false;
1539                 }
1540             }
1541         }
1542
1543         if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1544             $author = $notice->getProfile();
1545             if (!Subscription::exists($this, $author)) {
1546                 return false;
1547             }
1548         }
1549
1550         return true;
1551     }
1552
1553     static function current()
1554     {
1555         $user = common_current_user();
1556         if (empty($user)) {
1557             $profile = null;
1558         } else {
1559             $profile = $user->getProfile();
1560         }
1561         return $profile;
1562     }
1563
1564     /**
1565      * Magic function called at serialize() time.
1566      *
1567      * We use this to drop a couple process-specific references
1568      * from DB_DataObject which can cause trouble in future
1569      * processes.
1570      *
1571      * @return array of variable names to include in serialization.
1572      */
1573
1574     function __sleep()
1575     {
1576         $vars = parent::__sleep();
1577         $skip = array('_user', '_group');
1578         return array_diff($vars, $skip);
1579     }
1580
1581     public function getProfile()
1582     {
1583         return $this;
1584     }
1585
1586     public function sameAs(Profile $other)
1587     {
1588         return $this->getID() === $other->getID();
1589     }
1590
1591     /**
1592      * This will perform shortenLinks with the connected User object.
1593      *
1594      * Won't work on remote profiles or groups, so expect a
1595      * NoSuchUserException if you don't know it's a local User.
1596      *
1597      * @param string $text      String to shorten
1598      * @param boolean $always   Disrespect minimum length etc.
1599      *
1600      * @return string link-shortened $text
1601      */
1602     public function shortenLinks($text, $always=false)
1603     {
1604         return $this->getUser()->shortenLinks($text, $always);
1605     }
1606
1607     public function isPrivateStream()
1608     {
1609         // We only know of public remote users as of yet...
1610         if (!$this->isLocal()) {
1611             return false;
1612         }
1613         return $this->getUser()->private_stream ? true : false;
1614     }
1615
1616     public function delPref($namespace, $topic) {
1617         return Profile_prefs::setData($this, $namespace, $topic, null);
1618     }
1619
1620     public function getPref($namespace, $topic, $default=null) {
1621         // If you want an exception to be thrown, call Profile_prefs::getData directly
1622         try {
1623             return Profile_prefs::getData($this, $namespace, $topic, $default);
1624         } catch (NoResultException $e) {
1625             return null;
1626         }
1627     }
1628
1629     // The same as getPref but will fall back to common_config value for the same namespace/topic
1630     public function getConfigPref($namespace, $topic)
1631     {
1632         return Profile_prefs::getConfigData($this, $namespace, $topic);
1633     }
1634
1635     public function setPref($namespace, $topic, $data) {
1636         return Profile_prefs::setData($this, $namespace, $topic, $data);
1637     }
1638
1639     public function getConnectedApps($offset=0, $limit=null)
1640     {
1641         return $this->getUser()->getConnectedApps($offset, $limit);
1642     }
1643 }