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