We are no longer offering accounts on this server. Consider https://gitlab.freedesktop.org/ as a place to host projects.

Profile.php 47 KB
Newer Older
Evan Prodromou's avatar
Evan Prodromou committed
1
<?php
Evan Prodromou's avatar
Evan Prodromou committed
2
/*
3
 * StatusNet - the distributed open-source microblogging tool
4
 * Copyright (C) 2008-2011, StatusNet, Inc.
Evan Prodromou's avatar
Evan Prodromou committed
5
 *
Evan Prodromou's avatar
Evan Prodromou committed
6 7 8 9
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
Evan Prodromou's avatar
Evan Prodromou committed
10
 *
Evan Prodromou's avatar
Evan Prodromou committed
11 12 13 14
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
Evan Prodromou's avatar
Evan Prodromou committed
15
 *
Evan Prodromou's avatar
Evan Prodromou committed
16 17 18 19
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

20
if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
Evan Prodromou's avatar
Evan Prodromou committed
21

Evan Prodromou's avatar
Evan Prodromou committed
22 23 24
/**
 * Table Definition for profile
 */
25
class Profile extends Managed_DataObject
Evan Prodromou's avatar
Evan Prodromou committed
26 27 28 29 30 31
{
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'profile';                         // table name
    public $id;                              // int(4)  primary_key not_null
32 33
    public $nickname;                        // varchar(64)  multiple_key not_null
    public $fullname;                        // varchar(255)  multiple_key
Evan Prodromou's avatar
Evan Prodromou committed
34
    public $profileurl;                      // varchar(255)
35
    public $homepage;                        // varchar(255)  multiple_key
36
    public $bio;                             // text()  multiple_key
37
    public $location;                        // varchar(255)  multiple_key
38 39 40 41
    public $lat;                             // decimal(10,7)
    public $lon;                             // decimal(10,7)
    public $location_id;                     // int(4)
    public $location_ns;                     // int(4)
Evan Prodromou's avatar
Evan Prodromou committed
42 43 44
    public $created;                         // datetime()   not_null
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

45 46
    public static function schemaDef()
    {
47
        $def = array(
48 49 50
            'description' => 'local and remote users have profiles',
            'fields' => array(
                'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
51 52
                'nickname' => array('type' => 'varchar', 'length' => 64, 'not null' => true, 'description' => 'nickname or username', 'collate' => 'utf8_general_ci'),
                'fullname' => array('type' => 'varchar', 'length' => 255, 'description' => 'display name', 'collate' => 'utf8_general_ci'),
53
                'profileurl' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
54 55 56
                'homepage' => array('type' => 'varchar', 'length' => 255, 'description' => 'identifying URL', 'collate' => 'utf8_general_ci'),
                'bio' => array('type' => 'text', 'description' => 'descriptive biography', 'collate' => 'utf8_general_ci'),
                'location' => array('type' => 'varchar', 'length' => 255, 'description' => 'physical location', 'collate' => 'utf8_general_ci'),
57 58 59 60 61 62 63 64 65 66 67
                'lat' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'latitude'),
                'lon' => array('type' => 'numeric', 'precision' => 10, 'scale' => 7, 'description' => 'longitude'),
                'location_id' => array('type' => 'int', 'description' => 'location id if possible'),
                'location_ns' => array('type' => 'int', 'description' => 'namespace for location'),

                'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
                'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
            ),
            'primary key' => array('id'),
            'indexes' => array(
                'profile_nickname_idx' => array('nickname'),
68
            )
69
        );
70 71 72 73 74 75 76 77

        // Add a fulltext index

        if (common_config('search', 'type') == 'fulltext') {
            $def['fulltext indexes'] = array('nickname' => array('nickname', 'fullname', 'location', 'bio', 'homepage'));
        }

        return $def;
78
    }
79
	
Evan Prodromou's avatar
Evan Prodromou committed
80 81
    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE
Evan Prodromou's avatar
Evan Prodromou committed
82

mattl's avatar
mattl committed
83 84 85 86 87 88 89 90 91 92
    public static function getByEmail($email)
    {
        // in the future, profiles should have emails stored...
        $user = User::getKV('email', $email);
        if (!($user instanceof User)) {
            throw new NoSuchUserException(array('email'=>$email));
        }
        return $user->getProfile();
    } 

93
    protected $_user = array();
94

