]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Profile.php
Fix reversed poll & poll response object types in ActivityStreams output
[quix0rs-gnu-social.git] / classes / Profile.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, 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 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
26
27 class Profile extends Memcached_DataObject
28 {
29     ###START_AUTOCODE
30     /* the code below is auto generated do not remove the above tag */
31
32     public $__table = 'profile';                         // table name
33     public $id;                              // int(4)  primary_key not_null
34     public $nickname;                        // varchar(64)  multiple_key not_null
35     public $fullname;                        // varchar(255)  multiple_key
36     public $profileurl;                      // varchar(255)
37     public $homepage;                        // varchar(255)  multiple_key
38     public $bio;                             // text()  multiple_key
39     public $location;                        // varchar(255)  multiple_key
40     public $lat;                             // decimal(10,7)
41     public $lon;                             // decimal(10,7)
42     public $location_id;                     // int(4)
43     public $location_ns;                     // int(4)
44     public $created;                         // datetime()   not_null
45     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
46
47     /* Static get */
48     function staticGet($k,$v=NULL) {
49         return Memcached_DataObject::staticGet('Profile',$k,$v);
50     }
51
52     /* the code above is auto generated do not remove the tag below */
53     ###END_AUTOCODE
54
55     function getUser()
56     {
57         return User::staticGet('id', $this->id);
58     }
59
60     function getAvatar($width, $height=null)
61     {
62         if (is_null($height)) {
63             $height = $width;
64         }
65         return Avatar::pkeyGet(array('profile_id' => $this->id,
66                                      'width' => $width,
67                                      'height' => $height));
68     }
69
70     function getOriginalAvatar()
71     {
72         $avatar = DB_DataObject::factory('avatar');
73         $avatar->profile_id = $this->id;
74         $avatar->original = true;
75         if ($avatar->find(true)) {
76             return $avatar;
77         } else {
78             return null;
79         }
80     }
81
82     function setOriginal($filename)
83     {
84         $imagefile = new ImageFile($this->id, Avatar::path($filename));
85
86         $avatar = new Avatar();
87         $avatar->profile_id = $this->id;
88         $avatar->width = $imagefile->width;
89         $avatar->height = $imagefile->height;
90         $avatar->mediatype = image_type_to_mime_type($imagefile->type);
91         $avatar->filename = $filename;
92         $avatar->original = true;
93         $avatar->url = Avatar::url($filename);
94         $avatar->created = DB_DataObject_Cast::dateTime(); # current time
95
96         # XXX: start a transaction here
97
98         if (!$this->delete_avatars() || !$avatar->insert()) {
99             @unlink(Avatar::path($filename));
100             return null;
101         }
102
103         foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
104             # We don't do a scaled one if original is our scaled size
105             if (!($avatar->width == $size && $avatar->height == $size)) {
106                 $scaled_filename = $imagefile->resize($size);
107
108                 //$scaled = DB_DataObject::factory('avatar');
109                 $scaled = new Avatar();
110                 $scaled->profile_id = $this->id;
111                 $scaled->width = $size;
112                 $scaled->height = $size;
113                 $scaled->original = false;
114                 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
115                 $scaled->filename = $scaled_filename;
116                 $scaled->url = Avatar::url($scaled_filename);
117                 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
118
119                 if (!$scaled->insert()) {
120                     return null;
121                 }
122             }
123         }
124
125         return $avatar;
126     }
127
128     /**
129      * Delete attached avatars for this user from the database and filesystem.
130      * This should be used instead of a batch delete() to ensure that files
131      * get removed correctly.
132      *
133      * @param boolean $original true to delete only the original-size file
134      * @return <type>
135      */
136     function delete_avatars($original=true)
137     {
138         $avatar = new Avatar();
139         $avatar->profile_id = $this->id;
140         $avatar->find();
141         while ($avatar->fetch()) {
142             if ($avatar->original) {
143                 if ($original == false) {
144                     continue;
145                 }
146             }
147             $avatar->delete();
148         }
149         return true;
150     }
151
152     /**
153      * Gets either the full name (if filled) or the nickname.
154      *
155      * @return string
156      */
157     function getBestName()
158     {
159         return ($this->fullname) ? $this->fullname : $this->nickname;
160     }
161
162     /**
163      * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
164      * if no fullname is provided.
165      *
166      * @return string
167      */
168     function getFancyName()
169     {
170         if ($this->fullname) {
171             // TRANS: Full name of a profile or group followed by nickname in parens
172             return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
173         } else {
174             return $this->nickname;
175         }
176     }
177
178     /**
179      * Get the most recent notice posted by this user, if any.
180      *
181      * @return mixed Notice or null
182      */
183
184     function getCurrentNotice()
185     {
186         $notice = $this->getNotices(0, 1);
187
188         if ($notice->fetch()) {
189             if ($notice instanceof ArrayWrapper) {
190                 // hack for things trying to work with single notices
191                 return $notice->_items[0];
192             }
193             return $notice;
194         } else {
195             return null;
196         }
197     }
198
199     function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
200     {
201         $ids = Notice::stream(array($this, '_streamTaggedDirect'),
202                               array($tag),
203                               'profile:notice_ids_tagged:' . $this->id . ':' . $tag,
204                               $offset, $limit, $since_id, $max_id);
205         return Notice::getStreamByIds($ids);
206     }
207
208     function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
209     {
210         // XXX: I'm not sure this is going to be any faster. It probably isn't.
211         $ids = Notice::stream(array($this, '_streamDirect'),
212                               array(),
213                               'profile:notice_ids:' . $this->id,
214                               $offset, $limit, $since_id, $max_id);
215
216         return Notice::getStreamByIds($ids);
217     }
218
219     function _streamTaggedDirect($tag, $offset, $limit, $since_id, $max_id)
220     {
221         // XXX It would be nice to do this without a join
222         // (necessary to do it efficiently on accounts with long history)
223
224         $notice = new Notice();
225
226         $query =
227           "select id from notice join notice_tag on id=notice_id where tag='".
228           $notice->escape($tag) .
229           "' and profile_id=" . intval($this->id);
230
231         $since = Notice::whereSinceId($since_id, 'id', 'notice.created');
232         if ($since) {
233             $query .= " and ($since)";
234         }
235
236         $max = Notice::whereMaxId($max_id, 'id', 'notice.created');
237         if ($max) {
238             $query .= " and ($max)";
239         }
240
241         $query .= ' order by notice.created DESC, id DESC';
242
243         if (!is_null($offset)) {
244             $query .= " LIMIT " . intval($limit) . " OFFSET " . intval($offset);
245         }
246
247         $notice->query($query);
248
249         $ids = array();
250
251         while ($notice->fetch()) {
252             $ids[] = $notice->id;
253         }
254
255         return $ids;
256     }
257
258     function _streamDirect($offset, $limit, $since_id, $max_id)
259     {
260         $notice = new Notice();
261
262         $notice->profile_id = $this->id;
263
264         $notice->selectAdd();
265         $notice->selectAdd('id');
266
267         Notice::addWhereSinceId($notice, $since_id);
268         Notice::addWhereMaxId($notice, $max_id);
269
270         $notice->orderBy('created DESC, id DESC');
271
272         if (!is_null($offset)) {
273             $notice->limit($offset, $limit);
274         }
275
276         $notice->find();
277
278         $ids = array();
279
280         while ($notice->fetch()) {
281             $ids[] = $notice->id;
282         }
283
284         return $ids;
285     }
286
287     function isMember($group)
288     {
289         $mem = new Group_member();
290
291         $mem->group_id = $group->id;
292         $mem->profile_id = $this->id;
293
294         if ($mem->find()) {
295             return true;
296         } else {
297             return false;
298         }
299     }
300
301     function isAdmin($group)
302     {
303         $mem = new Group_member();
304
305         $mem->group_id = $group->id;
306         $mem->profile_id = $this->id;
307         $mem->is_admin = 1;
308
309         if ($mem->find()) {
310             return true;
311         } else {
312             return false;
313         }
314     }
315
316     function getGroups($offset=0, $limit=null)
317     {
318         $qry =
319           'SELECT user_group.* ' .
320           'FROM user_group JOIN group_member '.
321           'ON user_group.id = group_member.group_id ' .
322           'WHERE group_member.profile_id = %d ' .
323           'ORDER BY group_member.created DESC ';
324
325         if ($offset>0 && !is_null($limit)) {
326             if ($offset) {
327                 if (common_config('db','type') == 'pgsql') {
328                     $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
329                 } else {
330                     $qry .= ' LIMIT ' . $offset . ', ' . $limit;
331                 }
332             }
333         }
334
335         $groups = new User_group();
336
337         $cnt = $groups->query(sprintf($qry, $this->id));
338
339         return $groups;
340     }
341
342     function avatarUrl($size=AVATAR_PROFILE_SIZE)
343     {
344         $avatar = $this->getAvatar($size);
345         if ($avatar) {
346             return $avatar->displayUrl();
347         } else {
348             return Avatar::defaultImage($size);
349         }
350     }
351
352     function getSubscriptions($offset=0, $limit=null)
353     {
354         $subs = Subscription::bySubscriber($this->id,
355                                            $offset,
356                                            $limit);
357
358         $profiles = array();
359
360         while ($subs->fetch()) {
361             $profile = Profile::staticGet($subs->subscribed);
362             if ($profile) {
363                 $profiles[] = $profile;
364             }
365         }
366
367         return new ArrayWrapper($profiles);
368     }
369
370     function getSubscribers($offset=0, $limit=null)
371     {
372         $subs = Subscription::bySubscribed($this->id,
373                                            $offset,
374                                            $limit);
375
376         $profiles = array();
377
378         while ($subs->fetch()) {
379             $profile = Profile::staticGet($subs->subscriber);
380             if ($profile) {
381                 $profiles[] = $profile;
382             }
383         }
384
385         return new ArrayWrapper($profiles);
386     }
387
388     function subscriptionCount()
389     {
390         $c = Cache::instance();
391
392         if (!empty($c)) {
393             $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
394             if (is_integer($cnt)) {
395                 return (int) $cnt;
396             }
397         }
398
399         $sub = new Subscription();
400         $sub->subscriber = $this->id;
401
402         $cnt = (int) $sub->count('distinct subscribed');
403
404         $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
405
406         if (!empty($c)) {
407             $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
408         }
409
410         return $cnt;
411     }
412
413     function subscriberCount()
414     {
415         $c = Cache::instance();
416         if (!empty($c)) {
417             $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
418             if (is_integer($cnt)) {
419                 return (int) $cnt;
420             }
421         }
422
423         $sub = new Subscription();
424         $sub->subscribed = $this->id;
425         $sub->whereAdd('subscriber != subscribed');
426         $cnt = (int) $sub->count('distinct subscriber');
427
428         if (!empty($c)) {
429             $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
430         }
431
432         return $cnt;
433     }
434
435     /**
436      * Is this profile subscribed to another profile?
437      *
438      * @param Profile $other
439      * @return boolean
440      */
441     function isSubscribed($other)
442     {
443         return Subscription::exists($this, $other);
444     }
445
446     /**
447      * Are these two profiles subscribed to each other?
448      *
449      * @param Profile $other
450      * @return boolean
451      */
452     function mutuallySubscribed($other)
453     {
454         return $this->isSubscribed($other) &&
455           $other->isSubscribed($this);
456     }
457
458     function hasFave($notice)
459     {
460         $cache = Cache::instance();
461
462         // XXX: Kind of a hack.
463
464         if (!empty($cache)) {
465             // This is the stream of favorite notices, in rev chron
466             // order. This forces it into cache.
467
468             $ids = Fave::stream($this->id, 0, NOTICE_CACHE_WINDOW);
469
470             // If it's in the list, then it's a fave
471
472             if (in_array($notice->id, $ids)) {
473                 return true;
474             }
475
476             // If we're not past the end of the cache window,
477             // then the cache has all available faves, so this one
478             // is not a fave.
479
480             if (count($ids) < NOTICE_CACHE_WINDOW) {
481                 return false;
482             }
483
484             // Otherwise, cache doesn't have all faves;
485             // fall through to the default
486         }
487
488         $fave = Fave::pkeyGet(array('user_id' => $this->id,
489                                     'notice_id' => $notice->id));
490         return ((is_null($fave)) ? false : true);
491     }
492
493     function faveCount()
494     {
495         $c = Cache::instance();
496         if (!empty($c)) {
497             $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
498             if (is_integer($cnt)) {
499                 return (int) $cnt;
500             }
501         }
502
503         $faves = new Fave();
504         $faves->user_id = $this->id;
505         $cnt = (int) $faves->count('distinct notice_id');
506
507         if (!empty($c)) {
508             $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
509         }
510
511         return $cnt;
512     }
513
514     function noticeCount()
515     {
516         $c = Cache::instance();
517
518         if (!empty($c)) {
519             $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
520             if (is_integer($cnt)) {
521                 return (int) $cnt;
522             }
523         }
524
525         $notices = new Notice();
526         $notices->profile_id = $this->id;
527         $cnt = (int) $notices->count('distinct id');
528
529         if (!empty($c)) {
530             $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
531         }
532
533         return $cnt;
534     }
535
536     function blowFavesCache()
537     {
538         $cache = Cache::instance();
539         if ($cache) {
540             // Faves don't happen chronologically, so we need to blow
541             // ;last cache, too
542             $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
543             $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
544             $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
545             $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
546         }
547         $this->blowFaveCount();
548     }
549
550     function blowSubscriberCount()
551     {
552         $c = Cache::instance();
553         if (!empty($c)) {
554             $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
555         }
556     }
557
558     function blowSubscriptionCount()
559     {
560         $c = Cache::instance();
561         if (!empty($c)) {
562             $c->delete(Cache::key('profile:subscription_count:'.$this->id));
563         }
564     }
565
566     function blowFaveCount()
567     {
568         $c = Cache::instance();
569         if (!empty($c)) {
570             $c->delete(Cache::key('profile:fave_count:'.$this->id));
571         }
572     }
573
574     function blowNoticeCount()
575     {
576         $c = Cache::instance();
577         if (!empty($c)) {
578             $c->delete(Cache::key('profile:notice_count:'.$this->id));
579         }
580     }
581
582     static function maxBio()
583     {
584         $biolimit = common_config('profile', 'biolimit');
585         // null => use global limit (distinct from 0!)
586         if (is_null($biolimit)) {
587             $biolimit = common_config('site', 'textlimit');
588         }
589         return $biolimit;
590     }
591
592     static function bioTooLong($bio)
593     {
594         $biolimit = self::maxBio();
595         return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
596     }
597
598     function delete()
599     {
600         $this->_deleteNotices();
601         $this->_deleteSubscriptions();
602         $this->_deleteMessages();
603         $this->_deleteTags();
604         $this->_deleteBlocks();
605         $this->delete_avatars();
606
607         // Warning: delete() will run on the batch objects,
608         // not on individual objects.
609         $related = array('Reply',
610                          'Group_member',
611                          );
612         Event::handle('ProfileDeleteRelated', array($this, &$related));
613
614         foreach ($related as $cls) {
615             $inst = new $cls();
616             $inst->profile_id = $this->id;
617             $inst->delete();
618         }
619
620         parent::delete();
621     }
622
623     function _deleteNotices()
624     {
625         $notice = new Notice();
626         $notice->profile_id = $this->id;
627
628         if ($notice->find()) {
629             while ($notice->fetch()) {
630                 $other = clone($notice);
631                 $other->delete();
632             }
633         }
634     }
635
636     function _deleteSubscriptions()
637     {
638         $sub = new Subscription();
639         $sub->subscriber = $this->id;
640
641         $sub->find();
642
643         while ($sub->fetch()) {
644             $other = Profile::staticGet('id', $sub->subscribed);
645             if (empty($other)) {
646                 continue;
647             }
648             if ($other->id == $this->id) {
649                 continue;
650             }
651             Subscription::cancel($this, $other);
652         }
653
654         $subd = new Subscription();
655         $subd->subscribed = $this->id;
656         $subd->find();
657
658         while ($subd->fetch()) {
659             $other = Profile::staticGet('id', $subd->subscriber);
660             if (empty($other)) {
661                 continue;
662             }
663             if ($other->id == $this->id) {
664                 continue;
665             }
666             Subscription::cancel($other, $this);
667         }
668
669         $self = new Subscription();
670
671         $self->subscriber = $this->id;
672         $self->subscribed = $this->id;
673
674         $self->delete();
675     }
676
677     function _deleteMessages()
678     {
679         $msg = new Message();
680         $msg->from_profile = $this->id;
681         $msg->delete();
682
683         $msg = new Message();
684         $msg->to_profile = $this->id;
685         $msg->delete();
686     }
687
688     function _deleteTags()
689     {
690         $tag = new Profile_tag();
691         $tag->tagged = $this->id;
692         $tag->delete();
693     }
694
695     function _deleteBlocks()
696     {
697         $block = new Profile_block();
698         $block->blocked = $this->id;
699         $block->delete();
700
701         $block = new Group_block();
702         $block->blocked = $this->id;
703         $block->delete();
704     }
705
706     // XXX: identical to Notice::getLocation.
707
708     function getLocation()
709     {
710         $location = null;
711
712         if (!empty($this->location_id) && !empty($this->location_ns)) {
713             $location = Location::fromId($this->location_id, $this->location_ns);
714         }
715
716         if (is_null($location)) { // no ID, or Location::fromId() failed
717             if (!empty($this->lat) && !empty($this->lon)) {
718                 $location = Location::fromLatLon($this->lat, $this->lon);
719             }
720         }
721
722         if (is_null($location)) { // still haven't found it!
723             if (!empty($this->location)) {
724                 $location = Location::fromName($this->location);
725             }
726         }
727
728         return $location;
729     }
730
731     function hasRole($name)
732     {
733         $has_role = false;
734         if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
735             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
736                                                 'role' => $name));
737             $has_role = !empty($role);
738             Event::handle('EndHasRole', array($this, $name, $has_role));
739         }
740         return $has_role;
741     }
742
743     function grantRole($name)
744     {
745         if (Event::handle('StartGrantRole', array($this, $name))) {
746
747             $role = new Profile_role();
748
749             $role->profile_id = $this->id;
750             $role->role       = $name;
751             $role->created    = common_sql_now();
752
753             $result = $role->insert();
754
755             if (!$result) {
756                 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
757             }
758
759             if ($name == 'owner') {
760                 User::blow('user:site_owner');
761             }
762
763             Event::handle('EndGrantRole', array($this, $name));
764         }
765
766         return $result;
767     }
768
769     function revokeRole($name)
770     {
771         if (Event::handle('StartRevokeRole', array($this, $name))) {
772
773             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
774                                                 'role' => $name));
775
776             if (empty($role)) {
777                 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
778                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
779                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
780             }
781
782             $result = $role->delete();
783
784             if (!$result) {
785                 common_log_db_error($role, 'DELETE', __FILE__);
786                 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
787                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
788                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
789             }
790
791             if ($name == 'owner') {
792                 User::blow('user:site_owner');
793             }
794
795             Event::handle('EndRevokeRole', array($this, $name));
796
797             return true;
798         }
799     }
800
801     function isSandboxed()
802     {
803         return $this->hasRole(Profile_role::SANDBOXED);
804     }
805
806     function isSilenced()
807     {
808         return $this->hasRole(Profile_role::SILENCED);
809     }
810
811     function sandbox()
812     {
813         $this->grantRole(Profile_role::SANDBOXED);
814     }
815
816     function unsandbox()
817     {
818         $this->revokeRole(Profile_role::SANDBOXED);
819     }
820
821     function silence()
822     {
823         $this->grantRole(Profile_role::SILENCED);
824     }
825
826     function unsilence()
827     {
828         $this->revokeRole(Profile_role::SILENCED);
829     }
830
831     /**
832      * Does this user have the right to do X?
833      *
834      * With our role-based authorization, this is merely a lookup for whether the user
835      * has a particular role. The implementation currently uses a switch statement
836      * to determine if the user has the pre-defined role to exercise the right. Future
837      * implementations may allow per-site roles, and different mappings of roles to rights.
838      *
839      * @param $right string Name of the right, usually a constant in class Right
840      * @return boolean whether the user has the right in question
841      */
842     function hasRight($right)
843     {
844         $result = false;
845
846         if ($this->hasRole(Profile_role::DELETED)) {
847             return false;
848         }
849
850         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
851             switch ($right)
852             {
853             case Right::DELETEOTHERSNOTICE:
854             case Right::MAKEGROUPADMIN:
855             case Right::SANDBOXUSER:
856             case Right::SILENCEUSER:
857             case Right::DELETEUSER:
858             case Right::DELETEGROUP:
859                 $result = $this->hasRole(Profile_role::MODERATOR);
860                 break;
861             case Right::CONFIGURESITE:
862                 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
863                 break;
864             case Right::GRANTROLE:
865             case Right::REVOKEROLE:
866                 $result = $this->hasRole(Profile_role::OWNER);
867                 break;
868             case Right::NEWNOTICE:
869             case Right::NEWMESSAGE:
870             case Right::SUBSCRIBE:
871             case Right::CREATEGROUP:
872                 $result = !$this->isSilenced();
873                 break;
874             case Right::PUBLICNOTICE:
875             case Right::EMAILONREPLY:
876             case Right::EMAILONSUBSCRIBE:
877             case Right::EMAILONFAVE:
878                 $result = !$this->isSandboxed();
879                 break;
880             case Right::WEBLOGIN:
881                 $result = !$this->isSilenced();
882                 break;
883             case Right::API:
884                 $result = !$this->isSilenced();
885                 break;
886             case Right::BACKUPACCOUNT:
887                 $result = common_config('profile', 'backup');
888                 break;
889             case Right::RESTOREACCOUNT:
890                 $result = common_config('profile', 'restore');
891                 break;
892             case Right::DELETEACCOUNT:
893                 $result = common_config('profile', 'delete');
894                 break;
895             case Right::MOVEACCOUNT:
896                 $result = common_config('profile', 'move');
897                 break;
898             default:
899                 $result = false;
900                 break;
901             }
902         }
903         return $result;
904     }
905
906     function hasRepeated($notice_id)
907     {
908         // XXX: not really a pkey, but should work
909
910         $notice = Memcached_DataObject::pkeyGet('Notice',
911                                                 array('profile_id' => $this->id,
912                                                       'repeat_of' => $notice_id));
913
914         return !empty($notice);
915     }
916
917     /**
918      * Returns an XML string fragment with limited profile information
919      * as an Atom <author> element.
920      *
921      * Assumes that Atom has been previously set up as the base namespace.
922      *
923      * @param Profile $cur the current authenticated user
924      *
925      * @return string
926      */
927     function asAtomAuthor($cur = null)
928     {
929         $xs = new XMLStringer(true);
930
931         $xs->elementStart('author');
932         $xs->element('name', null, $this->nickname);
933         $xs->element('uri', null, $this->getUri());
934         if ($cur != null) {
935             $attrs = Array();
936             $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
937             $attrs['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
938             $xs->element('statusnet:profile_info', $attrs, null);
939         }
940         $xs->elementEnd('author');
941
942         return $xs->getString();
943     }
944
945     /**
946      * Extra profile info for atom entries
947      *
948      * Clients use some extra profile info in the atom stream.
949      * This gives it to them.
950      *
951      * @param User $cur Current user
952      *
953      * @return array representation of <statusnet:profile_info> element or null
954      */
955
956     function profileInfo($cur)
957     {
958         $profileInfoAttr = array('local_id' => $this->id);
959
960         if ($cur != null) {
961             // Whether the current user is a subscribed to this profile
962             $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
963             // Whether the current user is has blocked this profile
964             $profileInfoAttr['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
965         }
966
967         return array('statusnet:profile_info', $profileInfoAttr, null);
968     }
969
970     /**
971      * Returns an XML string fragment with profile information as an
972      * Activity Streams <activity:actor> element.
973      *
974      * Assumes that 'activity' namespace has been previously defined.
975      *
976      * @return string
977      */
978     function asActivityActor()
979     {
980         return $this->asActivityNoun('actor');
981     }
982
983     /**
984      * Returns an XML string fragment with profile information as an
985      * Activity Streams noun object with the given element type.
986      *
987      * Assumes that 'activity', 'georss', and 'poco' namespace has been
988      * previously defined.
989      *
990      * @param string $element one of 'actor', 'subject', 'object', 'target'
991      *
992      * @return string
993      */
994     function asActivityNoun($element)
995     {
996         $noun = ActivityObject::fromProfile($this);
997         return $noun->asString('activity:' . $element);
998     }
999
1000     /**
1001      * Returns the best URI for a profile. Plugins may override.
1002      *
1003      * @return string $uri
1004      */
1005     function getUri()
1006     {
1007         $uri = null;
1008
1009         // give plugins a chance to set the URI
1010         if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1011
1012             // check for a local user first
1013             $user = User::staticGet('id', $this->id);
1014
1015             if (!empty($user)) {
1016                 $uri = $user->uri;
1017             } else {
1018                 // return OMB profile if any
1019                 $remote = Remote_profile::staticGet('id', $this->id);
1020                 if (!empty($remote)) {
1021                     $uri = $remote->uri;
1022                 }
1023             }
1024             Event::handle('EndGetProfileUri', array($this, &$uri));
1025         }
1026
1027         return $uri;
1028     }
1029
1030     function hasBlocked($other)
1031     {
1032         $block = Profile_block::get($this->id, $other->id);
1033
1034         if (empty($block)) {
1035             $result = false;
1036         } else {
1037             $result = true;
1038         }
1039
1040         return $result;
1041     }
1042
1043     function getAtomFeed()
1044     {
1045         $feed = null;
1046
1047         if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1048             $user = User::staticGet('id', $this->id);
1049             if (!empty($user)) {
1050                 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1051                                                                   'format' => 'atom'));
1052             }
1053             Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1054         }
1055
1056         return $feed;
1057     }
1058
1059     static function fromURI($uri)
1060     {
1061         $profile = null;
1062
1063         if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1064             // Get a local user or remote (OMB 0.1) profile
1065             $user = User::staticGet('uri', $uri);
1066             if (!empty($user)) {
1067                 $profile = $user->getProfile();
1068             } else {
1069                 $remote_profile = Remote_profile::staticGet('uri', $uri);
1070                 if (!empty($remote_profile)) {
1071                     $profile = Profile::staticGet('id', $remote_profile->profile_id);
1072                 }
1073             }
1074             Event::handle('EndGetProfileFromURI', array($uri, $profile));
1075         }
1076
1077         return $profile;
1078     }
1079 }