source: trunk/globals/functions.php @ 248

Revision 248, 12.8 KB checked in by sque, 11 months ago (diff)

Fix: Google Map didn't work with no authentication key.

Line 
1<?php
2/*
3 * WiND - Wireless Nodes Database
4 *
5 * Copyright (C) 2005 Nikolaos Nikalexis <winner@cube.gr>
6 * Copyright (C) 2009-2010 Vasilis Tsiligiannis <b_tsiligiannis@silverton.gr>
7 * Copyright (C) 2011 K. Paliouras <squarious@gmail.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; version 2 dated June, 1991.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21 *
22 */
23
24function redirect($url, $sec=0, $exit=TRUE) {
25        global $main;
26        $sec = (integer)($sec);
27        if ($main->message->show && $main->message->forward != $url) {
28                if ($main->message->forward == '') $main->message->forward = $url;
29                return;
30        }
31        if (@preg_match('/Microsoft|WebSTAR|Xitami/', getenv('SERVER_SOFTWARE')) || @preg_match('/Safari/', $_SERVER['HTTP_USER_AGENT']) || $sec>0) {
32                header("Refresh: $sec; URL=".html_entity_decode($url));
33                $main->html->head->add_meta("$sec; url=$url", "", "refresh");
34        } else {
35                header("Location: ".html_entity_decode($url));         
36        }
37        if ($exit && !$main->message->show) {
38                exit;
39        }
40}
41
42function get_qs($htmlspecialchars=TRUE) {
43        $ret = "";
44        if ($_SERVER['REQUEST_METHOD'] == 'GET') {
45                $ret = $_SERVER['QUERY_STRING'];
46        } else {
47                $ret = $_POST['query_string'];
48        }
49        return ($htmlspecialchars?htmlspecialchars($ret):$ret);
50}
51
52function get($key) {
53        global $page_admin, $main;
54        if ($_SERVER['REQUEST_METHOD'] == 'GET') {
55                $ret = "";
56                if (isset($_GET[$key])) {
57                    $ret = $_GET[$key];
58                }               
59        } else {
60                parse_str($_POST['query_string'], $output);
61                $ret = "";
62                if (isset($output[$key])) {
63                    $ret = $output[$key];
64                }
65        }
66        switch ($key) {
67                case 'page':
68                        $valid_array = getdirlist(ROOT_PATH."includes/pages/");
69                        array_unshift($valid_array, 'startup');
70                        break;
71                case 'subpage':
72                        $valid_array = getdirlist(ROOT_PATH."includes/pages/".get('page').'/', FALSE, TRUE);
73                        for ($key=0;$key<count($valid_array);$key++) {
74                                $valid_array[$key] = basename($valid_array[$key], '.php');
75                                if (substr($valid_array[$key], 0, strlen(get('page'))+1) != get('page').'_') {
76                                        array_splice($valid_array, $key, 1);
77                                        $key--;
78                                } else {
79                                        $valid_array[$key] = substr($valid_array[$key], strlen(get('page'))+1);
80                                }
81                        }
82                        array_unshift($valid_array, '');
83                        break;
84        }
85        if (isset($valid_array) && !in_array($ret, $valid_array)) $ret = $valid_array[0];
86        return $ret;
87}
88
89function getdirlist($dirName, $dirs=TRUE, $files=FALSE) { 
90        $d = dir($dirName);
91        $a = array();
92        while($entry = $d->read()) { 
93                if ($entry != "." && $entry != "..") { 
94                        if (is_dir($dirName."/".$entry)) { 
95                                if ($dirs==TRUE) array_push($a, $entry); 
96                        } else { 
97                                if ($files==TRUE) array_push($a, $entry); 
98                        } 
99                } 
100        } 
101        $d->close();
102        return $a;
103} 
104
105function makelink($extra="", $cur_qs=FALSE, $cur_gs_vars=TRUE, $htmlspecialchars=TRUE) {
106        global $qs_vars;
107        $o = array();
108        if(get('show_map') == "no") $o = array_merge($o,array("show_map" => "no"));
109        if ($cur_qs == TRUE) {
110                parse_str(get_qs(FALSE), $qs);
111                $o = array_merge($o, $qs);
112        }
113        if ($cur_gs_vars == TRUE) {
114                $o = array_merge($o, (array)$qs_vars);
115        }
116        $o = array_merge($o, (array)$extra);
117        return ($htmlspecialchars?htmlspecialchars('?'.query_str($o)):'?'.query_str($o));
118}
119
120function query_str($params) {
121   $str = '';
122   foreach( (array) $params as $key => $value) {
123                if ($value == '') continue;
124           $str .= (strlen($str) < 1) ? '' : '&';
125           $str .= $key . '=' . rawurlencode($value);
126   }
127   return ($str);
128}
129
130function cookie($name, $value) {
131        global $vars;
132        $expire = time() + $vars['cookies']['expire'];
133        return setcookie($name, $value, $expire, "/");
134}
135
136function date_now() {
137      return date("Y-m-d H:i:s");
138 }
139 
140function message($arg) {
141        global $lang;
142        $mes = $lang['message'][func_get_arg(0)][func_get_arg(1)][func_get_arg(2)];
143        for ($i=3;$i<func_num_args();$i++) {
144                $par = func_get_arg($i);
145                $mes = str_replace('%'.($i-2).'%', $par, $mes);
146        }
147        return $mes;
148}
149
150function lang($arg) {
151        global $lang;
152        $mes = $lang[func_get_arg(0)];
153        for ($i=1;$i<func_num_args();$i++) {
154                $par = func_get_arg($i);
155                $mes = str_replace('%'.($i).'%', $par, $mes);
156        }
157        return $mes;
158}
159
160function template($assign_array, $file) {
161        global $smarty;
162        $path_parts = pathinfo($file);
163        if (substr(strrchr($file, "."), 1) != "tpl") {
164                $tpl_file = 'includes'.substr($path_parts['dirname'], strpos($path_parts['dirname'], 'includes') + 8)."/".basename($path_parts['basename'], '.'.$path_parts['extension']).'.tpl';
165        } else {
166                $tpl_file = $file;
167        }
168        reset_smarty();
169        $smarty->assign($assign_array);
170        return $smarty->fetch($tpl_file);
171}
172
173function reset_smarty() {
174        global $smarty, $lang;
175        $smarty->clear_all_assign();
176        $smarty->assign_by_ref('lang', $lang);
177        $smarty->assign('tpl_dir', $smarty->template_dir);
178        $smarty->assign('img_dir', $smarty->template_dir."images/");
179        $smarty->assign('css_dir', $smarty->template_dir."css/");
180        $smarty->assign('js_dir', $smarty->template_dir."scripts/javascripts/");
181}
182
183function delfile($str) 
184{ 
185   foreach( (array) glob($str) as $fn) { 
186           unlink($fn); 
187   } 
188} 
189
190function resizeJPG($filename, $width, $height) {
191
192        list($width_orig, $height_orig) = getimagesize($filename);
193       
194        if ($width && ($width_orig < $height_orig)) {
195           $width = ($height / $height_orig) * $width_orig;
196        } else {
197           $height = ($width / $width_orig) * $height_orig;
198        }
199
200   // Resample
201        $image_p = imagecreatetruecolor($width, $height);
202        $image = imagecreatefromjpeg($filename);
203        imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);
204        return $image_p;
205}
206
207function reverse_zone_from_ip($ip) {
208        global $vars;
209        $ret = explode(".", $ip);
210        $ret = $ret[2].".".$ret[1].".".$ret[0].".".$vars['dns']['reverse_zone'];
211        return $ret;
212}
213
214function is8bit($str) {
215        for($i=0; $i <= strlen($str); $i++)
216                if(ord($str{$i}) >> 7)   
217                        return TRUE;
218        return FALSE;
219}
220
221function sendmail($to, $subject, $body, $from_name='', $from_email='', $cc_to_sender=FALSE) {
222        global $vars, $lang;
223        $subject = mb_encode_mimeheader($subject, $lang['charset'], 'B', "\n");
224        if (empty($from_email)) {
225                $from_name = $vars['mail']['from_name'];
226                $from_email = $vars['mail']['from'];
227        }
228        $from_name = mb_encode_mimeheader($from_name, $lang['charset'], 'B', "\n");
229        if ($from_name == $from_email) {
230                $from = $from_email;
231        } else {
232                $from = $from_name.' <'.$from_email.'>';
233        }
234        $headers = "From: $from\n";
235        if ($cc_to_sender) $headers .= "Cc: $from\n";
236        $headers .= "MIME-Version: 1.0\n";
237        $headers .= 'Content-Type: text/plain; charset='.$lang['charset']."\n";
238        $headers .= 'Content-Transfer-Encoding: '.(is8bit($body) ? '8bit' : '7bit');
239        return @mail($to, $subject, $body, $headers);
240}
241
242function ip_to_ranges($ip, $ret_null=TRUE) {
243        if ($ip == '' && $ret_null === TRUE) return array();
244        $t = explode(".", $ip, 4);
245        for ($i=0;$i<=3;$i++) {
246                if (isset($t[$i]) && $t[$i] != '' && $i != 3) $t[$i] = $t1[$i] = $t2[$i] = (integer)($t[$i]);
247                else {
248                        $t1[$i] = 0;
249                        $t2[$i] = 255;
250                }
251        }
252        $ret[] = array("min" => implode(".", $t1), "max" => implode(".", $t2));
253        $p = count($t) - 1;
254        if ($p <= 2 && $t[$p] != 0) {
255                $d = 2 - intval(log10($t[$p]));
256                for ($i=1;$i<=$d;$i++) {
257                        $t1[$p] = $t[$p] * pow(10,$i);
258                        if ($t1[$p] > 255) continue;
259                        $t2[$p] = $t1[$p] + pow(10,$i) - 1;
260                        if ($t2[$p] > 255) $t2[$p] = 255;
261                        $ret[] = array("min" => implode(".", $t1), "max" => implode(".", $t2));
262                }
263        }
264        return $ret;
265}
266
267function generate_account_code() {
268        $ret = '';
269        for ($i=1;$i<=20;$i++) {
270                $ret .= rand(0, 9);
271        }
272        return $ret;
273}
274
275function translate($field, $section='') {
276        global $lang;
277        if ($section == '') {
278                $t = $lang[$field];
279        } else {
280                $t = $lang[$section][$field];
281        }
282        return ($t == '' ? $field : $t);
283}
284
285function validate_zone($name) {
286        $name = str_replace("_", "-", $name);
287        $name = strtolower($name);
288        if (preg_match('/^((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)*([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])|)$/', $name) == 0) return NULL;
289        return $name;
290}
291
292function validate_name_ns($name, $node) {
293        global $db;
294        $name = str_replace("_", "-", $name);
295        $name = strtolower($name);
296        $allowchars = 'abcdefghijklmnopqrstuvwxyz0123456789-';
297        $ret = '';
298        for ($i=0; $i<strlen($name); $i++) {
299                $char = substr($name, $i, 1);
300                if (strstr($allowchars, $char) !== FALSE) $ret .= $char;
301        }
302        if ($ret == '') $ret = 'noname';
303        $i=2;
304        $extension = '';
305        do {
306                $cnt = $db->cnt('', 'nodes', "name_ns = '".$ret.$extension."' AND id != '".$node."'");
307                if ($cnt > 0) {
308                        $extension = "-".$i;
309                        $i++;
310                }
311        } while ($cnt > 0);
312        return ($extension != '' ? $ret.$extension : $ret);
313}
314
315function is_ip($ip, $full_ip=TRUE) {
316        $ip_ex = explode(".", $ip, 4);
317        if ($ip == '') return FALSE;
318        for ($i=0;$i<count($ip_ex);$i++) {
319                if ($i == count($ip_ex)-1 && $ip_ex[$i] == '') continue;
320                if (!is_numeric($ip_ex[$i]) || $ip_ex[$i] < 0 || $ip_ex[$i] > 255) return FALSE; 
321        }
322        return ($full_ip?(count($ip_ex)==4):TRUE);
323}
324
325function include_gmap($javascript) {
326        global $main, $vars, $lang;
327       
328       
329        $serve_host = strtolower($_SERVER['SERVER_NAME']);
330        $serve_path = $serve_host.$_SERVER['PHP_SELF'];
331        $gmap_key = false;
332       
333        // Loop around all keys to find the most appropriate   
334        foreach($vars['gmap']['keys'] as $key_path => $key) {
335                $key_path = strtolower($key_path);
336               
337                // remove prefixed http://
338                if (substr($key_path, 0, 7) == 'http://') {
339                        $path = substr($key_path, 7);
340                } else if (substr($key_path, 0, 8) == 'https://') {
341                        $path = substr($key_path, 8);
342                }
343               
344               
345                // If host name is not the same then false
346                if (substr($key_path, 0, strlen($serve_host)) != $serve_host)
347                        continue;
348
349                // Compare if server_path includes $key_path
350                if (substr($serve_path, 0, strlen($key_path)) != $key_path)
351                        continue;
352               
353                $gmap_key = $key;
354        }
355        $script_params = array(
356                'file' => 'api',
357                'v' => $vars['gmap']['api'],
358                'hl=' => $lang["iso639"]
359        );
360        if ($gmap_key !== false)
361                $script_params['key'] = $gmap_key;
362        $main->html->head->add_script("text/javascript",
363                htmlspecialchars("http://{$vars['gmap']['server']}/maps?" .
364                        http_build_query($script_params)
365                )
366        );
367        $main->html->head->add_script("text/javascript", $javascript);
368        $main->html->head->add_extra(
369                '<style type="text/css">
370                        v\:* {
371                        behavior:url(#default#VML);
372                        }
373                </style>');
374       
375        if(!$main->html->body->tags['onload']) {
376                $main->html->body->tags['onload']="gmap_onload();";
377        } else {
378                $main->html->body->tags['onload'].="gmap_onload();";
379        }
380        $main->html->body->tags['onunload'] = "GUnload()"; //added to reduce IE memory leaks
381        return TRUE;
382}
383
384function getmicrotime(){ 
385        list($usec, $sec) = explode(" ",microtime()); 
386        return ((float)$usec + (float)$sec); 
387} 
388
389function array_multimerge($array1, $array2) {
390        if (is_array($array2) && count($array2)) {
391                foreach ($array2 as $k => $v) {
392                        if (is_array($v) && count($v)) {
393                                $array1[$k] = array_multimerge($array1[$k], $v);
394                        } else {
395                                $array1[$k] = $v;
396                        }
397                }
398        } else {
399                $array1 = $array2;
400        }
401       
402        return $array1;
403}
404
405function language_set($language='', $force=FALSE) {
406        global $vars, $db, $lang;
407        if ($force) {
408                $tl = $language;
409        } elseif (get('lang') != '') {
410                $tl = get('lang');
411        } elseif (isset($_SESSION['lang']) && $_SESSION['lang'] != '') {
412                $tl = $_SESSION['lang'];
413        } elseif ($language != '') {
414                $tl = $language;
415        } else {
416                $tl = $vars['language']['default'];
417        }
418       
419        if ($vars['language']['enabled'][$tl] === TRUE && 
420                        file_exists(ROOT_PATH."globals/language/".$tl.".php")) {
421
422                include_once(ROOT_PATH."globals/language/".$tl.".php");
423                if (file_exists(ROOT_PATH."config/language/".$tl."_overwrite.php")) {
424                        include_once(ROOT_PATH."config/language/".$tl."_overwrite.php");
425                        $lang = array_multimerge($lang, $lang_overwrite);
426                }
427                // Set-up mbstring's internal encoding (mainly for supporting UTF-8)
428                mb_internal_encoding($lang['charset']);
429               
430                // Set-up NAMES on database system
431                if($vars['db']['version']>=4.1)
432                        $db->query("SET NAMES '".$lang['mysql_charset']."'");
433
434        } else {
435
436                if ($tl == $_SESSION['lang']) unset($_SESSION['lang']);
437                die("WiND error: Selected language not found.");
438
439        }
440}
441
442function url_fix ($url, $default_prefix="http://") {
443        if($url == "") {
444                return;
445        }
446        // Windows shares (samba) check
447        if (substr(stripslashes($url), 0, 2) == '\\\\') {
448                return 'file://'.str_replace('\\', '/', substr(stripslashes($url), 2));
449        }
450        // Insert default prefix
451        if (strpos($url, '://') === FALSE) {
452                return $default_prefix.$url;
453        }
454        return $url;
455       
456}
457
458function replace_sql_wildcards($str) {
459        $str = str_replace("*", "%", $str);
460        $str = str_replace("?", "_", $str);
461        return $str;
462}
463
464function format_version($version_array) {
465        $str = '';
466        foreach ($version_array as $dig) {
467                $glue =  is_numeric($dig)? '.' : '-';
468                $str .= empty($str)?$dig:$glue . $dig;
469        }
470        return $str;   
471}
Note: See TracBrowser for help on using the repository browser.