User_group.php 27.7 KB
Newer Older
1 2 3 4 5
<?php
/**
 * Table Definition for user_group
 */

6
class User_group extends Managed_DataObject
7
{
8 9
    const JOIN_POLICY_OPEN = 0;
    const JOIN_POLICY_MODERATE = 1;
10
    const CACHE_WINDOW = 201;
11

12 13 14 15 16
    ###START_AUTOCODE
    /* the code below is auto generated do not remove the above tag */

    public $__table = 'user_group';                      // table name
    public $id;                              // int(4)  primary_key not_null
17
    public $profile_id;                      // int(4)  primary_key not_null
18
    public $nickname;                        // varchar(64)
19 20
    public $fullname;                        // varchar(191)   not 255 because utf8mb4 takes more space
    public $homepage;                        // varchar(191)   not 255 because utf8mb4 takes more space
21
    public $description;                     // text
22 23 24 25 26
    public $location;                        // varchar(191)   not 255 because utf8mb4 takes more space
    public $original_logo;                   // varchar(191)   not 255 because utf8mb4 takes more space
    public $homepage_logo;                   // varchar(191)   not 255 because utf8mb4 takes more space
    public $stream_logo;                     // varchar(191)   not 255 because utf8mb4 takes more space
    public $mini_logo;                       // varchar(191)   not 255 because utf8mb4 takes more space
27 28
    public $created;                         // datetime   not_null default_0000-00-00%2000%3A00%3A00
    public $modified;                        // timestamp   not_null default_CURRENT_TIMESTAMP
29 30
    public $uri;                             // varchar(191)  unique_key   not 255 because utf8mb4 takes more space
    public $mainpage;                        // varchar(191)   not 255 because utf8mb4 takes more space
31
    public $join_policy;                     // tinyint
32
    public $force_scope;                     // tinyint
33 34 35

    /* the code above is auto generated do not remove the tag below */
    ###END_AUTOCODE
36

chimo's avatar
chimo committed
37 38 39 40 41 42
    public function getObjectType()
    {
        return ActivityObject::GROUP;
    }


43 44 45 46 47
    public static function schemaDef()
    {
        return array(
            'fields' => array(
                'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
48
                'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
49 50

                'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname for addressing'),
51 52
                'fullname' => array('type' => 'varchar', 'length' => 191, 'description' => 'display name'),
                'homepage' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL, cached so we dont regenerate'),
53
                'description' => array('type' => 'text', 'description' => 'group description'),
54
                'location' => array('type' => 'varchar', 'length' => 191, 'description' => 'related physical location, if any'),
55

56 57 58 59
                'original_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'original size logo'),
                'homepage_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'homepage (profile) size logo'),
                'stream_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'stream-sized logo'),
                'mini_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'mini logo'),
60 61 62 63

                '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'),

64 65
                'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universal identifier'),
                'mainpage' => array('type' => 'varchar', 'length' => 191, 'description' => 'page for group info to link to'),
66 67 68 69 70 71
                'join_policy' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=open; 1=requires admin approval'),      
                'force_scope' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=never,1=sometimes,-1=always'),
            ),
            'primary key' => array('id'),
            'unique keys' => array(
                'user_group_uri_key' => array('uri'),
72
// when it's safe and everyone's run upgrade.php                'user_profile_id_key' => array('profile_id'),
73
            ),
74 75 76
            'foreign keys' => array(
                'user_group_id_fkey' => array('profile', array('profile_id' => 'id')),
            ),
77 78
            'indexes' => array(
                'user_group_nickname_idx' => array('nickname'),
79
                'user_group_profile_id_idx' => array('profile_id'), //make this unique in future
80 81 82 83
            ),
        );
    }

84
    protected $_profile = array();
85 86 87 88

    /**
     * @return Profile
     *
89
     * @throws GroupNoProfileException if user has no profile
90 91 92
     */
    public function getProfile()
    {
93
        if (!isset($this->_profile[$this->profile_id])) {
94 95 96 97 98
            $profile = Profile::getKV('id', $this->profile_id);
            if (!$profile instanceof Profile) {
                throw new GroupNoProfileException($this);
            }
            $this->_profile[$this->profile_id] = $profile;
99
        }
100 101
        return $this->_profile[$this->profile_id];
    }
102

103 104 105 106 107
    public function getNickname()
    {
        return $this->getProfile()->getNickname();
    }

mmn's avatar
mmn committed
108
    public static function defaultLogo($size)
