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