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