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