109
    {
110 111 112
        static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
                                  AVATAR_STREAM_SIZE => 'stream',
                                  AVATAR_MINI_SIZE => 'mini');
113
        return Theme::path('default-avatar-'.$sizenames[$size].'.png');
114 115
    }

116 117
    function homeUrl()
    {
mmn's avatar
mmn committed
118
        return $this->getProfile()->getUrl();
119 120
    }

121 122 123 124 125 126
    function getUri()
    {
        $uri = null;
        if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
            if (!empty($this->uri)) {
                $uri = $this->uri;
127
            } elseif ($this->isLocal()) {
128 129 130 131 132 133 134 135
                $uri = common_local_url('groupbyid',
                                        array('id' => $this->id));
            }
        }
        Event::handle('EndUserGroupGetUri', array($this, &$uri));
        return $uri;
    }

136 137
    function permalink()
    {
138 139
        $url = null;
        if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
140 141 142 143
            if ($this->isLocal()) {
                $url = common_local_url('groupbyid',
                                        array('id' => $this->id));
            }
144 145 146
        }
        Event::handle('EndUserGroupPermalink', array($this, &$url));
        return $url;
147 148
    }

149
    function getNotices($offset, $limit, $since_id=null, $max_id=null)
150
    {
151
        $stream = new GroupNoticeStream($this);
152

153
        return $stream->getNotices($offset, $limit, $since_id, $max_id);
154 155
    }

156
    function getMembers($offset=0, $limit=null) {
157
        $ids = null;
158
        if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
159 160
            $ids = $this->getMemberIDs($offset,
                                       $limit);
161
        } else {
Evan Prodromou's avatar
Evan Prodromou committed
162
            $key = sprintf('group:member_ids:%d', $this->id);
163 164
            $window = self::cacheGet($key);
            if ($window === false) {
165 166
                $window = $this->getMemberIDs(0,
                                              User_group::CACHE_WINDOW);
167 168
                self::cacheSet($key, $window);
            }
169 170 171 172

            $ids = array_slice($window,
                               $offset,
                               $limit);
173
        }
174 175

        return Profile::multiGet('id', $ids);
176 177
    }

178
    function getMemberIDs($offset=0, $limit=null)
179
    {
180
        $gm = new Group_member();
181

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
        $gm->selectAdd();
        $gm->selectAdd('profile_id');

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

        $gm->orderBy('created DESC');

        if (!is_null($limit)) {
            $gm->limit($offset, $limit);
        }

        $ids = array();

        if ($gm->find()) {
            while ($gm->fetch()) {
                $ids[] = $gm->profile_id;
198
            }
199 200
        }

201
        return $ids;
202
    }
Evan Prodromou's avatar
Evan Prodromou committed
203

204 205 206 207 208 209 210 211 212
    /**
     * Get pending members, who have not yet been approved.
     *
     * @param int $offset
     * @param int $limit
     * @return Profile
     */
    function getRequests($offset=0, $limit=null)
    {
chimo's avatar
chimo committed
213 214 215 216 217 218
        $rq = new Group_join_queue();
        $rq->group_id = $this->id;

        $members = new Profile();

        $members->joinAdd(['id', $rq, 'profile_id']);
219 220

        if ($limit != null) {
chimo's avatar
chimo committed
221
            $members->limit($offset, $limit);
222 223
        }

chimo's avatar
chimo committed
224
        $members->find();
225 226 227 228

        return $members;
    }

229 230
    public function getAdminCount()
    {
mmn's avatar
mmn committed
231 232 233 234 235
        $block = new Group_member();
        $block->group_id = $this->id;
        $block->is_admin = 1;

        return $block->count();
236 237 238
    }

    public function getMemberCount()
239
    {
240
        $key = sprintf("group:member_count:%d", $this->id);
241

242
        $cnt = self::cacheGet($key);
243

244 245
        if (is_integer($cnt)) {
            return (int) $cnt;
246 247
        }

248 249 250 251 252 253 254 255 256 257
        $mem = new Group_member();
        $mem->group_id = $this->id;

        // XXX: why 'distinct'?

        $cnt = (int) $mem->count('distinct profile_id');

        self::cacheSet($key, $cnt);

        return $cnt;
258 259
    }

260 261 262 263 264 265 266 267 268 269
    function getBlockedCount()
    {
        // XXX: WORM cache this

        $block = new Group_block();
        $block->group_id = $this->id;

        return $block->count();
    }

270 271 272 273 274 275 276 277 278 279
    function getQueueCount()
    {
        // XXX: WORM cache this

        $queue = new Group_join_queue();
        $queue->group_id = $this->id;

        return $queue->count();
    }

