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