Passed
Push — master ( 822a0b...93f4bd )
by Andreas
23:15
created

midcom_application::__set()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @package midcom
4
 * @author The Midgard Project, http://www.midgard-project.org
5
 * @copyright The Midgard Project, http://www.midgard-project.org
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 */
8
9
use Symfony\Component\HttpFoundation\Request;
10
use Symfony\Component\HttpKernel\HttpKernelInterface;
11
use Symfony\Component\HttpKernel\Kernel;
12
use Symfony\Component\Config\Loader\LoaderInterface;
13
use Symfony\Component\DependencyInjection\ContainerBuilder;
14
15
/**
16
 * Main controlling instance of the MidCOM Framework
17
 *
18
 * @property midcom_services_i18n $i18n
19
 * @property midcom_helper__componentloader $componentloader
20
 * @property midcom_services_dbclassloader $dbclassloader
21
 * @property midcom_helper__dbfactory $dbfactory
22
 * @property midcom_helper_head $head
23
 * @property midcom_helper__styleloader $style
24
 * @property midcom_services_auth $auth
25
 * @property midcom_services_permalinks $permalinks
26
 * @property midcom_services_toolbars $toolbars
27
 * @property midcom_services_uimessages $uimessages
28
 * @property midcom_services_metadata $metadata
29
 * @property midcom_services_rcs $rcs
30
 * @property midcom_services__sessioning $session
31
 * @property midcom_services_indexer $indexer
32
 * @property midcom_config $config
33
 * @property midcom_services_cache $cache
34
 * @property midcom\events\dispatcher $dispatcher
35
 * @property midcom_debug $debug
36
 * @package midcom
37
 */
