]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Profile.php
Subscription "get by" functions now don't use ArrayWrappers
[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 getSubscribed($offset=0, $limit=null)
650     {
651         $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
652         $profiles = Profile::listFind('id', $subs);
653         return $profiles;
654     }
655
656     function getSubscribers($offset=0, $limit=null)
657     {
658         $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
659         $profiles = Profile::listFind('id', $subs);
660         return $profiles;
661     }
662
663     function getTaggedSubscribers($tag)
664     {
665         $qry =
666           'SELECT profile.* ' .
667           'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
668           'ON profile.id = subscription.subscriber ' .
669           'AND profile.id = profile_tag.tagged ' .
670           'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
671           'WHERE subscription.subscribed = %d ' .
672           'AND subscription.subscribed != subscription.subscriber ' .
673           'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
674           'AND profile_list.private = false ' .
675           'ORDER BY subscription.created DESC';
676
677         $profile = new Profile();
678         $tagged = array();
679
680         $cnt = $profile->query(sprintf($qry, $this->id, $this->id, $profile->escape($tag)));
681
682         while ($profile->fetch()) {
683             $tagged[] = clone($profile);
684         }
685         return $tagged;
686     }
687
688     /**
689      * Get pending subscribers, who have not yet been approved.
690      *
691      * @param int $offset
692      * @param int $limit
693      * @return Profile
694      */
695     function getRequests($offset=0, $limit=null)
696     {
697         $qry =
698           'SELECT profile.* ' .
699           'FROM profile JOIN subscription_queue '.
700           'ON profile.id = subscription_queue.subscriber ' .
701           'WHERE subscription_queue.subscribed = %d ' .
702           'ORDER BY subscription_queue.created DESC ';
703
704         if ($limit != null) {
705             if (common_config('db','type') == 'pgsql') {
706                 $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
707             } else {
708                 $qry .= ' LIMIT ' . $offset . ', ' . $limit;
709             }
710         }
711
712         $members = new Profile();
713
714         $members->query(sprintf($qry, $this->id));
715         return $members;
716     }
717
718     function subscriptionCount()
719     {
720         $c = Cache::instance();
721
722         if (!empty($c)) {
723             $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
724             if (is_integer($cnt)) {
725                 return (int) $cnt;
726             }
727         }
728
729         $sub = new Subscription();
730         $sub->subscriber = $this->id;
731
732         $cnt = (int) $sub->count('distinct subscribed');
733
734         $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;
735
736         if (!empty($c)) {
737             $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
738         }
739
740         return $cnt;
741     }
742
743     function subscriberCount()
744     {
745         $c = Cache::instance();
746         if (!empty($c)) {
747             $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
748             if (is_integer($cnt)) {
749                 return (int) $cnt;
750             }
751         }
752
753         $sub = new Subscription();
754         $sub->subscribed = $this->id;
755         $sub->whereAdd('subscriber != subscribed');
756         $cnt = (int) $sub->count('distinct subscriber');
757
758         if (!empty($c)) {
759             $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
760         }
761
762         return $cnt;
763     }
764
765     /**
766      * Is this profile subscribed to another profile?
767      *
768      * @param Profile $other
769      * @return boolean
770      */
771     function isSubscribed($other)
772     {
773         return Subscription::exists($this, $other);
774     }
775
776     /**
777      * Check if a pending subscription request is outstanding for this...
778      *
779      * @param Profile $other
780      * @return boolean
781      */
782     function hasPendingSubscription($other)
783     {
784         return Subscription_queue::exists($this, $other);
785     }
786
787     /**
788      * Are these two profiles subscribed to each other?
789      *
790      * @param Profile $other
791      * @return boolean
792      */
793     function mutuallySubscribed($other)
794     {
795         return $this->isSubscribed($other) &&
796           $other->isSubscribed($this);
797     }
798
799     function hasFave($notice)
800     {
801         $fave = Fave::pkeyGet(array('user_id' => $this->id,
802                                     'notice_id' => $notice->id));
803         return ((is_null($fave)) ? false : true);
804     }
805
806     function faveCount()
807     {
808         $c = Cache::instance();
809         if (!empty($c)) {
810             $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
811             if (is_integer($cnt)) {
812                 return (int) $cnt;
813             }
814         }
815
816         $faves = new Fave();
817         $faves->user_id = $this->id;
818         $cnt = (int) $faves->count('notice_id');
819
820         if (!empty($c)) {
821             $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
822         }
823
824         return $cnt;
825     }
826
827     function noticeCount()
828     {
829         $c = Cache::instance();
830
831         if (!empty($c)) {
832             $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
833             if (is_integer($cnt)) {
834                 return (int) $cnt;
835             }
836         }
837
838         $notices = new Notice();
839         $notices->profile_id = $this->id;
840         $cnt = (int) $notices->count('distinct id');
841
842         if (!empty($c)) {
843             $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
844         }
845
846         return $cnt;
847     }
848
849     function blowFavesCache()
850     {
851         $cache = Cache::instance();
852         if ($cache) {
853             // Faves don't happen chronologically, so we need to blow
854             // ;last cache, too
855             $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
856             $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
857             $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
858             $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
859         }
860         $this->blowFaveCount();
861     }
862
863     function blowSubscriberCount()
864     {
865         $c = Cache::instance();
866         if (!empty($c)) {
867             $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
868         }
869     }
870
871     function blowSubscriptionCount()
872     {
873         $c = Cache::instance();
874         if (!empty($c)) {
875             $c->delete(Cache::key('profile:subscription_count:'.$this->id));
876         }
877     }
878
879     function blowFaveCount()
880     {
881         $c = Cache::instance();
882         if (!empty($c)) {
883             $c->delete(Cache::key('profile:fave_count:'.$this->id));
884         }
885     }
886
887     function blowNoticeCount()
888     {
889         $c = Cache::instance();
890         if (!empty($c)) {
891             $c->delete(Cache::key('profile:notice_count:'.$this->id));
892         }
893     }
894
895     static function maxBio()
896     {
897         $biolimit = common_config('profile', 'biolimit');
898         // null => use global limit (distinct from 0!)
899         if (is_null($biolimit)) {
900             $biolimit = common_config('site', 'textlimit');
901         }
902         return $biolimit;
903     }
904
905     static function bioTooLong($bio)
906     {
907         $biolimit = self::maxBio();
908         return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
909     }
910
911     function delete()
912     {
913         $this->_deleteNotices();
914         $this->_deleteSubscriptions();
915         $this->_deleteMessages();
916         $this->_deleteTags();
917         $this->_deleteBlocks();
918         $this->delete_avatars();
919
920         // Warning: delete() will run on the batch objects,
921         // not on individual objects.
922         $related = array('Reply',
923                          'Group_member',
924                          );
925         Event::handle('ProfileDeleteRelated', array($this, &$related));
926
927         foreach ($related as $cls) {
928             $inst = new $cls();
929             $inst->profile_id = $this->id;
930             $inst->delete();
931         }
932
933         parent::delete();
934     }
935
936     function _deleteNotices()
937     {
938         $notice = new Notice();
939         $notice->profile_id = $this->id;
940
941         if ($notice->find()) {
942             while ($notice->fetch()) {
943                 $other = clone($notice);
944                 $other->delete();
945             }
946         }
947     }
948
949     function _deleteSubscriptions()
950     {
951         $sub = new Subscription();
952         $sub->subscriber = $this->id;
953
954         $sub->find();
955
956         while ($sub->fetch()) {
957             $other = Profile::getKV('id', $sub->subscribed);
958             if (empty($other)) {
959                 continue;
960             }
961             if ($other->id == $this->id) {
962                 continue;
963             }
964             Subscription::cancel($this, $other);
965         }
966
967         $subd = new Subscription();
968         $subd->subscribed = $this->id;
969         $subd->find();
970
971         while ($subd->fetch()) {
972             $other = Profile::getKV('id', $subd->subscriber);
973             if (empty($other)) {
974                 continue;
975             }
976             if ($other->id == $this->id) {
977                 continue;
978             }
979             Subscription::cancel($other, $this);
980         }
981
982         $self = new Subscription();
983
984         $self->subscriber = $this->id;
985         $self->subscribed = $this->id;
986
987         $self->delete();
988     }
989
990     function _deleteMessages()
991     {
992         $msg = new Message();
993         $msg->from_profile = $this->id;
994         $msg->delete();
995
996         $msg = new Message();
997         $msg->to_profile = $this->id;
998         $msg->delete();
999     }
1000
1001     function _deleteTags()
1002     {
1003         $tag = new Profile_tag();
1004         $tag->tagged = $this->id;
1005         $tag->delete();
1006     }
1007
1008     function _deleteBlocks()
1009     {
1010         $block = new Profile_block();
1011         $block->blocked = $this->id;
1012         $block->delete();
1013
1014         $block = new Group_block();
1015         $block->blocked = $this->id;
1016         $block->delete();
1017     }
1018
1019     // XXX: identical to Notice::getLocation.
1020
1021     function getLocation()
1022     {
1023         $location = null;
1024
1025         if (!empty($this->location_id) && !empty($this->location_ns)) {
1026             $location = Location::fromId($this->location_id, $this->location_ns);
1027         }
1028
1029         if (is_null($location)) { // no ID, or Location::fromId() failed
1030             if (!empty($this->lat) && !empty($this->lon)) {
1031                 $location = Location::fromLatLon($this->lat, $this->lon);
1032             }
1033         }
1034
1035         if (is_null($location)) { // still haven't found it!
1036             if (!empty($this->location)) {
1037                 $location = Location::fromName($this->location);
1038             }
1039         }
1040
1041         return $location;
1042     }
1043
1044     function hasRole($name)
1045     {
1046         $has_role = false;
1047         if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
1048             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1049                                                 'role' => $name));
1050             $has_role = !empty($role);
1051             Event::handle('EndHasRole', array($this, $name, $has_role));
1052         }
1053         return $has_role;
1054     }
1055
1056     function grantRole($name)
1057     {
1058         if (Event::handle('StartGrantRole', array($this, $name))) {
1059
1060             $role = new Profile_role();
1061
1062             $role->profile_id = $this->id;
1063             $role->role       = $name;
1064             $role->created    = common_sql_now();
1065
1066             $result = $role->insert();
1067
1068             if (!$result) {
1069                 throw new Exception("Can't save role '$name' for profile '{$this->id}'");
1070             }
1071
1072             if ($name == 'owner') {
1073                 User::blow('user:site_owner');
1074             }
1075
1076             Event::handle('EndGrantRole', array($this, $name));
1077         }
1078
1079         return $result;
1080     }
1081
1082     function revokeRole($name)
1083     {
1084         if (Event::handle('StartRevokeRole', array($this, $name))) {
1085
1086             $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
1087                                                 'role' => $name));
1088
1089             if (empty($role)) {
1090                 // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
1091                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1092                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
1093             }
1094
1095             $result = $role->delete();
1096
1097             if (!$result) {
1098                 common_log_db_error($role, 'DELETE', __FILE__);
1099                 // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
1100                 // TRANS: %1$s is the role name, %2$s is the user ID (number).
1101                 throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
1102             }
1103
1104             if ($name == 'owner') {
1105                 User::blow('user:site_owner');
1106             }
1107
1108             Event::handle('EndRevokeRole', array($this, $name));
1109
1110             return true;
1111         }
1112     }
1113
1114     function isSandboxed()
1115     {
1116         return $this->hasRole(Profile_role::SANDBOXED);
1117     }
1118
1119     function isSilenced()
1120     {
1121         return $this->hasRole(Profile_role::SILENCED);
1122     }
1123
1124     function sandbox()
1125     {
1126         $this->grantRole(Profile_role::SANDBOXED);
1127     }
1128
1129     function unsandbox()
1130     {
1131         $this->revokeRole(Profile_role::SANDBOXED);
1132     }
1133
1134     function silence()
1135     {
1136         $this->grantRole(Profile_role::SILENCED);
1137         if (common_config('notice', 'hidespam')) {
1138             $this->flushVisibility();
1139         }
1140     }
1141
1142     function unsilence()
1143     {
1144         $this->revokeRole(Profile_role::SILENCED);
1145         if (common_config('notice', 'hidespam')) {
1146             $this->flushVisibility();
1147         }
1148     }
1149
1150     function flushVisibility()
1151     {
1152         // Get all notices
1153         $stream = new ProfileNoticeStream($this, $this);
1154         $ids = $stream->getNoticeIds(0, CachingNoticeStream::CACHE_WINDOW);
1155         foreach ($ids as $id) {
1156             self::blow('notice:in-scope-for:%d:null', $id);
1157         }
1158     }
1159
1160     /**
1161      * Does this user have the right to do X?
1162      *
1163      * With our role-based authorization, this is merely a lookup for whether the user
1164      * has a particular role. The implementation currently uses a switch statement
1165      * to determine if the user has the pre-defined role to exercise the right. Future
1166      * implementations may allow per-site roles, and different mappings of roles to rights.
1167      *
1168      * @param $right string Name of the right, usually a constant in class Right
1169      * @return boolean whether the user has the right in question
1170      */
1171     function hasRight($right)
1172     {
1173         $result = false;
1174
1175         if ($this->hasRole(Profile_role::DELETED)) {
1176             return false;
1177         }
1178
1179         if (Event::handle('UserRightsCheck', array($this, $right, &$result))) {
1180             switch ($right)
1181             {
1182             case Right::DELETEOTHERSNOTICE:
1183             case Right::MAKEGROUPADMIN:
1184             case Right::SANDBOXUSER:
1185             case Right::SILENCEUSER:
1186             case Right::DELETEUSER:
1187             case Right::DELETEGROUP:
1188             case Right::TRAINSPAM:
1189             case Right::REVIEWSPAM:
1190                 $result = $this->hasRole(Profile_role::MODERATOR);
1191                 break;
1192             case Right::CONFIGURESITE:
1193                 $result = $this->hasRole(Profile_role::ADMINISTRATOR);
1194                 break;
1195             case Right::GRANTROLE:
1196             case Right::REVOKEROLE:
1197                 $result = $this->hasRole(Profile_role::OWNER);
1198                 break;
1199             case Right::NEWNOTICE:
1200             case Right::NEWMESSAGE:
1201             case Right::SUBSCRIBE:
1202             case Right::CREATEGROUP:
1203                 $result = !$this->isSilenced();
1204                 break;
1205             case Right::PUBLICNOTICE:
1206             case Right::EMAILONREPLY:
1207             case Right::EMAILONSUBSCRIBE:
1208             case Right::EMAILONFAVE:
1209                 $result = !$this->isSandboxed();
1210                 break;
1211             case Right::WEBLOGIN:
1212                 $result = !$this->isSilenced();
1213                 break;
1214             case Right::API:
1215                 $result = !$this->isSilenced();
1216                 break;
1217             case Right::BACKUPACCOUNT:
1218                 $result = common_config('profile', 'backup');
1219                 break;
1220             case Right::RESTOREACCOUNT:
1221                 $result = common_config('profile', 'restore');
1222                 break;
1223             case Right::DELETEACCOUNT:
1224                 $result = common_config('profile', 'delete');
1225                 break;
1226             case Right::MOVEACCOUNT:
1227                 $result = common_config('profile', 'move');
1228                 break;
1229             default:
1230                 $result = false;
1231                 break;
1232             }
1233         }
1234         return $result;
1235     }
1236
1237     function hasRepeated($notice_id)
1238     {
1239         // XXX: not really a pkey, but should work
1240
1241         $notice = Notice::pkeyGet(array('profile_id' => $this->id,
1242                                         'repeat_of' => $notice_id));
1243
1244         return !empty($notice);
1245     }
1246
1247     /**
1248      * Returns an XML string fragment with limited profile information
1249      * as an Atom <author> element.
1250      *
1251      * Assumes that Atom has been previously set up as the base namespace.
1252      *
1253      * @param Profile $cur the current authenticated user
1254      *
1255      * @return string
1256      */
1257     function asAtomAuthor($cur = null)
1258     {
1259         $xs = new XMLStringer(true);
1260
1261         $xs->elementStart('author');
1262         $xs->element('name', null, $this->nickname);
1263         $xs->element('uri', null, $this->getUri());
1264         if ($cur != null) {
1265             $attrs = Array();
1266             $attrs['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1267             $attrs['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
1268             $xs->element('statusnet:profile_info', $attrs, null);
1269         }
1270         $xs->elementEnd('author');
1271
1272         return $xs->getString();
1273     }
1274
1275     /**
1276      * Extra profile info for atom entries
1277      *
1278      * Clients use some extra profile info in the atom stream.
1279      * This gives it to them.
1280      *
1281      * @param User $cur Current user
1282      *
1283      * @return array representation of <statusnet:profile_info> element or null
1284      */
1285
1286     function profileInfo($cur)
1287     {
1288         $profileInfoAttr = array('local_id' => $this->id);
1289
1290         if ($cur != null) {
1291             // Whether the current user is a subscribed to this profile
1292             $profileInfoAttr['following'] = $cur->isSubscribed($this) ? 'true' : 'false';
1293             // Whether the current user is has blocked this profile
1294             $profileInfoAttr['blocking']  = $cur->hasBlocked($this) ? 'true' : 'false';
1295         }
1296
1297         return array('statusnet:profile_info', $profileInfoAttr, null);
1298     }
1299
1300     /**
1301      * Returns an XML string fragment with profile information as an
1302      * Activity Streams <activity:actor> element.
1303      *
1304      * Assumes that 'activity' namespace has been previously defined.
1305      *
1306      * @return string
1307      */
1308     function asActivityActor()
1309     {
1310         return $this->asActivityNoun('actor');
1311     }
1312
1313     /**
1314      * Returns an XML string fragment with profile information as an
1315      * Activity Streams noun object with the given element type.
1316      *
1317      * Assumes that 'activity', 'georss', and 'poco' namespace has been
1318      * previously defined.
1319      *
1320      * @param string $element one of 'actor', 'subject', 'object', 'target'
1321      *
1322      * @return string
1323      */
1324     function asActivityNoun($element)
1325     {
1326         $noun = ActivityObject::fromProfile($this);
1327         return $noun->asString('activity:' . $element);
1328     }
1329
1330     /**
1331      * Returns the best URI for a profile. Plugins may override.
1332      *
1333      * @return string $uri
1334      */
1335     function getUri()
1336     {
1337         $uri = null;
1338
1339         // give plugins a chance to set the URI
1340         if (Event::handle('StartGetProfileUri', array($this, &$uri))) {
1341
1342             // check for a local user first
1343             $user = User::getKV('id', $this->id);
1344
1345             if (!empty($user)) {
1346                 $uri = $user->uri;
1347             }
1348
1349             Event::handle('EndGetProfileUri', array($this, &$uri));
1350         }
1351
1352         return $uri;
1353     }
1354
1355     function hasBlocked($other)
1356     {
1357         $block = Profile_block::exists($this, $other);
1358         return !empty($block);
1359     }
1360
1361     function getAtomFeed()
1362     {
1363         $feed = null;
1364
1365         if (Event::handle('StartProfileGetAtomFeed', array($this, &$feed))) {
1366             $user = User::getKV('id', $this->id);
1367             if (!empty($user)) {
1368                 $feed = common_local_url('ApiTimelineUser', array('id' => $user->id,
1369                                                                   'format' => 'atom'));
1370             }
1371             Event::handle('EndProfileGetAtomFeed', array($this, $feed));
1372         }
1373
1374         return $feed;
1375     }
1376
1377     static function fromURI($uri)
1378     {
1379         $profile = null;
1380
1381         if (Event::handle('StartGetProfileFromURI', array($uri, &$profile))) {
1382             // Get a local user or remote (OMB 0.1) profile
1383             $user = User::getKV('uri', $uri);
1384             if (!empty($user)) {
1385                 $profile = $user->getProfile();
1386             }
1387             Event::handle('EndGetProfileFromURI', array($uri, $profile));
1388         }
1389
1390         return $profile;
1391     }
1392
1393     function canRead(Notice $notice)
1394     {
1395         if ($notice->scope & Notice::SITE_SCOPE) {
1396             $user = $this->getUser();
1397             if (empty($user)) {
1398                 return false;
1399             }
1400         }
1401
1402         if ($notice->scope & Notice::ADDRESSEE_SCOPE) {
1403             $replies = $notice->getReplies();
1404
1405             if (!in_array($this->id, $replies)) {
1406                 $groups = $notice->getGroups();
1407
1408                 $foundOne = false;
1409
1410                 foreach ($groups as $group) {
1411                     if ($this->isMember($group)) {
1412                         $foundOne = true;
1413                         break;
1414                     }
1415                 }
1416
1417                 if (!$foundOne) {
1418                     return false;
1419                 }
1420             }
1421         }
1422
1423         if ($notice->scope & Notice::FOLLOWER_SCOPE) {
1424             $author = $notice->getProfile();
1425             if (!Subscription::exists($this, $author)) {
1426                 return false;
1427             }
1428         }
1429
1430         return true;
1431     }
1432
1433     static function current()
1434     {
1435         $user = common_current_user();
1436         if (empty($user)) {
1437             $profile = null;
1438         } else {
1439             $profile = $user->getProfile();
1440         }
1441         return $profile;
1442     }
1443
1444     /**
1445      * Magic function called at serialize() time.
1446      *
1447      * We use this to drop a couple process-specific references
1448      * from DB_DataObject which can cause trouble in future
1449      * processes.
1450      *
1451      * @return array of variable names to include in serialization.
1452      */
1453
1454     function __sleep()
1455     {
1456         $vars = parent::__sleep();
1457         $skip = array('_user', '_avatars');
1458         return array_diff($vars, $skip);
1459     }
1460     
1461     static function fillAvatars(&$profiles, $width)
1462     {
1463         $ids = array();
1464         foreach ($profiles as $profile) {
1465             if (!empty($profile)) {
1466                 $ids[] = $profile->id;
1467             }
1468         }
1469         
1470         $avatars = Avatar::pivotGet('profile_id', $ids, array('width' => $width,
1471                                                                                                                           'height' => $width));
1472         
1473         foreach ($profiles as $profile) {
1474             if (!empty($profile)) { // ???
1475                 $profile->_fillAvatar($width, $avatars[$profile->id]);
1476             }
1477         }
1478     }
1479     
1480     // Can't seem to find how to fix this.
1481
1482     function getProfile()
1483     {
1484         return $this;
1485     }
1486 }