Парсинг картинок - помогите поправить код

Статус
В этой теме нельзя размещать новые ответы.

webrulez

Постоялец
Регистрация
12 Май 2008
Сообщения
138
Реакции
2
Собственно DLE Grabber Private дополненный от AkyHa_MaTaTa, вроде должен заливать картинки на сервер при парсинге страниц, но чета ничего не заливает - просто грабит. Вот кусок кода, который отвечает за это дело. Чувствую здесь надо что-то менять.

PHP:
function fix_img($source,$patern,$path_to_save=null){
  if($path_to_save==null)
   $path_to_save="../uploads/posts/". date("Y-m")."/";
 if(!file_exists($path_to_save)){
    if(!mkdir($path_to_save, 0777))
       return $source;
 
В этом участке кода нет сохранения на сервер...
Суда по строке
PHP:
if(!file_exists($path_to_save)){
должно быть продолжение указанной функции...
приведите ее полную - возможно помогу.
 
PHP:
<?php

function myReadFile($url) {
	global $cookie_file;
  $ch=curl_init($url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch,CURLOPT_TIMEOUT,50);
  curl_setopt($ch,CURLOPT_HEADER,0);
  curl_setopt($ch,CURLOPT_REFERER,$url);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
  curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
  curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
  $contents=curl_exec($ch);
	//$contents = str_replace("\n","",$contents);
	//$contents = str_replace("\r","",$contents);
  //return 
  return $contents;
}

function preg_match_dotall($in,$patern=null,$i=1){
 if($patern !== null || !empty($in)){
  if(is_array($patern)){
   foreach($patern as $subpatern){
     preg_match($subpatern,$in,$match);
     if(!empty($match[$i]))
      return trim($match[$i]); 
   }
  }
  else{
   preg_match($patern,$in,$match);
    if(!empty($match[$i]))
      return trim($match[$i]); 
  }
 }
}

function fix_img($source,$patern,$path_to_save=null){
  if($path_to_save==null)
   $path_to_save="../uploads/posts/". date("Y-m")."/";
 if(!file_exists($path_to_save)){
    if(!mkdir($path_to_save, 0777))
       return $source;
 }        
 $adres=preg_match_dotall($source,$patern);
 $full_path_info=pathinfo($adres);
 if(strpos($full_path_info['basename'], '?'))
    list($full_path_info['basename'],$query)=explode('?',$full_path_info['basename']);   
 if(!empty($full_path_info['extension']))
    $full_path_info['basename']=str_ireplace(array('.php','.html','.php3','.htm','.asp','.jsp','.php4','.php5','.pl'),".jpeg",$full_path_info['basename']);
 else
  $full_path_info['basename']=$full_path_info['basename'].".jpeg";
  $fullpath=$path_to_save.$full_path_info['basename'];
  if(file_exists($fullpath))
     return str_ireplace($adres,'/'.$fullpath,$source); 
  elseif(copy($adres,$fullpath)){
         if(filesize($fullpath) && filesize($fullpath)>0)
            return str_ireplace($adres,'/'.$fullpath,$source);
         else
            return $source;       
  }
  else
     return $source;    
}

function curl_redir_exec($ch) {
	global $cookie_file;
  static $curl_loops = 0;
  static $curl_max_loops = 20;
  if ($curl_loops++ >= $curl_max_loops) {
	  $curl_loops = 0;
	  return FALSE;
  }
  curl_setopt($ch, CURLOPT_HEADER, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0'); 
	curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
  curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
  $data = curl_exec($ch);
  list($header, $data) = explode("\n\n", $data, 2);
  $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  if ($http_code == 301 || $http_code == 302) {
    $matches = array();
    preg_match('/Location:(.*?)\n/', $header, $matches);
    $url = @parse_url(trim(array_pop($matches)));
    if (!$url){
      //couldn't process the url to redirect to
      $curl_loops = 0;
      return $data;
    }
    $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
    if (!$url['scheme']) $url['scheme'] = $last_url['scheme'];
    if (!$url['host']) $url['host'] = $last_url['host'];
    if (!$url['path']) $url['path'] = $last_url['path'];
    $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
    curl_setopt($ch, CURLOPT_URL, $new_url);
		//debug('Redirecting to', $new_url);
    return curl_redir_exec($ch);
  } else {
    $curl_loops=0;
    return $data;
  }
}

function update_cookies($url, $login, $pass) {
	global $cookie_file;
	$params = array();
	$params['login_name'] = $login;
	$params['login_password'] = $pass;
	$params['login'] = 'submit';
	$postdata = array();
	foreach ($params as $name => $value) {
    $postdata[] = $name.'='.$value;
  }
	$postdata = implode('&', $postdata);
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, 'http://'.$url.'/#');
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_TIMEOUT, 50);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)');
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
  curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
  curl_exec($ch);
  unset($ch);
}

function transliteral($text=null){
  $maska=array('Ч'=>'Ch','Ш'=>'Sh','Щ'=>'Sch','Ю'=>'Yu'
              ,'ш'=>'sh','щ'=>'sch','ю'=>'yu','я'=>'ya'
              ,'А'=>'A','Б'=>'B','В'=>'V','Г'=>'G'
              ,'Д'=>'D','Е'=>'E','Ё'=>'E','Ж'=>'J'
              ,'З'=>'Z','И'=>'I','Й'=>'Y','К'=>'K'
              ,'Л'=>'L','М'=>'M','Н'=>'N','О'=>'O'
              ,'П'=>'P','Р'=>'R','С'=>'S','Т'=>'T'
              ,'У'=>'U','Ф'=>'F','Х'=>'H','Ц'=>'C'
              ,'Ъ'=>'"','Ы'=>'Y','Ь'=>'\'','Э'=>'E'
              ,'а'=>'a','б'=>'b','в'=>'v','г'=>'g'
              ,'д'=>'d','е'=>'e','ё'=>'e','ж'=>'j'
              ,'з'=>'z','и'=>'i','й'=>'y','к'=>'k'
              ,'л'=>'l','м'=>'m','н'=>'n','о'=>'o'
              ,'п'=>'p','р'=>'r','с'=>'s','т'=>'t'
              ,'у'=>'u','ф'=>'f','х'=>'h','ц'=>'c'
              ,'ь'=>'\'','ы'=>'y','ъ'=>'"','э'=>'e'
              ,'Я'=>'Ya','ч'=>'ch');
 return !empty($text) ? strtr($text,$maska) : null;
}

function date_ ($date_in){
 if(!empty($date_in)){
  $date_in=trim(strtolower($date_in));
  if(strpos($date_in, ',') && strpos($date_in, ':')){
    list($data,$time)=explode(',',$date_in);
    $yes_today= date("d")!==1 ? date("Y-m-d",mktime(0,0,0,date("m"),date("d")-1,date("Y"))) : date("Y-m-d",mktime(0,0,0,date("m")-1,0,date("Y"))) ;
    $data=strtr($data,array('cегодня'=>date("Y-m-d"),'вчера'=>$yes_today));
    return "$data $time:00";  
  }
  else{
   $mount = array ('january'=>'01','february'=>'02','march'=>'03',
                      'april'=>'04','may'=>'05','june'=>'06',
                      'july'=>'07','august'=>'08','september'=>'09',
                      'october'=>'10','november'=>'11','december'=>'12',
                      
                      'jan'=>'01','feb'=>'02','mar'=>'03','apr'=>'04',
                      'jun'=>'06','jul'=>'07','aug'=>'08','sep'=>'09',
                      'oct'=>'10','nov'=>'11','dec'=>'12',
                      
                      'января'=>'01','февраля'=>'02','марта'=>'03',
                      'апреля'=>'04','мая'=>'05','июня'=>'06',
                      'июля'=>'07','августа'=>'08','сентября'=>'09',
                      'октября'=>'10','ноября'=>'11','декабря'=>'12',
                      
                      'янв'=>'01','фев'=>'02','мар'=>'03',
                      'апр'=>'04','июн'=>'06','июл'=>'07',
                      'авг'=>'08','сен'=>'09','окт'=>'10',
                      'ноя'=>'11','дек'=>'12');
                      
   $date_in=strtr($date_in,$mount);
   list($data,$mount,$year)=explode(" ",$date_in);
   if(is_numeric($data) && is_numeric($data) && is_numeric($year)){
    return  date("Y-m-d H:i:s",mktime(rand(1,23),rand(1,59),0,$mount,$data,$year));    
   }
  }
 }
 else 
   return date("Y-m-d H:i:s"); 
}
 
функций, конечно, налеплено валом...
1) меня вот лично смущает сразу строка "../uploads/posts/"! А если вы используете скрипт в корне, то куда должен тогда сохранять?!
2) попробуйте сделать отладку каждой фукции. Посмотрите что она возвращает на выходе. Найдете лживую функцию, потом в ней на каждый шаг отладку с выводом. Так найдете где она вас обманывает.
 
