Add URL rewrites/replacements
[phinde.git] / src / phinde / Helper.php
1 <?php
2 namespace phinde;
3
4 class Helper
5 {
6     public static function rewriteUrl($url)
7     {
8         if (!isset($GLOBALS['phinde']['urlRewrites'])
9             || count($GLOBALS['phinde']['urlRewrites']) == 0
10         ) {
11             return $url;
12         }
13
14         foreach ($GLOBALS['phinde']['urlRewrites'] as $pattern => $replacement) {
15             $url = preg_replace('#' . $pattern . '#', $replacement, $url);
16         }
17         return $url;
18     }
19
20     public static function isUrlAllowed($url)
21     {
22         $urlDomain = parse_url($url, PHP_URL_HOST);
23         if (!in_array($urlDomain, $GLOBALS['phinde']['domains'])) {
24             return false;
25         }
26         return true;
27     }
28
29     public static function noSchema($url)
30     {
31         return str_replace(
32             array('http://', 'https://'),
33             '',
34             $url
35         );
36     }
37
38     public static function addSchema($url)
39     {
40         if (substr($url, 0, 7) == 'http://'
41             || substr($url, 0, 8) == 'https://'
42         ) {
43             return $url;
44         }
45         return 'http://' . $url;
46     }
47
48     public static function removeAnchor($url)
49     {
50         $parts = explode('#', $url, 2);
51         return $parts[0];
52     }
53
54     public static function sanitizeTitle($str)
55     {
56         return trim(
57             str_replace(
58                 array("\r", "\n", '  ', '  '),
59                 array('', ' ', ' ', ' '),
60                 $str
61             )
62         );
63     }
64
65     /**
66      * Create a full URL with protocol and host name
67      *
68      * @param string $path Path to the file, with leading /
69      *
70      * @return string Full URL
71      */
72     public static function fullUrl($path = '/')
73     {
74         if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']) {
75             $prot = 'https';
76         } else {
77             $prot = 'http';
78         }
79         return $prot . '://' . $_SERVER['HTTP_HOST'] . $path;
80     }
81
82     static $timer = [];
83
84     public static function start($timer = 'timer')
85     {
86         static::$timer[$timer] = microtime(true);
87     }
88
89     public static function stop($timer = 'timer')
90     {
91         $diff = microtime(true) - static::$timer[$timer];
92         echo '+timer: ' . number_format($diff, 3) . 'ms ' . $timer . "\n";
93     }
94
95     public static function baseDoc($url)
96     {
97         $esDoc = new \stdClass();
98         $esDoc->status = new \stdClass();
99         $esDoc->url = $url;
100         $esDoc->schemalessUrl = Helper::noSchema($url);
101         return $esDoc;
102     }
103 }
104 ?>