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