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