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