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

Profile.php 43.9 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
require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
Evan Prodromou's avatar
Evan Prodromou committed
26

27
class Profile extends Managed_DataObject
Evan Prodromou's avatar
Evan Prodromou committed
28 29 30 31 32 33
{
    ###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
34 35
    public $nickname;                        // varchar(64)  multiple_key not_null
    public $fullname;                        // varchar(255)  multiple_key
Evan Prodromou's avatar
Evan Prodromou committed
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 41 42 43
    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
44 45 46 47
    public $created;                         // datetime()   not_null
    public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP

    /* Static get */
48 49 50
    function staticGet($k,$v=NULL) {
        return Memcached_DataObject::staticGet('Profile',$k,$v);
    }
Evan Prodromou's avatar
Evan Prodromou committed
51

52 53
    public static function schemaDef()
    {
54
        $def = array(
55 56 57
            'description' => 'local and remote users have profiles',
            'fields' => array(
                'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
58 59
                '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'),
60
                'profileurl' => array('type' => 'varchar', 'length' => 255, 'description' => 'URL, cached so we dont regenerate'),
61 62 63
                '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'),
64 65 66 67 68 69 70 71 72 73 74
                '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'),
75
            )
76
        );
77 78 79 80 81 82 83 84

        // Add a fulltext index

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

        return $def;
85 86
    }

87 88 89 90 91
	function multiGet($keyCol, $keyVals, $skipNulls=true)
	{
	    return parent::multiGet('Profile', $keyCol, $keyVals, $skipNulls);
	}
	
Evan Prodromou's avatar
Evan Prodromou committed
92 93
    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE
Evan Prodromou's avatar
Evan Prodromou committed
94

95 96
    protected $_user = -1;  // Uninitialized value distinct from null

97 98
    function getUser()
    {
99
        if (is_int($this->_user) && $this->_user == -1) {
100 101 102 103
            $this->_user = User::staticGet('id', $this->id);
        }

        return $this->_user;
104 105
    }

106 107
    protected $_avatars;

108 109
    function getAvatar($width, $height=null)
    {
110 111 112
        if (is_null($height)) {
            $height = $width;
        }
113

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
        $avatar = $this->_getAvatar($width);

        if (empty($avatar)) {

            if (Event::handle('StartProfileGetAvatar', array($this, $width, &$avatar))) {
                $avatar = Avatar::pkeyGet(
                    array(
                        'profile_id' => $this->id,
                        'width'      => $width,
                        'height'     => $height
                    )
                );
                Event::handle('EndProfileGetAvatar', array($this, $width, &$avatar));
            }

            $this->_fillAvatar($width, $avatar);
        }

        return $avatar;
    }

    // XXX: @Fix me gargargar
    function _getAvatar($width)
    {
        if (empty($this->_avatars)) {
139 140 141
            $this->_avatars = array();
        }

142 143 144 145 146 147 148
        // GAR! I cannot figure out where _avatars gets pre-filled with the avatar from
        // the previously used profile! Please shoot me now! --Zach
        if (array_key_exists($width, $this->_avatars)) {
            // Don't return cached avatar unless it's really for this profile
            if ($this->_avatars[$width]->profile_id == $this->id) {
                return $this->_avatars[$width];
            }
149 150
        }

151 152 153 154 155 156 157 158
        return null;
    }

    function _fillAvatar($width, $avatar)
    {
      //common_debug("Storing avatar of width: {$avatar->width} and profile_id {$avatar->profile_id} in profile {$this->id}.");
        $this->_avatars[$width] = $avatar;

159 160
    }

161 162
    function getOriginalAvatar()
    {
163 164 165 166 167 168
        $avatar = DB_DataObject::factory('avatar');
        $avatar->profile_id = $this->id;
        $avatar->original = true;
        if ($avatar->find(true)) {
            return $avatar;
        } else {
Evan Prodromou's avatar
Evan Prodromou committed
169
            return null;
170 171 172
        }
    }

173
    function setOriginal($filename)
