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