95
    public function getUser()
96
    {
97
        if (!isset($this->_user[$this->id])) {
98 99 100 101 102
            $user = User::getKV('id', $this->id);
            if (!$user instanceof User) {
                throw new NoSuchUserException(array('id'=>$this->id));
            }
            $this->_user[$this->id] = $user;
103
        }
104 105 106 107
        return $this->_user[$this->id];
    }

    protected $_group = array();
108 109 110

    public function getGroup()
    {
111
        if (!isset($this->_group[$this->id])) {
112 113 114 115 116
            $group = User_group::getKV('profile_id', $this->id);
            if (!$group instanceof User_group) {
                throw new NoSuchGroupException(array('profile_id'=>$this->id));
            }
            $this->_group[$this->id] = $group;
117
        }
118 119 120
        return $this->_group[$this->id];
    }

121 122 123 124 125 126 127 128 129 130
    public function isGroup()
    {
        try {
            $this->getGroup();
            return true;
        } catch (NoSuchGroupException $e) {
            return false;
        }
    }

131 132 133 134 135 136 137 138 139 140
    public function isLocal()
    {
        try {
            $this->getUser();
        } catch (NoSuchUserException $e) {
            return false;
        }
        return true;
    }

141 142 143 144 145 146 147 148 149 150
    public function getObjectType()
    {
        // FIXME: More types... like peopletags and whatever
        if ($this->isGroup()) {
            return ActivityObject::GROUP;
        } else {
            return ActivityObject::PERSON;
        }
    }

151
    public function getAvatar($width, $height=null)
152
    {
153
        return Avatar::byProfile($this, $width, $height);
154 155
    }

156
    public function setOriginal($filename)
157
    {
158
        $imagefile = new ImageFile($this->id, Avatar::path($filename));
159 160 161

        $avatar = new Avatar();
        $avatar->profile_id = $this->id;
162 163 164
        $avatar->width = $imagefile->width;
        $avatar->height = $imagefile->height;
        $avatar->mediatype = image_type_to_mime_type($imagefile->type);
165 166
        $avatar->filename = $filename;
        $avatar->original = true;
167
        $avatar->url = Avatar::url($filename);
mattl's avatar
mattl committed
168
        $avatar->created = common_sql_now();
169

170
        // XXX: start a transaction here
171 172
        if (!Avatar::deleteFromProfile($this, true) || !$avatar->insert()) {
            // If we can't delete the old avatars, let's abort right here.
173
            @unlink(Avatar::path($filename));
Evan Prodromou's avatar
Evan Prodromou committed
174
            return null;
175 176 177 178 179
        }

        return $avatar;
    }

180 181 182 183 184
    /**
     * Gets either the full name (if filled) or the nickname.
     *
     * @return string
     */
185 186
    function getBestName()
    {
187 188
        return ($this->fullname) ? $this->fullname : $this->nickname;
    }
189

190 191 192 193 194 195 196 197 198 199 200 201 202 203
    /**
     * Takes the currently scoped profile into account to give a name 
     * to list in notice streams. Preferences may differ between profiles.
     */
    function getStreamName()
    {
        $user = common_current_user();
        if ($user instanceof User && $user->streamNicknames()) {
            return $this->nickname;
        }

        return $this->getBestName();
    }

204 205 206 207 208 209 210 211 212
    /**
     * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
     * if no fullname is provided.
     *
     * @return string
     */
    function getFancyName()
    {
        if ($this->fullname) {
Siebrand Mazeland's avatar
Siebrand Mazeland committed
213
            // TRANS: Full name of a profile or group (%1$s) followed by nickname (%2$s) in parentheses.
214
            return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
215 216 217 218 219
        } else {
            return $this->nickname;
        }
    }

220 221 222 223 224 225
    /**
     * Get the most recent notice posted by this user, if any.
     *
     * @return mixed Notice or null
     */
    function getCurrentNotice()
226
    {
227 228 229
        $notice = $this->getNotices(0, 1);

        if ($notice->fetch()) {
230 231 232 233
            if ($notice instanceof ArrayWrapper) {
                // hack for things trying to work with single notices
                return $notice->_items[0];
            }
234 235
            return $notice;
        }
236 237
        
        return null;
238 239
    }

240
    function getTaggedNotices($tag, $offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0)
