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