User_group.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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() not_null default_0000-00-00%2000%3A00%3A00
  40. public $modified; // datetime() 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', 'not null' => true, 'default' => '0000-00-00 00:00:00', 'description' => 'date this record was created'),
  67. 'modified' => array('type' => 'datetime', 'not null' => true, 'default' => 'CURRENT_TIMESTAMP', '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_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(array('id', 'group_member:profile_id'));
  247. $admins->whereAdd('group_member.group_id = ' . $this->id . ' AND group_member.is_admin = true');
  248. $admins->orderBy('group_member.modified ASC');
  249. $admins->limit($offset, $limit);
  250. $admins->find();
  251. return $admins;
  252. }
  253. // offset is null because DataObject wants it, 0 would mean no results
  254. public function getBlocked($offset = null, $limit = null)
  255. {
  256. $blocked = new Profile();
  257. $blocked->joinAdd(array('id', 'group_block:blocked'));
  258. $blocked->whereAdd(sprintf('group_block.group_id = %u', $this->id));
  259. $blocked->orderBy('group_block.modified DESC');
  260. $blocked->limit($offset, $limit);
  261. $blocked->find();
  262. return $blocked;
  263. }
  264. public function setOriginal($filename)
  265. {
  266. // This should be handled by the Profile->setOriginal function so user and group avatars are handled the same
  267. $imagefile = new ImageFile(null, Avatar::path($filename));
  268. $sizes = array('homepage_logo' => AVATAR_PROFILE_SIZE,
  269. 'stream_logo' => AVATAR_STREAM_SIZE,
  270. 'mini_logo' => AVATAR_MINI_SIZE);
  271. $orig = clone($this);
  272. $this->original_logo = Avatar::url($filename);
  273. foreach ($sizes as $name=>$size) {
  274. $filename = Avatar::filename(
  275. $this->profile_id,
  276. image_type_to_extension($imagefile->preferredType()),
  277. $size,
  278. common_timestamp()
  279. );
  280. $imagefile->resizeTo(Avatar::path($filename), array('width'=>$size, 'height'=>$size));
  281. $this->$name = Avatar::url($filename);
  282. }
  283. common_debug(common_log_objstring($this));
  284. return $this->update($orig);
  285. }
  286. public function getBestName()
  287. {
  288. return ($this->fullname) ? $this->fullname : $this->nickname;
  289. }
  290. /**
  291. * Gets the full name (if filled) with nickname as a parenthetical, or the nickname alone
  292. * if no fullname is provided.
  293. *
  294. * @return string
  295. */
  296. public function getFancyName()
  297. {
  298. if ($this->fullname) {
  299. // TRANS: Full name of a profile or group followed by nickname in parens
  300. return sprintf(_m('FANCYNAME', '%1$s (%2$s)'), $this->fullname, $this->nickname);
  301. } else {
  302. return $this->nickname;
  303. }
  304. }
  305. public function getAliases()
  306. {
  307. $aliases = array();
  308. // XXX: cache this
  309. $alias = new Group_alias();
  310. $alias->group_id = $this->id;
  311. if ($alias->find()) {
  312. while ($alias->fetch()) {
  313. $aliases[] = $alias->alias;
  314. }
  315. }
  316. $alias->free();
  317. return $aliases;
  318. }
  319. public function setAliases($newaliases)
  320. {
  321. $newaliases = array_unique($newaliases);
  322. $oldaliases = $this->getAliases();
  323. // Delete stuff that's old that not in new
  324. $to_delete = array_diff($oldaliases, $newaliases);
  325. // Insert stuff that's in new and not in old
  326. $to_insert = array_diff($newaliases, $oldaliases);
  327. $alias = new Group_alias();
  328. $alias->group_id = $this->id;
  329. foreach ($to_delete as $delalias) {
  330. $alias->alias = $delalias;
  331. $result = $alias->delete();
  332. if (!$result) {
  333. common_log_db_error($alias, 'DELETE', __FILE__);
  334. return false;
  335. }
  336. }
  337. foreach ($to_insert as $insalias) {
  338. if ($insalias === $this->nickname) {
  339. continue;
  340. }
  341. $alias->alias = Nickname::normalize($insalias, true);
  342. $result = $alias->insert();
  343. if (!$result) {
  344. common_log_db_error($alias, 'INSERT', __FILE__);
  345. return false;
  346. }
  347. }
  348. return true;
  349. }
  350. public static function getForNickname($nickname, Profile $profile = null)
  351. {
  352. $nickname = Nickname::normalize($nickname);
  353. // Are there any matching remote groups this profile's in?
  354. if ($profile instanceof Profile) {
  355. $group = $profile->getGroups(0, null);
  356. while ($group instanceof User_group && $group->fetch()) {
  357. if ($group->nickname == $nickname) {
  358. // @fixme is this the best way?
  359. return clone($group);
  360. }
  361. }
  362. }
  363. // If not, check local groups.
  364. $group = Local_group::getKV('nickname', $nickname);
  365. if ($group instanceof Local_group) {
  366. return User_group::getKV('id', $group->group_id);
  367. }
  368. $alias = Group_alias::getKV('alias', $nickname);
  369. if ($alias instanceof Group_alias) {
  370. return User_group::getKV('id', $alias->group_id);
  371. }
  372. return null;
  373. }
  374. public function getUserMembers()
  375. {
  376. // XXX: cache this
  377. $user = new User();
  378. $user->query(sprintf(
  379. 'SELECT id FROM %1$s INNER JOIN group_member ' .
  380. 'ON %1$s.id = group_member.profile_id ' .
  381. 'WHERE group_member.group_id = %2$d ',
  382. $user->escapedTableName(),
  383. $this->id
  384. ));
  385. $ids = [];
  386. while ($user->fetch()) {
  387. $ids[] = $user->id;
  388. }
  389. $user->free();
  390. return $ids;
  391. }
  392. public static function maxDescription()
  393. {
  394. $desclimit = common_config('group', 'desclimit');
  395. // null => use global limit (distinct from 0!)
  396. if (is_null($desclimit)) {
  397. $desclimit = common_config('site', 'textlimit');
  398. }
  399. return $desclimit;
  400. }
  401. public static function descriptionTooLong($desc)
  402. {
  403. $desclimit = self::maxDescription();
  404. return ($desclimit > 0 && !empty($desc) && (mb_strlen($desc) > $desclimit));
  405. }
  406. public function asAtomEntry($namespace = false, $source = false)
  407. {
  408. $xs = new XMLStringer(true);
  409. if ($namespace) {
  410. $attrs = array('xmlns' => 'http://www.w3.org/2005/Atom',
  411. 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0');
  412. } else {
  413. $attrs = array();
  414. }
  415. $xs->elementStart('entry', $attrs);
  416. if ($source) {
  417. $xs->elementStart('source');
  418. $xs->element('id', null, $this->permalink());
  419. $xs->element('title', null, $profile->nickname . " - " . common_config('site', 'name'));
  420. $xs->element('link', array('href' => $this->permalink()));
  421. $xs->element('updated', null, $this->modified);
  422. $xs->elementEnd('source');
  423. }
  424. $xs->element('title', null, $this->nickname);
  425. $xs->element('summary', null, common_xml_safe_str($this->description));
  426. $xs->element('link', array('rel' => 'alternate',
  427. 'href' => $this->permalink()));
  428. $xs->element('id', null, $this->permalink());
  429. $xs->element('published', null, common_date_w3dtf($this->created));
  430. $xs->element('updated', null, common_date_w3dtf($this->modified));
  431. $xs->element(
  432. 'content',
  433. array('type' => 'html'),
  434. common_xml_safe_str($this->description)
  435. );
  436. $xs->elementEnd('entry');
  437. return $xs->getString();
  438. }
  439. public function asAtomAuthor()
  440. {
  441. $xs = new XMLStringer(true);
  442. $xs->elementStart('author');
  443. $xs->element('name', null, $this->nickname);
  444. $xs->element('uri', null, $this->permalink());
  445. $xs->elementEnd('author');
  446. return $xs->getString();
  447. }
  448. /**
  449. * Returns an XML string fragment with group information as an
  450. * Activity Streams noun object with the given element type.
  451. *
  452. * Assumes that 'activity', 'georss', and 'poco' namespace has been
  453. * previously defined.
  454. *
  455. * @param string $element one of 'actor', 'subject', 'object', 'target'
  456. *
  457. * @return string
  458. */
  459. public function asActivityNoun($element)
  460. {
  461. $noun = ActivityObject::fromGroup($this);
  462. return $noun->asString('activity:' . $element);
  463. }
  464. public function getAvatar()
  465. {
  466. return empty($this->homepage_logo)
  467. ? User_group::defaultLogo(AVATAR_PROFILE_SIZE)
  468. : $this->homepage_logo;
  469. }
  470. public static function register($fields)
  471. {
  472. if (!empty($fields['userid'])) {
  473. $profile = Profile::getKV('id', $fields['userid']);
  474. if ($profile && !$profile->hasRight(Right::CREATEGROUP)) {
  475. common_log(LOG_WARNING, "Attempted group creation from banned user: " . $profile->nickname);
  476. // TRANS: Client exception thrown when a user tries to create a group while banned.
  477. throw new ClientException(_('You are not allowed to create groups on this site.'), 403);
  478. }
  479. }
  480. $fields['nickname'] = Nickname::normalize($fields['nickname']);
  481. // MAGICALLY put fields into current scope
  482. // @fixme kill extract(); it makes debugging absurdly hard
  483. $defaults = [
  484. 'nickname' => null,
  485. 'fullname' => null,
  486. 'homepage' => null,
  487. 'description' => null,
  488. 'location' => null,
  489. 'uri' => null,
  490. 'mainpage' => null,
  491. 'aliases' => [],
  492. 'userid' => null,
  493. ];
  494. $fields = array_merge($defaults, $fields);
  495. extract($fields);
  496. $group = new User_group();
  497. if (empty($uri)) {
  498. // fill in later...
  499. $uri = null;
  500. }
  501. if (empty($mainpage)) {
  502. $mainpage = common_local_url('showgroup', array('nickname' => $nickname));
  503. }
  504. // We must create a new, incrementally assigned profile_id
  505. $profile = new Profile();
  506. $profile->nickname = $nickname;
  507. $profile->fullname = $fullname;
  508. $profile->profileurl = $mainpage;
  509. $profile->homepage = $homepage;
  510. $profile->bio = $description;
  511. $profile->location = $location;
  512. $profile->created = common_sql_now();
  513. $group->nickname = $profile->nickname;
  514. $group->fullname = $profile->fullname;
  515. $group->homepage = $profile->homepage;
  516. $group->description = $profile->bio;
  517. $group->location = $profile->location;
  518. $group->mainpage = $profile->profileurl;
  519. $group->created = $profile->created;
  520. $profile->query('BEGIN');
  521. $id = $profile->insert();
  522. if ($id === false) {
  523. $profile->query('ROLLBACK');
  524. throw new ServerException(_('Profile insertion failed'));
  525. }
  526. $group->profile_id = $id;
  527. $group->uri = $uri;
  528. if (isset($fields['join_policy'])) {
  529. $group->join_policy = intval($fields['join_policy']);
  530. } else {
  531. $group->join_policy = 0;
  532. }
  533. if (isset($fields['force_scope'])) {
  534. $group->force_scope = intval($fields['force_scope']);
  535. } else {
  536. $group->force_scope = 0;
  537. }
  538. if (Event::handle('StartGroupSave', array(&$group))) {
  539. $result = $group->insert();
  540. if ($result === false) {
  541. common_log_db_error($group, 'INSERT', __FILE__);
  542. // TRANS: Server exception thrown when creating a group failed.
  543. throw new ServerException(_('Could not create group.'));
  544. }
  545. if (!isset($uri) || empty($uri)) {
  546. $orig = clone($group);
  547. $group->uri = common_local_url('groupbyid', array('id' => $group->id));
  548. $result = $group->update($orig);
  549. if (!$result) {
  550. common_log_db_error($group, 'UPDATE', __FILE__);
  551. // TRANS: Server exception thrown when updating a group URI failed.
  552. throw new ServerException(_('Could not set group URI.'));
  553. }
  554. }
  555. $result = $group->setAliases($aliases);
  556. if (!$result) {
  557. // TRANS: Server exception thrown when creating group aliases failed.
  558. throw new ServerException(_('Could not create aliases.'));
  559. }
  560. $member = new Group_member();
  561. $member->group_id = $group->id;
  562. $member->profile_id = $userid;
  563. $member->is_admin = true;
  564. $member->created = $group->created;
  565. $result = $member->insert();
  566. if (!$result) {
  567. common_log_db_error($member, 'INSERT', __FILE__);
  568. // TRANS: Server exception thrown when setting group membership failed.
  569. throw new ServerException(_('Could not set group membership.'));
  570. }
  571. self::blow('profile:groups:%d', $userid);
  572. if ($local) {
  573. $local_group = new Local_group();
  574. $local_group->group_id = $group->id;
  575. $local_group->nickname = $nickname;
  576. $local_group->created = common_sql_now();
  577. $result = $local_group->insert();
  578. if (!$result) {
  579. common_log_db_error($local_group, 'INSERT', __FILE__);
  580. // TRANS: Server exception thrown when saving local group information failed.
  581. throw new ServerException(_('Could not save local group info.'));
  582. }
  583. }
  584. Event::handle('EndGroupSave', array($group));
  585. }
  586. $profile->query('COMMIT');
  587. return $group;
  588. }
  589. /**
  590. * Handle cascading deletion, on the model of notice and profile.
  591. *
  592. * This should handle freeing up cached entries for the group's
  593. * id, nickname, URI, and aliases. There may be other areas that
  594. * are not de-cached in the UI, including the sidebar lists on
  595. * GroupsAction
  596. */
  597. public function delete($useWhere = false)
  598. {
  599. if (empty($this->id)) {
  600. common_log(LOG_WARNING, "Ambiguous User_group->delete(); skipping related tables.");
  601. return parent::delete($useWhere);
  602. }
  603. try {
  604. $profile = $this->getProfile();
  605. $profile->delete();
  606. } catch (GroupNoProfileException $unp) {
  607. common_log(LOG_INFO, "Group {$this->nickname} has no profile; continuing deletion.");
  608. }
  609. // Safe to delete in bulk for now
  610. $related = array('Group_inbox',
  611. 'Group_block',
  612. 'Group_member',
  613. 'Related_group');
  614. Event::handle('UserGroupDeleteRelated', array($this, &$related));
  615. foreach ($related as $cls) {
  616. $inst = new $cls();
  617. $inst->group_id = $this->id;
  618. if ($inst->find()) {
  619. while ($inst->fetch()) {
  620. $dup = clone($inst);
  621. $dup->delete();
  622. }
  623. }
  624. }
  625. // And related groups in the other direction...
  626. $inst = new Related_group();
  627. $inst->related_group_id = $this->id;
  628. $inst->delete();
  629. // Aliases and the local_group entry need to be cleared explicitly
  630. // or we'll miss clearing some cache keys; that can make it hard
  631. // to create a new group with one of those names or aliases.
  632. $this->setAliases(array());
  633. // $this->isLocal() but we're using the resulting object
  634. $local = Local_group::getKV('group_id', $this->id);
  635. if ($local instanceof Local_group) {
  636. $local->delete();
  637. }
  638. // blow the cached ids
  639. self::blow('user_group:notice_ids:%d', $this->id);
  640. return parent::delete($useWhere);
  641. }
  642. public function update($dataObject=false)
  643. {
  644. // Whenever the User_group is updated, find the Local_group
  645. // and update its nickname too.
  646. if ($this->nickname != $dataObject->nickname) {
  647. $local = Local_group::getKV('group_id', $this->id);
  648. if ($local instanceof Local_group) {
  649. common_debug("Updating Local_group ({$this->id}) nickname from {$dataObject->nickname} to {$this->nickname}");
  650. $local->setNickname($this->nickname);
  651. }
  652. }
  653. // Also make sure the Profile table is up to date!
  654. $fields = array(/*group field => profile field*/
  655. 'nickname' => 'nickname',
  656. 'fullname' => 'fullname',
  657. 'mainpage' => 'profileurl',
  658. 'homepage' => 'homepage',
  659. 'description' => 'bio',
  660. 'location' => 'location',
  661. 'created' => 'created',
  662. 'modified' => 'modified',
  663. );
  664. $profile = $this->getProfile();
  665. $origpro = clone($profile);
  666. foreach ($fields as $gf=>$pf) {
  667. $profile->$pf = $this->$gf;
  668. }
  669. if ($profile->update($origpro) === false) {
  670. throw new ServerException(_('Unable to update profile'));
  671. }
  672. return parent::update($dataObject);
  673. }
  674. public function isPrivate()
  675. {
  676. return ($this->join_policy == self::JOIN_POLICY_MODERATE &&
  677. intval($this->force_scope) === 1);
  678. }
  679. public function isLocal()
  680. {
  681. $local = Local_group::getKV('group_id', $this->id);
  682. return ($local instanceof Local_group);
  683. }
  684. public static function groupsFromText($text, Profile $profile)
  685. {
  686. $groups = array();
  687. /* extract all !group */
  688. $count = preg_match_all(
  689. '/(?:^|\s)!(' . Nickname::DISPLAY_FMT . ')/',
  690. strtolower($text),
  691. $match
  692. );
  693. if (!$count) {
  694. return $groups;
  695. }
  696. foreach (array_unique($match[1]) as $nickname) {
  697. $group = self::getForNickname($nickname, $profile);
  698. if ($group instanceof User_group && $profile->isMember($group)) {
  699. $groups[] = clone($group);
  700. }
  701. }
  702. return $groups;
  703. }
  704. public static function idsFromText($text, Profile $profile)
  705. {
  706. $ids = array();
  707. $groups = self::groupsFromText($text, $profile);
  708. foreach ($groups as $group) {
  709. $ids[$group->id] = true;
  710. }
  711. return array_keys($ids);
  712. }
  713. }