174
    {
175
        $imagefile = new ImageFile($this->id, Avatar::path($filename));
176 177 178

        $avatar = new Avatar();
        $avatar->profile_id = $this->id;
179 180 181
        $avatar->width = $imagefile->width;
        $avatar->height = $imagefile->height;
        $avatar->mediatype = image_type_to_mime_type($imagefile->type);
182 183
        $avatar->filename = $filename;
        $avatar->original = true;
184
        $avatar->url = Avatar::url($filename);
185 186
        $avatar->created = DB_DataObject_Cast::dateTime(); # current time

187
        // XXX: start a transaction here
188

189
        if (!$this->delete_avatars() || !$avatar->insert()) {
190
            @unlink(Avatar::path($filename));
Evan Prodromou's avatar
Evan Prodromou committed
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 200 201 202 203 204 205 206
                //$scaled = DB_DataObject::factory('avatar');
                $scaled = new Avatar();
                $scaled->profile_id = $this->id;
                $scaled->width = $size;
                $scaled->height = $size;
                $scaled->original = false;
                $scaled->mediatype = image_type_to_mime_type($imagefile->type);
                $scaled->filename = $scaled_filename;
207
                $scaled->url = Avatar::url($scaled_filename);
208 209 210
                $scaled->created = DB_DataObject_Cast::dateTime(); # current time

                if (!$scaled->insert()) {
Evan Prodromou's avatar
Evan Prodromou committed
211
                    return null;
212 213 214 215 216 217 218
                }
            }
        }

        return $avatar;
    }

219 220 221 222 223 224 225 226
    /**
     * Delete attached avatars for this user from the database and filesystem.
     * This should be used instead of a batch delete() to ensure that files
     * get removed correctly.
     *
     * @param boolean $original true to delete only the original-size file
     * @return <type>
     */
227
    function delete_avatars($original=true)
228 229 230 231 232 233 234 235 236 237 238 239 240 241
    {
        $avatar = new Avatar();
        $avatar->profile_id = $this->id;
        $avatar->find();
        while ($avatar->fetch()) {
            if ($avatar->original) {
                if ($original == false) {
                    continue;
                }
            }
            $avatar->delete();
        }
        return true;
    }
242

243 244 245 246 247
    /**
     * Gets either the full name (if filled) or the nickname.
     *
     * @return string
     */
248 249
    function getBestName()
    {
250 251
        return ($this->fullname) ? $this->fullname : $this->nickname;
    }
252

253 254 255 256 257 258 259 260 261
    /**
     * 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
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 265 266 267 268
        } else {
            return $this->nickname;
        }
    }

269 270 271 272 273 274
    /**
     * Get the most recent notice posted by this user, if any.
     *
     * @return mixed Notice or null
     */
    function getCurrentNotice()
275
    {
276 277 278
        $notice = $this->getNotices(0, 1);

        if ($notice->fetch()) {
279 280 281 282
            if ($notice instanceof ArrayWrapper) {
                // hack for things trying to work with single notices
                return $notice->_items[0];
            }
283
            return $notice;
284 285
        } else {
            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 304

    function isMember($group)
    {
305 306 307 308 309 310 311 312
    	$groups = $this->getGroups(0, null);
    	$gs = $groups->fetchAll();
    	foreach ($gs as $g) {
    	    if ($group->id == $g->id) {
    	        return true;
    	    }
    	}
    	return false;
313 314 315 316
    }

    function isAdmin($group)
    {
317 318 319
        $gm = Group_member::pkeyGet(array('profile_id' => $this->id,
                                          'group_id' => $group->id));
        return (!empty($gm) && $gm->is_admin);
320 321
    }

322 323 324 325 326 327 328
    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
329
    function getGroups($offset=0, $limit=PROFILES_PER_PAGE)
330
    {
Evan Prodromou's avatar
Evan Prodromou committed
331
        $ids = array();
332

Evan Prodromou's avatar
Evan Prodromou committed
333 334 335 336 337 338 339 340 341 342 343 344 345 346
        $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;
347 348
                }
            }
Evan Prodromou's avatar
Evan Prodromou committed
349 350

            self::cacheSet($keypart, implode(',', $ids));
351 352
        }

353 354 355 356
        if (!is_null($offset) && !is_null($limit)) {
            $ids = array_slice($ids, $offset, $limit);
        }

357
        return User_group::multiGet('id', $ids);
358 359
    }

Shashi Gowda's avatar
Shashi Gowda committed
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
    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;
    }

401
    function getLists($auth_user, $offset=0, $limit=null, $since_id=0, $max_id=0)
