]> git.mxchange.org Git - friendica.git/blob - src/Model/Group.php
Implement parts of the list API:
[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\DBM;
10 use dba;
11
12 require_once 'boot.php';
13 require_once 'include/dba.php';
14 require_once 'include/text.php';
15
16 /**
17  * @brief functions for interacting with the group database table
18  */
19 class Group extends BaseObject
20 {
21         /**
22          * @brief Create a new contact group
23          *
24          * Note: If we found a deleted group with the same name, we restore it
25          *
26          * @param int $uid
27          * @param string $name
28          * @return boolean
29          */
30         public static function create($uid, $name)
31         {
32                 $return = false;
33                 if (x($uid) && x($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 (DBM::is_result($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          */
65         public static function update($id, $name)
66         {
67                 return dba::update('group', ['name' => $name], ['id' => $id]);
68         }
69
70         /**
71          * @brief Get a list of group ids a contact belongs to
72          *
73          * @param int $cid
74          * @return array
75          */
76         public static function getIdsByContactId($cid)
77         {
78                 $condition = ['contact-id' => $cid];
79                 $stmt = dba::select('group_member', ['gid'], $condition);
80
81                 $return = [];
82
83                 while ($group = dba::fetch($stmt)) {
84                         $return[] = $group['gid'];
85                 }
86
87                 return $return;
88         }
89
90         /**
91          * @brief count unread group items
92          *
93          * Count unread items of each groups of the local user
94          *
95          * @return array
96          *      'id' => group id
97          *      'name' => group name
98          *      'count' => counted unseen group items
99          */
100         public static function countUnseen()
101         {
102                 $stmt = dba::p("SELECT `group`.`id`, `group`.`name`,
103                                 (SELECT COUNT(*) FROM `item` FORCE INDEX (`uid_unseen_contactid`)
104                                         WHERE `uid` = ?
105                                         AND `unseen`
106                                         AND `contact-id` IN
107                                                 (SELECT `contact-id`
108                                                 FROM `group_member`
109                                                 WHERE `group_member`.`gid` = `group`.`id`)
110                                         ) AS `count`
111                                 FROM `group`
112                                 WHERE `group`.`uid` = ?;",
113                         local_user(),
114                         local_user()
115                 );
116
117                 return dba::inArray($stmt);
118         }
119
120         /**
121          * @brief Get the group id for a user/name couple
122          *
123          * Returns false if no group has been found.
124          *
125          * @param int $uid
126          * @param string $name
127          * @return int|boolean
128          */
129         public static function getIdByName($uid, $name)
130         {
131                 if (!$uid || !strlen($name)) {
132                         return false;
133                 }
134
135                 $group = dba::selectFirst('group', ['id'], ['uid' => $uid, 'name' => $name]);
136                 if (DBM::is_result($group)) {
137                         return $group['id'];
138                 }
139
140                 return false;
141         }
142
143         /**
144          * @brief Mark a group as deleted
145          *
146          * @param int $gid
147          * @return boolean
148          */
149         public static function remove($gid) {
150                 if (! $gid) {
151                         return false;
152                 }
153
154                 $group = dba::selectFirst('group', ['uid'], ['id' => $gid]);
155                 if (!DBM::is_result($group)) {
156                         return false;
157                 }
158
159                 // remove group from default posting lists
160                 $user = dba::selectFirst('user', ['def_gid', 'allow_gid', 'deny_gid'], ['uid' => $group['uid']]);
161                 if (DBM::is_result($user)) {
162                         $change = false;
163
164                         if ($user['def_gid'] == $gid) {
165                                 $user['def_gid'] = 0;
166                                 $change = true;
167                         }
168                         if (strpos($user['allow_gid'], '<' . $gid . '>') !== false) {
169                                 $user['allow_gid'] = str_replace('<' . $gid . '>', '', $user['allow_gid']);
170                                 $change = true;
171                         }
172                         if (strpos($user['deny_gid'], '<' . $gid . '>') !== false) {
173                                 $user['deny_gid'] = str_replace('<' . $gid . '>', '', $user['deny_gid']);
174                                 $change = true;
175                         }
176
177                         if ($change) {
178                                 dba::update('user', $user, ['uid' => $group['uid']]);
179                         }
180                 }
181
182                 // remove all members
183                 dba::delete('group_member', ['gid' => $gid]);
184
185                 // remove group
186                 $return = dba::update('group', ['deleted' => 1], ['id' => $gid]);
187
188                 return $return;
189         }
190
191         /**
192          * @brief Mark a group as deleted based on its name
193          *
194          * @deprecated Use Group::remove instead
195          *
196          * @param int $uid
197          * @param string $name
198          * @return bool
199          */
200         public static function removeByName($uid, $name) {
201                 $return = false;
202                 if (x($uid) && x($name)) {
203                         $gid = self::getIdByName($uid, $name);
204
205                         $return = self::remove($gid);
206                 }
207
208                 return $return;
209         }
210
211         /**
212          * @brief Adds a contact to a group
213          *
214          * @param int $gid
215          * @param int $cid
216          * @return boolean
217          */
218         public static function addMember($gid, $cid)
219         {
220                 if (!$gid || !$cid) {
221                         return false;
222                 }
223
224                 $row_exists = dba::exists('group_member', ['gid' => $gid, 'contact-id' => $cid]);
225                 if ($row_exists) {
226                         // Row already existing, nothing to do
227                         $return = true;
228                 } else {
229                         $return = dba::insert('group_member', ['gid' => $gid, 'contact-id' => $cid]);
230                 }
231
232                 return $return;
233         }
234
235         /**
236          * @brief Removes a contact from a group
237          *
238          * @param int $gid
239          * @param int $cid
240          * @return boolean
241          */
242         public static function removeMember($gid, $cid)
243         {
244                 if (!$gid || !$cid) {
245                         return false;
246                 }
247
248                 $return = dba::delete('group_member', ['gid' => $gid, 'contact-id' => $cid]);
249
250                 return $return;
251         }
252
253         /**
254          * @brief Removes a contact from a group based on its name
255          *
256          * @deprecated Use Group::removeMember instead
257          *
258          * @param int $uid
259          * @param string $name
260          * @param int $cid
261          * @return boolean
262          */
263         public static function removeMemberByName($uid, $name, $cid)
264         {
265                 $gid = self::getIdByName($uid, $name);
266
267                 $return = self::removeMember($gid, $cid);
268
269                 return $return;
270         }
271
272         /**
273          * @brief Returns the combined list of contact ids from a group id list
274          *
275          * @param array $group_ids
276          * @param boolean $check_dead
277          * @param boolean $use_gcontact
278          * @return array
279          */
280         public static function expand($group_ids, $check_dead = false, $use_gcontact = false)
281         {
282                 if (!is_array($group_ids) || !count($group_ids)) {
283                         return [];
284                 }
285
286                 $condition = '`gid` IN (' . substr(str_repeat("?, ", count($group_ids)), 0, -2) . ')';
287                 if ($use_gcontact) {
288                         $sql = 'SELECT `gcontact`.`id` AS `contact-id` FROM `group_member`
289                                         INNER JOIN `contact` ON `contact`.`id` = `group_member`.`contact-id`
290                                         INNER JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
291                                 WHERE ' . $condition;
292                         $param_arr = array_merge([$sql], $group_ids);
293                         $stmt = call_user_func_array('dba::p', $param_arr);
294                 } else {
295                         $condition_array = array_merge([$condition], $group_ids);
296                         $stmt = dba::select('group_member', ['contact-id'], $condition_array);
297                 }
298
299                 $return = [];
300                 while($group_member = dba::fetch($stmt)) {
301                         $return[] = $group_member['contact-id'];
302                 }
303
304                 if ($check_dead && !$use_gcontact) {
305                         Contact::pruneUnavailable($return);
306                 }
307                 return $return;
308         }
309
310         /**
311          * @brief Returns a templated group selection list
312          *
313          * @param int $uid
314          * @param int $gid An optional pre-selected group
315          * @param string $label An optional label of the list
316          * @return string
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('groups: ' . print_r($display_groups, true));
339
340                 if ($label == '') {
341                         $label = L10n::t('Default privacy group for new contacts');
342                 }
343
344                 $o = replace_macros(get_markup_template('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 int $group_id
361          * @param int $cid
362          * @return string
363          */
364         public static function sidebarWidget($every = 'contacts', $each = 'group', $editmode = 'standard', $group_id = 0, $cid = 0)
365         {
366                 $o = '';
367
368                 if (!local_user()) {
369                         return '';
370                 }
371
372                 $display_groups = [
373                         [
374                                 'text' => L10n::t('Everybody'),
375                                 'id' => 0,
376                                 'selected' => (($group_id == 0) ? 'group-selected' : ''),
377                                 'href' => $every,
378                         ]
379                 ];
380
381                 $stmt = dba::select('group', [], ['deleted' => 0, 'uid' => local_user()], ['order' => ['name']]);
382
383                 $member_of = [];
384                 if ($cid) {
385                         $member_of = self::getIdsByContactId($cid);
386                 }
387
388                 while ($group = dba::fetch($stmt)) {
389                         $selected = (($group_id == $group['id']) ? ' group-selected' : '');
390
391                         if ($editmode == 'full') {
392                                 $groupedit = [
393                                         'href' => 'group/' . $group['id'],
394                                         'title' => L10n::t('edit'),
395                                 ];
396                         } else {
397                                 $groupedit = null;
398                         }
399
400                         $display_groups[] = [
401                                 'id'   => $group['id'],
402                                 'cid'  => $cid,
403                                 'text' => $group['name'],
404                                 'href' => $each . '/' . $group['id'],
405                                 'edit' => $groupedit,
406                                 'selected' => $selected,
407                                 'ismember' => in_array($group['id'], $member_of),
408                         ];
409                 }
410
411                 $tpl = get_markup_template('group_side.tpl');
412                 $o = replace_macros($tpl, [
413                         '$add' => L10n::t('add'),
414                         '$title' => L10n::t('Groups'),
415                         '$groups' => $display_groups,
416                         'newgroup' => $editmode == 'extended' || $editmode == 'full' ? 1 : '',
417                         'grouppage' => 'group/',
418                         '$edittext' => L10n::t('Edit group'),
419                         '$ungrouped' => $every === 'contacts' ? L10n::t('Contacts not in any group') : '',
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 }