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