38
class midcom_application extends Kernel
39
{
40
    /**
41
     * Host prefix cache to avoid computing it each time.
42
     *
43
     * @var string
44
     * @see get_host_prefix()
45
     */
46
    private $_cached_host_prefix = '';
47
48
    /**
49
     * Page prefix cache to avoid computing it each time.
50
     *
51
     * @var string
52
     * @see get_page_prefix()
53
     */
54
    private $_cached_page_prefix = '';
55
56
    /**
57
     * @var Request
58
     */
59
    private $request;
60
61
    /**
62
     * Set this variable to true during the handle phase of your component to
63
     * not show the site's style around the component output. This is mainly
64
     * targeted at XML output like RSS feeds and similar things. The output
65
     * handler of the site, excluding the style-init/-finish tags will be executed
66
     * immediately after the handle phase
67
     *
68
     * Changing this flag after the handle phase or for dynamically loaded
69
     * components won't change anything.
70
     *
71
     * @var boolean
72
     */
73
    public $skip_page_style = false;
74
75
    private $project_dir;
76
77
    public function __construct(string $environment, bool $debug)
78
    {
79
        midcom_compat_environment::initialize();
80
        $this->request = Request::createFromGlobals();
81
        parent::__construct($environment, $debug);
82
    }
83
84
    public function registerContainerConfiguration(LoaderInterface $loader)
85
    {
86
        $loader->load(__DIR__ . '/config/services.yml');
87
        if ($classes = midcom::get_registered_service_classes()) {
88
            $loader->load(function (ContainerBuilder $container) use ($classes) {
89
                foreach ($classes as $id => $class) {
90
                    $container->findDefinition($id)->setClass($class);
91
                }
92
            });
93
        }
94
        midcom_exception_handler::register();
95
    }
96
97
    public function registerBundles()
98
    {
99
        return [];
100
    }
101
102
    public function getProjectDir()
103
    {
104
        if ($this->project_dir === null) {
105
            if (basename(dirname(__DIR__, 4)) === 'vendor') {
106
                // this is the case where we're installed as a dependency
107
                $this->project_dir = dirname(__DIR__, 5);
108
            } else {
109
                $this->project_dir = dirname(__DIR__, 2);
110
            }
111
        }
112
        return $this->project_dir;
113
    }
114
115
    /**
116
     * Magic getter for service loading
117
     */
118 737
    public function __get($key)
119
    {
120 737
        return $this->getContainer()->get($key);
121
    }
122
123
    /**
124
     * Magic setter
125
     */
126
    public function __set($key, $value)
127
    {
128
        $this->getContainer()->set($key, $value);
129
    }
130
131
    /* *************************************************************************
132
     * Control framework:
133
     * codeinit      - Handle the current request
134
     * dynamic_load   - Dynamically load and execute a URL
135
     * finish         - Cleanup Work
136
     */
137
138
    /**
139
     * Initialize the URL parser and process the request.
140
     *
141
     * This function must be called before any output starts.
142
     */
143
    public function codeinit()
144
    {
145
        $this->handle($this->request)->send();
146
    }
147
148
    /**
149
     * Dynamically execute a subrequest and insert its output in place of the
150
     * function call.
151
     *
152
     * It tries to load the component referenced with the URL $url and executes
153
     * it as if it was used as primary component.
154
     *
155
     * This is only possible if the system is in the Page-Style output phase. It
156
     * cannot be used within code-init or during the output phase of another
157
     * component.
158
     *
159
     * Example code, executed on a site's homepage, it will load the news listing from
160
     * the given URL and display it using a substyle of the node style that is assigned
161
     * to the loaded one:
162
     *
163
     * <code>
164
     * $blog = '/blog/latest/3/';
165
     * $substyle = 'homepage';
166
     * midcom::get()->dynamic_load("/midcom-substyle-{$substyle}/{$blog}");
167
     * </code>
168
     *
169
     * Results of dynamic_loads are cached with the system cache strategy
170
     *
171
     * @param string $url                The URL, relative to the Midgard Page, that is to be requested.
172
     */
173 16
    public function dynamic_load($url)
174
    {
175 16
        debug_add("Dynamic load of URL {$url}");
176 16
        $url = midcom_connection::get_url('prefix') . $url;
177
178
        // Determine new Context ID and set current context,
179
        // enter that context and prepare its data structure.
180 16
        $oldcontext = midcom_core_context::get();
181 16
        $context = midcom_core_context::enter($url, $oldcontext->get_key(MIDCOM_CONTEXT_ROOTTOPIC));
0 ignored issues
show
Bug introduced by
It seems like $oldcontext->get_key(MIDCOM_CONTEXT_ROOTTOPIC) can also be of type false; however, parameter $topic of midcom_core_context::enter() does only seem to accept midcom_db_topic|null, 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

181
        $context = midcom_core_context::enter($url, /** @scrutinizer ignore-type */ $oldcontext->get_key(MIDCOM_CONTEXT_ROOTTOPIC));
Loading history...
182
183 16
        $request = $this->request->duplicate([], null, []);
184 16
        $request->attributes->set('context', $context);
185
186 16
        $cached = $this->cache->content->check_dl_hit($request);
187 16
        if ($cached !== false) {
188
            echo $cached;
189
            midcom_core_context::leave();
190
            return;
191
        }
192
193 16
        $backup = $this->skip_page_style;
194 16
        $this->skip_page_style = true;
195
        try {
196 16
            $response = $this->handle($request, HttpKernelInterface::SUB_REQUEST, false);
197 12
        } catch (midcom_error $e) {
198 12
            if ($e instanceof midcom_error_notfound || $e instanceof midcom_error_forbidden) {
199 12
                $e->log();
200 12
                midcom_core_context::leave();
201 12
                return;
202
            }
203
            throw $e;
204 4
        } finally {
205 16
            $this->skip_page_style = $backup;
206
        }
207
208 4
        $dl_cache_data = $response->getContent();
209 4
        echo $dl_cache_data;
210
211
        /* Cache DL the content */
212 4
        $this->cache->content->store_dl_content($context->id, $dl_cache_data, $request);
213
214 4
        midcom_core_context::leave();
215 4
    }
216
217
    /**
218
     * Exit from the framework, execute after all output has been made.
219
     *
220
     * <b>WARNING:</b> Anything done after calling this method will be lost.
221
     */
222
    public function finish()
223
    {
224
        debug_add("End of MidCOM run: " . $this->request->server->get('REQUEST_URI'));
225
        _midcom_stop_request();
226
    }
227
228
    /* *************************************************************************
229
     * Framework Access Helper functions
230
     */
231
232
    /**
233
     * Retrieves the name of the current host, fully qualified with protocol and
234
     * port (http[s]://www.my.domain.com[:1234])
235
     */
236 37
    function get_host_name() : string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
237
    {
238 37
        return $this->request->getSchemeAndHttpHost();
239
    }
240
241
    /**
242
     * Return the prefix required to build relative links on the current site.
243
     * This includes the http[s] prefix, the hosts port (if necessary) and the
244
     * base url of the Midgard Page. Be aware, that this does *not* point to the
245
     * base host of the site.
246
     *
247
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/page_prefix/
248
     */
249
    function get_page_prefix() : string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
250
    {
251
        if (!$this->_cached_page_prefix) {
252
            $host_name = $this->get_host_name();
253
            $this->_cached_page_prefix = $host_name . midcom_connection::get_url('self');
254
        }
255
256
        return $this->_cached_page_prefix;
257
    }
258
259
    /**
260
     * Return the prefix required to build relative links on the current site.
261
     * This includes the http[s] prefix, the hosts port (if necessary) and the
262
     * base url of the main host. This is not necessarily the currently active
263
     * MidCOM Page however, use the get_page_prefix() function for that.
264
     *
265
     * e.g. something like http[s]://www.domain.com[:8080]/host_prefix/
266
     */
267 7
    function get_host_prefix() : string
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
268
    {
269 7
        if (!$this->_cached_host_prefix) {
270 1
            $host_name = $this->get_host_name();
271 1
            $host_prefix = midcom_connection::get_url('prefix');
272 1
            if (substr($host_prefix, 0, 1) != '/') {
273
                $host_prefix = "/{$host_prefix}";
274
            }
275 1
            if (substr($host_prefix, -1, 1) != '/') {
276
                $host_prefix .= '/';
277
            }
278 1
            $this->_cached_host_prefix = "{$host_name}{$host_prefix}";
279
        }
280
281 7
        return $this->_cached_host_prefix;
282
    }
283
284
    /* *************************************************************************
285
     * Generic Helper Functions not directly related with MidCOM:
286
     *
287
     * relocate           - executes a HTTP relocation to the given URL
288
     */
289
290
    /**
291
     * Sends a header out to the client.
292
     *
293
     * This function is syntactically identical to
294
     * the regular PHP header() function, but is integrated into the framework. Every
295
     * Header you sent must go through this function or it might be lost later on;
296
     * this is especially important with caching.
297
     *
298
     * @param string $header    The header to send.
299
     * @param integer $response_code HTTP response code to send with the header
300
     */
301 17
    public function header($header, $response_code = null)
302
    {
303 17
        $this->cache->content->register_sent_header($header);
304 17
        midcom_compat_environment::get()->header($header, true, $response_code);
305 17
    }
306
307
    /**
308
     * Relocate to another URL.
309
     *
310
     * The helper actually can distinguish between site-local, absolute redirects and external
311
     * redirects. If the url does not start with http[s] or /, it is taken as a URL relative to
312
     * the current anchor prefix, which gets prepended automatically (no other characters
313
     * as the anchor prefix get inserted).
314
     *
315
     * Fully qualified urls (starting with http[s]) are used as-is.
316
     *
317
     * Note, that this function automatically makes the page uncacheable, calls
318
     * midcom_finish and exit, so it will never return. If the headers have already
319
     * been sent, this will leave you with a partially completed page, so beware.
320
     *
321
     * @param string $url    The URL to redirect to, will be preprocessed as outlined above.
322
     * @param int $response_code HTTP response code to send with the relocation, from 3xx series
323
     */
324
    public function relocate($url, $response_code = 302)
325
    {
326
        $response = new midcom_response_relocate($url, $response_code);
327
        $response->send();
328
        $this->finish();
329
    }
330
331
    /**
332
     * Raise some PHP limits for resource-intensive tasks
333
     */
334 8
    public function disable_limits()
335
    {
336 8
        $stat = @ini_set('max_execution_time', $this->config->get('midcom_max_execution_time'));
337 8
        if (false === $stat) {
338
            debug_add('ini_set("max_execution_time", ' . $this->config->get('midcom_max_execution_time') . ') returned false', MIDCOM_LOG_WARN);
339
        }
340 8
        $stat = @ini_set('memory_limit', $this->config->get('midcom_max_memory'));
341 8
        if (false === $stat) {
342
            debug_add('ini_set("memory_limit", ' . $this->config->get('midcom_max_memory') . ') returned false', MIDCOM_LOG_WARN);
343
        }
344 8
    }
345
}
346