241
    {
242
        $stream = new TaggedProfileNoticeStream($this, $tag);
243

244
        return $stream->getNotices($offset, $limit, $since_id, $max_id);
245 246
    }

247
    function getNotices($offset=0, $limit=NOTICES_PER_PAGE, $since_id=0, $max_id=0, Profile $scoped=null)
248
    {
249
        $stream = new ProfileNoticeStream($this, $scoped);
250

251
        return $stream->getNotices($offset, $limit, $since_id, $max_id);
252
    }
253

254
    function isMember(User_group $group)
255
    {
256
    	$groups = $this->getGroups(0, null);
257 258
        while ($groups instanceof User_group && $groups->fetch()) {
    	    if ($groups->id == $group->id) {
259 260 261 262
    	        return true;
    	    }
    	}
    	return false;
263 264
    }

265
    function isAdmin(User_group $group)
266
    {
267 268 269
        $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
                                          'group_id' => $group->id));
        return (!empty($gm) && $gm->is_admin);
270 271
    }

272 273 274 275 276 277 278
    function isPendingMember($group)
    {
        $request = Group_join_queue::pkeyGet(array('profile_id' => $this->id,
                                                   'group_id' => $group->id));
        return !empty($request);
    }

Evan Prodromou's avatar
Evan Prodromou committed
279
    function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
280
    {
Evan Prodromou's avatar
Evan Prodromou committed
281
        $ids = array();
282

Evan Prodromou's avatar
Evan Prodromou committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296
        $keypart = sprintf('profile:groups:%d', $this->id);

        $idstring = self::cacheGet($keypart);

        if ($idstring !== false) {
            $ids = explode(',', $idstring);
        } else {
            $gm = new Group_member();

            $gm->profile_id = $this->id;

            if ($gm->find()) {
                while ($gm->fetch()) {
                    $ids[] = $gm->group_id;
297 298
                }
            }
Evan Prodromou's avatar
Evan Prodromou committed
299 300

            self::cacheSet($keypart, implode(',', $ids));
301 302
        }

303 304 305 306
        if (!is_null($offset) && !is_null($limit)) {
            $ids = array_slice($ids, $offset, $limit);
        }

307
        try {
308
            return User_group::multiGet('id', $ids);
309 310 311 312 313 314 315 316 317 318
        } catch (NoResultException $e) {
            return null;    // throw exception when we handle it everywhere
        }
    }

    function getGroupCount() {
        $groups = $this->getGroups(0, null);
        return $groups instanceof User_group
                ? $groups->N
                : 0;
319 320
    }

Shashi Gowda's avatar
Shashi Gowda committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    function isTagged($peopletag)
    {
        $tag = Profile_tag::pkeyGet(array('tagger' => $peopletag->tagger,
                                          'tagged' => $this->id,
                                          'tag'    => $peopletag->tag));
        return !empty($tag);
    }

    function canTag($tagged)
    {
        if (empty($tagged)) {
            return false;
        }

        if ($tagged->id == $this->id) {
            return true;
        }

        $all = common_config('peopletag', 'allow_tagging', 'all');
        $local = common_config('peopletag', 'allow_tagging', 'local');
        $remote = common_config('peopletag', 'allow_tagging', 'remote');
        $subs = common_config('peopletag', 'allow_tagging', 'subs');

        if ($all) {
            return true;
        }

        $tagged_user = $tagged->getUser();
        if (!empty($tagged_user)) {
            if ($local) {
                return true;
            }
        } else if ($subs) {
            return (Subscription::exists($this, $tagged) ||
                    Subscription::exists($tagged, $this));
        } else if ($remote) {
            return true;
        }
        return false;
    }

362
    function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
