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