]> git.mxchange.org Git - friendica.git/blob - src/Model/Group.php
Merge pull request #5617 from MrPetovan/task/use-contact-network
[friendica.git] / src / Model / Group.php
1 <?php
2 /**
3  * @file src/Model/Group.php
4  */
5 namespace Friendica\Model;
6
7 use Friendica\BaseObject;
8 use Friendica\Core\L10n;
9 use Friendica\Database\DBA;
10
11 require_once 'boot.php';
12 require_once 'include/dba.php';
13 require_once 'include/text.php';
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          */
29         public static function create($uid, $name)
30         {
31                 $return = false;
32                 if (x($uid) && x($name)) {
33                         $gid = self::getIdByName($uid, $name); // check for dupes
34                         if ($gid !== false) {
35                                 // This could be a problem.
36                                 // Let's assume we've just created a group which we once deleted
37                                 // all the old members are gone, but the group remains so we don't break any security
38                                 // access lists. What we're doing here is reviving the dead group, but old content which
39                                 // was restricted to this group may now be seen by the new group members.
40                                 $group = DBA::selectFirst('group', ['deleted'], ['id' => $gid]);
41                                 if (DBA::isResult($group) && $group['deleted']) {
42                                         DBA::update('group', ['deleted' => 0], ['id' => $gid]);
43                                         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);
44                                 }
45                                 return true;
46                         }
47
48                         $return = DBA::insert('group', ['uid' => $uid, 'name' => $name]);
49                         if ($return) {
50                                 $return = DBA::lastInsertId();
51                         }
52                 }
53                 return $return;
54         }
55
56         /**
57          * Update group information.
58          *
59          * @param  int    $id   Group ID
60          * @param  string $name Group name
61          *
62          * @return bool Was the update successful?
63          */
64         public static function update($id, $name)
65         {
66                 return DBA::update('group', ['name' => $name], ['id' => $id]);
67         }
68
69         /**
70          * @brief Get a list of group ids a contact belongs to
71          *
72          * @param int $cid
73          * @return array
74          */
75         public static function getIdsByContactId($cid)
76         {
77                 $condition = ['contact-id' => $cid];
78                 $stmt = DBA::select('group_member', ['gid'], $condition);
79
80                 $return = [];
81
82                 while ($group = DBA::fetch($stmt)) {
83                         $return[] = $group['gid'];
84                 }
85
86                 return $return;
87         }
88
89         /**
90          * @brief count unread group items
91          *
92          * Count unread items of each groups of the local user
93          *
94          * @return array
95          *      'id' => group id
96          *      'name' => group name
97          *      'count' => counted unseen group items
98          */
99         public static function countUnseen()
100         {
101                 $stmt = DBA::p("SELECT `group`.`id`, `group`.`name`,
102                                 (SELECT COUNT(*) FROM `item` FORCE INDEX (`uid_unseen_contactid`)
103                                         WHERE `uid` = ?
104                                         AND `unseen`
105                                         AND `contact-id` IN
106                                                 (SELECT `contact-id`
107                                                 FROM `group_member`
108                                                 WHERE `group_member`.`gid` = `group`.`id`)
109                                         ) AS `count`
110                                 FROM `group`
111                                 WHERE `group`.`uid` = ?;",
112                         local_user(),
113                         local_user()
114                 );
115
116                 return DBA::toArray($stmt);
117         }
118
119         /**
120          * @brief Get the group id for a user/name couple
121          *
122          * Returns false if no group has been found.
123          *
124          * @param int $uid
125          * @param string $name
126          * @return int|boolean
127          */
128         public static function getIdByName($uid, $name)
129         {
130                 if (!$uid || !strlen($name)) {
131                         return false;
132                 }
133
134                 $group = DBA::selectFirst('group', ['id'], ['uid' => $uid, 'name' => $name]);
135                 if (DBA::isResult($group)) {
136                         return $group['id'];
137                 }
138
139                 return false;
140         }
141
142         /**
143          * @brief Mark a group as deleted
144          *
145          * @param int $gid
146          * @return boolean
147          */
148         public static function remove($gid) {
149                 if (! $gid) {
150                         return false;
151                 }
152
153                 $group = DBA::selectFirst('group', ['uid'], ['id' => $gid]);
154                 if (!DBA::isResult($group)) {
155                         return false;
156                 }
157
158                 // remove group from default posting lists
159                 $user = DBA::selectFirst('user', ['def_gid', 'allow_gid', 'deny_gid'], ['uid' => $group['uid']]);
160                 if (DBA::isResult($user)) {
161                         $change = false;
162
163                         if ($user['def_gid'] == $gid) {
164                                 $user['def_gid'] = 0;
165                                 $change = true;
166                         }
167                         if (strpos($user['allow_gid'], '<' . $gid . '>') !== false) {
168                                 $user['allow_gid'] = str_replace('<' . $gid . '>', '', $user['allow_gid']);
169                                 $change = true;
170                         }
171                         if (strpos($user['deny_gid'], '<' . $gid . '>') !== false) {
172                                 $user['deny_gid'] = str_replace('<' . $gid . '>', '', $user['deny_gid']);
173                                 $change = true;
174                         }
175
176                         if ($change) {
177                                 DBA::update('user', $user, ['uid' => $group['uid']]);
178                         }
179                 }
180
181                 // remove all members
182                 DBA::delete('group_member', ['gid' => $gid]);
183
184                 // remove group
185                 $return = DBA::update('group', ['deleted' => 1], ['id' => $gid]);
186
187                 return $return;
188         }
189
190         /**
191          * @brief Mark a group as deleted based on its name
192          *
193          * @deprecated Use Group::remove instead
194          *
195          * @param int $uid
196          * @param string $name
197          * @return bool
198          */
199         public static function removeByName($uid, $name) {
200                 $return = false;
201                 if (x($uid) && x($name)) {
202                         $gid = self::getIdByName($uid, $name);
203
204                         $return = self::remove($gid);
205                 }
206
207                 return $return;
208         }
209
210         /**
211          * @brief Adds a contact to a group
212          *
213          * @param int $gid
214          * @param int $cid
215          * @return boolean
216          */
217         public static function addMember($gid, $cid)
218         {
219                 if (!$gid || !$cid) {
220                         return false;
221                 }
222
223                 $row_exists = DBA::exists('group_member', ['gid' => $gid, 'contact-id' => $cid]);
224                 if ($row_exists) {
225                         // Row already existing, nothing to do
226                         $return = true;
227                 } else {
228                         $return = DBA::insert('group_member', ['gid' => $gid, 'contact-id' => $cid]);
229                 }
230
231                 return $return;
232         }
233
234         /**
235          * @brief Removes a contact from a group
236          *
237          * @param int $gid
238          * @param int $cid
239          * @return boolean
240          */
241         public static function removeMember($gid, $cid)
242         {
243                 if (!$gid || !$cid) {
244                         return false;
245                 }
246
247                 $return = DBA::delete('group_member', ['gid' => $gid, 'contact-id' => $cid]);
248
249                 return $return;
250         }
251
252         /**
253          * @brief Removes a contact from a group based on its name
254          *
255          * @deprecated Use Group::removeMember instead
256          *
257          * @param int $uid
258          * @param string $name
259          * @param int $cid
260          * @return boolean
261          */
262         public static function removeMemberByName($uid, $name, $cid)
263         {
264                 $gid = self::getIdByName($uid, $name);
265
266                 $return = self::removeMember($gid, $cid);
267
268                 return $return;
269         }
270
271         /**
272          * @brief Returns the combined list of contact ids from a group id list
273          *
274          * @param array $group_ids
275          * @param boolean $check_dead
276          * @param boolean $use_gcontact
277          * @return array
278          */
279         public static function expand($group_ids, $check_dead = false, $use_gcontact = false)
280         {
281                 if (!is_array($group_ids) || !count($group_ids)) {
282                         return [];
283                 }
284
285                 $condition = '`gid` IN (' . substr(str_repeat("?, ", count($group_ids)), 0, -2) . ')';
286                 if ($use_gcontact) {
287                         $sql = 'SELECT `gcontact`.`id` AS `contact-id` FROM `group_member`
288                                         INNER JOIN `contact` ON `contact`.`id` = `group_member`.`contact-id`
289                                         INNER JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
290                                 WHERE ' . $condition;
291                         $param_arr = array_merge([$sql], $group_ids);
292                         $stmt = call_user_func_array('dba::p', $param_arr);
293                 } else {
294                         $condition_array = array_merge([$condition], $group_ids);
295                         $stmt = DBA::select('group_member', ['contact-id'], $condition_array);
296                 }
297
298                 $return = [];
299                 while($group_member = DBA::fetch($stmt)) {
300                         $return[] = $group_member['contact-id'];
301                 }
302
303                 if ($check_dead && !$use_gcontact) {
304                         Contact::pruneUnavailable($return);
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          */
317         public static function displayGroupSelection($uid, $gid = 0, $label = '')
318         {
319                 $o = '';
320
321                 $stmt = DBA::select('group', [], ['deleted' => 0, 'uid' => $uid], ['order' => ['name']]);
322
323                 $display_groups = [
324                         [
325                                 'name' => '',
326                                 'id' => '0',
327                                 'selected' => ''
328                         ]
329                 ];
330                 while ($group = DBA::fetch($stmt)) {
331                         $display_groups[] = [
332                                 'name' => $group['name'],
333                                 'id' => $group['id'],
334                                 'selected' => $gid == $group['id'] ? 'true' : ''
335                         ];
336                 }
337                 logger('groups: ' . print_r($display_groups, true));
338
339                 if ($label == '') {
340                         $label = L10n::t('Default privacy group for new contacts');
341                 }
342
343                 $o = replace_macros(get_markup_template('group_selection.tpl'), [
344                         '$label' => $label,
345                         '$groups' => $display_groups
346                 ]);
347                 return $o;
348         }
349
350         /**
351          * @brief Create group sidebar widget
352          *
353          * @param string $every
354          * @param string $each
355          * @param string $editmode
356          *      'standard' => include link 'Edit groups'
357          *      'extended' => include link 'Create new group'
358          *      'full' => include link 'Create new group' and provide for each group a link to edit this group
359          * @param int $group_id
360          * @param int $cid
361          * @return string
362          */
363         public static function sidebarWidget($every = 'contacts', $each = 'group', $editmode = 'standard', $group_id = '', $cid = 0)
364         {
365                 $o = '';
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                 $tpl = get_markup_template('group_side.tpl');
411                 $o = replace_macros($tpl, [
412                         '$add' => L10n::t('add'),
413                         '$title' => L10n::t('Groups'),
414                         '$groups' => $display_groups,
415                         'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
416                         'grouppage' => 'group/',
417                         '$edittext' => L10n::t('Edit group'),
418                         '$ungrouped' => $every === 'contacts' ? L10n::t('Contacts not in any group') : '',
419                         '$ungrouped_selected' => (($group_id === 'none') ? 'group-selected' : ''),
420                         '$createtext' => L10n::t('Create a new group'),
421                         '$creategroup' => L10n::t('Group Name: '),
422                         '$editgroupstext' => L10n::t('Edit groups'),
423                         '$form_security_token' => get_form_security_token('group_edit'),
424                 ]);
425
426
427                 return $o;
428         }
429 }