]> git.mxchange.org Git - friendica.git/blob - src/Model/Group.php
a3f4455e624bdcc7bd0a6090e5299400cd16388e
[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                 $return = [];
117
118                 $stmt = DBA::select('group_member', ['gid'], ['contact-id' => $cid]);
119                 while ($group = DBA::fetch($stmt)) {
120                         $return[] = $group['gid'];
121                 }
122                 DBA::close($stmt);
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                         $followers = Contact::selectToArray(['id'], [
336                                 'uid' => $uid,
337                                 'rel' => [Contact::FOLLOWER, Contact::FRIEND],
338                                 'protocol' => Protocol::SUPPORT_PRIVATE,
339                         ]);
340
341                         foreach ($followers as $follower) {
342                                 $return[] = $follower['id'];
343                         }
344
345                         unset($group_ids[$key]);
346                 }
347
348                 $key = array_search(self::MUTUALS, $group_ids);
349                 if ($key !== false) {
350                         $mutuals = Contact::selectToArray(['id'], [
351                                 'uid' => $uid,
352                                 'rel' => [Contact::FRIEND],
353                                 'protocol' => Protocol::SUPPORT_PRIVATE,
354                         ]);
355
356                         foreach ($mutuals as $mutual) {
357                                 $return[] = $mutual['id'];
358                         }
359
360                         unset($group_ids[$key]);
361                 }
362
363                 $stmt = DBA::select('group_member', ['contact-id'], ['gid' => $group_ids]);
364                 while($group_member = DBA::fetch($stmt)) {
365                         $return[] = $group_member['contact-id'];
366                 }
367                 DBA::close($stmt);
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                 $display_groups = [
388                         [
389                                 'name' => '',
390                                 'id' => '0',
391                                 'selected' => ''
392                         ]
393                 ];
394
395                 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid], ['order' => ['name']]);
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                 DBA::close($stmt);
404
405                 Logger::info('groups: ' . print_r($display_groups, true));
406
407                 if ($label == '') {
408                         $label = L10n::t('Default privacy group for new contacts');
409                 }
410
411                 $o = Renderer::replaceMacros(Renderer::getMarkupTemplate('group_selection.tpl'), [
412                         '$label' => $label,
413                         '$groups' => $display_groups
414                 ]);
415                 return $o;
416         }
417
418         /**
419          * @brief Create group sidebar widget
420          *
421          * @param string $every
422          * @param string $each
423          * @param string $editmode
424          *    'standard' => include link 'Edit groups'
425          *    'extended' => include link 'Create new group'
426          *    'full' => include link 'Create new group' and provide for each group a link to edit this group
427          * @param string $group_id
428          * @param int    $cid
429          * @return string
430          * @throws \Exception
431          */
432         public static function sidebarWidget($every = 'contact', $each = 'group', $editmode = 'standard', $group_id = '', $cid = 0)
433         {
434                 if (!local_user()) {
435                         return '';
436                 }
437
438                 $display_groups = [
439                         [
440                                 'text' => L10n::t('Everybody'),
441                                 'id' => 0,
442                                 'selected' => (($group_id === 'everyone') ? 'group-selected' : ''),
443                                 'href' => $every,
444                         ]
445                 ];
446
447                 $member_of = [];
448                 if ($cid) {
449                         $member_of = self::getIdsByContactId($cid);
450                 }
451
452                 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => local_user()], ['order' => ['name']]);
453                 while ($group = DBA::fetch($stmt)) {
454                         $selected = (($group_id == $group['id']) ? ' group-selected' : '');
455
456                         if ($editmode == 'full') {
457                                 $groupedit = [
458                                         'href' => 'group/' . $group['id'],
459                                         'title' => L10n::t('edit'),
460                                 ];
461                         } else {
462                                 $groupedit = null;
463                         }
464
465                         $display_groups[] = [
466                                 'id'   => $group['id'],
467                                 'cid'  => $cid,
468                                 'text' => $group['name'],
469                                 'href' => $each . '/' . $group['id'],
470                                 'edit' => $groupedit,
471                                 'selected' => $selected,
472                                 'ismember' => in_array($group['id'], $member_of),
473                         ];
474                 }
475                 DBA::close($stmt);
476
477                 // Don't show the groups on the network page when there is only one
478                 if ((count($display_groups) <= 2) && ($each == 'network')) {
479                         return '';
480                 }
481
482                 $tpl = Renderer::getMarkupTemplate('group_side.tpl');
483                 $o = Renderer::replaceMacros($tpl, [
484                         '$add' => L10n::t('add'),
485                         '$title' => L10n::t('Groups'),
486                         '$groups' => $display_groups,
487                         'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
488                         'grouppage' => 'group/',
489                         '$edittext' => L10n::t('Edit group'),
490                         '$ungrouped' => $every === 'contact' ? L10n::t('Contacts not in any group') : '',
491                         '$ungrouped_selected' => (($group_id === 'none') ? 'group-selected' : ''),
492                         '$createtext' => L10n::t('Create a new group'),
493                         '$creategroup' => L10n::t('Group Name: '),
494                         '$editgroupstext' => L10n::t('Edit groups'),
495                         '$form_security_token' => BaseModule::getFormSecurityToken('group_edit'),
496                 ]);
497
498                 return $o;
499         }
500 }