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