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