Completed
Push — master ( a7cf71...06c6ea )
by Craig
06:43
created

AdminController::adduserAction()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the Zikula package.
5
 *
6
 * Copyright Zikula Foundation - http://zikula.org/
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Zikula\GroupsModule\Controller;
13
14
use ModUtil;
15
use UserUtil;
16
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
20
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
22
use Zikula\Core\Controller\AbstractController;
23
use Zikula\GroupsModule\Entity\GroupEntity;
24
use Zikula\GroupsModule\Form\Type\ManageApplicationType;
25
use Zikula\GroupsModule\Form\Type\RemoveUserType;
26
use Zikula\ThemeModule\Engine\Annotation\Theme;
27
28
/**
29
 * @Route("/admin")
30
 *
31
 * Administrative controllers for the groups module
32
 */
33
class AdminController extends AbstractController
34
{
35
    /**
36
     * @Route("/membership/{gid}/{letter}/{startNum}", requirements={"gid" = "^[1-9]\d*$", "letter" = "[a-zA-Z]|\*", "startNum" = "\d+"})
37
     */
38
    public function groupmembershipAction($gid = 0, $letter = '*', $startNum = 0)
39
    {
40
        @trigger_error('This method is deprecated. Please use MembershipAdministrationController::listAction', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
41
42
        return $this->redirectToRoute('zikulagroupsmodule_membershipadministration_list', ['gid' => $gid, 'letter' => $letter, 'startNum' => $startNum]);
43
    }
44
45
    /**
46
     * @Route("/adduser/{uid}/{gid}/{csrfToken}", requirements={"gid" = "^[1-9]\d*$", "uid" = "^[1-9]\d*$"})
47
     */
48
    public function adduserAction($uid, $gid, $csrfToken)
49
    {
50
        @trigger_error('This method is deprecated. Please use MembershipAdministrationController::addAction', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
51
52
        return $this->redirectToRoute('zikulagroupsmodule_membershipadministration_add', ['uid' => $uid, 'gid' => $gid, 'csrfToken' => $csrfToken]);
53
    }
54
55
    /**
56
     * @Route("/removeuser/{gid}/{uid}", requirements={"gid" = "^[1-9]\d*$", "uid" = "^[1-9]\d*$"})
57
     */
58
    public function removeuserAction(Request $request, $gid = 0, $uid = 0)
59
    {
60
        @trigger_error('This method is deprecated. Please use MembershipAdministrationController::addAction', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
61
62
        return $this->redirectToRoute('zikulagroupsmodule_membershipadministration_remove', ['uid' => $uid, 'gid' => $gid, 'request' => $request]);
63
    }
64
65
    /**
66
     * @Route("/pendingusers/{action}/{userid}/{gid}", requirements={"action" = "deny|accept", "userid" = "^[1-9]\d*$", "gid" = "^[1-9]\d*$"})
67
     * @Theme("admin")
68
     * @Template
69
     *
70
     * display a list of group applications
71
     *
72
     * @param Request $request
73
     * @param string  $action  Name of desired action
74
     * @param int     $userid  Id of the user
75
     * @param int     $gid     Id of the group
76
     *
77
     * @return Response symfony response object
78
     *
79
     * @throws \InvalidArgumentException Thrown if either the gid or userid parameters are not provided or
80
     *                                          if the action parameter isn't one of 'deny' or 'accept'
81
     * @throws \RuntimeException Thrown if the requested action couldn't be carried out
82
     */
83
    public function userpendingAction(Request $request, $action = 'accept', $userid = 0, $gid = 0)
84
    {
85
        if ($gid < 1 || $userid < 1) {
86
            throw new \InvalidArgumentException($this->__('Invalid Group ID or User ID.'));
87
        }
88
89
        $group = ModUtil::apiFunc('ZikulaGroupsModule', 'user', 'get', ['gid' => $gid]);
90
        if (!$group) {
91
            throw new NotFoundHttpException($this->__('Sorry! No such group found.'));
92
        }
93
94
        $appInfo = ModUtil::apiFunc('ZikulaGroupsModule', 'admin', 'getapplicationinfo', ['gid' => $gid, 'userid' => $userid]);
95
96
        $formValues = [
97
            'gid' => $gid,
98
            'userid' => $userid,
99
            'action' => $action,
100
            'userName' => UserUtil::getVar('uname', $userid),
101
            'application' => $appInfo['application']
102
        ];
103
        if ($action == 'deny') {
104
            $formValues['reason'] = $this->__('Sorry! This is a message to inform you with regret that your application for membership of the aforementioned private group has been rejected.');
105
        }
106
107
        $form = $this->createForm(ManageApplicationType::class, $formValues, [
108
            'translator' => $this->get('translator.default')
109
        ]);
110
111
        if ($form->handleRequest($request)->isValid()) {
112
            if ($form->get('save')->isClicked()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
113
                $formData = $form->getData();
114
115
                $sendtag = isset($formData['sendtag']) ? $formData['sendtag'] : 0;
116
                $reason = isset($formData['reason']) ? $formData['reason'] : '';
117
118
                $reasonTitle = '';
119
                if ($action == 'deny') {
120
                    $reasonTitle = $this->__f('Concerning your %s group membership application', ['%s' => $group['name']]);
121
                    if (empty($reason)) {
122
                        // Get Default TEXT
123
                        $reason = $this->__('Sorry! This is a message to inform you with regret that your application for membership of the aforementioned private group has been rejected.');
124
                    }
125
                } elseif ($action == 'accept') {
126
                    $reasonTitle = $this->__f('Done! The user has been added to the %s group.', ['%s' => $group['name']]);
127
                    if (empty($reason)) {
128
                        // Get Default TEXT
129
                        $reason = $this->__('Done! Your application has been accepted. You have been granted all the privileges assigned to the group of which you are now member.');
130
                    }
131
                }
132
133
                try {
134
                    $result = ModUtil::apiFunc('ZikulaGroupsModule', 'admin', 'pendingaction', [
135
                        'userid'      => $userid,
136
                        'gid'         => $gid,
137
                        'sendtag'     => $sendtag,
138
                        'reason'      => $reason,
139
                        'reasontitle' => $reasonTitle,
140
                        'action'      => $action
141
                    ]);
142
143
                    if (!$result) {
144
                        if ($action == 'deny') {
145
                            $this->addFlash('error', $this->__("Error! Could not execute 'Reject' action."));
146
                        } else {
147
                            $this->addFlash('error', $this->__("Error! Could not execute 'Accept' action."));
148
                        }
149
                    } else {
150
                        if ($action == 'accept') {
151
                            $this->addFlash('status', $this->__('Done! The user was added to the group.'));
152
                        } else {
153
                            $this->addFlash('status', $this->__("Done! The user's application for group membership has been rejected."));
154
                        }
155
                    }
156
                } catch (\RuntimeException $e) {
157
                    $this->addFlash('error', $e->getMessage());
158
                }
159
            }
160
            if ($form->get('cancel')->isClicked()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
161
                $this->addFlash('status', $this->__('Operation cancelled.'));
162
            }
163
164
            return $this->redirectToRoute('zikulagroupsmodule_group_list');
165
        }
166
167
        return [
168
            'form' => $form->createView(),
169
            'action' => $action
170
        ];
171
    }
172
173
    /**
174
     * @Route("")
175
     */
176
    public function indexAction()
177
    {
178
        @trigger_error('This method is deprecated. Please use GroupController::listAction', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
179
180
        return $this->redirectToRoute('zikulagroupsmodule_group_list');
181
    }
182
183
    /**
184
     * @Route("/view/{startnum}", requirements={"startnum" = "\d+"})
185
     */
186
    public function viewAction($startnum = 0)
187
    {
188
        @trigger_error('This method is deprecated. Please use GroupController::listAction', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
189
190
        return $this->redirectToRoute('zikulagroupsmodule_group_list', ['startnum' => $startnum]);
191
    }
192
193
    /**
194
     * @Route("/new")
195
     */
196
    public function newgroupAction(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
197
    {
198
        @trigger_error('This method is deprecated. Please use GroupController::newgroupAction', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
199
200
        return $this->redirectToRoute('zikulagroupsmodule_group_create');
201
    }
202
203
    /**
204
     * @Route("/modify/{gid}", requirements={"gid" = "^[1-9]\d*$"})
205
     */
206
    public function modifyAction(Request $request, GroupEntity $groupEntity)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
207
    {
208
        @trigger_error('This method is deprecated. Please use GroupController::modifyAction', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
209
210
        return $this->redirectToRoute('zikulagroupsmodule_group_edit', ['gid' => $groupEntity->getGid()]);
211
    }
212
213
    /**
214
     * @Route("/delete", requirements={"gid"="\d+"})
215
     */
216
    public function deleteAction(Request $request, GroupEntity $groupEntity)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
217
    {
218
        @trigger_error('This method is deprecated. Please use GroupController::deleteAction', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
219
220
        return $this->redirectToRoute('zikulagroupsmodule_group_remove', ['gid' => $groupEntity->getGid()]);
221
    }
222
223
    /**
224
     * @Route("/config")
225
     */
226
    public function modifyconfigAction()
227
    {
228
        @trigger_error('The zikulagroupsmodule_admin_config route is deprecated. please use zikulagroupsmodule_config_config instead.', E_USER_DEPRECATED);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
229
230
        return $this->redirectToRoute('zikulagroupsmodule_config_config');
231
    }
232
}
233