aboutsummaryrefslogtreecommitdiffhomepage
path: root/main/app/sprinkles/admin/src/Controller/PostController.php
blob: 3b77bfe429f7ea9e11a9867813b117ebc742f130 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
/**
 * UserFrosting (http://www.userfrosting.com)
 *
 * @link      https://github.com/userfrosting/UserFrosting
 * @license   https://github.com/userfrosting/UserFrosting/blob/master/licenses/UserFrosting.md (MIT License)
 */

namespace UserFrosting\Sprinkle\Admin\Controller;

use function GuzzleHttp\Psr7\str;
use UserFrosting\Fortress\RequestDataTransformer;
use UserFrosting\Fortress\RequestSchema;
use UserFrosting\Fortress\ServerSideValidator;
use UserFrosting\Support\Exception\ForbiddenException;
use UserFrosting\Sprinkle\Core\Controller\SimpleController;
use UserFrosting\Support\Exception\BadRequestException;
use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Http\UploadedFile;
use Illuminate\Database\Capsule\Manager as DB;
use UserFrosting\Support\Exception\NotFoundException;

/**
 * Controller class for user-related requests, including listing users, CRUD for users, etc.
 *
 * @author Alex Weissman (https://alexanderweissman.com)
 */
class PostController extends SimpleController
{

    public function showImage(Request $request, Response $response, $args) {
        // check if user is authorized
        $authorizer = $this->ci->authorizer;
        $currentUser = $this->ci->currentUser;
        if (!$authorizer->checkAccess($currentUser, 'view_image')) {
            throw new ForbiddenException();
        }
        $postID = $args['PostID'];

        // get filename from database
        $FileRequestedImage = DB::table('image_posts')
            ->where('PostID', '=', $postID)
            ->value('File');

        if ($FileRequestedImage) {
            $FileType = pathinfo($FileRequestedImage, PATHINFO_EXTENSION);

            // echo image
            $response->write(file_get_contents(__DIR__ . '/../../../../../uploads/' . $FileRequestedImage));
            return $response->withHeader('Content-type', 'image/' . $FileType);
        } else {
            throw new NotFoundException();
        }
    }

    public function postImage(Request $request, Response $response) {
        // check if user is authorized
        $authorizer = $this->ci->authorizer;
        $currentUser = $this->ci->currentUser;
        if (!$authorizer->checkAccess($currentUser, 'post_image')) {
            throw new ForbiddenException();
        }

        $uploadedFiles = $request->getUploadedFiles();
        $uploadedFile = $uploadedFiles['image'];

        if (!strpos($uploadedFile->getClientMediaType(), "mage")) {
            return $response->withStatus(415);
        } else if ($uploadedFile->getError() === 1) {
            return $response->withStatus(406);
        } else if ($uploadedFile->getSize() > 10485760) {
            return $response->withStatus(413);
        } else { // Upload is accepted
            // Move file to upload directory
            $extension = pathinfo($uploadedFile->getClientFilename(), PATHINFO_EXTENSION);
            $basename = bin2hex(random_bytes(8));
            $filename = sprintf('%s.%0.8s', $basename, $extension);
            $uploadedFile->moveTo(__DIR__ . '/../../../../../uploads' . DIRECTORY_SEPARATOR . $filename);

            // Store in Database
            DB::table('image_posts')->insert(
                ['UserID' => $currentUser->id, 'File' => $filename]
            );

            $response->write('Uploaded successfully! <br/>');
        }
    }

    protected function getUserFromParams($params) {
        // Load the request schema
        $schema = new RequestSchema('schema://requests/user/get-by-username.yaml');

        // Whitelist and set parameter defaults
        $transformer = new RequestDataTransformer($schema);
        $data = $transformer->transform($params);

        // Validate, and throw exception on validation errors.
        $validator = new ServerSideValidator($schema, $this->ci->translator);
        if (!$validator->validate($data)) {
            // TODO: encapsulate the communication of error messages from ServerSideValidator to the BadRequestException
            $e = new BadRequestException();
            foreach ($validator->errors() as $idx => $field) {
                foreach ($field as $eidx => $error) {
                    $e->addUserMessage($error);
                }
            }
            throw $e;
        }

        /** @var UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        // Get the user to delete
        $user = $classMapper->staticMethod('user', 'where', 'user_name', $data['user_name'])
            ->first();

        return $user;
    }
}