mmn's avatar
mmn committed
280
    function getAdmins($offset=null, $limit=null)   // offset is null because DataObject wants it, 0 would mean no results
281 282
    {
        $admins = new Profile();
mmn's avatar
mmn committed
283 284 285 286 287
        $admins->joinAdd(array('id', 'group_member:profile_id'));
        $admins->whereAdd(sprintf('group_member.group_id = %u AND group_member.is_admin = 1', $this->id));
        $admins->orderBy('group_member.modified ASC');
        $admins->limit($offset, $limit);
        $admins->find();
288 289 290 291

        return $admins;
    }

mmn's avatar
mmn committed
292
    function getBlocked($offset=null, $limit=null)   // offset is null because DataObject wants it, 0 would mean no results
293 294
    {
        $blocked = new Profile();
mmn's avatar
mmn committed
295 296 297 298 299
        $blocked->joinAdd(array('id', 'group_block:blocked'));
        $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
        $blocked->orderBy('group_block.modified DESC');
        $blocked->limit($offset, $limit);
        $blocked->find();
300 301 302 303

        return $blocked;
    }

304
    function setOriginal($filename)
Evan Prodromou's avatar
Evan Prodromou committed
305
    {
306
        // This should be handled by the Profile->setOriginal function so user and group avatars are handled the same
307
        $imagefile = new ImageFile(null, Avatar::path($filename));
308

309 310 311 312
        $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
                       'stream_logo' => AVATAR_STREAM_SIZE,
                       'mini_logo' => AVATAR_MINI_SIZE);

Evan Prodromou's avatar
Evan Prodromou committed
313
        $orig = clone($this);
314
        $this->original_logo = Avatar::url($filename);
315 316 317 318 319 320
        foreach ($sizes as $name=>$size) {
            $filename = Avatar::filename($this->profile_id, image_type_to_extension($imagefile->preferredType()),
                                         $size, common_timestamp());
            $imagefile->resizeTo(Avatar::path($filename), array('width'=>$size, 'height'=>$size));
            $this->$name = Avatar::url($filename);
        }
Evan Prodromou's avatar
Evan Prodromou committed
321 322 323
        common_debug(common_log_objstring($this));
        return $this->update($orig);
    }
324 325 326 327 328

    function getBestName()
    {
        return ($this->fullname) ? $this->fullname : $this->nickname;
    }
329