Shashi Gowda's avatar
Shashi Gowda committed
363
    {
364
        $ids = array();
Shashi Gowda's avatar
Shashi Gowda committed
365

366 367 368 369 370 371
        $keypart = sprintf('profile:lists:%d', $this->id);

        $idstr = self::cacheGet($keypart);

        if ($idstr !== false) {
            $ids = explode(',', $idstr);
Shashi Gowda's avatar
Shashi Gowda committed
372
        } else {
373 374 375 376 377
            $list = new Profile_list();
            $list->selectAdd();
            $list->selectAdd('id');
            $list->tagger = $this->id;
            $list->selectAdd('id as "cursor"');
Shashi Gowda's avatar
Shashi Gowda committed
378

379 380 381
            if ($since_id>0) {
               $list->whereAdd('id > '.$since_id);
            }
Shashi Gowda's avatar
Shashi Gowda committed
382

383 384 385
            if ($max_id>0) {
                $list->whereAdd('id <= '.$max_id);
            }
Shashi Gowda's avatar
Shashi Gowda committed
386

387 388 389
            if($offset>=0 && !is_null($limit)) {
                $list->limit($offset, $limit);
            }
Shashi Gowda's avatar
Shashi Gowda committed
390

391 392 393 394 395 396 397 398 399
            $list->orderBy('id DESC');

            if ($list->find()) {
                while ($list->fetch()) {
                    $ids[] = $list->id;
                }
            }

            self::cacheSet($keypart, implode(',', $ids));
Shashi Gowda's avatar
Shashi Gowda committed
400 401
        }

402 403 404
        $showPrivate = (($auth_user instanceof User ||
                            $auth_user instanceof Profile) &&
                        $auth_user->id === $this->id);
Shashi Gowda's avatar
Shashi Gowda committed
405

406 407 408
        $lists = array();

        foreach ($ids as $id) {
409
            $list = Profile_list::getKV('id', $id);
410 411 412 413 414 415 416 417 418 419 420 421
            if (!empty($list) &&
                ($showPrivate || !$list->private)) {

                if (!isset($list->cursor)) {
                    $list->cursor = $list->id;
                }

                $lists[] = $list;
            }
        }

        return new ArrayWrapper($lists);
Shashi Gowda's avatar
Shashi Gowda committed
422 423
    }

424 425 426 427 428 429 430 431 432 433 434 435
    /**
     * Get tags that other people put on this profile, in reverse-chron order
     *
     * @param (Profile|User) $auth_user  Authorized user (used for privacy)
     * @param int            $offset     Offset from latest
     * @param int            $limit      Max number to get
     * @param datetime       $since_id   max date
     * @param datetime       $max_id     min date
     *
     * @return Profile_list resulting lists
     */

Shashi Gowda's avatar
Shashi Gowda committed
436 437
    function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
    {
438
        $list = new Profile_list();
Shashi Gowda's avatar
Shashi Gowda committed
439

440 441 442 443 444 445
        $qry = sprintf('select profile_list.*, unix_timestamp(profile_tag.modified) as "cursor" ' .
                       'from profile_tag join profile_list '.
                       'on (profile_tag.tagger = profile_list.tagger ' .
                       '    and profile_tag.tag = profile_list.tag) ' .
                       'where profile_tag.tagged = %d ',
                       $this->id);
446

Shashi Gowda's avatar
Shashi Gowda committed
447 448

        if ($auth_user instanceof User || $auth_user instanceof Profile) {
449 450 451 452
            $qry .= sprintf('AND ( ( profile_list.private = false ) ' .
                            'OR ( profile_list.tagger = %d AND ' .
                            'profile_list.private = true ) )',
                            $auth_user->id);
Shashi Gowda's avatar
Shashi Gowda committed
453
        } else {
454
            $qry .= 'AND profile_list.private = 0 ';
Shashi Gowda's avatar
Shashi Gowda committed
455 456
        }

457 458
        if ($since_id > 0) {
            $qry .= sprintf('AND (cursor > %d) ', $since_id);
Shashi Gowda's avatar
Shashi Gowda committed
459 460
        }

461 462
        if ($max_id > 0) {
            $qry .= sprintf('AND (cursor < %d) ', $max_id);
Shashi Gowda's avatar
Shashi Gowda committed
463 464
        }

465
        $qry .= 'ORDER BY profile_tag.modified DESC ';
Shashi Gowda's avatar
Shashi Gowda committed
466

467 468 469
        if ($offset >= 0 && !is_null($limit)) {
            $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
        }
Shashi Gowda's avatar
Shashi Gowda committed
470

471 472
        $list->query($qry);
        return $list;
Shashi Gowda's avatar
Shashi Gowda committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
    }

    function getPrivateTags($offset=0, $limit=null, $since_id=0, $max_id=0)
    {
        $tags = new Profile_list();
        $tags->private = true;
        $tags->tagger = $this->id;

        if ($since_id>0) {
           $tags->whereAdd('id > '.$since_id);
        }

        if ($max_id>0) {
            $tags->whereAdd('id <= '.$max_id);
        }

        if($offset>=0 && !is_null($limit)) {
            $tags->limit($offset, $limit);
        }

        $tags->orderBy('id DESC');
        $tags->find();

        return $tags;
    }

    function hasLocalTags()
    {
        $tags = new Profile_tag();

        $tags->joinAdd(array('tagger', 'user:id'));
        $tags->whereAdd('tagged  = '.$this->id);
        $tags->whereAdd('tagger != '.$this->id);

        $tags->limit(0, 1);
        $tags->fetch();

        return ($tags->N == 0) ? false : true;
    }

    function getTagSubscriptions($offset=0, $limit=null, $since_id=0, $max_id=0)
    {
        $lists = new Profile_list();
        $subs = new Profile_tag_subscription();

mattl's avatar
mattl committed
518
        $lists->joinAdd(array('id', 'profile_tag_subscription:profile_tag_id'));
519

Shashi Gowda's avatar
Shashi Gowda committed
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
        #@fixme: postgres (round(date_part('epoch', my_date)))
        $lists->selectAdd('unix_timestamp(profile_tag_subscription.created) as "cursor"');

        $lists->whereAdd('profile_tag_subscription.profile_id = '.$this->id);

        if ($since_id>0) {
           $lists->whereAdd('cursor > '.$since_id);
        }

        if ($max_id>0) {
            $lists->whereAdd('cursor <= '.$max_id);
        }

        if($offset>=0 && !is_null($limit)) {
            $lists->limit($offset, $limit);
        }

        $lists->orderBy('"cursor" DESC');
        $lists->find();

        return $lists;
    }

