Completed
Push — master ( 473b86...9fe868 )
by Dimas
88:17 queued 74:29
created

themes::admin()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 0
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace MVC;
4
5
if (!function_exists('folder_session')) {
6
  include __DIR__ . '/loader.php';
7
}
8
9
use JSON\json;
10
11
class themes
12
{
13
  public $root_theme;
14
  public $theme;
15
  public $view;
16
  public $meta = [];
17
  public $title = '';
18
  public $config;
19
  public $config_folder;
20
  protected $admin_user = 'admin';
21
  protected $admin_pass = 'admin';
22
  /**
23
   * Session instances.
24
   *
25
   * @var \Session\session
26
   */
27
  public $session = null;
28
29
  public function __construct()
30
  {
31
    /**
32
     * Load image cache if exists.
33
     */
34
    $imgproxy = isset($_REQUEST['image-proxy']) ? $_REQUEST['image-proxy'] : (isset($_REQUEST['img-source']) ? $_REQUEST['img-source'] : null);
35
    if ($imgproxy) {
36
      $url = urldecode(trim($imgproxy));
37
      if (helper::is_url($url)) {
38
        helper::cleanBuffer();
39
        exit(\img\cache::imageCache($url));
0 ignored issues
show
Bug introduced by
Are you sure the usage of img\cache::imageCache($url) targeting img\cache::imageCache() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
40
      }
41
    }
42
43
    /*
44
     * Load admin utility
45
     */
46
    if ($this->is_admin()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->is_admin() of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
47
      // Metadata receiver
48
      if (isset($_POST['meta-save']) && helper::is_header('Save-Metadata')) {
49
        unset($_POST['meta-save']);
50
        if (isset($_POST['meta-config'])) {
51
          $config_meta = $_POST['meta-config'];
52
          unset($_POST['meta-config']);
53
          if ($config_meta = realpath($config_meta)) {
54
            foreach ($_POST as $key => $value) {
55
              if ('true' == $value) {
56
                $_POST[$key] = true;
57
              } elseif ('false' == $value) {
58
                $_POST[$key] = false;
59
              } elseif (is_numeric($value)) {
60
                settype($_POST[$key], 'integer');
61
              } elseif (is_string($value)) {
62
                $_POST[$key] = trim($value);
63
              }
64
            }
65
            $meta_data = $_POST;
66
            //robot tag header
67
            if (!isset($meta_data['robot'])) {
68
              $meta_data['robot'] = 'noindex, nofollow';
69
            }
70
            //allow comments
71
            if (!isset($meta_data['comments'])) {
72
              $meta_data['comments'] = false;
73
            }
74
            //cache page
75
            if (!isset($meta_data['cache'])) {
76
              $meta_data['cache'] = false;
77
            }
78
            // obfuscate javascript
79
            if (!isset($meta_data['obfuscate'])) {
80
              $meta_data['obfuscate'] = true;
81
            }
82
            if (file_exists($config_meta)) {
83
              \Filemanager\file::file($config_meta, $meta_data, true);
84
              if (!\MVC\helper::cors()) {
85
                safe_redirect(\MVC\helper::geturl());
86
              } else {
87
                if (ob_get_level()) {
88
                  ob_end_clean();
89
                }
90
                exit(\JSON\json::json(['message' => 'Meta Saved', 'title' => 'Meta Changer', 'reload' => true]));
0 ignored issues
show
Bug introduced by
Are you sure the usage of JSON\json::json(array('m...er', 'reload' => true)) targeting JSON\json::json() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
91
              }
92
            }
93
          }
94
        }
95
      }
96
    }
97
98
    /*
99
     * Setup default meta
100
     */
101
    $this->meta = [
102
      'published' => date('m/j/y g:i A'),
103
      'modified' => date('m/j/y g:i A'),
104
      'thumbnail' => 'https://1.bp.blogspot.com/-rkXCUBbNXyw/XfY0hwoFu5I/AAAAAAAAAhw/BUyeKW5BtMoIJLlPUcPSdqGZBQRncXjDQCK4BGAYYCw/s600/PicsArt_09-09-12.12.25.jpg',
105
      'theme' => true,
106
      'title' => $_SERVER['REQUEST_URI'],
107
      'share' => false,
108
      'desc' => '',
109
      'content' => null,
110
      'robot' => 'noindex, nofollow',
111
      'obfuscate' => false,
112
      'cache' => false,
113
    ];
114
    $this->root = realpath(__DIR__ . '/../../');
0 ignored issues
show
Bug Best Practice introduced by
The property root does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
115
    $this->root_theme = realpath(__DIR__ . '/themes');
116
    $this->view = helper::platformSlashes($this->root . '/view');
117
    $this->config_folder = helper::platformSlashes(__DIR__ . '/config');
118
    $config_theme = json_decode(file_get_contents($this->config_folder . '/theme-admin.json'), true);
119
    $this->admin_user = $config_theme['user'];
120
    $this->admin_pass = $config_theme['pass'];
121
  }
122
123
  /**
124
   * Turn zone into maintenance mode (Maintenance page).
125
   *
126
   * @param string $zone if empty, will turn into maintenance mode in all zone
127
   *
128
   * @return \MVC\themes
129
   */
130
  public function shutdown(string $zone)
131
  {
132
    $current = get_zone();
133
134
    if ($current == $zone) {
135
      maintenance();
136
    } elseif (empty($zone)) {
137
      maintenance();
138
    }
139
140
    return $this;
141
  }
142
143
  public function published($time)
144
  {
145
    $date = $this->date($time);
146
    $this->meta['published'] = $date;
147
148
    return $this;
149
  }
150
151
  public function modified($time)
152
  {
153
    $date = $this->date($time);
154
    $this->meta['modified'] = $date;
155
156
    return $this;
157
  }
158
159
  public function thumbnail($src)
160
  {
161
    $this->meta['thumbnail'] = $src;
162
  }
163
164
  public function date($time, $format = 'm/j/y g:i A')
165
  {
166
    if (!is_numeric($time)) {
167
      $time = strtotime($time);
168
    }
169
170
    return date($format, $time);
171
  }
172
173
  /**
174
   * Set theme default.
175
   *
176
   * @return $this
177
   */
178
  public function set(string $theme, bool $useTheme = true)
179
  {
180
    $this->theme = $theme;
181
    $this->root_theme = helper::platformSlashes($this->root_theme . '/' . $theme);
182
    if (isset($_REQUEST['theme']) && $this->is_admin()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->is_admin() of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
183
      $useTheme = 'false' == $_REQUEST['theme'] ? false : true;
184
    }
185
    //exit(var_dump($useTheme));
186
    $this->meta['theme'] = $useTheme;
187
188
    return $this;
189
  }
190
191
  /**
192
   * ```php
193
   * setThemeByZones([ 'theme-name'=>['zone1', 'zone2'], 'another-theme'=>['zone3','zone4'], 'default-template'])
194
   * ```
195
   * Set theme by zone divider.
196
   * if not exists in zone divider, will using default template.
197
   * @throws Exception
198
   * @return $this
199
   */
200
  public function setThemeByZones(array $config, string $default)
201
  {
202
    $current = get_zone();
203
    $set = false;
204
    foreach ($config as $theme_name => $zones) {
205
      if (in_array($current, $zones)) {
206
        $this->set($theme_name);
207
        $set = true;
208
      }
209
    }
210
    if (!$set) {
211
      $this->set($default);
212
    }
213
214
    return $this;
215
  }
216
217
  public function view($file)
218
  {
219
    $this->view = helper::platformSlashes($this->root . '/' . $file);
220
    $this->view = str_replace(helper::platformSlashes($this->root), '', $this->view);
221
    $this->view = $this->root . $this->view;
222
223
    if (realpath($this->view)) {
224
      $this->view = realpath($this->view);
225
      $this->meta['content'] = $this->remove_root($this->view);
226
      $this->prepare_config();
227
228
      /**
229
       * begin form include.
230
       *
231
       * @todo Form includer
232
       */
233
      $form = preg_replace('/\.php$/s', '-f.php', $this->view);
234
      helper::include_asset($form);
235
      if (!$this->meta['theme'] && $this->NoThemeRequest()) {
236
        include $this->view;
237
238
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
239
      }
240
    }
241
242
    return $this;
243
  }
244
245
  public function remove_root($path)
246
  {
247
    return str_replace($this->root, '', $path);
248
  }
249
250
  public function fix_slash($path)
251
  {
252
    return preg_replace('/(\/|\\\\){2,100}/m', '/', $path);
253
  }
254
255
  public function prepare_config()
256
  {
257
    $viewNoRoot = str_replace($this->root, '', $this->view);
258
    $this->config = $this->config_folder . '/' . preg_replace('/\.php$/s', '', $viewNoRoot) . '.json';
259
    if ($config = helper::platformSlashes($this->config)) {
260
      $this->config = $config;
261
      if (!is_dir(dirname($config)) && !file_exists(dirname($config))) {
262
        mkdir(dirname($config), 0777, true);
263
      }
264
      if (!file_exists($config)) {
265
        file_put_contents($config, json_encode($this->meta, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
266
      } else {
267
        $this->meta = json_decode(file_get_contents($config), true);
268
        if (!isset($this->meta['robot'])) {
269
          $this->meta['robot'] = 'noindex, nofollow';
270
        }
271
        header('X-Robots-Tag: ' . trim($this->meta['robot']), true);
272
        // obfuscate javascript
273
        if (!isset($this->meta['obfuscate'])) {
274
          $this->meta['obfuscate'] = false;
275
        }
276
        // cache
277
        if (!isset($this->meta['cache'])) {
278
          $this->meta['cache'] = true;
279
        }
280
        $this->meta['content'] = $this->root . $this->meta['content'];
281
        if ($this->is_admin() && !helper::cors()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->is_admin() of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
282
          if (isset($_REQUEST['theme'])) {
283
            $this->meta['theme'] = 'true' == trim($_REQUEST['theme']) ? true : false;
284
            file_put_contents($config, json_encode($this->meta, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
285
          }
286
          if (isset($_REQUEST['obfuscate'])) {
287
            $this->meta['obfuscate'] = 'true' == trim($_REQUEST['theme']) ? true : false;
288
            file_put_contents($config, json_encode($this->meta, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
289
          }
290
        }
291
      }
292
    }
293
294
    return $this;
295
  }
296
297
  /**
298
   * Dump this variable.
299
   *
300
   * @param variadic ...$var
0 ignored issues
show
Bug introduced by
The type MVC\variadic was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
301
   */
302
  public function dump(...$var)
303
  {
304
    if (ob_get_level()) {
305
      ob_end_clean();
306
      ob_start();
307
    }
308
    \JSON\json::headerJSON();
309
    exit(var_dump($var));
0 ignored issues
show
Bug introduced by
Are you sure the usage of var_dump($var) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
Security Debugging Code introduced by
var_dump($var) looks like debug code. Are you sure you do not want to remove it?
Loading history...
310
  }
311
312
  public function is_admin()
313
  {
314
    if (isset($_SESSION['login']['role'])) {
315
      return preg_match(\User\user::get_admin_pattern(), $_SESSION['login']['role']);
316
    }
317
  }
318
319
  /*public function admin()
320
  {
321
    http_response_code(200);
322
    $this->root_theme = realpath(__DIR__ . '/themes');
323
    $view = $this->root_theme . '/admin/view.php';
324
    if ($form = realpath(preg_replace('/\.php$/s', '-f.php', $view))) {
325
      include $form;
326
    }
327
    $this->set('admin');
328
    $this->view($view);
329
    //var_dump($this);
330
    $this->render();
331
  }*/
332
333
  /**
334
   * Include passed variable.
335
   */
336
  public function render($variables = [], $print = true)
337
  {
338
    //exit('xxx');
339
    \MVC\helper::trycatch(function () use ($variables, $print) {
340
      $this->load_render($variables, $print);
341
    });
342
343
    return $this;
344
  }
345
346
  public function isJSONRequest()
347
  {
348
    $hasJSON = isset($_REQUEST['json']);
349
    if (!$hasJSON) {
350
      if (isset($_SERVER['HTTP_ACCEPT'])) {
351
        $hasJSON = preg_match('/^application\/json/m', $_SERVER['HTTP_ACCEPT']);
352
      }
353
    }
354
355
    return $hasJSON;
356
  }
357
358
  public function NoThemeRequest()
359
  {
360
    if (!isset($this->meta['theme']) || $this->meta['theme']) {
361
      return false;
362
    }
363
    $accept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : false;
364
    if (false !== $accept) {
365
      if (preg_match('/((application|text)\/(json|javascript))/m', $accept, $match)) {
366
        if (isset($match[0]) && !headers_sent()) {
367
          header('Content-Type: ' . $match[0]);
368
        }
369
370
        return true;
371
      }
372
    }
373
374
    return false;
375
  }
376
377
  public function load_render(array $variables, bool $print = true)
378
  {
379
    //exit(\JSON\json::json($this));
380
    if (file_exists($this->view)) {
381
      // Extract the variables to a local namespace
382
      extract($variables);
383
      extract($this->meta);
384
      $_SESSION['var'] = get_defined_vars();
385
      $content = $this->view;
386
387
      $theme = $this;
388
      //exit(\JSON\json::json($theme));
389
390
      // if not using theme
391
      if (!$this->meta['theme']) {
392
        include $content;
393
394
        return;
395
      } elseif ($this->meta['theme']) {
396
        // Include the template file
397
        $template_content = $this->root_theme . '/content.php';
398
        if (file_exists($template_content)) {
399
          include $template_content;
400
        } else {
401
          return json::json([
0 ignored issues
show
Bug introduced by
Are you sure the usage of JSON\json::json(array('e...ntent . ' not exists')) targeting JSON\json::json() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
402
            'error' => true,
403
            'message' => $template_content . ' not exists',
404
          ]);
405
        }
406
      } else {
407
        exit('meta theme not defined');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
408
      }
409
410
      /*// End buffering and return its contents
411
      $output = ob_get_clean();*/
412
    } else {
413
      json::json([
414
        'error' => true,
415
        'message' => $this->view . ' not exists',
416
      ]);
417
      exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
418
    }
419
  }
420
421
  public function load_admin_tools()
422
  {
423
    if ($this->is_admin()) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->is_admin() of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
424
      $Config = normalize_path(realpath($this->config));
425
      include __DIR__ . '/themes/admin.php';
426
    }
427
  }
428
}
429