330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    /**
     * 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) {
            // TRANS: Full name of a profile or group followed by nickname in parens
            return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
        } else {
            return $this->nickname;
        }
    }

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
    function getAliases()
    {
        $aliases = array();

        // XXX: cache this

        $alias = new Group_alias();

        $alias->group_id = $this->id;

        if ($alias->find()) {
            while ($alias->fetch()) {
                $aliases[] = $alias->alias;
            }
        }

        $alias->free();

        return $aliases;
    }

    function setAliases($newaliases) {

        $newaliases = array_unique($newaliases);

        $oldaliases = $this->getAliases();

373
        // Delete stuff that's old that not in new
374 375 376

        $to_delete = array_diff($oldaliases, $newaliases);

377
        // Insert stuff that's in new and not in old
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

        $to_insert = array_diff($newaliases, $oldaliases);

        $alias = new Group_alias();

        $alias->group_id = $this->id;

        foreach ($to_delete as $delalias) {
            $alias->alias = $delalias;
            $result = $alias->delete();
            if (!$result) {
                common_log_db_error($alias, 'DELETE', __FILE__);
                return false;
            }
        }

        foreach ($to_insert as $insalias) {
395 396 397 398
            if ($insalias === $this->nickname) {
                continue;
            }
            $alias->alias = Nickname::normalize($insalias, true);
399 400 401 402 403 404 405 406 407
            $result = $alias->insert();
            if (!$result) {
                common_log_db_error($alias, 'INSERT', __FILE__);
                return false;
            }
        }

        return true;
    }
408

409
    static function getForNickname($nickname, Profile $profile=null)
410
    {
411
        $nickname = Nickname::normalize($nickname);
412 413

        // Are there any matching remote groups this profile's in?
414
        if ($profile instanceof Profile) {
415
            $group = $profile->getGroups(0, null);
416
            while ($group instanceof User_group && $group->fetch()) {
417 418 419 420 421 422 423 424
                if ($group->nickname == $nickname) {
                    // @fixme is this the best way?
                    return clone($group);
                }
            }
        }

        // If not, check local groups.
425
        $group = Local_group::getKV('nickname', $nickname);
426
        if ($group instanceof Local_group) {
427
            return User_group::getKV('id', $group->group_id);
428
        }
429
        $alias = Group_alias::getKV('alias', $nickname);
430
        if ($alias instanceof Group_alias) {
431
            return User_group::getKV('id', $alias->group_id);
432 433 434
        }
        return null;
    }
Zach Copley's avatar
Zach Copley committed
435

436 437 438 439 440
    function getUserMembers()
    {
        // XXX: cache this

        $user = new User();
441 442 443
        if(common_config('db','quote_identifiers'))
            $user_table = '"user"';
        else $user_table = 'user';
444 445 446

        $qry =
          'SELECT id ' .
447 448
          'FROM '. $user_table .' JOIN group_member '.
          'ON '. $user_table .'.id = group_member.profile_id ' .
449 450 451 452 453 454 455 456 457 458 459 460 461 462
          'WHERE group_member.group_id = %d ';

        $user->query(sprintf($qry, $this->id));

        $ids = array();

        while ($user->fetch()) {
            $ids[] = $user->id;
        }

        $user->free();

        return $ids;
    }
463 464 465 466

    static function maxDescription()
    {
        $desclimit = common_config('group', 'desclimit');
467 468
        // null => use global limit (distinct from 0!)
        if (is_null($desclimit)) {
469 470 471 472 473 474 475 476
            $desclimit = common_config('site', 'textlimit');
        }
        return $desclimit;
    }

    static function descriptionTooLong($desc)
    {
        $desclimit = self::maxDescription();
477
        return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
478
    }
479

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
    function asAtomEntry($namespace=false, $source=false)
    {
        $xs = new XMLStringer(true);

        if ($namespace) {
            $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
                           'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
        } else {
            $attrs = array();
        }

        $xs->elementStart('entry', $attrs);

        if ($source) {
            $xs->elementStart('source');
495
            $xs->element('id', null, $this->permalink());
496 497
            $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
            $xs->element('link', array('href' => $this->permalink()));
498
            $xs->element('updated', null, $this->modified);
499 500 501 502
            $xs->elementEnd('source');
        }

        $xs->element('title', null, $this->nickname);
503
        $xs->element('summary', null, common_xml_safe_str($this->description));
504 505 506 507 508 509 510 511 512

        $xs->element('link', array('rel' => 'alternate',
                                   'href' => $this->permalink()));

        $xs->element('id', null, $this->permalink());

        $xs->element('published', null, common_date_w3dtf($this->created));
        $xs->element('updated', null, common_date_w3dtf($this->modified));

513 514 515 516 517
        $xs->element(
            'content',
            array('type' => 'html'),
            common_xml_safe_str($this->description)
        );
518 519 520 521 522

        $xs->elementEnd('entry');

        return $xs->getString();
    }
523

524 525 526 527 528 529 530 531 532 533 534 535
    function asAtomAuthor()
    {
        $xs = new XMLStringer(true);

        $xs->elementStart('author');
        $xs->element('name', null, $this->nickname);
        $xs->element('uri', null, $this->permalink());
        $xs->elementEnd('author');

        return $xs->getString();
    }

536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
    /**
     * Returns an XML string fragment with group information as an
     * Activity Streams noun object with the given element type.
     *
     * Assumes that 'activity', 'georss', and 'poco' namespace has been
     * previously defined.
     *
     * @param string $element one of 'actor', 'subject', 'object', 'target'
     *
     * @return string
     */
    function asActivityNoun($element)
    {
        $noun = ActivityObject::fromGroup($this);
        return $noun->asString('activity:' . $element);
    }
552

553 554 555 556 557
    function getAvatar()
    {
        return empty($this->homepage_logo)
            ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
            : $this->homepage_logo;
558 559
    }

560
    static function register($fields) {
561
        if (!empty($fields['userid'])) {
562
            $profile = Profile::getKV('id', $fields['userid']);
563 564 565 566 567 568 569 570
            if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
                common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);

                // TRANS: Client exception thrown when a user tries to create a group while banned.
                throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
            }
        }

571 572
        $fields['nickname'] = Nickname::normalize($fields['nickname']);

573
        // MAGICALLY put fields into current scope
574
        // @fixme kill extract(); it makes debugging absurdly hard
575

