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