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