User_group.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  1. <?php
  2. /**
  3. * Table Definition for user_group
  4. */
  5. class User_group extends Managed_DataObject
  6. {
  7. const JOIN_POLICY_OPEN = 0;
  8. const JOIN_POLICY_MODERATE = 1;
  9. const CACHE_WINDOW = 201;
  10. ###START_AUTOCODE
  11. /* the code below is auto generated do not remove the above tag */
  12. public $__table = 'user_group'; // table name
  13. public $id; // int(4) primary_key not_null
  14. public $profile_id; // int(4) primary_key not_null
  15. public $nickname; // varchar(64)
  16. public $fullname; // varchar(191) not 255 because utf8mb4 takes more space
  17. public $homepage; // varchar(191) not 255 because utf8mb4 takes more space
  18. public $description; // text
  19. public $location; // varchar(191) not 255 because utf8mb4 takes more space
  20. public $original_logo; // varchar(191) not 255 because utf8mb4 takes more space
  21. public $homepage_logo; // varchar(191) not 255 because utf8mb4 takes more space
  22. public $stream_logo; // varchar(191) not 255 because utf8mb4 takes more space
  23. public $mini_logo; // varchar(191) not 255 because utf8mb4 takes more space
  24. public $created; // datetime() not_null default_0000-00-00%2000%3A00%3A00
  25. public $modified; // datetime() not_null default_CURRENT_TIMESTAMP
  26. public $uri; // varchar(191) unique_key not 255 because utf8mb4 takes more space
  27. public $mainpage; // varchar(191) not 255 because utf8mb4 takes more space
  28. public $join_policy; // tinyint
  29. public $force_scope; // tinyint
  30. /* the code above is auto generated do not remove the tag below */
  31. ###END_AUTOCODE
  32. public function getObjectType()
  33. {
  34. return ActivityObject::GROUP;
  35. }
  36. public static function schemaDef()
  37. {
  38. return array(
  39. 'fields' => array(
  40. 'id' => array('type' => 'serial', 'not null' => true, 'description' => 'unique identifier'),
  41. 'profile_id' => array('type' => 'int', 'not null' => true, 'description' => 'foreign key to profile table'),
  42. 'nickname' => array('type' => 'varchar', 'length' => 64, 'description' => 'nickname for addressing'),
  43. 'fullname' => array('type' => 'varchar', 'length' => 191, 'description' => 'display name'),
  44. 'homepage' => array('type' => 'varchar', 'length' => 191, 'description' => 'URL, cached so we dont regenerate'),
  45. 'description' => array('type' => 'text', 'description' => 'group description'),
  46. 'location' => array('type' => 'varchar', 'length' => 191, 'description' => 'related physical location, if any'),
  47. 'original_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'original size logo'),
  48. 'homepage_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'homepage (profile) size logo'),
  49. 'stream_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'stream-sized logo'),
  50. 'mini_logo' => array('type' => 'varchar', 'length' => 191, 'description' => 'mini logo'),
  51. 'created' => array('type' => 'datetime', 'not null' => true, 'default' => '0000-00-00 00:00:00', 'description' => 'date this record was created'),
  52. 'modified' => array('type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', 'description' => 'date this record was modified'),
  53. 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universal identifier'),
  54. 'mainpage' => array('type' => 'varchar', 'length' => 191, 'description' => 'page for group info to link to'),
  55. 'join_policy' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=open; 1=requires admin approval'),
  56. 'force_scope' => array('type' => 'int', 'size' => 'tiny', 'description' => '0=never,1=sometimes,-1=always'),
  57. ),
  58. 'primary key' => array('id'),
  59. 'unique keys' => array(
  60. 'user_group_uri_key' => array('uri'),
  61. // when it's safe and everyone's run upgrade.php 'user_profile_id_key' => array('profile_id'),
  62. ),
  63. 'foreign keys' => array(
  64. 'user_group_id_fkey' => array('profile', array('profile_id' => 'id')),
  65. ),
  66. 'indexes' => array(
  67. 'user_group_nickname_idx' => array('nickname'),
  68. 'user_group_profile_id_idx' => array('profile_id'), //make this unique in future
  69. ),
  70. );
  71. }
  72. protected $_profile = array();
  73. /**
  74. * @return Profile
  75. *
  76. * @throws GroupNoProfileException if user has no profile
  77. */
  78. public function getProfile()
  79. {
  80. if (!isset($this->_profile[$this->profile_id])) {
  81. $profile = Profile::getKV('id', $this->profile_id);
  82. if (!$profile instanceof Profile) {
  83. throw new GroupNoProfileException($this);
  84. }
  85. $this->_profile[$this->profile_id] = $profile;
  86. }
  87. return $this->_profile[$this->profile_id];
  88. }
  89. public function getNickname()
  90. {
  91. return $this->getProfile()->getNickname();
  92. }
  93. public function getFullname()
  94. {
  95. return $this->getProfile()->getFullname();
  96. }
  97. public static function defaultLogo($size)
  98. {
  99. static $sizenames = array(AVATAR_PROFILE_SIZE => 'profile',
  100. AVATAR_STREAM_SIZE => 'stream',
  101. AVATAR_MINI_SIZE => 'mini');
  102. return Theme::path('default-avatar-'.$sizenames[$size].'.png');
  103. }
  104. function homeUrl()
  105. {
  106. return $this->getProfile()->getUrl();
  107. }
  108. function getUri()
  109. {
  110. $uri = null;
  111. if (Event::handle('StartUserGroupGetUri', array($this, &$uri))) {
  112. if (!empty($this->uri)) {
  113. $uri = $this->uri;
  114. } elseif ($this->isLocal()) {
  115. $uri = common_local_url('groupbyid',
  116. array('id' => $this->id));
  117. }
  118. }
  119. Event::handle('EndUserGroupGetUri', array($this, &$uri));
  120. return $uri;
  121. }
  122. function permalink()
  123. {
  124. $url = null;
  125. if (Event::handle('StartUserGroupPermalink', array($this, &$url))) {
  126. if ($this->isLocal()) {
  127. $url = common_local_url('groupbyid',
  128. array('id' => $this->id));
  129. }
  130. }
  131. Event::handle('EndUserGroupPermalink', array($this, &$url));
  132. return $url;
  133. }
  134. function getNotices($offset, $limit, $since_id=null, $max_id=null)
  135. {
  136. // FIXME: Get the Profile::current() some other way, to avoid
  137. // possible confusion between current session and queue process.
  138. $stream = new GroupNoticeStream($this, Profile::current());
  139. return $stream->getNotices($offset, $limit, $since_id, $max_id);
  140. }
  141. function getMembers($offset=0, $limit=null) {
  142. $ids = null;
  143. if (is_null($limit) || $offset + $limit > User_group::CACHE_WINDOW) {
  144. $ids = $this->getMemberIDs($offset,
  145. $limit);
  146. } else {
  147. $key = sprintf('group:member_ids:%d', $this->id);
  148. $window = self::cacheGet($key);
  149. if ($window === false) {
  150. $window = $this->getMemberIDs(0,
  151. User_group::CACHE_WINDOW);
  152. self::cacheSet($key, $window);
  153. }
  154. $ids = array_slice($window,
  155. $offset,
  156. $limit);
  157. }
  158. return Profile::multiGet('id', $ids);
  159. }
  160. function getMemberIDs($offset=0, $limit=null)
  161. {
  162. $gm = new Group_member();
  163. $gm->selectAdd();
  164. $gm->selectAdd('profile_id');
  165. $gm->group_id = $this->id;
  166. $gm->orderBy('created DESC');
  167. if (!is_null($limit)) {
  168. $gm->limit($offset, $limit);
  169. }
  170. $ids = array();
  171. if ($gm->find()) {
  172. while ($gm->fetch()) {
  173. $ids[] = $gm->profile_id;
  174. }
  175. }
  176. return $ids;
  177. }
  178. /**
  179. * Get pending members, who have not yet been approved.
  180. *
  181. * @param int $offset
  182. * @param int $limit
  183. * @return Profile
  184. */
  185. function getRequests($offset=0, $limit=null)
  186. {
  187. $rq = new Group_join_queue();
  188. $rq->group_id = $this->id;
  189. $members = new Profile();
  190. $members->joinAdd(['id', $rq, 'profile_id']);
  191. if ($limit != null) {
  192. $members->limit($offset, $limit);
  193. }
  194. $members->find();
  195. return $members;
  196. }
  197. public function getAdminCount()
  198. {
  199. $block = new Group_member();
  200. $block->group_id = $this->id;
  201. $block->is_admin = 1;
  202. return $block->count();
  203. }
  204. public function getMemberCount()
  205. {
  206. $key = sprintf("group:member_count:%d", $this->id);
  207. $cnt = self::cacheGet($key);
  208. if (is_integer($cnt)) {
  209. return (int) $cnt;
  210. }
  211. $mem = new Group_member();
  212. $mem->group_id = $this->id;
  213. // XXX: why 'distinct'?
  214. $cnt = (int) $mem->count('distinct profile_id');
  215. self::cacheSet($key, $cnt);
  216. return $cnt;
  217. }
  218. function getBlockedCount()
  219. {
  220. // XXX: WORM cache this
  221. $block = new Group_block();
  222. $block->group_id = $this->id;
  223. return $block->count();
  224. }
  225. function getQueueCount()
  226. {
  227. // XXX: WORM cache this
  228. $queue = new Group_join_queue();
  229. $queue->group_id = $this->id;
  230. return $queue->count();
  231. }
  232. function getAdmins($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
  233. {
  234. $admins = new Profile();
  235. $admins->joinAdd(array('id', 'group_member:profile_id'));
  236. $admins->whereAdd(sprintf('group_member.group_id = %u AND group_member.is_admin = 1', $this->id));
  237. $admins->orderBy('group_member.modified ASC');
  238. $admins->limit($offset, $limit);
  239. $admins->find();
  240. return $admins;
  241. }
  242. function getBlocked($offset=null, $limit=null) // offset is null because DataObject wants it, 0 would mean no results
  243. {
  244. $blocked = new Profile();
  245. $blocked->joinAdd(array('id', 'group_block:blocked'));
  246. $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
  247. $blocked->orderBy('group_block.modified DESC');
  248. $blocked->limit($offset, $limit);
  249. $blocked->find();
  250. return $blocked;
  251. }
  252. function setOriginal($filename)
  253. {
  254. // This should be handled by the Profile->setOriginal function so user and group avatars are handled the same
  255. $imagefile = new ImageFile(null, Avatar::path($filename));
  256. $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
  257. 'stream_logo' => AVATAR_STREAM_SIZE,
  258. 'mini_logo' => AVATAR_MINI_SIZE);
  259. $orig = clone($this);
  260. $this->original_logo = Avatar::url($filename);
  261. foreach ($sizes as $name=>$size) {
  262. $filename = Avatar::filename($this->profile_id, image_type_to_extension($imagefile->preferredType()),
  263. $size, common_timestamp());
  264. $imagefile->resizeTo(Avatar::path($filename), array('width'=>$size, 'height'=>$size));
  265. $this->$name = Avatar::url($filename);
  266. }
  267. common_debug(common_log_objstring($this));
  268. return $this->update($orig);
  269. }
  270. function getBestName()
  271. {
  272. return ($this->fullname) ? $this->fullname : $this->nickname;
  273. }
  274. /**
  275. * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
  276. * if no fullname is provided.
  277. *
  278. * @return string
  279. */
  280. function getFancyName()
  281. {
  282. if ($this->fullname) {
  283. // TRANS: Full name of a profile or group followed by nickname in parens
  284. return sprintf(_m('FANCYNAME','%1$s (%2$s)'), $this->fullname, $this->nickname);
  285. } else {
  286. return $this->nickname;
  287. }
  288. }
  289. function getAliases()
  290. {
  291. $aliases = array();
  292. // XXX: cache this
  293. $alias = new Group_alias();
  294. $alias->group_id = $this->id;
  295. if ($alias->find()) {
  296. while ($alias->fetch()) {
  297. $aliases[] = $alias->alias;
  298. }
  299. }
  300. $alias->free();
  301. return $aliases;
  302. }
  303. function setAliases($newaliases) {
  304. $newaliases = array_unique($newaliases);
  305. $oldaliases = $this->getAliases();
  306. // Delete stuff that's old that not in new
  307. $to_delete = array_diff($oldaliases, $newaliases);
  308. // Insert stuff that's in new and not in old
  309. $to_insert = array_diff($newaliases, $oldaliases);
  310. $alias = new Group_alias();
  311. $alias->group_id = $this->id;
  312. foreach ($to_delete as $delalias) {
  313. $alias->alias = $delalias;
  314. $result = $alias->delete();
  315. if (!$result) {
  316. common_log_db_error($alias, 'DELETE', __FILE__);
  317. return false;
  318. }
  319. }
  320. foreach ($to_insert as $insalias) {
  321. if ($insalias === $this->nickname) {
  322. continue;
  323. }
  324. $alias->alias = Nickname::normalize($insalias, true);
  325. $result = $alias->insert();
  326. if (!$result) {
  327. common_log_db_error($alias, 'INSERT', __FILE__);
  328. return false;
  329. }
  330. }
  331. return true;
  332. }
  333. static function getForNickname($nickname, Profile $profile=null)
  334. {
  335. $nickname = Nickname::normalize($nickname);
  336. // Are there any matching remote groups this profile's in?
  337. if ($profile instanceof Profile) {
  338. $group = $profile->getGroups(0, null);
  339. while ($group instanceof User_group && $group->fetch()) {
  340. if ($group->nickname == $nickname) {
  341. // @fixme is this the best way?
  342. return clone($group);
  343. }
  344. }
  345. }
  346. // If not, check local groups.
  347. $group = Local_group::getKV('nickname', $nickname);
  348. if ($group instanceof Local_group) {
  349. return User_group::getKV('id', $group->group_id);
  350. }
  351. $alias = Group_alias::getKV('alias', $nickname);
  352. if ($alias instanceof Group_alias) {
  353. return User_group::getKV('id', $alias->group_id);
  354. }
  355. return null;
  356. }
  357. function getUserMembers()
  358. {
  359. // XXX: cache this
  360. $user = new User();
  361. if(common_config('db','quote_identifiers'))
  362. $user_table = '"user"';
  363. else $user_table = 'user';
  364. $qry =
  365. 'SELECT id ' .
  366. 'FROM '. $user_table .' JOIN group_member '.
  367. 'ON '. $user_table .'.id = group_member.profile_id ' .
  368. 'WHERE group_member.group_id = %d ';
  369. $user->query(sprintf($qry, $this->id));
  370. $ids = array();
  371. while ($user->fetch()) {
  372. $ids[] = $user->id;
  373. }
  374. $user->free();
  375. return $ids;
  376. }
  377. static function maxDescription()
  378. {
  379. $desclimit = common_config('group', 'desclimit');
  380. // null => use global limit (distinct from 0!)
  381. if (is_null($desclimit)) {
  382. $desclimit = common_config('site', 'textlimit');
  383. }
  384. return $desclimit;
  385. }
  386. static function descriptionTooLong($desc)
  387. {
  388. $desclimit = self::maxDescription();
  389. return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
  390. }
  391. function asAtomEntry($namespace=false, $source=false)
  392. {
  393. $xs = new XMLStringer(true);
  394. if ($namespace) {
  395. $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
  396. 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
  397. } else {
  398. $attrs = array();
  399. }
  400. $xs->elementStart('entry', $attrs);
  401. if ($source) {
  402. $xs->elementStart('source');
  403. $xs->element('id', null, $this->permalink());
  404. $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
  405. $xs->element('link', array('href' => $this->permalink()));
  406. $xs->element('updated', null, $this->modified);
  407. $xs->elementEnd('source');
  408. }
  409. $xs->element('title', null, $this->nickname);
  410. $xs->element('summary', null, common_xml_safe_str($this->description));
  411. $xs->element('link', array('rel' => 'alternate',
  412. 'href' => $this->permalink()));
  413. $xs->element('id', null, $this->permalink());
  414. $xs->element('published', null, common_date_w3dtf($this->created));
  415. $xs->element('updated', null, common_date_w3dtf($this->modified));
  416. $xs->element(
  417. 'content',
  418. array('type' => 'html'),
  419. common_xml_safe_str($this->description)
  420. );
  421. $xs->elementEnd('entry');
  422. return $xs->getString();
  423. }
  424. function asAtomAuthor()
  425. {
  426. $xs = new XMLStringer(true);
  427. $xs->elementStart('author');
  428. $xs->element('name', null, $this->nickname);
  429. $xs->element('uri', null, $this->permalink());
  430. $xs->elementEnd('author');
  431. return $xs->getString();
  432. }
  433. /**
  434. * Returns an XML string fragment with group information as an
  435. * Activity Streams noun object with the given element type.
  436. *
  437. * Assumes that 'activity', 'georss', and 'poco' namespace has been
  438. * previously defined.
  439. *
  440. * @param string $element one of 'actor', 'subject', 'object', 'target'
  441. *
  442. * @return string
  443. */
  444. function asActivityNoun($element)
  445. {
  446. $noun = ActivityObject::fromGroup($this);
  447. return $noun->asString('activity:' . $element);
  448. }
  449. function getAvatar()
  450. {
  451. return empty($this->homepage_logo)
  452. ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
  453. : $this->homepage_logo;
  454. }
  455. static function register($fields) {
  456. if (!empty($fields['userid'])) {
  457. $profile = Profile::getKV('id', $fields['userid']);
  458. if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
  459. common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
  460. // TRANS: Client exception thrown when a user tries to create a group while banned.
  461. throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
  462. }
  463. }
  464. $fields['nickname'] = Nickname::normalize($fields['nickname']);
  465. // MAGICALLY put fields into current scope
  466. // @fixme kill extract(); it makes debugging absurdly hard
  467. $defaults = array('nickname' => null,
  468. 'fullname' => null,
  469. 'homepage' => null,
  470. 'description' => null,
  471. 'location' => null,
  472. 'uri' => null,
  473. 'mainpage' => null,
  474. 'aliases' => array(),
  475. 'userid' => null);
  476. $fields = array_merge($defaults, $fields);
  477. extract($fields);
  478. $group = new User_group();
  479. if (empty($uri)) {
  480. // fill in later...
  481. $uri = null;
  482. }
  483. if (empty($mainpage)) {
  484. $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
  485. }
  486. // We must create a new, incrementally assigned profile_id
  487. $profile = new Profile();
  488. $profile->nickname = $nickname;
  489. $profile->fullname = $fullname;
  490. $profile->profileurl = $mainpage;
  491. $profile->homepage = $homepage;
  492. $profile->bio = $description;
  493. $profile->location = $location;
  494. $profile->created = common_sql_now();
  495. $group->nickname = $profile->nickname;
  496. $group->fullname = $profile->fullname;
  497. $group->homepage = $profile->homepage;
  498. $group->description = $profile->bio;
  499. $group->location = $profile->location;
  500. $group->mainpage = $profile->profileurl;
  501. $group->created = $profile->created;
  502. $profile->query('BEGIN');
  503. $id = $profile->insert();
  504. if ($id === false) {
  505. $profile->query('ROLLBACK');
  506. throw new ServerException(_('Profile insertion failed'));
  507. }
  508. $group->profile_id = $id;
  509. $group->uri = $uri;
  510. if (isset($fields['join_policy'])) {
  511. $group->join_policy = intval($fields['join_policy']);
  512. } else {
  513. $group->join_policy = 0;
  514. }
  515. if (isset($fields['force_scope'])) {
  516. $group->force_scope = intval($fields['force_scope']);
  517. } else {
  518. $group->force_scope = 0;
  519. }
  520. if (Event::handle('StartGroupSave', array(&$group))) {
  521. $result = $group->insert();
  522. if ($result === false) {
  523. common_log_db_error($group, 'INSERT', __FILE__);
  524. // TRANS: Server exception thrown when creating a group failed.
  525. throw new ServerException(_('Could not create group.'));
  526. }
  527. if (!isset($uri) || empty($uri)) {
  528. $orig = clone($group);
  529. $group->uri = common_local_url('groupbyid', array('id' => $group->id));
  530. $result = $group->update($orig);
  531. if (!$result) {
  532. common_log_db_error($group, 'UPDATE', __FILE__);
  533. // TRANS: Server exception thrown when updating a group URI failed.
  534. throw new ServerException(_('Could not set group URI.'));
  535. }
  536. }
  537. $result = $group->setAliases($aliases);
  538. if (!$result) {
  539. // TRANS: Server exception thrown when creating group aliases failed.
  540. throw new ServerException(_('Could not create aliases.'));
  541. }
  542. $member = new Group_member();
  543. $member->group_id = $group->id;
  544. $member->profile_id = $userid;
  545. $member->is_admin = 1;
  546. $member->created = $group->created;
  547. $result = $member->insert();
  548. if (!$result) {
  549. common_log_db_error($member, 'INSERT', __FILE__);
  550. // TRANS: Server exception thrown when setting group membership failed.
  551. throw new ServerException(_('Could not set group membership.'));
  552. }
  553. self::blow('profile:groups:%d', $userid);
  554. if ($local) {
  555. $local_group = new Local_group();
  556. $local_group->group_id = $group->id;
  557. $local_group->nickname = $nickname;
  558. $local_group->created = common_sql_now();
  559. $result = $local_group->insert();
  560. if (!$result) {
  561. common_log_db_error($local_group, 'INSERT', __FILE__);
  562. // TRANS: Server exception thrown when saving local group information failed.
  563. throw new ServerException(_('Could not save local group info.'));
  564. }
  565. }
  566. Event::handle('EndGroupSave', array($group));
  567. }
  568. $profile->query('COMMIT');
  569. return $group;
  570. }
  571. /**
  572. * Handle cascading deletion, on the model of notice and profile.
  573. *
  574. * This should handle freeing up cached entries for the group's
  575. * id, nickname, URI, and aliases. There may be other areas that
  576. * are not de-cached in the UI, including the sidebar lists on
  577. * GroupsAction
  578. */
  579. function delete($useWhere=false)
  580. {
  581. if (empty($this->id)) {
  582. common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
  583. return parent::delete($useWhere);
  584. }
  585. try {
  586. $profile = $this->getProfile();
  587. $profile->delete();
  588. } catch (GroupNoProfileException $unp) {
  589. common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
  590. }
  591. // Safe to delete in bulk for now
  592. $related = array('Group_inbox',
  593. 'Group_block',
  594. 'Group_member',
  595. 'Related_group');
  596. Event::handle('UserGroupDeleteRelated', array($this, &$related));
  597. foreach ($related as $cls) {
  598. $inst = new $cls();
  599. $inst->group_id = $this->id;
  600. if ($inst->find()) {
  601. while ($inst->fetch()) {
  602. $dup = clone($inst);
  603. $dup->delete();
  604. }
  605. }
  606. }
  607. // And related groups in the other direction...
  608. $inst = new Related_group();
  609. $inst->related_group_id = $this->id;
  610. $inst->delete();
  611. // Aliases and the local_group entry need to be cleared explicitly
  612. // or we'll miss clearing some cache keys; that can make it hard
  613. // to create a new group with one of those names or aliases.
  614. $this->setAliases(array());
  615. // $this->isLocal() but we're using the resulting object
  616. $local = Local_group::getKV('group_id', $this->id);
  617. if ($local instanceof Local_group) {
  618. $local->delete();
  619. }
  620. // blow the cached ids
  621. self::blow('user_group:notice_ids:%d', $this->id);
  622. return parent::delete($useWhere);
  623. }
  624. public function update($dataObject=false)
  625. {
  626. // Whenever the User_group is updated, find the Local_group
  627. // and update its nickname too.
  628. if ($this->nickname != $dataObject->nickname) {
  629. $local = Local_group::getKV('group_id', $this->id);
  630. if ($local instanceof Local_group) {
  631. common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
  632. $local->setNickname($this->nickname);
  633. }
  634. }
  635. // Also make sure the Profile table is up to date!
  636. $fields = array(/*group field => profile field*/
  637. 'nickname' => 'nickname',
  638. 'fullname' => 'fullname',
  639. 'mainpage' => 'profileurl',
  640. 'homepage' => 'homepage',
  641. 'description' => 'bio',
  642. 'location' => 'location',
  643. 'created' => 'created',
  644. 'modified' => 'modified',
  645. );
  646. $profile = $this->getProfile();
  647. $origpro = clone($profile);
  648. foreach ($fields as $gf=>$pf) {
  649. $profile->$pf = $this->$gf;
  650. }
  651. if ($profile->update($origpro) === false) {
  652. throw new ServerException(_('Unable to update profile'));
  653. }
  654. return parent::update($dataObject);
  655. }
  656. function isPrivate()
  657. {
  658. return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
  659. intval($this->force_scope) === 1);
  660. }
  661. public function isLocal()
  662. {
  663. $local = Local_group::getKV('group_id', $this->id);
  664. return ($local instanceof Local_group);
  665. }
  666. static function groupsFromText($text, Profile $profile)
  667. {
  668. $groups = array();
  669. /* extract all !group */
  670. $count = preg_match_all('/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
  671. strtolower($text),
  672. $match);
  673. if (!$count) {
  674. return $groups;
  675. }
  676. foreach (array_unique($match[1]) as $nickname) {
  677. $group = self::getForNickname($nickname, $profile);
  678. if ($group instanceof User_group && $profile->isMember($group)) {
  679. $groups[] = clone($group);
  680. }
  681. }
  682. return $groups;
  683. }
  684. static function idsFromText($text, Profile $profile)
  685. {
  686. $ids = array();
  687. $groups = self::groupsFromText($text, $profile);
  688. foreach ($groups as $group) {
  689. $ids[$group->id] = true;
  690. }
  691. return array_keys($ids);
  692. }
  693. }