Shashi Gowda's avatar
Shashi Gowda committed
402
    {
403
        $ids = array();
Shashi Gowda's avatar
Shashi Gowda committed
404

405 406 407 408 409 410
        $keypart = sprintf('profile:lists:%d', $this->id);

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

        if ($idstr !== false) {
            $ids = explode(',', $idstr);
Shashi Gowda's avatar
Shashi Gowda committed
411
        } else {
412 413 414 415 416
            $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
417

418 419 420
            if ($since_id>0) {
               $list->whereAdd('id > '.$since_id);
            }
Shashi Gowda's avatar
Shashi Gowda committed
421

422 423 424
            if ($max_id>0) {
                $list->whereAdd('id <= '.$max_id);
            }
Shashi Gowda's avatar
Shashi Gowda committed
425

426 427 428
            if($offset>=0 && !is_null($limit)) {
                $list->limit($offset, $limit);
            }
Shashi Gowda's avatar
Shashi Gowda committed
429

430 431 432 433 434 435 436 437 438
            $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
439 440
        }

441 442 443
        $showPrivate = (($auth_user instanceof User ||
                            $auth_user instanceof Profile) &&
                        $auth_user->id === $this->id);
Shashi Gowda's avatar
Shashi Gowda committed
444

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
        $lists = array();

        foreach ($ids as $id) {
            $list = Profile_list::staticGet('id', $id);
            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
461 462
    }

463 464 465 466 467 468 469 470 471 472 473 474
    /**
     * 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
475 476
    function getOtherTags($auth_user=null, $offset=0, $limit=null, $since_id=0, $max_id=0)
    {
477
        $list = new Profile_list();
Shashi Gowda's avatar
Shashi Gowda committed
478

479 480 481 482 483 484
        $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);
485

Shashi Gowda's avatar
Shashi Gowda committed
486 487

        if ($auth_user instanceof User || $auth_user instanceof Profile) {
488 489 490 491
            $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
492
        } else {
493
            $qry .= 'AND profile_list.private = 0 ';
Shashi Gowda's avatar
Shashi Gowda committed
494 495
        }

496 497
        if ($since_id > 0) {
            $qry .= sprintf('AND (cursor > %d) ', $since_id);
Shashi Gowda's avatar
Shashi Gowda committed
498 499
        }

500 501
        if ($max_id > 0) {
            $qry .= sprintf('AND (cursor < %d) ', $max_id);
Shashi Gowda's avatar
Shashi Gowda committed
502 503
        }

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

506 507 508
        if ($offset >= 0 && !is_null($limit)) {
            $qry .= sprintf('LIMIT %d OFFSET %d ', $limit, $offset);
        }
Shashi Gowda's avatar
Shashi Gowda committed
509

510 511
        $list->query($qry);
        return $list;
Shashi Gowda's avatar
Shashi Gowda committed
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    }

    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();

557 558
        $lists->joinAdd('id', 'profile_tag_subscription:profile_tag_id');

Shashi Gowda's avatar
Shashi Gowda committed
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
        #@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;
    }

582 583 584 585 586
    /**
     * Request to join the given group.
     * May throw exceptions on failure.
     *
     * @param User_group $group
587
     * @return mixed: Group_member on success, Group_join_queue if pending approval, null on some cancels?
588 589 590
     */
    function joinGroup(User_group $group)
    {
591
        $join = null;
592
        if ($group->join_policy == User_group::JOIN_POLICY_MODERATE) {
593
            $join = Group_join_queue::saveNew($this, $group);
594 595
        } else {
            if (Event::handle('StartJoinGroup', array($group, $this))) {
596
                $join = Group_member::join($group->id, $this->id);
Evan Prodromou's avatar
Evan Prodromou committed
597
                self::blow('profile:groups:%d', $this->id);
598 599
                Event::handle('EndJoinGroup', array($group, $this));
            }
600
        }
601 602 603
        if ($join) {
            // Send any applicable notifications...
            $join->notify();
604
        }
605
        return $join;
606 607
    }

608 609 610
    /**
     * Leave a group that this profile is a member of.
     *
611
     * @param User_group $group
612 613 614
     */
    function leaveGroup(User_group $group)
    {
615 616
        if (Event::handle('StartLeaveGroup', array($group, $this))) {
            Group_member::leave($group->id, $this->id);
Evan Prodromou's avatar
Evan Prodromou committed
617
            self::blow('profile:groups:%d', $this->id);
618
            Event::handle('EndLeaveGroup', array($group, $this));
619 620 621
        }
    }

622 623 624 625 626 627 628 629 630
    function avatarUrl($size=AVATAR_PROFILE_SIZE)
    {
        $avatar = $this->getAvatar($size);
        if ($avatar) {
            return $avatar->displayUrl();
        } else {
            return Avatar::defaultImage($size);
        }
    }
631 632 633

    function getSubscriptions($offset=0, $limit=null)
    {
Evan Prodromou's avatar
Evan Prodromou committed
634 635 636
        $subs = Subscription::bySubscriber($this->id,
                                           $offset,
                                           $limit);
637

Evan Prodromou's avatar
Evan Prodromou committed
638
        $profiles = array();
639

Evan Prodromou's avatar
Evan Prodromou committed
640
        while ($subs->fetch()) {
641 642 643 644
            $profile = Profile::staticGet($subs->subscribed);
            if ($profile) {
                $profiles[] = $profile;
            }
Evan Prodromou's avatar
Evan Prodromou committed
645
        }
646

Evan Prodromou's avatar
Evan Prodromou committed
647
        return new ArrayWrapper($profiles);
648 649 650 651
    }

    function getSubscribers($offset=0, $limit=null)
    {
Evan Prodromou's avatar
Evan Prodromou committed
652 653 654
        $subs = Subscription::bySubscribed($this->id,
                                           $offset,
                                           $limit);
655

Evan Prodromou's avatar
Evan Prodromou committed
656
        $profiles = array();
657

Evan Prodromou's avatar
Evan Prodromou committed
658
        while ($subs->fetch()) {
659 660 661 662
            $profile = Profile::staticGet($subs->subscriber);
            if ($profile) {
                $profiles[] = $profile;
            }
663 664
        }

Evan Prodromou's avatar
Evan Prodromou committed
665
        return new ArrayWrapper($profiles);
666 667
    }

Shashi Gowda's avatar
Shashi Gowda committed
668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
    function getTaggedSubscribers($tag)
    {
        $qry =
          'SELECT profile.* ' .
          'FROM profile JOIN (subscription, profile_tag, profile_list) ' .
          'ON profile.id = subscription.subscriber ' .
          'AND profile.id = profile_tag.tagged ' .
          'AND profile_tag.tagger = profile_list.tagger AND profile_tag.tag = profile_list.tag ' .
          'WHERE subscription.subscribed = %d ' .
          'AND subscription.subscribed != subscription.subscriber ' .
          'AND profile_tag.tagger = %d AND profile_tag.tag = "%s" ' .
          'AND profile_list.private = false ' .
          'ORDER BY subscription.created DESC';

        $profile = new Profile();
        $tagged = array();

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

        while ($profile->fetch()) {
            $tagged[] = clone($profile);
        }
        return $tagged;
    }

Brion Vibber's avatar
Brion Vibber committed
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722
    /**
     * 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;
    }

723 724
    function subscriptionCount()
    {
725
        $c = Cache::instance();
726 727

        if (!empty($c)) {
728
            $cnt = $c->get(Cache::key('profile:subscription_count:'.$this->id));
729 730 731 732 733 734 735 736 737 738 739 740 741
            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)) {
742
            $c->set(Cache::key('profile:subscription_count:'.$this->id), $cnt);
743 744 745 746 747 748 749
        }

        return $cnt;
    }

    function subscriberCount()
    {
750
        $c = Cache::instance();
751
        if (!empty($c)) {
752
            $cnt = $c->get(Cache::key('profile:subscriber_count:'.$this->id));
753 754 755 756 757 758 759
            if (is_integer($cnt)) {
                return (int) $cnt;
            }
        }

        $sub = new Subscription();
        $sub->subscribed = $this->id;
760
        $sub->whereAdd('subscriber != subscribed');
761 762 763
        $cnt = (int) $sub->count('distinct subscriber');

        if (!empty($c)) {
764
            $c->set(Cache::key('profile:subscriber_count:'.$this->id), $cnt);
765 766 767 768 769
        }

        return $cnt;
    }

770 771 772 773 774 775 776 777 778 779 780
    /**
     * Is this profile subscribed to another profile?
     *
     * @param Profile $other
     * @return boolean
     */
    function isSubscribed($other)
    {
        return Subscription::exists($this, $other);
    }

781 782 783 784 785 786 787 788 789 790
    /**
     * Check if a pending subscription request is outstanding for this...
     *
     * @param Profile $other
     * @return boolean
     */
    function hasPendingSubscription($other)
    {
        return Subscription_queue::exists($this, $other);
    }
791 792 793 794 795 796 797 798 799 800 801 802 803

    /**
     * Are these two profiles subscribed to each other?
     *
     * @param Profile $other
     * @return boolean
     */
    function mutuallySubscribed($other)
    {
        return $this->isSubscribed($other) &&
          $other->isSubscribed($this);
    }

Zach Copley's avatar
Zach Copley committed
804 805 806 807 808 809 810
    function hasFave($notice)
    {
        $fave = Fave::pkeyGet(array('user_id' => $this->id,
                                    'notice_id' => $notice->id));
        return ((is_null($fave)) ? false : true);
    }

811 812
    function faveCount()
    {
813
        $c = Cache::instance();
814
        if (!empty($c)) {
815
            $cnt = $c->get(Cache::key('profile:fave_count:'.$this->id));
816 817 818 819 820 821 822
            if (is_integer($cnt)) {
                return (int) $cnt;
            }
        }

        $faves = new Fave();
        $faves->user_id = $this->id;
823
        $cnt = (int) $faves->count('notice_id');
824 825

        if (!empty($c)) {
826
            $c->set(Cache::key('profile:fave_count:'.$this->id), $cnt);
827 828 829 830 831 832 833
        }

        return $cnt;
    }

    function noticeCount()
    {
834
        $c = Cache::instance();
835 836

        if (!empty($c)) {
837
            $cnt = $c->get(Cache::key('profile:notice_count:'.$this->id));
838 839 840 841 842 843 844 845 846 847
            if (is_integer($cnt)) {
                return (int) $cnt;
            }
        }

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

        if (!empty($c)) {
848
            $c->set(Cache::key('profile:notice_count:'.$this->id), $cnt);
849 850 851 852 853
        }

        return $cnt;
    }

Zach Copley's avatar
Zach Copley committed
854 855
    function blowFavesCache()
    {
856
        $cache = Cache::instance();
Zach Copley's avatar
Zach Copley committed
857 858 859
        if ($cache) {
            // Faves don't happen chronologically, so we need to blow
            // ;last cache, too
860 861 862 863
            $cache->delete(Cache::key('fave:ids_by_user:'.$this->id));
            $cache->delete(Cache::key('fave:ids_by_user:'.$this->id.';last'));
            $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id));
            $cache->delete(Cache::key('fave:ids_by_user_own:'.$this->id.';last'));
Zach Copley's avatar
Zach Copley committed
864 865 866 867
        }
        $this->blowFaveCount();
    }

