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