543 544 545 546 547
    /**
     * Request to join the given group.
     * May throw exceptions on failure.
     *
     * @param User_group $group
548
     * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
549 550 551
     */
    function joinGroup(User_group $group)
    {
552
        $join = null;
553
        if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
554
            $join = Group_join_queue::saveNew($this, $group);
555 556
        } else {
            if (Event::handle('StartJoinGroup', array($group, $this))) {
557
                $join = Group_member::join($group->id, $this->id);
Evan Prodromou's avatar
Evan Prodromou committed
558
                self::blow('profile:groups:%d', $this->id);
Evan Prodromou's avatar
Evan Prodromou committed
559
                self::blow('group:member_ids:%d', $group->id);
560
                self::blow('group:member_count:%d', $group->id);
561 562
                Event::handle('EndJoinGroup', array($group, $this));
            }
563
        }
564 565 566
        if ($join) {
            // Send any applicable notifications...
            $join->notify();
567
        }
568
        return $join;
569 570
    }

571 572 573
    /**
     * Leave a group that this profile is a member of.
     *
574
     * @param User_group $group
575 576 577
     */
    function leaveGroup(User_group $group)
    {
578 579
        if (Event::handle('StartLeaveGroup', array($group, $this))) {
            Group_member::leave($group->id, $this->id);
Evan Prodromou's avatar
Evan Prodromou committed
580
            self::blow('profile:groups:%d', $this->id);
Evan Prodromou's avatar
Evan Prodromou committed
581
            self::blow('group:member_ids:%d', $group->id);
582
            self::blow('group:member_count:%d', $group->id);
583
            Event::handle('EndLeaveGroup', array($group, $this));
584 585 586
        }
    }

587 588
    function avatarUrl($size=AVATAR_PROFILE_SIZE)
    {
589
        return Avatar::urlByProfile($this, $size);
590
    }
591

592
    function getSubscribed($offset=0, $limit=null)
593
    {
594
        $subs = Subscription::getSubscribedIDs($this->id, $offset, $limit);
595
        try {
596
            $profiles = Profile::multiGet('id', $subs);
597 598 599
        } catch (NoResultException $e) {
            return $e->obj;
        }
600
        return $profiles;
601 602 603 604
    }

    function getSubscribers($offset=0, $limit=null)
    {
605
        $subs = Subscription::getSubscriberIDs($this->id, $offset, $limit);
606
        try {
607
            $profiles = Profile::multiGet('id', $subs);
608 609 610
        } catch (NoResultException $e) {
            return $e->obj;
        }
611
        return $profiles;
612 613
    }

614
    function getTaggedSubscribers($tag, $offset=0, $limit=null)