576 577 578 579 580 581 582 583 584 585 586 587
		$defaults = array('nickname' => null,
						  'fullname' => null,
						  'homepage' => null,
						  'description' => null,
						  'location' => null,
						  'uri' => null,
						  'mainpage' => null,
						  'aliases' => array(),
						  'userid' => null);
		
		$fields = array_merge($defaults, $fields);
		
588 589 590 591
        extract($fields);

        $group = new User_group();

592 593 594 595
        if (empty($uri)) {
            // fill in later...
            $uri = null;
        }
596 597 598
        if (empty($mainpage)) {
            $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
        }
599

600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
        // We must create a new, incrementally assigned profile_id
        $profile = new Profile();
        $profile->nickname   = $nickname;
        $profile->fullname   = $fullname;
        $profile->profileurl = $mainpage;
        $profile->homepage   = $homepage;
        $profile->bio        = $description;
        $profile->location   = $location;
        $profile->created    = common_sql_now();

        $group->nickname    = $profile->nickname;
        $group->fullname    = $profile->fullname;
        $group->homepage    = $profile->homepage;
        $group->description = $profile->bio;
        $group->location    = $profile->location;
        $group->mainpage    = $profile->profileurl;
        $group->created     = $profile->created;

        $profile->query('BEGIN');
        $id = $profile->insert();
620
        if ($id === false) {
621 622 623 624 625 626
            $profile->query('ROLLBACK');
            throw new ServerException(_('Profile insertion failed'));
        }

        $group->profile_id = $id;
        $group->uri        = $uri;
627

628 629 630 631 632
        if (isset($fields['join_policy'])) {
            $group->join_policy = intval($fields['join_policy']);
        } else {
            $group->join_policy = 0;
        }
633

634 635 636 637 638 639
        if (isset($fields['force_scope'])) {
            $group->force_scope = intval($fields['force_scope']);
        } else {
            $group->force_scope = 0;
        }

Evan Prodromou's avatar
Evan Prodromou committed
640
        if (Event::handle('StartGroupSave', array(&$group))) {
641

Evan Prodromou's avatar
Evan Prodromou committed
642
            $result = $group->insert();
643

644
            if ($result === false) {
Evan Prodromou's avatar
Evan Prodromou committed
645 646 647
                common_log_db_error($group, 'INSERT', __FILE__);
                // TRANS: Server exception thrown when creating a group failed.
                throw new ServerException(_('Could not create group.'));
648 649
            }

Evan Prodromou's avatar
Evan Prodromou committed
650 651 652 653 654 655 656 657 658 659
            if (!isset($uri) || empty($uri)) {
                $orig = clone($group);
                $group->uri = common_local_url('groupbyid', array('id' => $group->id));
                $result = $group->update($orig);
                if (!$result) {
                    common_log_db_error($group, 'UPDATE', __FILE__);
                    // TRANS: Server exception thrown when updating a group URI failed.
                    throw new ServerException(_('Could not set group URI.'));
                }
            }
660

Evan Prodromou's avatar
Evan Prodromou committed
661
            $result = $group->setAliases($aliases);
662

Evan Prodromou's avatar
Evan Prodromou committed
663 664 665 666
            if (!$result) {
                // TRANS: Server exception thrown when creating group aliases failed.
                throw new ServerException(_('Could not create aliases.'));
            }
667

Evan Prodromou's avatar
Evan Prodromou committed
668
            $member = new Group_member();
669

Evan Prodromou's avatar
Evan Prodromou committed
670 671 672 673
            $member->group_id   = $group->id;
            $member->profile_id = $userid;
            $member->is_admin   = 1;
            $member->created    = $group->created;
674

Evan Prodromou's avatar
Evan Prodromou committed
675
            $result = $member->insert();
676

Evan Prodromou's avatar
Evan Prodromou committed
677 678 679 680 681
            if (!$result) {
                common_log_db_error($member, 'INSERT', __FILE__);
                // TRANS: Server exception thrown when setting group membership failed.
                throw new ServerException(_('Could not set group membership.'));
            }
682

683 684
            self::blow('profile:groups:%d', $userid);
            
Evan Prodromou's avatar
Evan Prodromou committed
685 686
            if ($local) {
                $local_group = new Local_group();
687

Evan Prodromou's avatar
Evan Prodromou committed
688 689 690
                $local_group->group_id = $group->id;
                $local_group->nickname = $nickname;
                $local_group->created  = common_sql_now();
691

Evan Prodromou's avatar
Evan Prodromou committed
692 693 694 695 696 697 698
                $result = $local_group->insert();

                if (!$result) {
                    common_log_db_error($local_group, 'INSERT', __FILE__);
                    // TRANS: Server exception thrown when saving local group information failed.
                    throw new ServerException(_('Could not save local group info.'));
                }
699
            }
Evan Prodromou's avatar
Evan Prodromou committed
700 701

            Event::handle('EndGroupSave', array($group));
702 703
        }

