]> git.mxchange.org Git - friendica.git/blob - src/Model/Group.php
Add user meta-groups for followers and mutual contacts
[friendica.git] / src / Model / Group.php
1 <?php
2 /**
3  * @file src/Model/Group.php
4  */
5 namespace Friendica\Model;
6
7 use Friendica\BaseModule;
8 use Friendica\BaseObject;
9 use Friendica\Core\L10n;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Renderer;
12 use Friendica\Database\DBA;
13
14 /**
15  * @brief functions for interacting with the group database table
16  */
17 class Group extends BaseObject
18 {
19         const FOLLOWERS = '~';
20         const MUTUALS = '&';
21
22         public static function getByUserId($uid, $includesDeleted = false)
23         {
24                 $DB = self::getApp()->getDatabase();
25
26                 $conditions = ['uid' => $uid];
27
28                 if (!$includesDeleted) {
29                         $conditions['deleted'] = false;
30                 }
31
32                 $groupsStmt = $DB->select('group', [], $conditions);
33
34                 return $DB->toArray($groupsStmt);
35         }
36
37         /**
38          * @param int $group_id
39          * @return bool
40          * @throws \Exception
41          */
42         public static function exists($group_id, $uid = null)
43         {
44                 $condition = ['id' => $group_id, 'deleted' => false];
45
46                 if (isset($uid)) {
47                         $condition = [
48                                 'uid' => $uid
49                         ];
50                 }
51
52                 return DBA::exists('group', $condition);
53         }
54
55         /**
56          * @brief Create a new contact group
57          *
58          * Note: If we found a deleted group with the same name, we restore it
59          *
60          * @param int    $uid
61          * @param string $name
62          * @return boolean
63          * @throws \Exception
64          */
65         public static function create($uid, $name)
66         {
67                 $return = false;
68                 if (!empty($uid) && !empty($name)) {
69                         $gid = self::getIdByName($uid, $name); // check for dupes
70                         if ($gid !== false) {
71                                 // This could be a problem.
72                                 // Let's assume we've just created a group which we once deleted
73                                 // all the old members are gone, but the group remains so we don't break any security
74                                 // access lists. What we're doing here is reviving the dead group, but old content which
75                                 // was restricted to this group may now be seen by the new group members.
76                                 $group = DBA::selectFirst('group', ['deleted'], ['id' => $gid]);
77                                 if (DBA::isResult($group) && $group['deleted']) {
78                                         DBA::update('group', ['deleted' => 0], ['id' => $gid]);
79                                         notice(L10n::t('A deleted group with this name was revived. Existing item permissions <strong>may</strong> apply to this group and any future members. If this is not what you intended, please create another group with a different name.') . EOL);
80                                 }
81                                 return true;
82                         }
83
84                         $return = DBA::insert('group', ['uid' => $uid, 'name' => $name]);
85                         if ($return) {
86                                 $return = DBA::lastInsertId();
87                         }
88                 }
89                 return $return;
90         }
91
92         /**
93          * Update group information.
94          *
95          * @param  int    $id   Group ID
96          * @param  string $name Group name
97          *
98          * @return bool Was the update successful?
99          * @throws \Exception
100          */
101         public static function update($id, $name)
102         {
103                 return DBA::update('group', ['name' => $name], ['id' => $id]);
104         }
105
106         /**
107          * @brief Get a list of group ids a contact belongs to
108          *
109          * @param int $cid
110          * @return array
111          * @throws \Exception
112          */
113         public static function getIdsByContactId($cid)
114         {
115                 $condition = ['contact-id' => $cid];
116                 $stmt = DBA::select('group_member', ['gid'], $condition);
117
118                 $return = [];
119
120                 while ($group = DBA::fetch($stmt)) {
121                         $return[] = $group['gid'];
122                 }
123
124                 return $return;
125         }
126
127         /**
128          * @brief count unread group items
129          *
130          * Count unread items of each groups of the local user
131          *
132          * @return array
133          *    'id' => group id
134          *    'name' => group name
135          *    'count' => counted unseen group items
136          * @throws \Exception
137          */
138         public static function countUnseen()
139         {
140                 $stmt = DBA::p("SELECT `group`.`id`, `group`.`name`,
141                                 (SELECT COUNT(*) FROM `item` FORCE INDEX (`uid_unseen_contactid`)
142                                         WHERE `uid` = ?
143                                         AND `unseen`
144                                         AND `contact-id` IN
145                                                 (SELECT `contact-id`
146                                                 FROM `group_member`
147                                                 WHERE `group_member`.`gid` = `group`.`id`)
148                                         ) AS `count`
149                                 FROM `group`
150                                 WHERE `group`.`uid` = ?;",
151                         local_user(),
152                         local_user()
153                 );
154
155                 return DBA::toArray($stmt);
156         }
157
158         /**
159          * @brief Get the group id for a user/name couple
160          *
161          * Returns false if no group has been found.
162          *
163          * @param int    $uid
164          * @param string $name
165          * @return int|boolean
166          * @throws \Exception
167          */
168         public static function getIdByName($uid, $name)
169         {
170                 if (!$uid || !strlen($name)) {
171                         return false;
172                 }
173
174                 $group = DBA::selectFirst('group', ['id'], ['uid' => $uid, 'name' => $name]);
175                 if (DBA::isResult($group)) {
176                         return $group['id'];
177                 }
178
179                 return false;
180         }
181
182         /**
183          * @brief Mark a group as deleted
184          *
185          * @param int $gid
186          * @return boolean
187          * @throws \Exception
188          */
189         public static function remove($gid) {
190                 if (! $gid) {
191                         return false;
192                 }
193
194                 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
195                 if (!DBA::isResult($group)) {
196                         return false;
197                 }
198
199                 // remove group from default posting lists
200                 $user = DBA::selectFirst('user', ['def_gid', 'allow_gid', 'deny_gid'], ['uid' => $group['uid']]);
201                 if (DBA::isResult($user)) {
202                         $change = false;
203
204                         if ($user['def_gid'] == $gid) {
205                                 $user['def_gid'] = 0;
206                                 $change = true;
207                         }
208                         if (strpos($user['allow_gid'], '<' . $gid . '>') !== false) {
209                                 $user['allow_gid'] = str_replace('<' . $gid . '>', '', $user['allow_gid']);
210                                 $change = true;
211                         }
212                         if (strpos($user['deny_gid'], '<' . $gid . '>') !== false) {
213                                 $user['deny_gid'] = str_replace('<' . $gid . '>', '', $user['deny_gid']);
214                                 $change = true;
215                         }
216
217                         if ($change) {
218                                 DBA::update('user', $user, ['uid' => $group['uid']]);
219                         }
220                 }
221
222                 // remove all members
223                 DBA::delete('group_member', ['gid' => $gid]);
224
225                 // remove group
226                 $return = DBA::update('group', ['deleted' => 1], ['id' => $gid]);
227
228                 return $return;
229         }
230
231         /**
232          * @brief      Mark a group as deleted based on its name
233          *
234          * @deprecated Use Group::remove instead
235          *
236          * @param int    $uid
237          * @param string $name
238          * @return bool
239          * @throws \Exception
240          */
241         public static function removeByName($uid, $name) {
242                 $return = false;
243                 if (!empty($uid) && !empty($name)) {
244                         $gid = self::getIdByName($uid, $name);
245
246                         $return = self::remove($gid);
247                 }
248
249                 return $return;
250         }
251
252         /**
253          * @brief Adds a contact to a group
254          *
255          * @param int $gid
256          * @param int $cid
257          * @return boolean
258          * @throws \Exception
259          */
260         public static function addMember($gid, $cid)
261         {
262                 if (!$gid || !$cid) {
263                         return false;
264                 }
265
266                 $row_exists = DBA::exists('group_member', ['gid' => $gid, 'contact-id' => $cid]);
267                 if ($row_exists) {
268                         // Row already existing, nothing to do
269                         $return = true;
270                 } else {
271                         $return = DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cid]);
272                 }
273
274                 return $return;
275         }
276
277         /**
278          * @brief Removes a contact from a group
279          *
280          * @param int $gid
281          * @param int $cid
282          * @return boolean
283          * @throws \Exception
284          */
285         public static function removeMember($gid, $cid)
286         {
287                 if (!$gid || !$cid) {
288                         return false;
289                 }
290
291                 $return = DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $cid]);
292
293                 return $return;
294         }
295
296         /**
297          * @brief      Removes a contact from a group based on its name
298          *
299          * @deprecated Use Group::removeMember instead
300          *
301          * @param int    $uid
302          * @param string $name
303          * @param int    $cid
304          * @return boolean
305          * @throws \Exception
306          */
307         public static function removeMemberByName($uid, $name, $cid)
308         {
309                 $gid = self::getIdByName($uid, $name);
310
311                 $return = self::removeMember($gid, $cid);
312
313                 return $return;
314         }
315
316         /**
317          * @brief Returns the combined list of contact ids from a group id list
318          *
319          * @param int     $uid
320          * @param array   $group_ids
321          * @param boolean $check_dead
322          * @return array
323          * @throws \Exception
324          */
325         public static function expand($uid, array $group_ids, $check_dead = false)
326         {
327                 if (!is_array($group_ids) || !count($group_ids)) {
328                         return [];
329                 }
330
331                 $return = [];
332
333                 $key = array_search(self::FOLLOWERS, $group_ids);
334                 if ($key !== false) {
335                         $followersStmt = Contact::select(['id'], ['uid' => $uid, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]]);
336
337                         while($follower = DBA::fetch($followersStmt)) {
338                                 $return[] = $follower['id'];
339                         }
340
341                         unset($group_ids[$key]);
342                 }
343
344                 $key = array_search(self::MUTUALS, $group_ids);
345                 if ($key !== false) {
346                         $mutualsStmt = Contact::select(['id'], ['uid' => $uid, 'rel' => [Contact::FRIEND]]);
347
348                         while($mutual = DBA::fetch($mutualsStmt)) {
349                                 $return[] = $mutual['id'];
350                         }
351
352                         unset($group_ids[$key]);
353                 }
354
355                 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $group_ids]);
356                 while($group_member = DBA::fetch($stmt)) {
357                         $return[] = $group_member['contact-id'];
358                 }
359
360                 if ($check_dead) {
361                         Contact::pruneUnavailable($return);
362                 }
363
364                 return $return;
365         }
366
367         /**
368          * @brief Returns a templated group selection list
369          *
370          * @param int    $uid
371          * @param int    $gid   An optional pre-selected group
372          * @param string $label An optional label of the list
373          * @return string
374          * @throws \Exception
375          */
376         public static function displayGroupSelection($uid, $gid = 0, $label = '')
377         {
378                 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid], ['order' => ['name']]);
379
380                 $display_groups = [
381                         [
382                                 'name' => '',
383                                 'id' => '0',
384                                 'selected' => ''
385                         ]
386                 ];
387                 while ($group = DBA::fetch($stmt)) {
388                         $display_groups[] = [
389                                 'name' => $group['name'],
390                                 'id' => $group['id'],
391                                 'selected' => $gid == $group['id'] ? 'true' : ''
392                         ];
393                 }
394                 Logger::log('groups: ' . print_r($display_groups, true));
395
396                 if ($label == '') {
397                         $label = L10n::t('Default privacy group for new contacts');
398                 }
399
400                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('group_selection.tpl'), [
401                         '$label' => $label,
402                         '$groups' => $display_groups
403                 ]);
404                 return $o;
405         }
406
407         /**
408          * @brief Create group sidebar widget
409          *
410          * @param string $every
411          * @param string $each
412          * @param string $editmode
413          *    'standard' => include link 'Edit groups'
414          *    'extended' => include link 'Create new group'
415          *    'full' => include link 'Create new group' and provide for each group a link to edit this group
416          * @param string $group_id
417          * @param int    $cid
418          * @return string
419          * @throws \Exception
420          */
421         public static function sidebarWidget($every = 'contact', $each = 'group', $editmode = 'standard', $group_id = '', $cid = 0)
422         {
423                 if (!local_user()) {
424                         return '';
425                 }
426
427                 $display_groups = [
428                         [
429                                 'text' => L10n::t('Everybody'),
430                                 'id' => 0,
431                                 'selected' => (($group_id === 'everyone') ? 'group-selected' : ''),
432                                 'href' => $every,
433                         ]
434                 ];
435
436                 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => local_user()], ['order' => ['name']]);
437
438                 $member_of = [];
439                 if ($cid) {
440                         $member_of = self::getIdsByContactId($cid);
441                 }
442
443                 while ($group = DBA::fetch($stmt)) {
444                         $selected = (($group_id == $group['id']) ? ' group-selected' : '');
445
446                         if ($editmode == 'full') {
447                                 $groupedit = [
448                                         'href' => 'group/' . $group['id'],
449                                         'title' => L10n::t('edit'),
450                                 ];
451                         } else {
452                                 $groupedit = null;
453                         }
454
455                         $display_groups[] = [
456                                 'id'   => $group['id'],
457                                 'cid'  => $cid,
458                                 'text' => $group['name'],
459                                 'href' => $each . '/' . $group['id'],
460                                 'edit' => $groupedit,
461                                 'selected' => $selected,
462                                 'ismember' => in_array($group['id'], $member_of),
463                         ];
464                 }
465
466                 // Don't show the groups on the network page when there is only one
467                 if ((count($display_groups) <= 2) && ($each == 'network')) {
468                         return '';
469                 }
470
471                 $tpl = Renderer::getMarkupTemplate('group_side.tpl');
472                 $o = Renderer::replaceMacros($tpl, [
473                         '$add' => L10n::t('add'),
474                         '$title' => L10n::t('Groups'),
475                         '$groups' => $display_groups,
476                         'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
477                         'grouppage' => 'group/',
478                         '$edittext' => L10n::t('Edit group'),
479                         '$ungrouped' => $every === 'contact' ? L10n::t('Contacts not in any group') : '',
480                         '$ungrouped_selected' => (($group_id === 'none') ? 'group-selected' : ''),
481                         '$createtext' => L10n::t('Create a new group'),
482                         '$creategroup' => L10n::t('Group Name: '),
483                         '$editgroupstext' => L10n::t('Edit groups'),
484                         '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),
485                 ]);
486
487
488                 return $o;
489         }
490 }