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