704 705
        $profile->query('COMMIT');

706 707
        return $group;
    }
708 709 710 711

    /**
     * Handle cascading deletion, on the model of notice and profile.
     *
712 713 714 715
     * This should handle freeing up cached entries for the group's
     * id, nickname, URI, and aliases. There may be other areas that
     * are not de-cached in the UI, including the sidebar lists on
     * GroupsAction
716
     */
717
    function delete($useWhere=false)
718
    {
719 720
        if (empty($this->id)) {
            common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
721
            return parent::delete($useWhere);
722
        }
723

724 725 726 727 728 729
        try {
            $profile = $this->getProfile();
            $profile->delete();
        } catch (GroupNoProfileException $unp) {
            common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
        }
730

731
        // Safe to delete in bulk for now
732

733 734 735 736
        $related = array('Group_inbox',
                         'Group_block',
                         'Group_member',
                         'Related_group');
737

738
        Event::handle('UserGroupDeleteRelated', array($this, &$related));
739

740 741 742
        foreach ($related as $cls) {
            $inst = new $cls();
            $inst->group_id = $this->id;
743

744 745 746 747
            if ($inst->find()) {
                while ($inst->fetch()) {
                    $dup = clone($inst);
                    $dup->delete();
748
                }
749
            }
750
        }
751

752 753 754 755 756 757 758 759 760
        // And related groups in the other direction...
        $inst = new Related_group();
        $inst->related_group_id = $this->id;
        $inst->delete();

        // Aliases and the local_group entry need to be cleared explicitly
        // or we'll miss clearing some cache keys; that can make it hard
        // to create a new group with one of those names or aliases.
        $this->setAliases(array());
mmn's avatar
mmn committed
761 762

        // $this->isLocal() but we're using the resulting object
763 764 765 766
        $local = Local_group::getKV('group_id', $this->id);
        if ($local instanceof Local_group) {
            $local->delete();
        }
767

768 769
        // blow the cached ids
        self::blow('user_group:notice_ids:%d', $this->id);
770

771
        return parent::delete($useWhere);
772
    }
773

774
    public function update($dataObject=false)
775 776
    {
        // Whenever the User_group is updated, find the Local_group
777 778
        // and update its nickname too.
        if ($this->nickname != $dataObject->nickname) {
779 780
            $local = Local_group::getKV('group_id', $this->id);
            if ($local instanceof Local_group) {
781
                common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
782 783 784 785
                $local->setNickname($this->nickname);
            }
        }

786
        // Also make sure the Profile table is up to date!
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
        $fields = array(/*group field => profile field*/
                    'nickname'      => 'nickname',
                    'fullname'      => 'fullname',
                    'mainpage'      => 'profileurl',
                    'homepage'      => 'homepage',
                    'description'   => 'bio',
                    'location'      => 'location',
                    'created'       => 'created',
                    'modified'      => 'modified',
                    );
        $profile = $this->getProfile();
        $origpro = clone($profile);
        foreach ($fields as $gf=>$pf) {
            $profile->$pf = $this->$gf;
        }
        if ($profile->update($origpro) === false) {
            throw new ServerException(_('Unable to update profile'));
        }

806
        return parent::update($dataObject);
807 808
    }

809 810 811
    function isPrivate()
    {
        return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
812
                intval($this->force_scope) === 1);
813
    }
814

mmn's avatar
mmn committed
815 816 817 818 819 820
    public function isLocal()
    {
        $local = Local_group::getKV('group_id', $this->id);
        return ($local instanceof Local_group);
    }

821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
    static function groupsFromText($text, Profile $profile)
    {
        $groups = array();

        /* extract all !group */
        $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
                                strtolower($text),
                                $match);

        if (!$count) {
            return $groups;
        }

        foreach (array_unique($match[1]) as $nickname) {
            $group = self::getForNickname($nickname, $profile);
            if ($group instanceof User_group && $profile->isMember($group)) {
                $groups[] = clone($group);
            }
        }

        return $groups;
    }

    static function idsFromText($text, Profile $profile)
    {
        $ids = array();
        $groups = self::groupsFromText($text, $profile);
        foreach ($groups as $group) {
            $ids[$group->id] = true;
        }
        return array_keys($ids);
    }
853
}