868 869
    function blowSubscriberCount()
    {
870
        $c = Cache::instance();
871
        if (!empty($c)) {
872
            $c->delete(Cache::key('profile:subscriber_count:'.$this->id));
873 874 875 876 877
        }
    }

    function blowSubscriptionCount()
    {
878
        $c = Cache::instance();
879
        if (!empty($c)) {
880
            $c->delete(Cache::key('profile:subscription_count:'.$this->id));
881 882 883 884 885
        }
    }

    function blowFaveCount()
    {
886
        $c = Cache::instance();
887
        if (!empty($c)) {
888
            $c->delete(Cache::key('profile:fave_count:'.$this->id));
889 890 891 892 893
        }
    }

    function blowNoticeCount()
    {
894
        $c = Cache::instance();
895
        if (!empty($c)) {
896
            $c->delete(Cache::key('profile:notice_count:'.$this->id));
897 898
        }
    }
899 900 901

    static function maxBio()
    {
902
        $biolimit = common_config('profile', 'biolimit');
903 904 905 906 907 908 909 910 911 912 913 914
        // 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));
    }
915

916 917 918 919 920 921 922
    function delete()
    {
        $this->_deleteNotices();
        $this->_deleteSubscriptions();
        $this->_deleteMessages();
        $this->_deleteTags();
        $this->_deleteBlocks();
923
        $this->delete_avatars();
924

925 926 927
        // Warning: delete() will run on the batch objects,
        // not on individual objects.
        $related = array('Reply',
928 929
                         'Group_member',
                         );
930
        Event::handle('ProfileDeleteRelated', array($this, &$related));
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957

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

        parent::delete();
    }

    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;
