User_group.php 29 KB

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