source: extensions/Mail_supervisor/include/fonctions.php @ 22118

Last change on this file since 22118 was 22118, checked in by cljosse, 11 years ago

[extensions] mail_superviseur update to piwigo 2.5

File size: 21.3 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
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                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24if (!defined('PHPWG_ROOT_PATH')) die('Hacking attempt!');
25if (!defined('MAIL_SUPERV_PATH')) define('MAIL_SUPERV_PATH' , PHPWG_PLUGINS_PATH.basename(dirname(__FILE__)).'/');
26
27
28global  $superv_champs , $superv_type ,$superv_bl_champs , $superv_bl_type ;
29// if (!isset($_COOKIE[session_name()])){}
30
31global $lang ;
32global $template ;
33
34//================================================
35function corrige_header($Carbonne,$headers,$args,$cl_list_mail,$mailto="")  {
36        global $mails_options,$conf_mail,$infos_message;
37        if (!empty($args[$Carbonne]) && count($args[$Carbonne]) > 0 ){
38                $cl_list_mail  =  str_replace(","," , ",get_strict_email_list(implode(',', $args[$Carbonne])))." \n"  ;
39                $cl_liste_dest = implode(', ', $args[$Carbonne])." \n";
40                if ($mails_options['check_header_carbon'] == 'on') {
41                        $headers = preg_replace('/.*'.$Carbonne.':(.*).\n/i', $Carbonne.': '.  $cl_list_mail, $headers);
42                }
43                $ret->list_mail = $cl_list_mail ;
44        } else {
45                // Raz Bcc, Cc dans headers
46                $headers = preg_replace('/.*'.$Carbonne.'(.*).\n/i', "" , $headers);
47                $ret->list_mail = "" ;
48        }
49        $ret->headers = $headers ;
50        return $ret;
51}
52
53function int_to_heure($int){
54        global $lang,$mails_donnees ;
55        $v0=Date_to_numeric(l10n('Day') );
56
57        $delta=(7*24*60*60) ;
58        $week = (int) ($int/$delta);
59        $int= $int-($week*$delta) ;
60
61        $delta=(24*60*60) ;
62        $day= (int) ($int/$delta);
63        $int=$int-($day*$delta);
64
65        $delta=(60*60) ;
66        $heures=(int) ($int/$delta);
67        $int=$int-($heures*$delta);
68
69        $delta=(60) ;
70        $minutes=(int) ($int/$delta);
71        $int= $int - ($minutes*$delta);
72
73        $secondes=(int) ($int);
74        $day      = substr ('00'.    $day,-2,2);
75        $heures   = substr ('00'. $heures,-2,2);
76        $minutes  = substr ('00'.$minutes,-2,2);
77        $secondes = substr ('00'.$secondes,-2,2);
78
79        $retour="";
80        $Week=explode(" ",l10n('Week %d'));
81        $Week= ($Week[0]);
82
83        if ($week > 0 ) $retour .= "+" . $week ." " . $Week ;
84        if ($day  > 0) $retour .= "+" . $day ." " .l10n('Day');
85        if ($heures > 0) $retour .= "+" . $heures." " .l10n('Hour');
86        if ($minutes > 0) $retour .= "+" . $minutes." " .l10n('Minute');
87        if ($secondes > 0) $retour .= "+" . $secondes." " .l10n('Second');
88        $retour=str_replace("+0","+",$retour);
89        //================================================================================================
90        return $retour;
91}
92
93
94function verif_base(){
95        global $lang,$superv_champs,$superv_type,$superv_bl_champs,$superv_bl_type;
96        load_language('plugin.lang', MAIL_SUPERV_PATH);
97        //==============================================================================
98        create_table(MAIL_BLACK_LISTE_TABLE,$superv_bl_champs,$superv_bl_type) ;
99        ajust_table(MAIL_BLACK_LISTE_TABLE,$superv_bl_champs,$superv_bl_type)  ;
100        //==============================================================================
101        create_table(mail_superv_TABLE,$superv_champs,$superv_type) ;
102        ajust_table(mail_superv_TABLE,$superv_champs,$superv_type)  ;
103        //==============================================================================
104        $valeurs= array (   1,
105                        0,
106                        time(),
107                        2000,
108                        '"604800"' ,
109                        0,
110                        time(),
111                        10,
112                        '"172800"',
113                        '"false"',
114                        time(),
115                        '"172800"',
116                        '"Init"',
117                        '"'.l10n('Sv_supervisor').'"',
118                        '"'.l10n('hello').'"',
119                        '"Test Mail_supervisor"',
120                        '"Information"'
121        );
122        ajout_ligne(mail_superv_TABLE,$superv_champs, $valeurs,false ) ;
123}
124//=========================================
125function Get_colonnes_de($table){
126        $query = 'DESC '.$table.';';
127        $result = pwg_query('desc '.$table);
128        $columns_of= array();
129        while ($row = pwg_db_fetch_assoc($result))
130        {
131                array_push($columns_of, $row['Field']);
132        }
133        pwg_db_free_result($result);
134        return $columns_of;
135}
136//=========================================
137function get_liste($group_id){
138        global $conf ;
139        $query = '
140                        SELECT DISTINCT u.'.$conf['user_fields']['id'].' AS id,
141                                        u.'.$conf['user_fields']['username'].' AS username,
142                                                        u.'.$conf['user_fields']['email'].' AS email,
143                                                                        ui.status,
144                                                                        ui.enabled_high,
145                                                                        ui.level
146                                                                        FROM '.USERS_TABLE.' AS u
147                                                                                        INNER JOIN '.USER_INFOS_TABLE.' AS ui
148                                                                                                        ON u.'.$conf['user_fields']['id'].' = ui.user_id
149                                                                                                                        LEFT JOIN '.USER_GROUP_TABLE.' AS ug
150                                                                                                                                        ON u.'.$conf['user_fields']['id'].' = ug.user_id
151                                                                                                                                                        WHERE ug.group_id='.$group_id.' ';
152        $groups=array();
153        $datas = pwg_query($query);
154
155        if (!empty($datas)) {
156                while ($group = mysqli_fetch_array($datas,MYSQL_ASSOC)){
157                        if (!empty($group['email'])){
158                                //array_push($groups, format_email($group['username'], $group['email'] ));
159                                array_push($groups,
160                                array( 'username' => $group['username'],
161                                'email' => $group['email'],
162                                'format_email' => format_email($group['username'], $group['email'] )
163                                )
164                                );
165                        }
166                }
167        }
168        return $groups ;
169
170}
171//=================================================================================
172
173function create_table($nom_table,$champs,$types)  //mail_superv_TABLE
174{
175        $i=0;
176        $valeurs=array();
177        foreach ( $champs as $champ) {
178                $champ = trim($champ);
179                array_push($valeurs , " `".$champ."`" . '  ' . $types[ $i] )  ;
180                $i +=1;
181        }
182        if ( count($valeurs) == 0) return ;
183        $valeurs=implode(", ",$valeurs) ;
184        //===============================================================================
185        $query = "CREATE TABLE IF NOT EXISTS  `" . $nom_table . "` (". $valeurs . " , PRIMARY KEY  (`id` ) ) ENGINE=MyISAM  ;";
186        if ( pwg_query($query) ) return ;
187        die("ERREUR CREATION ".$query);
188
189
190}
191//===========================================================
192function ajust_table($nom_table,$champs,$types){  //mail_superv_TABLE
193        global $infos_message ;
194        $colonnes = Get_colonnes_de($nom_table);
195        $data =     $types ;
196        $i=0;
197        $valeurs=array();
198        foreach ( $champs as $champ) {
199                $champ = trim($champ);
200                if (!in_array( $champ,$colonnes)) {
201                        array_push($valeurs , " ADD `".$champ."`" . '  ' . $data[  $i] )  ;
202                }
203                $i +=1;
204
205        }
206        //=============================================================================
207        if ( count($valeurs) == 0) return ;
208        $valeurs=implode(", ",$valeurs) ;
209        //===============================================================================
210        $query = "ALTER TABLE `" . $nom_table . "` ". $valeurs ;
211        if (   pwg_query($query)) return ;
212        die($query);
213}
214//==============================================================================
215function ajout_ligne($nom_table,$champs,$valeurs,$force){
216        if (!$force) {
217                $query = "
218                                SELECT `id` , COUNT(`id`) as total
219                                FROM `".$nom_table."` GROUP by  `id`
220                                                ;";
221                $datas=pwg_query($query) ;
222                if (!empty($datas)) {
223                        list($count) = mysqli_fetch_row($datas);
224                }
225
226        }else{
227                $count = 0 ;
228        }
229
230        $data=array();
231        $query = " SELECT *    FROM `".$nom_table."`        ;";
232        $datas = pwg_query($query);
233        if (!empty($datas)) {
234                while ($row = mysqli_fetch_array($datas,MYSQL_ASSOC)){
235                        array_push($data,$row);
236                }
237        }
238
239        $count=  count($data);
240        if ($count == 0) {
241                $n_champs=implode(",",$champs);
242                $n_valeurs=implode(",",$valeurs);
243                $query = "
244                                INSERT INTO `".$nom_table."` (". $n_champs.")
245                                                VALUES ( ". $n_valeurs .")";
246
247                if (pwg_query($query)) return ;
248                die("fonction.php 256".$query);
249        }
250
251}
252//=====================================================================
253function verif_mails_donnees(){
254        global $mails_donnees,$infos_message,$erreur_message,$page;
255
256        if (!is_numeric($mails_donnees['nb_mails_periode'])){
257                $periode = Str_To_Time( $mails_donnees['nb_mails_periode'],0);
258                $mails_donnees['nb_mails_periode']= ($periode > 0) ? $periode : '604800' ;
259        }
260        if (!is_numeric($mails_donnees['nb_spams_periode'])){
261                $periode=Str_To_Time( $mails_donnees['nb_spams_periode'],0);
262                $mails_donnees['nb_spams_periode']= ($periode > 0) ? $periode : '172800' ; ;
263        }
264        if (!is_numeric($mails_donnees['quarantaine_periode'])){
265                $periode=Str_To_Time( $mails_donnees['quarantaine_periode'],0);
266                $mails_donnees['quarantaine_periode']= ($periode > 0) ? $periode : '172800' ;
267        }
268        if  ($infos_message != "")  {
269                array_push($page['infos'],  $infos_message);
270                $infos_message="";
271        }
272        if  ($erreur_message != "")  {
273                array_push($page['errors'], $erreur_message);
274                $erreur_message ="";
275        }
276
277}
278//=======================================================================
279function Date_to_numeric( $Valeurs ){
280        global $lang,$erreur_message,$infos_message;
281
282        $a_ajouter = $Valeurs ;
283
284
285        if (!isset($lang['Sv_second'])) {
286                $Week=explode(" ",l10n('Week %d'));
287                $Week= ($Week[0]);
288
289                $lang['Sv_week'] = $Week;
290                $lang['Sv_day'] =   l10n('Day')  ;
291                $lang['Sv_hour'] =   l10n('Hour')  ;
292                $lang['Sv_minute'] =   l10n('Minute') ;
293                $lang['Sv_second'] =   l10n('Second');
294
295                $lang['Sv_'. $lang['Sv_week']] = 'week';
296                $lang['Sv_'. $lang['Sv_day']] = 'day';
297                $lang['Sv_'. $lang['Sv_hour']] = 'hour';
298                $lang['Sv_'. $lang['Sv_minute']] = 'minute';
299                $lang['Sv_'. $lang['Sv_second']] = 'second';
300
301        }
302        //--- traduction --> anglais ---
303
304        //========= suppression numeric et symbole ==========
305        $new_valeur =( preg_replace("/[0-9+\-.*\/()%]/"," ",$a_ajouter));
306        $nv =  trim( sup_double_espace($new_valeur)) ;
307
308
309
310        $conv['week']= (7*24*60*60);
311        $conv['day']= (24*60*60);
312        $conv['hour']=  (60*60) ;
313        $conv['minute']=  60 ;
314        $conv['second']= 1;
315
316        $nv = explode(" ", $nv );
317
318        foreach($nv as $nv1){
319                if (!isset($lang['Sv_'. $nv1]) ) {
320                        //==== au cas pluriel ===
321                        $nv0 =  substr($nv1, 0,-1) ;
322                        $a_ajouter= str_replace( $nv1,$nv0,   $a_ajouter);
323                        $nv1 = $nv0 ;
324                }
325                if (!isset($lang['Sv_'. $nv1]) ) {
326                        $erreur_message .= $nv1. " ".l10n('not_found')."<br />";
327                        //  die($erreur_message);
328                }else {
329                        ob_start();
330                        $match = $conv[strtolower($lang['Sv_'. $nv1])] ;
331                        $a_ajouter = str_replace($nv1," ". $match  ." ",$a_ajouter) ;
332                        $erreur_message .= ob_get_contents();
333                        ob_end_clean();
334                }
335        }
336
337        $a_ajouter = "+ " .   $a_ajouter ;
338        $a_ajouter=sup_double_espace($a_ajouter);
339        $v1 = array('- ','+ ',' -', ' +', ' ');
340        $v2 = array('-' ,'+' ,'|-', '|+', "*");
341
342        $new_valeur =  str_replace($v1,$v2,$a_ajouter) ;
343        $new_valeur =  str_replace('++','+',$new_valeur ) ;
344
345        return   $new_valeur;
346}
347//=====================================================================
348function Str_To_Time( $ajout,$init_date)
349{
350        //========================================================
351        global $erreur_message,$infos_message,$user;
352        global $lang;
353
354        $ajout=ucwords ($ajout);
355
356
357        if (is_numeric($ajout))
358                $valeur=   $ajout ;
359        else
360        {
361                $valeur= Date_to_numeric( $ajout) ;
362
363        }
364
365        $new_valeur = explode( "|", $valeur );
366
367        $p = $init_date ;
368        $n0=0;
369        $erreur = false;
370
371        //$new_valeur = $a_ajouter + $init_date ;
372        foreach($new_valeur as $nv)
373        {
374                $return = matheval($nv) ;
375                if (strpos("error",$return)===false) {
376                        $p += $return ;
377                }else {
378                        $erreur_message .=   "[" . $ajout . "] --> " . l10n('Sv_syntax_error') . " : " .  $nv ."<br />";
379                        $erreur = true;
380                }
381
382
383        }
384        if ($erreur) $p = -1000 ;
385        return    intval($p) ;
386
387}
388//=====================================================================================
389function matheval($equation)
390{
391
392        $return="error";
393
394
395        $equation = preg_replace("/[^0-9+\-.*\/()%]/","",$equation);
396        $equation = preg_replace("/([+-])([0-9]{1})(%)/","*(1\$1.0\$2)",$equation);
397        $equation = preg_replace("/([+-])([0-9]+)(%)/","*(1\$1.\$2)",$equation);
398        $equation = preg_replace("/([0-9]+)(%)/",".\$1",$equation);
399
400        if ( $equation == "" )
401        {
402                $return = 0;
403        }     else  {
404                @eval("\$return=" . $equation . ";" );
405        }
406        return $return;
407
408}
409
410//======================================================================================
411function sup_double_espace($chaine){
412        global $erreur_message;
413        $str_temp = $chaine." ";
414        $sep=" ";
415        $chaine = trim($chaine);
416        if ($chaine=="") return ;
417        $existe = (strpos($sep.$sep,$chaine )===false) ;
418        while  ($existe ){
419                $str_temp = str_replace($sep.$sep, $sep, $chaine );
420                if($str_temp == $chaine ) return $chaine ;
421                //          $erreur_message .=  $mail_supervisor->Memo_Var($str_temp) ;
422                $chaine  = $str_temp;
423                $existe =  (strpos($sep.$sep,$chaine )===false) ;
424        }
425        return $chaine;
426}
427//==================== TEST black_liste ============================================
428function kill_list() {
429        global $pays,$region,$ville,$ip ;
430        global $erreur_message,$infos_message,$conf;
431        global $conf, $user, $page;
432        global $mails_options ;
433        global $superv_bl_champs,$superv_bl_type ;
434        global $nb ;
435        if (!isset($ip)) {
436                if (getenv("HTTP_CLIENT_IP"))   {
437                        $ip=getenv("HTTP_CLIENT_IP");
438                }else{
439                        $ip=getenv("REMOTE_ADDR");
440                }
441        }
442        $champs=implode(',',$superv_bl_champs);
443        $query = "SELECT ".$champs.",COUNT(`ip`) as total
444                        FROM `".MAIL_BLACK_LISTE_TABLE."`
445                                        WHERE '".$ip."' LIKE `ip`
446                                                        GROUP by `ip`
447                                                        ;";
448        $result = @pwg_query($query);
449        if (!$result) {
450                verif_base();
451                $result = @pwg_query($query);
452        }
453        $datas = mysqli_fetch_array($result,MYSQL_ASSOC);
454        $nb = $datas['total']|0;
455        //=======================================================================
456        if ($mails_options['set_auto'] == 'on') {
457                global $user_name,$mail_adresse;
458
459                if (isset($nb) && $nb>0) {
460                        //if (test_spam($ip,$user['username'] ,$user['email']))  // ne plus tester automatiquement .
461                        if ($nb==0) {
462                                $valeurs=array( 'NULL',
463                                                "'".$ip."'",
464                                                "'".$pays."'",
465                                                "'".$region."'",
466                                                "'".$ville."'",
467                                                "'".$user['email']."'",
468                                                "'".$user['username']."'",
469                                                $nb+1
470                                );
471                                ajout_ligne(MAIL_BLACK_LISTE_TABLE,$superv_bl_champs, $valeurs,$nb==0) ;
472                        }else{
473                                $mail_supervisor->Get_geo();
474                                $nb +=1;
475                                $query ="UPDATE " . MAIL_BLACK_LISTE_TABLE . " SET ";
476                                if (isset($_POST['pays']))
477                                        $query .= "`pays` = '". $pays ."',
478                                                        `region` = '" . $region ."',
479                                                                        `ville` = '" . $ville . "',
480                                                                                        ";
481                                $query .= "`adresse` = '".$user['email']."',
482                                                `fai` = '".$user['username']."',
483                                                                `nb` = " . $nb . "
484                                                                                WHERE '".$ip."' like `ip` ";
485                                pwg_query($query );
486                        }
487                        $erreur_message .= $pays . $ip ." <br />User Name :".$user['username']."<br />User Mail :".$user['email'] . ' -----> ' . l10n('Sv_set_black_liste') ;
488                        // die($nb." ".$ip." ".$user['username']." ".$user['email']);
489
490                        return true ;
491                }
492        }
493        //==============================================================================
494        if (empty($mail_supervisor))  {
495                $mail_supervisor = new mail_supervisor();
496        }
497
498        if ( $mails_options['ip'] == $ip ) return ($nb > 0) ;
499        $ip0= $mails_options['ip'] ;
500        $mails_options['ip'] = $ip ;
501
502        $mail_supervisor->sauve_options();
503        if (  $nb > 0 )
504        {
505                $query = "
506                                SELECT ".$champs.",COUNT(`id`) as total
507                                                FROM `".MAIL_BLACK_LISTE_TABLE."`
508                                                                WHERE '".$ip."' = `ip`
509                                                                                GROUP by `ip`
510                                                                                ;";
511                $result = @pwg_query($query);
512
513                if (!$result) {
514                        verif_base();
515                        $result = @pwg_query($query);
516                }
517                $datas = mysqli_fetch_array($result,MYSQL_ASSOC);
518                $nb = $datas['total'];
519
520                $row  = mysqli_fetch_row(pwg_query($query));
521                $nb =  ($row[7]);
522                $erreur_message .= $ip0 . ' | ' .$ip . ' | ' . $pays . ' | ' . $region . ' | ' . $ville . ' ' . $nb . ' ==> ';
523
524                if ($nb == 0)
525                {
526                        $valeurs=array( 'NULL',
527                                        "'".$ip."'",
528                                        "'".$pays."'",
529                                        "'".$region."'",
530                                        "'".$ville."'",
531                                        "'".$user['email']."'",
532                                        "'".$user['username']."'",
533                                        1
534                        );
535                        ajout_ligne(MAIL_BLACK_LISTE_TABLE,$superv_bl_champs, $valeurs,true) ;
536
537                } else {
538                        $nb += 1;
539                        $query ="
540                                        UPDATE " . MAIL_BLACK_LISTE_TABLE . "
541                                                        SET ";
542                        if (isset($_POST['pays']))
543                                $query .= "
544                                                `pays` = '". $pays ."',
545                                                                `region` = '" . $region ."',
546                                                                                `ville` = '" . $ville . "',
547                                                                                                ";
548                        $query .= "
549                                        `adresse` = '".$user['email']."',
550                                                        `fai` = '".$user['username']."',
551                                                                        `nb` = " . $nb . "
552                                                                                        WHERE '".$ip."' = `ip`
553                                                                                                        ";
554
555                        pwg_query($query );
556                }
557        }
558        return ($nb > 0) ;
559}
560//=====================================================================================
561function test_spam($ip =0,$user_name ='', $mail_adresse = ""){
562        $buffer="";
563        global $page,$infos_message;
564        $src =  "http://www.stopforumspam.com/api?";
565        $type=array();
566        $result="";
567        $ip= sup_double_espace($ip);
568        if (strlen($ip)>3) {
569                //==================  Verifie si l'IP est correct  ================================
570                if (clj_is_ip($ip)){
571
572                } else {
573                        //==================  Verifie si l'adresse mail est correcte  ================================
574                        if( clj_is_mail($ip) ){
575                                $mail_adresse=$ip ;
576                                $ip="";
577                        }
578                        else
579                        {
580                                //==================  Login  ================
581                                $user_name=$ip;
582                                $ip="";
583                        }
584                }
585                //=============================================================================
586        }
587
588        $user_name=str_replace(" ","%20",trim($user_name));
589        if ($user_name==l10n('Sv_guest')) $user_name="";
590        $user_name="";  // ne plus tester sur le login.
591        $mail_adresse =str_replace(" ","%20",trim($mail_adresse));
592        if ( strlen($user_name) > 3)     $type[]="username=$user_name" ;
593        if ( strlen($mail_adresse) > 3)   $type[]="email=".$mail_adresse ;
594        if ( strlen($ip) > 3)   $type[]="ip=".$ip ;
595        foreach  ( $type as $fil ) {
596                $resultat="";
597                if (  clj_fetchRemote($src.$fil , $resultat,1))
598                        $result .= $resultat.'<br />'  ;
599        }
600
601        return !(strpos(  $result ,'yes' ) === false) ;
602
603}
604//==================================================================
605function lire_fichier_distant($fichier){
606        $buffer="";
607        $handle =  @fopen($fichier,"r");
608        if ($handle) {
609                while (!feof($handle)) {
610                        $buffer .= fgets($handle, 4096);
611                }
612                fclose($handle);
613        }
614
615        return  $buffer ;
616
617}
618//================================================
619function clj_is_ip($ip){
620        if (preg_match("/^(((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]{1}[0-9]|[1-9])\.){1}((25[0-5]|2[0-4][0-9]|[1]{1}[0-9]{2}|[1-9]{1}[0-9]|[0-9])\.){2}((25[0-5]|2[0-4][0-9]|[1]{1}[0-9]{2}|[1-9]{1}[0-9]|[0-9]){1}))$/",$ip))    return true ;
621
622}
623
624function clj_is_mail($mail)
625{
626
627        if(preg_match('/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,5}$/' ,$mail)) return true ;
628        if(preg_match('/#^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,5}$#/' ,$mail)) return true ;
629}
630
631
632function clj_fetchRemote($src, &$dest, $timeout=1, $user_agent='Piwigo', $step=0)
633{
634        // Try to retrieve data from local file?
635        // http://www.stopforumspam.com/api?ip=95.211.1.39
636
637        if ($src=="") return ;
638
639        if (!url_is_remote($src))
640        {
641
642                $content = @file_get_contents($src);
643                if ($content !== false)
644                {
645                        is_resource($dest) ? @fwrite($dest, $content) : $dest = $content;
646                        return true;
647                }
648                else
649                {
650                        return false;
651                }
652        }
653
654        // After 3 redirections, return false
655        if ($step > 3) return false;
656
657        // Initialize $dest
658        is_resource($dest) or $dest = '';
659
660        // Try curl to read remote file
661        if (function_exists('curl_init'))
662        {
663                $ch = @curl_init();
664                @curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
665                @curl_setopt($ch, CURLOPT_URL, $src);
666                @curl_setopt($ch, CURLOPT_HEADER, 1);
667                @curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
668                @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
669                $content = @curl_exec($ch);
670                $header_length = @curl_getinfo($ch, CURLINFO_HEADER_SIZE);
671                $status = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
672                @curl_close($content);
673                if ($content !== false and $status >= 200 and $status < 400)
674                {
675                        if (preg_match('/Location:\s+?(.+)/', substr($content, 0, $header_length), $m))
676                        {
677                                return clj_fetchRemote($m[1], $dest,$timeout, $user_agent, $step+1);
678                        }
679                        $content = substr($content, $header_length);
680                        is_resource($dest) ? @fwrite($dest, $content) : $dest = $content;
681                        return true;
682                }
683        }
684
685        // Try file_get_contents to read remote file
686        if (ini_get('allow_url_fopen'))
687        {
688
689                $opts['http'] = array('timeout' => $timeout);
690                $ctx = stream_context_create($opts);
691                $content = @file_get_contents($src, 0, $ctx);
692                if ($content !== false)
693                {
694                        is_resource($dest) ? @fwrite($dest, $content) : $dest = $content;
695                        return true;
696                }
697        }
698
699        return false;
700}
701
702
703?>
Note: See TracBrowser for help on using the repository browser.