958 959 960 961 962 963 964 965 966 967 968 969 970

        $sub->find();

        while ($sub->fetch()) {
            $other = Profile::staticGet('id', $sub->subscribed);
            if (empty($other)) {
                continue;
            }
            if ($other->id == $this->id) {
                continue;
            }
            Subscription::cancel($this, $other);
        }
971 972 973

        $subd = new Subscription();
        $subd->subscribed = $this->id;
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
        $subd->find();

        while ($subd->fetch()) {
            $other = Profile::staticGet('id', $subd->subscriber);
            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();
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    }

    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;
1010
        $tag->delete();
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
    }

    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
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047

    // XXX: identical to Notice::getLocation.

    function getLocation()
    {
        $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;
    }
1048 1049 1050

    function hasRole($name)
    {
Craig Andrews's avatar
Craig Andrews committed
1051 1052 1053 1054 1055 1056 1057 1058
        $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;
1059 1060 1061 1062
    }

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

1065
            $role = new Profile_role();
1066

1067 1068 1069
            $role->profile_id = $this->id;
            $role->role       = $name;
            $role->created    = common_sql_now();
1070

1071 1072 1073 1074 1075 1076
            $result = $role->insert();

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

1077 1078 1079 1080
            if ($name == 'owner') {
                User::blow('user:site_owner');
            }

