Completed
Push — master ( 8dbf53...6f2da7 )
by Andreas
17:26
created

midcom_core_urlmethods::invalidate_cache()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 17
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 12
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 17
ccs 0
cts 16
cp 0
crap 12
rs 9.8666
1
<?php
2
/**
3
 * @package midcom
4
 * @author CONTENT CONTROL http://www.contentcontrol-berlin.de/
5
 * @copyright CONTENT CONTROL http://www.contentcontrol-berlin.de/
6
 * @license http://www.gnu.org/licenses/gpl.html GNU General Public License
7
 */
8
9
use Symfony\Component\HttpFoundation\StreamedResponse;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\BinaryFileResponse;
12
use midgard\portable\api\blob;
13
use Symfony\Component\HttpFoundation\Response;
14
15
/**
16
 * MidCOM URL methods.
17
 *
18
 * See individual methods for documentation.
19
 *
20
 * @package midcom
21
 */
22
class midcom_core_urlmethods
23
{
24
    public function process_config() : Response
25
    {
26
        return new StreamedResponse(function() {
27
            midcom::get()->style->show_midcom('config-test');
28
        });
29
    }
30
31
    /**
32
     * This method will serve the attachment denoted by the given ID/GUID.
33
     * It should enable caching of browsers for Navigation images and so on.
34
     *
35
     * @param string $guid
36
     * @throws midcom_error_notfound
37
     */
38
    public function process_serveattachmentguid(Request $request, $guid) : Response
39
    {
40
        $attachment = new midcom_db_attachment($guid);
41
        if (!$attachment->can_do('midgard:autoserve_attachment')) {
42
            throw new midcom_error_notfound('Failed to access attachment: Autoserving denied.');
43
        }
44
45
        // Doublecheck that this is registered
46
        midcom::get()->cache->content->register($attachment->guid);
47
48
        $blob = new blob($attachment->__object);
49
        $response = new BinaryFileResponse($blob->get_path());
50
        $last_modified = (int) $response->getLastModified()->format('U');
51
        $etag = md5("{$last_modified}{$attachment->name}{$attachment->mimetype}{$attachment->guid}");
52
        $response->setEtag($etag);
53
54
        if (!$response->isNotModified($request)) {
55
            $response->prepare($request);
56
57
            if (midcom::get()->config->get('attachment_xsendfile_enable')) {
58
                BinaryFileResponse::trustXSendfileTypeHeader();
59
                $response->headers->set('X-Sendfile-Type', 'X-Sendfile');
60
            }
61
        }
62
        midcom::get()->cache->content->cache_control_headers($response);
63
        // Store metadata in cache so _check_hit() can help us
64
        midcom::get()->cache->content->write_meta_cache('A-' . $etag, $request, $response);
65
        return $response;
66
    }
67
68
    /**
69
     * This will resolve the given GUID into the MidCOM NAP tree, relocating to the
70
     * URL corresponding to the node/leaf. The Permalink can be created by using the
71
     * key MIDCOM_NAV_PERMALINK of any NAP data array. Upon resolving it, MidCOM will
72
     * relocate to the automatically computed MIDCOM_NAV_FULLURL.
73
     *
74
     * @param string $guid
75
     * @throws midcom_error_notfound
76
     */
77
    public function process_permalink(string $guid) : Response
78
    {
79
        $destination = midcom::get()->permalinks->resolve_permalink($guid);
80
        if ($destination === null) {
81
            throw new midcom_error_notfound("This Permalink is unknown.");
82
        }
83
84
        // We use "302 Found" here so that search engines and others will keep using the PermaLink instead of the temporary
85
        return new midcom_response_relocate($destination, 302);
86
    }
87
88
    /**
89
     * will clear the cache of the current site
90
     */
91
    public function invalidate_cache(Request $request)
92
    {
93
        if (!in_array($request->getClientIp(), midcom::get()->config->get('indexer_reindex_allowed_ips', []))) {
94
            midcom::get()->auth->require_valid_user('basic');
95
            midcom::get()->auth->require_admin_user();
96
        }
97
        $message = [
98
            midcom::get()->i18n->get_string('MidCOM', 'midcom'),
99
            midcom::get()->i18n->get_string('cache invalidation successful', 'midcom'),
100
            'info'
101
        ];
102
        midcom::get()->cache->content->enable_live_mode();
103
        midcom::get()->cache->invalidate_all();
104
        midcom::get()->uimessages->add(...$message);
105
106
        $url = $request->server->get('HTTP_REFERER') ?: midcom_connection::get_url('self');
107
        return new midcom_response_relocate($url);
0 ignored issues
show
Bug introduced by
It seems like $url can also be of type null; however, parameter $url of midcom_response_relocate::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

107
        return new midcom_response_relocate(/** @scrutinizer ignore-type */ $url);
Loading history...
108
    }
109
110
    public function process_logout(Request $request, $url) : Response
111
    {
112
        midcom::get()->cache->content->no_cache();
113
        midcom::get()->auth->logout();
114
        return $this->redirect($request, $url);
115
    }
116
117
    public function process_login(Request $request, $url) : Response
118
    {
119
        if (midcom::get()->auth->is_valid_user()) {
120
            return $this->redirect($request, $url);
121
        }
122
        return new midcom_response_login;
123
    }
124
125
    private function redirect(Request $request, string $redirect_to) : Response
126
    {
127
        if (!empty($request->server->get('QUERY_STRING'))) {
128
            $redirect_to .= '?' . $request->getQueryString();
129
        }
130
        return new midcom_response_relocate($redirect_to);
131
    }
132
133
    /**
134
     * Allows you to execute certain php files directly, in full MidCOM context.
135
     * The argument is the name of the component, which holds the script to be
136
     * executed. Script files are searched in the subdirectory "exec" of the component.
137
     * If you use "midcom" as component name, MidCOM core scripts, located in
138
     * lib/midcom/exec will be accessible. The next argument on the command line must
139
     * be the name of the script file. Accessing subdirectories is not possible, only
140
     * a single argument will be taken.
141
     *
142
     * The scripts executed need to do their own permission checks, they will work with
143
     * the credentials of the current MidCOM instance unconditionally.
144
     *
145
     * Example: http://$host/midcom-exec-midcom/reindex.php
146
     *
147
     * The script file is executed in the cache's live mode to allow for long running
148
     * scripts (just produce any output regularly, or Apache will kill you after ~ 2 mins.).
149
     *
150
     * The remaining arguments will be placed into the global $argv.
151
     *
152
     * @param Request $request
153
     * @param string $component The component to look in ("midcom" uses core scripts)
154
     * @param string $filename
155
     * @see midcom_services_cache_module_content::enable_live_mode()
156
     */
157
    public function process_exec(Request $request, $component, $filename, $argv) : Response
158
    {
159
        $componentloader = midcom::get()->componentloader;
160
        if (!$componentloader->is_installed($component)) {
161
            throw new midcom_error_notfound('The requested component is not installed');
162
        }
163
        $path = $componentloader->path_to_snippetpath($component) . '/exec/' . $filename;
164
        if (!is_file($path)) {
165
            throw new midcom_error_notfound("File not found.");
166
        }
167
168
        // We seem to be in a valid place
169
        $context = $request->attributes->get('context');
170
        if ($component !== 'midcom') {
171
            $context->set_key(MIDCOM_CONTEXT_COMPONENT, $component);
172
        }
173
        // Collect remaining arguments and put them to global vars.
174
        $GLOBALS['argv'] = explode('/', $argv);
175
176
        return new StreamedResponse(function() use ($path) {
177
            midcom::get()->cache->content->enable_live_mode();
178
179
            // Exec the file with the current permissions.
180
            require $path;
181
        });
182
    }
183
}
184