Да, грабер лежит в корнне. Насчет ../uploads/posts/ просто не заметил, но пути прописал бы потом правильные, просто сейчас главное решить вопрос №1. Я сам нифига не понимаю в php, просто подумал что для знающих людей это не окажется проблемой.
 
В приведенном вами коде нет записи в файл... покажите тот участок, откуда идет вызов функции fix_img();
 
Если кому-то интересно, то нужно было просто "NULL" заменить на "TRUE" и убрать двойное равно - и это при том что я ноль в PHP (просто порылся в справочнике).
Стыдно товарищи!

ТЕМА ЗАКРЫТА!
 
Приведите код строки, которую Вы правили.
Что-то я не найду, где можно убрать двойное равно.
 
Приведите код строки, которую Вы правили.
Что-то я не найду, где можно убрать двойное равно.

if($path_to_save==null)

заменил на

if($path_to_save=true)

и все заработало, без этого никак.
Правда тумбы не распознает.
 
строка
if($path_to_save=true)
с точки зрения синтаксиса языка будет означать следующие действия:
1. присвоить переменной $path_to_save значение true
2. Проверить верно ли, что $path_to_save равно true
3. Поскольку теперь она всегда true выполнить нижеследующее.

А ниже было задание адреса для сохранения
$path_to_save="../uploads/posts/". date("Y-m")."/";

Т.о. Вы только избавились от других значений адреса, передаваемых в функцию.
Остальное не изменилось.
Поищите место, откуда вызывается функция fix_img и посмотрите ее третий параметр,
если его нет, то действительно должна использоваться папка "../uploads/posts/". date("Y-m")."/",
а если есть, то надо разбираться, куда же на самом деле надо писать.
 
Статус
В этой теме нельзя размещать новые ответы.
Назад
Сверху