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