1081
            Event::handle('EndGrantRole', array($this, $name));
1082 1083
        }

1084
        return $result;
1085 1086 1087 1088
    }

    function revokeRole($name)
    {
1089
        if (Event::handle('StartRevokeRole', array($this, $name))) {
1090

1091 1092
            $role = Profile_role::pkeyGet(array('profile_id' => $this->id,
                                                'role' => $name));
1093

1094 1095 1096 1097 1098
            if (empty($role)) {
                // TRANS: Exception thrown when trying to revoke an existing role for a user that does not exist.
                // TRANS: %1$s is the role name, %2$s is the user ID (number).
                throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; does not exist.'),$name, $this->id));
            }
1099

1100
            $result = $role->delete();
1101

1102 1103 1104 1105 1106 1107 1108
            if (!$result) {
                common_log_db_error($role, 'DELETE', __FILE__);
                // TRANS: Exception thrown when trying to revoke a role for a user with a failing database query.
                // TRANS: %1$s is the role name, %2$s is the user ID (number).
                throw new Exception(sprintf(_('Cannot revoke role "%1$s" for user #%2$d; database error.'),$name, $this->id));
            }

1109 1110 1111 1112
            if ($name == 'owner') {
                User::blow('user:site_owner');
            }

1113 1114 1115 1116
            Event::handle('EndRevokeRole', array($this, $name));

            return true;
        }
1117 1118 1119 1120
    }

    function isSandboxed()
    {
1121
        return $this->hasRole(Profile_role::SANDBOXED);
1122 1123 1124 1125
    }

    function isSilenced()
    {
1126
        return $this->hasRole(Profile_role::SILENCED);
1127 1128 1129 1130
    }

    function sandbox()
    {
1131
        $this->grantRole(Profile_role::SANDBOXED);
1132 1133 1134 1135
    }

    function unsandbox()
    {
1136
        $this->revokeRole(Profile_role::SANDBOXED);
1137 1138 1139 1140
    }

    function silence()
    {
1141
        $this->grantRole(Profile_role::SILENCED);
1142 1143 1144
        if (common_config('notice', 'hidespam')) {
            $this->flushVisibility();
        }
1145 1146 1147 1148
    }

    function unsilence()
    {
1149
        $this->revokeRole(Profile_role::SILENCED);
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
        if (common_config('notice', 'hidespam')) {
            $this->flushVisibility();
        }
    }

    function flushVisibility()
    {
        // Get all notices
        $stream = new ProfileNoticeStream($this, $this);
        $ids = $stream<