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