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