source: extensions/PHP_Optimisateur/include/functions.php @ 10337

Last change on this file since 10337 was 10337, checked in by mistic100, 13 years ago

new version 1.4, new plugin for Charlies Content, NConvert updated

File size: 9.4 KB
Line 
1<?php
2
3// Affiche les textes localisés
4function l10n($code) {
5        global $Lang;
6        if (isset($Lang[$code])) {
7                $args = func_get_args();
8                if (count($args) > 1) {
9                        array_shift($args);
10                        return vsprintf($Lang[$code], $args);
11                } else {
12                        return $Lang[$code];
13                }
14        } else {
15                return $code;
16        }
17}
18
19// Retourne la langue de l'utilisateur et les langues installées
20function GetLanguage() {
21        // tableau avec les langues installées
22        $dh = opendir('language');
23        while ($file = readdir($dh)) {
24                if ($file !== '.' && $file !== '..' && is_dir('language/'.$file)) {
25                        $name = (file_exists('language/'.$file.'/iso.txt')) ? file_get_contents('language/'.$file.'/iso.txt') : $file;
26                        $languages[$file] = $name;
27                }
28        }
29        closedir($dh);
30       
31        // recherche du paramètre get ou session, ou langue du navigateur
32        if (isset($_GET['Lang'])) {
33                $user_lang = $_GET['Lang'];
34        } else if (isset($_SESSION['Lang']) AND $_SESSION['Lang'] != NULL) {
35                $user_lang = $_SESSION['Lang'];
36        } else {
37                $user_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
38        }
39       
40        // si langue navigateur cherche une correspondance dans la tableau
41        if (strlen($user_lang) == 2) {
42                foreach (array_keys($languages) as $lang) {
43                        if ($user_lang == substr($lang,0,2)) {
44                                $user_lang = $lang;
45                                break;
46                        }
47                }
48        }
49       
50        // si pas de correspondance OU get faux, langue par défaut
51        if (!in_array($user_lang, array_keys($languages))) {
52                $user_lang = 'en_UK';
53        }
54       
55        $_SESSION['Lang'] = $user_lang;
56        return array('user_lang' => $_SESSION['Lang'], 'languages' => $languages);
57}
58
59// Supprime tous les caractères speciaux
60function delete_special_car($string) {
61        global $CONF;
62       
63        $search = array ('#[éèêë]#','#[ÊËÈÉ]#','#[àâäã]#','#[ÂÄÁÀ]#','#[îïíì]#','#[ÎÏÍÌ]#','#[ûùüúµ]#','#[ÛÙÚÜ]#','#[ôóòõö]#','#[ÓÒÖÔÕ]#','#[ç]#','#[Ç]#','#[ñ]#','#[Ñ]#','#[ýÿ]#','#[Ý]#','#[ \&\!\?\#\"\(\)\{\}\[\]\=\+\~\%]#','#[^a-zA-Z0-9_\.\-]#');
64        $replace = array ('e','E','a','A','i','I','u','U','o','O','c','C',',n','N','y','Y','_','');
65       
66        if ($CONF['renameORNOT']) {
67                return preg_replace($search, $replace, $string);
68        } else {
69                return str_replace(array('%','$',' '), '_', $string);
70        }
71}
72
73// Teste si un dossier est vide
74function is_dir_empty($dir) {
75        $array = scandir($dir);
76        if (count($array) > 2) {
77                return false;
78        } else {
79                return true;
80        }
81}
82
83// Supprime un repertoire non-vide
84function rrmdir($dir) {
85        $dir = rtrim($dir, '/');
86        $objects = scandir($dir);
87       
88        foreach ($objects as $object) {
89                if ($object !== '.' && $object !== '..') {
90                        $path = $dir.'/'.$object;
91                        if (filetype($path) == 'dir') rrmdir($path); 
92                        else unlink($path);
93                }
94        }
95
96        rmdir($dir);
97} 
98
99// Parcours récursivement un dossier
100function recursive_readdir($dir, $array, $dirs=false) {
101        # si $dirs=true liste les dossiers plutot que les fichiers
102        global ${$array}; // Charge la tableau pour la sortie, déclaré à l'exterieur à cause de l'appel recursif de la fonction
103        $dir = rtrim($dir, '/');
104        $dh = opendir($dir);
105       
106        while (($file = readdir($dh)) !== false ) {
107                if ($file !== '.' && $file !== '..') {
108                        $path = $dir.'/'.$file;
109                        if (is_dir($path)) {
110                                if($dirs) ${$array}[] = $path;
111                                recursive_readdir($path, $array, $dirs);
112                        } else {
113                                if(!$dirs) ${$array}[] = $path;
114                        }
115                }
116        }
117        closedir($dh);
118}
119
120// Parse le fichier de configuration
121function XMLParse($xml) {
122        $content = array();
123        foreach ($xml as $nom => $elem) { 
124                if (trim($elem) == '' AND $elem != '') { 
125                        $content[$nom] = XMLParse($elem->children()); 
126                } else { 
127                        $content[$nom] = utf8_encode(utf8_decode($elem));
128                }
129        }
130        return $content;
131}
132
133// Crée le fichier de configuration
134function XMLCreate($array, $level=0) {
135        $content = null;
136        foreach ($array as $nom => $elem) {
137                if (is_array($elem)) {
138                        for($i=0;$i<=$level;$i++) $content .= "\t";
139                        $content .= '<'.$nom.'>'."\n";
140                        $content .= XMLCreate($elem, $level+1);
141                        for($i=0;$i<=$level;$i++) $content .= "\t";
142                        $content .= '</'.$nom.'>'."\n";
143                } else {
144                        for($i=0;$i<=$level;$i++) $content .= "\t";
145                        $content .= '<'.$nom.'>'.$elem.'</'.$nom.'>'."\n";
146                }
147        }
148        return $content;
149}
150
151// Charge la configuration
152function load_config($file) {
153        $config = simplexml_load_file($file);
154        $config = XMLParse($config);
155        $config = array_settype($config);
156        return $config;
157}
158
159// Convertit les booléens, entiers et flotants d'un tableau de 'string'
160function array_settype($array) {
161        foreach ($array as $key => $value) {
162                if (is_array($value)) {
163                        $array[$key] = array_settype($value);
164                } else {
165                        if ($value === 'true') {
166                                $array[$key] = true;           
167                        } else if ($value === 'false') {
168                                $array[$key] = false;   
169                        } else if ($value == null) {
170                                // rien à faire ^^
171                        } else if (preg_match('#^([0-9]*)$#', $value)) {
172                                settype($array[$key], 'int');           
173                        } else if (preg_match('#^([0-9]*)(\.)([0-9]*)$#', $value)) {
174                                settype($array[$key], 'float');         
175                        }
176                }
177        }
178               
179        return $array;
180}
181
182// Booléen vers français ou texte
183function bool_to_string($string, $just_echo=0) {
184        global $Lang;
185        # $just_echo pour pouvoir afficher un booléen tel quel (echo true; n'affiche rien)
186        if (is_bool($string)) {
187                if ($string) {
188                        if ($just_echo) return 'true';
189                        else return l10n('yes');
190                } else {
191                        if ($just_echo) return 'false';
192                        else return l10n('no');
193                }
194        } else {
195                return $string;
196        }
197}
198
199// Converti une chaine de config (param:value;param:value[;]) en tableau associatif
200function ExplodeString($string, $sep1=';', $sep2=':') {
201        $string = preg_replace('#[;]$#', '', $string);
202        $result = array();
203        $a = explode($sep1, $string);
204       
205        foreach ($a as $s) {
206           $v = explode($sep2, $s);
207           $result[$v[0]] = $v[1];
208        }
209        return $result;
210}
211
212// Converti un tableau associatif en chaine de config (param:value;param:value;)
213function ImplodeArray($array, $sep1=';', $sep2=':') {
214        $result = null;
215        foreach ($array as $key => $value) {
216                $result .= $key.$sep2.$value.$sep1;
217        }
218        return $result;
219}
220
221// Convertit les couleurs 'numériques' et gère les 0 manquants
222function nice_hex_color($hex) {
223        $hex = strval($hex);
224        for ($i=strlen($hex); $i<6; $i++) {
225                $hex = '0'.$hex;
226        }
227        return $hex;
228}
229
230// Converti une couleur HEX et RGB
231function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
232        $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
233       
234        if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
235                $colorVal = hexdec($hexStr);
236                $rgbArray['r'] = 0xFF & ($colorVal >> 0x10);
237                $rgbArray['g'] = 0xFF & ($colorVal >> 0x8);
238                $rgbArray['b'] = 0xFF & $colorVal;
239        } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
240                $rgbArray['r'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
241                $rgbArray['g'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
242                $rgbArray['b'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
243        } else {
244                return false; //Invalid hex color code
245        }
246       
247        return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
248}
249
250// Verifie si une chaine est un nombre décimal (plus strict que is_numeric qui fonctionne avec les hexadecimaux)
251function is_decimal($num) {
252        if((is_numeric($num) === true AND (float)$num == $num) OR $num === '0') {
253                return true;
254        } else {
255                return false;
256        }
257}
258
259// Charge le fichier de langue d'un plugin
260function load_plugin_lang($plugin_id) {
261        global $CONF, $Lang;
262        if (file_exists('plugins/'.$plugin_id.'/language/'.$CONF['user_lang'].'.php')) {
263                include('plugins/'.$plugin_id.'/language/'.$CONF['user_lang'].'.php');
264        } else {
265                include('plugins/'.$plugin_id.'/language/en_UK.php');
266        }
267}
268
269// fonction nconvert avec gestion du log
270function nconvert($param, $log=true) {
271        global $LOG;
272
273        exec('include\nconvert.exe '. $param .' 2>&1', $out);
274       
275        if ($log) {
276                for ($i=0; $i<=3; $i++)
277                        unset($out[$i]);
278                if (count($out)) $LOG[] = array_values($out);
279                //$LOG[] = "\t" . $param;
280        } else {
281                return $out;
282        }
283}
284
285// fonction mkdir avec gestion du log
286function mkdir_log($dir) {
287        global $LOG;
288        mkdir($dir, 0777, true);
289        $LOG[] = 'Dir '.$dir.' created';
290}
291
292// fonction copy avec gestion du log
293function copy_log($src, $dest) {
294        global $LOG;
295        copy($src, $dest);
296        $LOG[] = 'Copy '.$src.' to '.$dest;
297}
298
299// fonction rename avec gestion du log
300function rename_log($path, $new_path, $move=false) {
301        global $LOG;
302        rename($path, $new_path);
303        if ($move)
304                $LOG[] = 'Move '.$path.' to '.$new_path;
305        else
306                $LOG[] = 'Rename '.$path.' into '.$new_path;
307}
308
309// enregistre le log dans un fichier
310function print_log($nb, $s) {
311        global $APPversion, $LOG;
312       
313        $config = file_get_contents('config.xml');
314       
315        $string = 
316                "PHP Optimisateur " . $APPversion . "\r\n".
317                date('r') . "\r\n".
318                $nb . " files in " . $s . " seconds" . "\r\n\r\n".
319               
320                $config . "\r\n\r\n";
321       
322        foreach ($LOG as $event) {
323                if (is_array($event)) {
324                        $string .= implode("\r\n", $event) . "\r\n";
325                } else {
326                        $string .= $event . "\r\n";
327                }
328        }
329       
330        if (!file_exists('logs')) {
331                mkdir('logs', 0777, true);
332        }
333       
334        $filename = 'log_' . date('Y-m-d_H-i-s') . '.txt';
335        file_put_contents('logs/'.$filename, $string);
336        return $filename;
337}
338
339// case insentive version of in_array
340function in_arrayi($needle, $haystack) {
341        $needle = strtolower($needle);
342        $haystack = array_map('strtolower', $haystack);
343        return in_array($needle, $haystack);
344}
345
346?>
Note: See TracBrowser for help on using the repository browser.