Issues (3627)

bundles/ApiBundle/Controller/ClientController.php (2 issues)

1
<?php
2
3
/*
4
 * @copyright   2014 Mautic Contributors. All rights reserved
5
 * @author      Mautic
6
 *
7
 * @link        http://mautic.org
8
 *
9
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
10
 */
11
12
namespace Mautic\ApiBundle\Controller;
13
14
use Mautic\CoreBundle\Controller\FormController;
15
use Mautic\CoreBundle\Factory\PageHelperFactoryInterface;
16
use Symfony\Component\HttpFoundation\JsonResponse;
17
use Symfony\Component\HttpFoundation\RedirectResponse;
18
use Symfony\Component\HttpFoundation\Response;
19
20
class ClientController extends FormController
21
{
22
    /**
23
     * Generate's default client list.
24
     *
25
     * @param int $page
26
     *
27
     * @return JsonResponse|Response
28
     */
29
    public function indexAction($page = 1)
30
    {
31
        if (!$this->get('mautic.security')->isGranted('api:clients:view')) {
32
            return $this->accessDenied();
33
        }
34
35
        /** @var PageHelperFactoryInterface $pageHelperFacotry */
36
        $pageHelperFacotry = $this->get('mautic.page.helper.factory');
37
        $pageHelper        = $pageHelperFacotry->make('mautic.client', $page);
38
        $limit             = $pageHelper->getLimit();
39
        $start             = $pageHelper->getStart();
40
        $orderBy           = $this->get('session')->get('mautic.client.orderby', 'c.name');
41
        $orderByDir        = $this->get('session')->get('mautic.client.orderbydir', 'ASC');
42
        $filter            = $this->request->get('search', $this->get('session')->get('mautic.client.filter', ''));
43
        $apiMode           = $this->factory->getRequest()->get('api_mode', $this->get('session')->get('mautic.client.filter.api_mode', 'oauth1a'));
44
        $this->get('session')->set('mautic.client.filter.api_mode', $apiMode);
45
        $this->get('session')->set('mautic.client.filter', $filter);
46
47
        $clients = $this->getModel('api.client')->getEntities(
48
            [
49
                'start'      => $start,
50
                'limit'      => $limit,
51
                'filter'     => $filter,
52
                'orderBy'    => $orderBy,
53
                'orderByDir' => $orderByDir,
54
            ]
55
        );
56
57
        $count = count($clients);
58
        if ($count && $count < ($start + 1)) {
59
            $lastPage  = $pageHelper->countPage($count);
60
            $returnUrl = $this->generateUrl('mautic_client_index', ['page' => $lastPage]);
61
            $pageHelper->rememberPage($lastPage);
62
63
            return $this->postActionRedirect(
64
                [
65
                    'returnUrl'       => $returnUrl,
66
                    'viewParameters'  => ['page' => $lastPage],
67
                    'contentTemplate' => 'MauticApiBundle:Client:index',
68
                    'passthroughVars' => [
69
                        'activeLink'    => 'mautic_client_index',
70
                        'mauticContent' => 'client',
71
                    ],
72
                ]
73
            );
74
        }
75
76
        $pageHelper->rememberPage($page);
77
78
        // filters
79
        $filters = [];
80
81
        // api options
82
        $apiOptions           = [];
83
        $apiOptions['oauth1'] = 'OAuth 1';
84
        $apiOptions['oauth2'] = 'OAuth 2';
85
        $filters['api_mode']  = [
86
            'values'  => [$apiMode],
87
            'options' => $apiOptions,
88
        ];
89
90
        return $this->delegateView(
91
            [
92
                'viewParameters'  => [
93
                    'items'       => $clients,
94
                    'page'        => $page,
95
                    'limit'       => $limit,
96
                    'permissions' => [
97
                        'create' => $this->get('mautic.security')->isGranted('api:clients:create'),
98
                        'edit'   => $this->get('mautic.security')->isGranted('api:clients:editother'),
99
                        'delete' => $this->get('mautic.security')->isGranted('api:clients:deleteother'),
100
                    ],
101
                    'tmpl'        => $this->request->isXmlHttpRequest() ? $this->request->get('tmpl', 'index') : 'index',
102
                    'searchValue' => $filter,
103
                    'filters'     => $filters,
104
                ],
105
                'contentTemplate' => 'MauticApiBundle:Client:list.html.php',
106
                'passthroughVars' => [
107
                    'route'         => $this->generateUrl('mautic_client_index', ['page' => $page]),
108
                    'mauticContent' => 'client',
109
                ],
110
            ]
111
        );
112
    }
113
114
    /**
115
     * @return Response
116
     */
117
    public function authorizedClientsAction()
118
    {
119
        $me      = $this->get('security.token_storage')->getToken()->getUser();
120
        $clients = $this->getModel('api.client')->getUserClients($me);
121
122
        return $this->render('MauticApiBundle:Client:authorized.html.php', ['clients' => $clients]);
123
    }
124
125
    /**
126
     * @param int $clientId
127
     *
128
     * @return JsonResponse|RedirectResponse
129
     */
130
    public function revokeAction($clientId)
131
    {
132
        $success = 0;
133
        $flashes = [];
134
135
        if ('POST' == $this->request->getMethod()) {
136
            /** @var \Mautic\ApiBundle\Model\ClientModel $model */
137
            $model = $this->getModel('api.client');
138
139
            $client = $model->getEntity($clientId);
140
141
            if (null === $client) {
142
                $flashes[] = [
143
                    'type'    => 'error',
144
                    'msg'     => 'mautic.api.client.error.notfound',
145
                    'msgVars' => ['%id%' => $clientId],
146
                ];
147
            } else {
148
                $name = $client->getName();
149
150
                $model->revokeAccess($client);
151
152
                $flashes[] = [
153
                    'type'    => 'notice',
154
                    'msg'     => 'mautic.api.client.notice.revoked',
155
                    'msgVars' => [
156
                        '%name%' => $name,
157
                    ],
158
                ];
159
            }
160
        }
161
162
        return $this->postActionRedirect(
163
            [
164
                'returnUrl'       => $this->generateUrl('mautic_user_account'),
165
                'contentTemplate' => 'MauticUserBundle:Profile:index',
166
                'passthroughVars' => [
167
                    'success' => $success,
168
                ],
169
                'flashes' => $flashes,
170
            ]
171
        );
172
    }
173
174
    /**
175
     * @param mixed $objectId
176
     *
177
     * @return array|JsonResponse|RedirectResponse|Response
178
     */
179
    public function newAction($objectId = 0)
180
    {
181
        if (!$this->get('mautic.security')->isGranted('api:clients:create')) {
182
            return $this->accessDenied();
183
        }
184
185
        $apiMode = (0 === $objectId) ? $this->get('session')->get('mautic.client.filter.api_mode', 'oauth1a') : $objectId;
186
        $this->get('session')->set('mautic.client.filter.api_mode', $apiMode);
187
188
        /** @var \Mautic\ApiBundle\Model\ClientModel $model */
189
        $model = $this->getModel('api.client');
190
        $model->setApiMode($apiMode);
191
192
        //retrieve the entity
193
        $client = $model->getEntity();
194
195
        //set the return URL for post actions
196
        $returnUrl = $this->generateUrl('mautic_client_index');
197
198
        //get the user form factory
199
        $action = $this->generateUrl('mautic_client_action', ['objectAction' => 'new']);
200
        $form   = $model->createForm($client, $this->get('form.factory'), $action);
201
202
        //remove the client id and secret fields as they'll be auto generated
203
        $form->remove('randomId');
204
        $form->remove('secret');
205
        $form->remove('publicId');
206
        $form->remove('consumerKey');
207
        $form->remove('consumerSecret');
208
209
        ///Check for a submitted form and process it
210
        if ('POST' == $this->request->getMethod()) {
211
            $valid = false;
212
            if (!$cancelled = $this->isFormCancelled($form)) {
213
                if ($valid = $this->isFormValid($form)) {
214
                    //form is valid so process the data
215
                    $model->saveEntity($client);
216
                    $this->addFlash(
0 ignored issues
show
Deprecated Code introduced by
The function Mautic\CoreBundle\Contro...nController::addFlash() has been deprecated: Will be removed in Mautic 3.0. Use CommonController::flashBag->addFlash() instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

216
                    /** @scrutinizer ignore-deprecated */ $this->addFlash(

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
217
                        'mautic.api.client.notice.created',
218
                        [
219
                            '%name%'         => $client->getName(),
220
                            '%clientId%'     => $client->getPublicId(),
221
                            '%clientSecret%' => $client->getSecret(),
222
                            '%url%'          => $this->generateUrl(
223
                                'mautic_client_action',
224
                                [
225
                                    'objectAction' => 'edit',
226
                                    'objectId'     => $client->getId(),
227
                                ]
228
                            ),
229
                        ]
230
                    );
231
                }
232
            }
233
234
            if ($cancelled || ($valid && $form->get('buttons')->get('save')->isClicked())) {
235
                return $this->postActionRedirect(
236
                    [
237
                        'returnUrl'       => $returnUrl,
238
                        'contentTemplate' => 'MauticApiBundle:Client:index',
239
                        'passthroughVars' => [
240
                            'activeLink'    => '#mautic_client_index',
241
                            'mauticContent' => 'client',
242
                        ],
243
                    ]
244
                );
245
            } elseif ($valid && !$cancelled) {
246
                return $this->editAction($client->getId(), true);
247
            }
248
        }
249
250
        return $this->delegateView(
251
            [
252
                'viewParameters' => [
253
                    'form' => $form->createView(),
254
                    'tmpl' => $this->request->get('tmpl', 'form'),
255
                ],
256
                'contentTemplate' => 'MauticApiBundle:Client:form.html.php',
257
                'passthroughVars' => [
258
                    'activeLink'    => '#mautic_client_new',
259
                    'route'         => $action,
260
                    'mauticContent' => 'client',
261
                ],
262
            ]
263
        );
264
    }
265
266
    /**
267
     * Generates edit form and processes post data.
268
     *
269
     * @param int  $objectId
270
     * @param bool $ignorePost
271
     *
272
     * @return JsonResponse|RedirectResponse|Response
273
     */
274
    public function editAction($objectId, $ignorePost = false)
275
    {
276
        if (!$this->get('mautic.security')->isGranted('api:clients:editother')) {
277
            return $this->accessDenied();
278
        }
279
280
        /** @var \Mautic\ApiBundle\Model\ClientModel $model */
281
        $model     = $this->getModel('api.client');
282
        $client    = $model->getEntity($objectId);
283
        $returnUrl = $this->generateUrl('mautic_client_index');
284
285
        $postActionVars = [
286
            'returnUrl'       => $returnUrl,
287
            'contentTemplate' => 'MauticApiBundle:Client:index',
288
            'passthroughVars' => [
289
                'activeLink'    => '#mautic_client_index',
290
                'mauticContent' => 'client',
291
            ],
292
        ];
293
294
        //client not found
295
        if (null === $client) {
296
            return $this->postActionRedirect(
297
                array_merge(
298
                    $postActionVars,
299
                    [
300
                        'flashes' => [
301
                            [
302
                                'type'    => 'error',
303
                                'msg'     => 'mautic.api.client.error.notfound',
304
                                'msgVars' => ['%id%' => $objectId],
305
                            ],
306
                        ],
307
                    ]
308
                )
309
            );
310
        } elseif ($model->isLocked($client)) {
311
            //deny access if the entity is locked
312
            return $this->isLocked($postActionVars, $client, 'api.client');
313
        }
314
315
        $action = $this->generateUrl('mautic_client_action', ['objectAction' => 'edit', 'objectId' => $objectId]);
316
        $form   = $model->createForm($client, $this->get('form.factory'), $action);
317
318
        // remove api_mode field
319
        $form->remove('api_mode');
320
321
        ///Check for a submitted form and process it
322
        if (!$ignorePost && 'POST' == $this->request->getMethod()) {
323
            if (!$cancelled = $this->isFormCancelled($form)) {
324
                if ($valid = $this->isFormValid($form)) {
325
                    //form is valid so process the data
326
                    $model->saveEntity($client, $form->get('buttons')->get('save')->isClicked());
327
                    $this->addFlash(
0 ignored issues
show
Deprecated Code introduced by
The function Mautic\CoreBundle\Contro...nController::addFlash() has been deprecated: Will be removed in Mautic 3.0. Use CommonController::flashBag->addFlash() instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

327
                    /** @scrutinizer ignore-deprecated */ $this->addFlash(

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
328
                        'mautic.core.notice.updated',
329
                        [
330
                            '%name%'      => $client->getName(),
331
                            '%menu_link%' => 'mautic_client_index',
332
                            '%url%'       => $this->generateUrl(
333
                                'mautic_client_action',
334
                                [
335
                                    'objectAction' => 'edit',
336
                                    'objectId'     => $client->getId(),
337
                                ]
338
                            ),
339
                        ]
340
                    );
341
342
                    if ($form->get('buttons')->get('save')->isClicked()) {
343
                        return $this->postActionRedirect($postActionVars);
344
                    }
345
                }
346
            } else {
347
                //unlock the entity
348
                $model->unlockEntity($client);
349
350
                return $this->postActionRedirect($postActionVars);
351
            }
352
        } else {
353
            //lock the entity
354
            $model->lockEntity($client);
355
        }
356
357
        return $this->delegateView(
358
            [
359
                'viewParameters' => [
360
                    'form' => $form->createView(),
361
                    'tmpl' => $this->request->get('tmpl', 'form'),
362
                ],
363
                'contentTemplate' => 'MauticApiBundle:Client:form.html.php',
364
                'passthroughVars' => [
365
                    'activeLink'    => '#mautic_client_index',
366
                    'route'         => $action,
367
                    'mauticContent' => 'client',
368
                ],
369
            ]
370
        );
371
    }
372
373
    /**
374
     * Deletes the entity.
375
     *
376
     * @param int $objectId
377
     *
378
     * @return JsonResponse|RedirectResponse
379
     */
380
    public function deleteAction($objectId)
381
    {
382
        if (!$this->get('mautic.security')->isGranted('api:clients:delete')) {
383
            return $this->accessDenied();
384
        }
385
386
        $returnUrl = $this->generateUrl('mautic_client_index');
387
        $success   = 0;
388
        $flashes   = [];
389
390
        $postActionVars = [
391
            'returnUrl'       => $returnUrl,
392
            'contentTemplate' => 'MauticApiBundle:Client:index',
393
            'passthroughVars' => [
394
                'activeLink'    => '#mautic_client_index',
395
                'success'       => $success,
396
                'mauticContent' => 'client',
397
            ],
398
        ];
399
400
        if ('POST' == $this->request->getMethod()) {
401
            /** @var \Mautic\ApiBundle\Model\ClientModel $model */
402
            $model  = $this->getModel('api.client');
403
            $entity = $model->getEntity($objectId);
404
            if (null === $entity) {
405
                $flashes[] = [
406
                    'type'    => 'error',
407
                    'msg'     => 'mautic.api.client.error.notfound',
408
                    'msgVars' => ['%id%' => $objectId],
409
                ];
410
            } elseif ($model->isLocked($entity)) {
411
                //deny access if the entity is locked
412
                return $this->isLocked($postActionVars, $entity, 'api.client');
413
            } else {
414
                $model->deleteEntity($entity);
415
                $name      = $entity->getName();
416
                $flashes[] = [
417
                    'type'    => 'notice',
418
                    'msg'     => 'mautic.core.notice.deleted',
419
                    'msgVars' => [
420
                        '%name%' => $name,
421
                        '%id%'   => $objectId,
422
                    ],
423
                ];
424
            }
425
        }
426
427
        return $this->postActionRedirect(
428
            array_merge(
429
                $postActionVars,
430
                [
431
                    'flashes' => $flashes,
432
                ]
433
            )
434
        );
435
    }
436
}
437