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