]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Profile.php
Remove fulltext indexes from notice and profile tables. The default
[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         );
77     }
78
79         function multiGet($keyCol, $keyVals, $skipNulls=true)
80         {
81             return parent::multiGet('Profile', $keyCol, $keyVals, $skipNulls);
82         }
83         
84     /* the code above is auto generated do not remove the tag below */
85     ###END_AUTOCODE
86
87     protected $_user = -1;  // Uninitialized value distinct from null
88
89     function getUser()
90     {
91         if (is_int($this->_user) && $this->_user == -1) {
92             $this->_user = User::staticGet('id', $this->id);
93         }
94
95         return $this->_user;
96     }
97
98         protected $_avatars;
99         
100     function getAvatar($width, $height=null)
101     {
102         if (is_null($height)) {
103             $height = $width;
104         }
105
106         if (!isset($this->_avatars)) {
107             $this->_avatars = array();
108         }
109
110                 if (array_key_exists($width, $this->_avatars)) {
111                         return $this->_avatars[$width];
112                 }
113                 
114         $avatar = null;
115
116         if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
117             $avatar = Avatar::pkeyGet(array('profile_id' => $this->id,
118                                             'width' => $width,
119                                             'height' => $height));
120             Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
121         }
122
123                 $this->_avatars[$width] = $avatar;
124                 
125         return $avatar;
126     }
127
128         function _fillAvatar($width, $avatar)
129         {
130                 $this->_avatars[$width] = $avatar;    
131         }
132         
133     function getOriginalAvatar()
134     {
135         $avatar = DB_DataObject::factory('avatar');
136         $avatar->profile_id = $this->id;
137         $avatar->original = true;
138         if ($avatar->find(true)) {
139             return $avatar;
140         } else {
141             return null;
142         }
143     }
144
145     function setOriginal($filename)
146     {
147         $imagefile = new ImageFile($this->id, Avatar::path($filename));
148
149         $avatar = new Avatar();
150         $avatar->profile_id = $this->id;
151         $avatar->width = $imagefile->width;
152         $avatar->height = $imagefile->height;
153         $avatar->mediatype = image_type_to_mime_type($imagefile->type);
154         $avatar->filename = $filename;
155         $avatar->original = true;
156         $avatar->url = Avatar::url($filename);
157         $avatar->created = DB_DataObject_Cast::dateTime(); # current time
158
159         // XXX: start a transaction here
160
161         if (!$this->delete_avatars() || !$avatar->insert()) {
162             @unlink(Avatar::path($filename));
163             return null;
164         }
165
166         foreach (array(AVATAR_PROFILE_SIZE, AVATAR_STREAM_SIZE, AVATAR_MINI_SIZE) as $size) {
167             // We don't do a scaled one if original is our scaled size
168             if (!($avatar->width == $size && $avatar->height == $size)) {
169                 $scaled_filename = $imagefile->resize($size);
170
171                 //$scaled = DB_DataObject::factory('avatar');
172                 $scaled = new Avatar();
173                 $scaled->profile_id = $this->id;
174                 $scaled->width = $size;
175                 $scaled->height = $size;
176                 $scaled->original = false;
177                 $scaled->mediatype = image_type_to_mime_type($imagefile->type);
178                 $scaled->filename = $scaled_filename;
179                 $scaled->url = Avatar::url($scaled_filename);
180                 $scaled->created = DB_DataObject_Cast::dateTime(); # current time
181
182                 if (!$scaled->insert()) {
183                     return null;
184                 }
185             }
186         }
187
188         return $avatar;
189     }
190
191     /**
192      * Delete attached avatars for this user from the database and filesystem.
193      * This should be used instead of a batch delete() to ensure that files
194      * get removed correctly.
195      *
196      * @param boolean $original true to delete only the original-size file
197      * @return <type>
198      */
199     function delete_avatars($original=true)
200     {
201         $avatar = new Avatar();
202         $avatar->profile_id = $this->id;
203         $avatar->find();
204         while ($avatar->fetch()) {
205             if ($avatar->original) {
206                 if ($original == false) {
207                     continue;
208                 }
209             }
210             $avatar->delete();
211         }
212         return true;
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         return User_group::multiGet('id', $ids);
326     }
327
328     function isTagged($peopletag)
329     {
330         $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
331                                           'tagged' => $this->id,
332                                           'tag'    => $peopletag->tag));
333         return !empty($tag);
334     }
335
336     function canTag($tagged)
337     {
338         if (empty($tagged)) {
339             return false;
340         }
341
342         if ($tagged->id == $this->id) {
343             return true;
344         }
345
346         $all = common_config('peopletag', 'allow_tagging', 'all');
347         $local = common_config('peopletag', 'allow_tagging', 'local');
348         $remote = common_config('peopletag', 'allow_tagging', 'remote');
349         $subs = common_config('peopletag', 'allow_tagging', 'subs');
350
351         if ($all) {
352             return true;
353         }
354
355         $tagged_user = $tagged->getUser();
356         if (!empty($tagged_user)) {
357             if ($local) {
358                 return true;
359             }
360         } else if ($subs) {
361             return (Subscription::exists($this, $tagged) ||
362                     Subscription::exists($tagged, $this));
363         } else if ($remote) {
364             return true;
365         }
366         return false;
367     }
368
369     function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
370     {
371         $ids = array();
372
373         $keypart = sprintf('profile:lists:%d', $this->id);
374
375         $idstr = self::cacheGet($keypart);
376
377         if ($idstr !== false) {
378             $ids = explode(',', $idstr);
379         } else {
380             $list = new Profile_list();
381             $list->selectAdd();
382             $list->selectAdd('id');
383             $list->tagger = $this->id;
384             $list->selectAdd('id as "cursor"');
385
386             if ($since_id>0) {
387                $list->whereAdd('id > '.$since_id);
388             }
389
390             if ($max_id>0) {
391                 $list->whereAdd('id <= '.$max_id);
392             }
393
394             if($offset>=0 && !is_null($limit)) {
395                 $list->limit($offset, $limit);
396             }
397
398             $list->orderBy('id DESC');
399
400             if ($list->find()) {
401                 while ($list->fetch()) {
402                     $ids[] = $list->id;
403                 }
404             }
405
406             self::cacheSet($keypart, implode(',', $ids));
407         }
408
409         $showPrivate = (($auth_user instanceof User ||
410                             $auth_user instanceof Profile) &&
411                         $auth_user->id === $this->id);
412
413         $lists = array();
414
415         foreach ($ids as $id) {
416             $list = Profile_list::staticGet('id', $id);
417             if (!empty($list) &&
418                 ($showPrivate || !$list->private)) {
419
420                 if (!isset($list->cursor)) {
421                     $list->cursor = $list->id;
422                 }
423
424                 $lists[] = $list;
425             }
426         }
427
428         return new ArrayWrapper($lists);
429     }
430
431     function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
432     {
433         $lists = new Profile_list();
434
435         $tags = new Profile_tag();
436         $tags->tagged = $this->id;
437
438         $lists->joinAdd($tags);
439
440         #@fixme: postgres (round(date_part('epoch', my_date)))
441         $lists->selectAdd('unix_timestamp(profile_tag.modified) as "cursor"');
442
443         if ($auth_user instanceof User || $auth_user instanceof Profile) {
444             $lists->whereAdd('( ( profile_list.private = false ) ' .
445                              'OR ( profile_list.tagger = ' . $auth_user->id . ' AND ' .
446                              'profile_list.private = true ) )');
447         } else {
448             $lists->private = false;
449         }
450
451         if ($since_id>0) {
452            $lists->whereAdd('cursor > '.$since_id);
453         }
454
455         if ($max_id>0) {
456             $lists->whereAdd('cursor <= '.$max_id);
457         }
458
459         if($offset>=0 && !is_null($limit)) {
460             $lists->limit($offset, $limit);
461         }
462
463         $lists->orderBy('profile_tag.modified DESC');
464         $lists->find();
465
466         return $lists;
467     }
468
469     function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
470     {
471         $tags = new Profile_list();
472         $tags->private = true;
473         $tags->tagger = $this->id;
474
475         if ($since_id>0) {
476            $tags->whereAdd('id > '.$since_id);
477         }
478
479         if ($max_id>0) {
480             $tags->whereAdd('id <= '.$max_id);
481         }
482
483         if($offset>=0 && !is_null($limit)) {
484             $tags->limit($offset, $limit);
485         }
486
487         $tags->orderBy('id DESC');
488         $tags->find();
489
490         return $tags;
491     }
492
493     function hasLocalTags()
494     {
495         $tags = new Profile_tag();
496
497         $tags->joinAdd(array('tagger', 'user:id'));
498         $tags->whereAdd('tagged  = '.$this->id);
499         $tags->whereAdd('tagger != '.$this->id);
500
501         $tags->limit(0, 1);
502         $tags->fetch();
503
504         return ($tags->N == 0) ? false : true;
505     }
506
507     function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
508     {
509         $lists = new Profile_list();
510         $subs = new Profile_tag_subscription();
511
512         $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');
513
514         #@fixme: postgres (round(date_part('epoch', my_date)))
515         $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');
516
517         $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);
518
519         if ($since_id>0) {
520            $lists->whereAdd('cursor > '.$since_id);
521         }
522
523         if ($max_id>0) {
524             $lists->whereAdd('cursor <= '.$max_id);
525         }
526
527         if($offset>=0 && !is_null($limit)) {
528             $lists->limit($offset, $limit);
529         }
530
531         $lists->orderBy('"cursor" DESC');
532         $lists->find();
533
534         return $lists;
535     }
536
537     /**
538      * Request to join the given group.
539      * May throw exceptions on failure.
540      *
541      * @param User_group $group
542      * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
543      */
544     function joinGroup(User_group $group)
545     {
546         $join = null;
547         if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
548             $join = Group_join_queue::saveNew($this, $group);
549         } else {
550             if (Event::handle('StartJoinGroup', array($group, $this))) {
551                 $join = Group_member::join($group->id, $this->id);
552                 self::blow('profile:groups:%d', $this->id);
553                 Event::handle('EndJoinGroup', array($group, $this));
554             }
555         }
556         if ($join) {
557             // Send any applicable notifications...
558             $join->notify();
559         }
560         return $join;
561     }
562
563     /**
564      * Leave a group that this profile is a member of.
565      *
566      * @param User_group $group
567      */
568     function leaveGroup(User_group $group)
569     {
570         if (Event::handle('StartLeaveGroup', array($group, $this))) {
571             Group_member::leave($group->id, $this->id);
572             self::blow('profile:groups:%d', $this->id);
573             Event::handle('EndLeaveGroup', array($group, $this));
574         }
575     }
576
577     function avatarUrl($size=AVATAR_PROFILE_SIZE)
578     {
579         $avatar = $this->getAvatar($size);
580         if ($avatar) {
581             return $avatar->displayUrl();
582         } else {
583             return Avatar::defaultImage($size);
584         }
585     }
586
587     function getSubscriptions($offset=0, $limit=null)
588     {
589         $subs = Subscription::bySubscriber($this->id,
590                                            $offset,
591                                            $limit);
592
593         $profiles = array();
594
595         while ($subs->fetch()) {
596             $profile = Profile::staticGet($subs->subscribed);
597             if ($profile) {
598                 $profiles[] = $profile;
599             }
600         }
601
602         return new ArrayWrapper($profiles);
603     }
604
605     function getSubscribers($offset=0, $limit=null)
606     {
607         $subs = Subscription::bySubscribed($this->id,
608                                            $offset,
609                                            $limit);
610
611         $profiles = array();
612
613         while ($subs->fetch()) {
614             $profile = Profile::staticGet($subs->subscriber);
615             if ($profile) {
616                 $profiles[] = $profile;
617             }
618         }
619
620         return new ArrayWrapper($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, $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         $this->delete_avatars();
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::staticGet('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::staticGet('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     }
1098
1099     function unsilence()
1100     {
1101         $this->revokeRole(Profile_role::SILENCED);
1102     }
1103
1104     /**
1105      * Does this user have the right to do X?
1106      *
1107      * With our role-based authorization, this is merely a lookup for whether the user
1108      * has a particular role. The implementation currently uses a switch statement
1109      * to determine if the user has the pre-defined role to exercise the right. Future
1110      * implementations may allow per-site roles, and different mappings of roles to rights.
1111      *
1112      * @param $right string Name of the right, usually a constant in class Right
1113      * @return boolean whether the user has the right in question
1114      */
1115     function hasRight($right)
1116     {
1117         $result = false;
1118
1119         if ($this->hasRole(Profile_role::DELETED)) {
1120             return false;
1121         }
1122
1123         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1124             switch ($right)
1125             {
1126             case Right::DELETEOTHERSNOTICE:
1127             case Right::MAKEGROUPADMIN:
1128             case Right::SANDBOXUSER:
1129             case Right::SILENCEUSER:
1130             case Right::DELETEUSER:
1131             case Right::DELETEGROUP:
1132                 $result = $this->hasRole(Profile_role::MODERATOR);
1133                 break;
1134             case Right::CONFIGURESITE:
1135                 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1136                 break;
1137             case Right::GRANTROLE:
1138             case Right::REVOKEROLE:
1139                 $result = $this->hasRole(Profile_role::OWNER);
1140                 break;
1141             case Right::NEWNOTICE:
1142             case Right::NEWMESSAGE:
1143             case Right::SUBSCRIBE:
1144             case Right::CREATEGROUP:
1145                 $result = !$this->isSilenced();
1146                 break;
1147             case Right::PUBLICNOTICE:
1148             case Right::EMAILONREPLY:
1149             case Right::EMAILONSUBSCRIBE:
1150             case Right::EMAILONFAVE:
1151                 $result = !$this->isSandboxed();
1152                 break;
1153             case Right::WEBLOGIN:
1154                 $result = !$this->isSilenced();
1155                 break;
1156             case Right::API:
1157                 $result = !$this->isSilenced();
1158                 break;
1159             case Right::BACKUPACCOUNT:
1160                 $result = common_config('profile', 'backup');
1161                 break;
1162             case Right::RESTOREACCOUNT:
1163                 $result = common_config('profile', 'restore');
1164                 break;
1165             case Right::DELETEACCOUNT:
1166                 $result = common_config('profile', 'delete');
1167                 break;
1168             case Right::MOVEACCOUNT:
1169                 $result = common_config('profile', 'move');
1170                 break;
1171             default:
1172                 $result = false;
1173                 break;
1174             }
1175         }
1176         return $result;
1177     }
1178
1179     function hasRepeated($notice_id)
1180     {
1181         // XXX: not really a pkey, but should work
1182
1183         $notice = Memcached_DataObject::pkeyGet('Notice',
1184                                                 array('profile_id' => $this->id,
1185                                                       'repeat_of' => $notice_id));
1186
1187         return !empty($notice);
1188     }
1189
1190     /**
1191      * Returns an XML string fragment with limited profile information
1192      * as an Atom <author> element.
1193      *
1194      * Assumes that Atom has been previously set up as the base namespace.
1195      *
1196      * @param Profile $cur the current authenticated user
1197      *
1198      * @return string
1199      */
1200     function asAtomAuthor($cur = null)
1201     {
1202         $xs = new XMLStringer(true);
1203
1204         $xs->elementStart('author');
1205         $xs->element('name', null, $this->nickname);
1206         $xs->element('uri', null, $this->getUri());
1207         if ($cur != null) {
1208             $attrs = Array();
1209             $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1210             $attrs['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
1211             $xs->element('statusnet:profile_info', $attrs, null);
1212         }
1213         $xs->elementEnd('author');
1214
1215         return $xs->getString();
1216     }
1217
1218     /**
1219      * Extra profile info for atom entries
1220      *
1221      * Clients use some extra profile info in the atom stream.
1222      * This gives it to them.
1223      *
1224      * @param User $cur Current user
1225      *
1226      * @return array representation of <statusnet:profile_info> element or null
1227      */
1228
1229     function profileInfo($cur)
1230     {
1231         $profileInfoAttr = array('local_id' => $this->id);
1232
1233         if ($cur != null) {
1234             // Whether the current user is a subscribed to this profile
1235             $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1236             // Whether the current user is has blocked this profile
1237             $profileInfoAttr['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
1238         }
1239
1240         return array('statusnet:profile_info', $profileInfoAttr, null);
1241     }
1242
1243     /**
1244      * Returns an XML string fragment with profile information as an
1245      * Activity Streams <activity:actor> element.
1246      *
1247      * Assumes that 'activity' namespace has been previously defined.
1248      *
1249      * @return string
1250      */
1251     function asActivityActor()
1252     {
1253         return $this->asActivityNoun('actor');
1254     }
1255
1256     /**
1257      * Returns an XML string fragment with profile information as an
1258      * Activity Streams noun object with the given element type.
1259      *
1260      * Assumes that 'activity', 'georss', and 'poco' namespace has been
1261      * previously defined.
1262      *
1263      * @param string $element one of 'actor', 'subject', 'object', 'target'
1264      *
1265      * @return string
1266      */
1267     function asActivityNoun($element)
1268     {
1269         $noun = ActivityObject::fromProfile($this);
1270         return $noun->asString('activity:' . $element);
1271     }
1272
1273     /**
1274      * Returns the best URI for a profile. Plugins may override.
1275      *
1276      * @return string $uri
1277      */
1278     function getUri()
1279     {
1280         $uri = null;
1281
1282         // give plugins a chance to set the URI
1283         if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1284
1285             // check for a local user first
1286             $user = User::staticGet('id', $this->id);
1287
1288             if (!empty($user)) {
1289                 $uri = $user->uri;
1290             }
1291
1292             Event::handle('EndGetProfileUri', array($this, &$uri));
1293         }
1294
1295         return $uri;
1296     }
1297
1298     function hasBlocked($other)
1299     {
1300         $block = Profile_block::get($this->id, $other->id);
1301
1302         if (empty($block)) {
1303             $result = false;
1304         } else {
1305             $result = true;
1306         }
1307
1308         return $result;
1309     }
1310
1311     function getAtomFeed()
1312     {
1313         $feed = null;
1314
1315         if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1316             $user = User::staticGet('id', $this->id);
1317             if (!empty($user)) {
1318                 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1319                                                                   'format' => 'atom'));
1320             }
1321             Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1322         }
1323
1324         return $feed;
1325     }
1326
1327     static function fromURI($uri)
1328     {
1329         $profile = null;
1330
1331         if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1332             // Get a local user or remote (OMB 0.1) profile
1333             $user = User::staticGet('uri', $uri);
1334             if (!empty($user)) {
1335                 $profile = $user->getProfile();
1336             }
1337             Event::handle('EndGetProfileFromURI', array($uri, $profile));
1338         }
1339
1340         return $profile;
1341     }
1342
1343     function canRead(Notice $notice)
1344     {
1345         if ($notice->scope & Notice::SITE_SCOPE) {
1346             $user = $this->getUser();
1347             if (empty($user)) {
1348                 return false;
1349             }
1350         }
1351
1352         if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1353             $replies = $notice->getReplies();
1354
1355             if (!in_array($this->id, $replies)) {
1356                 $groups = $notice->getGroups();
1357
1358                 $foundOne = false;
1359
1360                 foreach ($groups as $group) {
1361                     if ($this->isMember($group)) {
1362                         $foundOne = true;
1363                         break;
1364                     }
1365                 }
1366
1367                 if (!$foundOne) {
1368                     return false;
1369                 }
1370             }
1371         }
1372
1373         if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1374             $author = $notice->getProfile();
1375             if (!Subscription::exists($this, $author)) {
1376                 return false;
1377             }
1378         }
1379
1380         return true;
1381     }
1382
1383     static function current()
1384     {
1385         $user = common_current_user();
1386         if (empty($user)) {
1387             $profile = null;
1388         } else {
1389             $profile = $user->getProfile();
1390         }
1391         return $profile;
1392     }
1393
1394     /**
1395      * Magic function called at serialize() time.
1396      *
1397      * We use this to drop a couple process-specific references
1398      * from DB_DataObject which can cause trouble in future
1399      * processes.
1400      *
1401      * @return array of variable names to include in serialization.
1402      */
1403
1404     function __sleep()
1405     {
1406         $vars = parent::__sleep();
1407         $skip = array('_user', '_avatars');
1408         return array_diff($vars, $skip);
1409     }
1410     
1411     static function fillAvatars(&$profiles, $width)
1412     {
1413         $ids = array();
1414         foreach ($profiles as $profile) {
1415             $ids[] = $profile->id;
1416         }
1417         
1418         $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1419                                                                                                                           'height' => $width));
1420         
1421         foreach ($profiles as $profile) {
1422             $profile->_fillAvatar($width, $avatars[$profile->id]);
1423         }
1424     }
1425 }