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