Shashi Gowda's avatar
Shashi Gowda committed
615 616 617
    {
        $qry =
          'SELECT profile.* ' .
618
          'FROM profile JOIN subscription ' .
Shashi Gowda's avatar
Shashi Gowda committed
619
          'ON profile.id = subscription.subscriber ' .
620 621
          'JOIN profile_tag ON (profile_tag.tagged = subscription.subscriber ' .
          'AND profile_tag.tagger = subscription.subscribed) ' .
Shashi Gowda's avatar
Shashi Gowda committed
622
          'WHERE subscription.subscribed = %d ' .
623
          "AND profile_tag.tag = '%s' " .
Shashi Gowda's avatar
Shashi Gowda committed
624
          'AND subscription.subscribed != subscription.subscriber ' .
625 626 627 628 629
          'ORDER BY subscription.created DESC ';

        if ($offset) {
            $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
        }
Shashi Gowda's avatar
Shashi Gowda committed
630 631 632

        $profile = new Profile();

633
        $cnt = $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));
Shashi Gowda's avatar
Shashi Gowda committed
634

635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
        return $profile;
    }

    function getTaggedSubscriptions($tag, $offset=0, $limit=null)
    {
        $qry =
          'SELECT profile.* ' .
          'FROM profile JOIN subscription ' .
          'ON profile.id = subscription.subscribed ' .
          'JOIN profile_tag on (profile_tag.tagged = subscription.subscribed ' .
          'AND profile_tag.tagger = subscription.subscriber) ' .
          'WHERE subscription.subscriber = %d ' .
          "AND profile_tag.tag = '%s' " .
          'AND subscription.subscribed != subscription.subscriber ' .
          'ORDER BY subscription.created DESC ';

        $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;

        $profile = new Profile();

        $profile->query(sprintf($qry, $this->id, $profile->escape($tag)));

        return $profile;
Shashi Gowda's avatar
Shashi Gowda committed
658 659
    }

Brion Vibber's avatar
Brion Vibber committed
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
    /**
     * Get pending subscribers, who have not yet been approved.
     *
     * @param int $offset
     * @param int $limit
     * @return Profile
     */
    function getRequests($offset=0, $limit=null)
    {
        $qry =
          'SELECT profile.* ' .
          'FROM profile JOIN subscription_queue '.
          'ON profile.id = subscription_queue.subscriber ' .
          'WHERE subscription_queue.subscribed = %d ' .
          'ORDER BY subscription_queue.created DESC ';

        if ($limit != null) {
            if (common_config('db','type') == 'pgsql') {
                $qry .= ' LIMIT ' . $limit . ' OFFSET ' . $offset;
            } else {
                $qry .= ' LIMIT ' . $offset . ', ' . $limit;
            }
        }

        $members = new Profile();

        $members->query(sprintf($qry, $this->id));
        return $members;
    }

690 691
    function subscriptionCount()
    {
692
        $c = Cache::instance();
693 694

        if (!empty($c)) {
695
            $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
696 697 698 699 700 701 702 703 704 705 706 707 708
            if (is_integer($cnt)) {
                return (int) $cnt;
            }
        }

        $sub = new Subscription();
        $sub->subscriber = $this->id;

        $cnt = (int) $sub->count('distinct subscribed');

        $cnt = ($cnt > 0) ? $cnt - 1 : $cnt;

        if (!empty($c)) {
709
            $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
710 711 712 713 714 715 716
        }

        return $cnt;
    }

    function subscriberCount()
    {
717
        $c = Cache::instance();
718
        if (!empty($c)) {
719
            $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
720 721 722 723 724 725 726
            if (is_integer($cnt)) {
                return (int) $cnt;
            }
        }

        $sub = new Subscription();
        $sub->subscribed = $this->id;
727
        $sub->whereAdd('subscriber != subscribed');
728 729 730
        $cnt = (int) $sub->count('distinct subscriber');

        if (!empty($c)) {
731
            $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
732 733 734 735 736
        }

        return $cnt;
    }

737 738 739 740 741 742
    /**
     * Is this profile subscribed to another profile?
     *
     * @param Profile $other
     * @return boolean
     */
mattl's avatar
mattl committed
743
    function isSubscribed(Profile $other)
744 745 746 747
    {
        return Subscription::exists($this, $other);
    }

748 749 750 751 752 753
    /**
     * Check if a pending subscription request is outstanding for this...
     *
     * @param Profile $other
     * @return boolean
     */
