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