mattl's avatar
mattl committed
754
    function hasPendingSubscription(Profile $other)
755 756 757
    {
        return Subscription_queue::exists($this, $other);
    }
758 759 760 761 762 763 764

    /**
     * Are these two profiles subscribed to each other?
     *
     * @param Profile $other
     * @return boolean
     */
mattl's avatar
mattl committed
765
    function mutuallySubscribed(Profile $other)
766 767 768 769 770
    {
        return $this->isSubscribed($other) &&
          $other->isSubscribed($this);
    }

771 772
    function noticeCount()
    {
773
        $c = Cache::instance();
774 775

        if (!empty($c)) {
776
            $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
777 778 779 780 781 782 783 784 785 786
            if (is_integer($cnt)) {
                return (int) $cnt;
            }
        }

        $notices = new Notice();
        $notices->profile_id = $this->id;
        $cnt = (int) $notices->count('distinct id');

        if (!empty($c)) {
787
            $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
788 789 790 791 792 793 794
        }

        return $cnt;
    }

    function blowSubscriberCount()
    {
795
        $c = Cache::instance();
796
        if (!empty($c)) {
797
            $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
798 799 800 801 802
        }
    }

    function blowSubscriptionCount()
    {
803
        $c = Cache::instance();
804
        if (!empty($c)) {
805
            $c->delete(Cache::key('profile:subscription_count:'.$this->id));
806 807 808 809 810
        }
    }

    function blowNoticeCount()
    {
811
        $c = Cache::instance();
812
        if (!empty($c)) {
813
            $c->delete(Cache::key('profile:notice_count:'.$this->id));
814 815
        }
    }
816 817 818

    static function maxBio()
    {
819
        $biolimit = common_config('profile', 'biolimit');
820 821 822 823 824 825 826 827 828 829 830 831
        // null => use global limit (distinct from 0!)
        if (is_null($biolimit)) {
            $biolimit = common_config('site', 'textlimit');
        }
        return $biolimit;
    }

    static function bioTooLong($bio)
    {
        $biolimit = self::maxBio();
        return ($biolimit > 0 && !empty($bio) && (mb_strlen($bio) > $biolimit));
    }
832

833
    function update($dataObject=false)
834
    {
835 836 837 838
        if (is_object($dataObject) && $this->nickname != $dataObject->nickname) {
            try {
                $local = $this->getUser();
                common_debug("Updating User ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
839 840 841 842 843 844 845 846 847 848 849 850 851
                $origuser = clone($local);
                $local->nickname = $this->nickname;
                $result = $local->updateKeys($origuser);
                if ($result === false) {
                    common_log_db_error($local, 'UPDATE', __FILE__);
                    // TRANS: Server error thrown when user profile settings could not be updated.
                    throw new ServerException(_('Could not update user nickname.'));
                }

                // Clear the site owner, in case nickname changed
                if ($local->hasRole(Profile_role::OWNER)) {
                    User::blow('user:site_owner');
                }
852 853
            } catch (NoSuchUserException $e) {
                // Nevermind...
854 855 856
            }
        }

857
        return parent::update($dataObject);
858 859
    }

860
    function delete($useWhere=false)
861 862 863 864 865 866
    {
        $this->_deleteNotices();
        $this->_deleteSubscriptions();
        $this->_deleteMessages();
        $this->_deleteTags();
        $this->_deleteBlocks();
867
        $this->_deleteAttentions();
868
        Avatar::deleteFromProfile($this, true);
869

870 871 872
        // Warning: delete() will run on the batch objects,
        // not on individual objects.
        $related = array('Reply',
873 874
                         'Group_member',
                         );
875
        Event::handle('ProfileDeleteRelated', array($this, &$related));
876 877 878 879 880 881 882

        foreach ($related as $cls) {
            $inst = new $cls();
            $inst->profile_id = $this->id;
            $inst->delete();
        }

883
        return parent::delete($useWhere);
884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
    }

    function _deleteNotices()
    {
        $notice = new Notice();
        $notice->profile_id = $this->id;

        if ($notice->find()) {
            while ($notice->fetch()) {
                $other = clone($notice);
                $other->delete();
            }
        }
    }

    function _deleteSubscriptions()
    {
        $sub = new Subscription();
        $sub->subscriber = $this->id;
903 904 905 906

        $sub->find();

        while ($sub->fetch()) {
907
            $other = Profile::getKV('id', $sub->subscribed);
908 909 910 911 912 913 914 915
            if (empty($other)) {
                continue;
            }
            if ($other->id == $this->id) {
                continue;
            }
            Subscription::cancel($this, $other);
        }
916 917 918

        $subd = new Subscription();
        $subd->subscribed = $this->id;
919 920 921
        $subd->find();

        while ($subd->fetch()) {
922
            $other = Profile::getKV('id', $subd->subscriber);
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
            if (empty($other)) {
                continue;
            }
            if ($other->id == $this->id) {
                continue;
            }
            Subscription::cancel($other, $this);
        }

        $self = new Subscription();

        $self->subscriber = $this->id;
        $self->subscribed = $this->id;

        $self->delete();
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
    }

    function _deleteMessages()
    {
        $msg = new Message();
        $msg->from_profile = $this->id;
        $msg->delete();

        $msg = new Message();
        $msg->to_profile = $this->id;
        $msg->delete();
    }

    function _deleteTags()
    {
        $tag = new Profile_tag();
        $tag->tagged = $this->id;
955
        $tag->delete();
956 957 958 959 960 961 962 963 964 965 966 967
    }

    function _deleteBlocks()
    {
        $block = new Profile_block();
        $block->blocked = $this->id;
        $block->delete();

        $block = new Group_block();
        $block->blocked = $this->id;
        $block->delete();
    }
Evan Prodromou's avatar
Evan Prodromou committed
968

969 970 971 972 973 974 975 976 977 978 979 980 981 982
    function _deleteAttentions()
    {
        $att = new Attention();
        $att->profile_id = $this->getID();

        if ($att->find()) {
            while ($att->fetch()) {
                // Can't do delete() on the object directly since it won't remove all of it
                $other = clone($att);
                $other->delete();
            }
        }
    }

Evan Prodromou's avatar
Evan Prodromou committed
983 984
    // XXX: identical to Notice::getLocation.

985
    public function getLocation()
Evan Prodromou's avatar
Evan Prodromou committed
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
    {
        $location = null;

        if (!empty($this->location_id) && !empty($this->location_ns)) {
            $location = Location::fromId($this->location_id, $this->location_ns);
        }

        if (is_null($location)) { // no ID, or Location::fromId() failed
            if (!empty($this->lat) && !empty($this->lon)) {
                $location = Location::fromLatLon($this->lat, $this->lon);
            }
        }

        if (is_null($location)) { // still haven't found it!
            if (!empty($this->location)) {
                $location = Location::fromName($this->location);
            }
        }

        return $location;
    }
1007

1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    public function shareLocation()
    {
        $cfg = common_config('location', 'share');

        if ($cfg == 'always') {
            return true;
        } else if ($cfg == 'never') {
            return false;
        } else { // user
            $share = common_config('location', 'sharedefault');

            // Check if user has a personal setting for this
            $prefs = User_location_prefs::getKV('user_id', $this->id);

            if (!empty($prefs)) {
                $share = $prefs->share_location;
                $prefs->free();
            }

            return $share;
        }
    }

1031 1032
    function hasRole($name)
    {
Craig Andrews's avatar
Craig Andrews committed
1033 1034 1035 1036 1037 1038 1039 1040
        $has_role = false;
        if (Event::handle('StartHasRole', array($this, $name, &$has_role))) {
            $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
                                                'role' => $name));
            $has_role = !empty($role);
            Event::handle('EndHasRole', array($this, $name, $has_role));
        }
        return $has_role;
1041 1042 1043 1044
    }

    function grantRole($name)
    {
1045
        if (Event::handle('StartGrantRole', array($this, $name))) {
1046

1047
            $role = new Profile_role();
1048

1049 1050 1051
            $role->profile_id = $this->id;
            $role->role       = $name;
            $role->created    = common_sql_now();
1052

1053 1054 1055 1056 1057 1058
            $result = $role->insert();

            if (!$result) {
                throw new Exception("Can't save role '$name' for profile '{$this->id}'");
            }

1059 1060 1061 1062
            if ($name == 'owner') {
                User::blow('user:site_owner');
            }

1063
            Event::handle('EndGrantRole', array($this, $name));
1064 1065
        }

1066
        return $result;
1067 1068 1069 1070
    }

    function revokeRole($name)
    {