<?php

function plugin_croozweb_init()
{
  $data = array('plugin_croozweb_dataset'=>array(
    'cache_time'    => 24,                                  // キャッシュ有効時間(h)
    'def_max'       => 10,                                 // デフォルト表示数
    'max_limit'     => 10,                                 // 最大表示数
    'head_msg'      => '<h2> %s に関する Web ページ</h2><p class="empty"></p>',
    'err_noresult'  => '%sに関する携帯サイトは見つかりませんでした。',
    'err_noconnect' => 'Crooz! に接続できませんでした。',
    ));
  set_plugin_messages($data);
}


function plugin_croozweb_action()
{
  global $get,$plugin_croozweb_dataset,$vars;
  
  
  if ($get['pmode'] == "refresh")
    {
      $word = (isset($get['q']))? $get['q'] : "";
      $page = (isset($get['ref']))? $get['ref'] : "";
      $vars['page'] = add_bracket($page);
      $vars['cmd'] = "read";
      
      // キャッシュファイル名
      $filename = P_CACHE_DIR.md5($word).".crw";
      
      $old_time = filemtime($filename);
      
      if (!is_readable($filename) || time() - filemtime($filename) > $plugin_croozweb_dataset['cache_time'] * 3600 )
        {
          // 処理中に別スレッドが走らないように
          touch($filename);
          
          @list($ret,$refresh) = plugin_croozweb_get($word,TRUE);
          
          if ($ret)
            {
              // plane_text DB を更新
              echo "updated plane_text DB";
              need_update_plaindb($page);
              // ページHTMLキャッシュを削除
              delete_page_html($page,"html");
            }
          else
            {
              // 失敗したのでタイムスタンプを戻す
              touch($filename,$old_time);
            }
        }
      
      header("Content-Type: image/gif");
      readfile('image/transparent.gif');
      exit;
    }
  
  return false;
}

function plugin_croozweb_convert()
{
  global $plugin_croozweb_dataset,$script,$vars;
  
  //$start = getmicrotime();
  
  $array = func_get_args();
  
  $word = "";
  $def_max = $max = $plugin_croozweb_dataset['def_max'];
  $max_limit = $plugin_croozweb_dataset['max_limit'];
  
  switch (func_num_args())
    {
    case 2:
      $max = min($array[1],$max_limit);
    case 1:
      $word = trim($array[0]);
    }
  $word_euc = $word;
  $word = mb_convert_encoding($word, "SJIS", "EUC-JP");
  
  if ($max < 1) $max = $def_max;
  
  @list($data,$refresh) = plugin_croozweb_get($word);
  
  // 指定件数切り出し
  //  $data = join("</li>\n",(array_slice(explode("</li>",$data),0,$max)));
  
  if ($refresh)
    {
      $vars['mc_refresh'][] = "?plugin=croozweb&pmode=refresh&ref=".rawurlencode(strip_bracket($vars["page"]))."&q=".rawurlencode($word_euc);
    }
  
  //$taketime = "<div style=\"text-align:right;\">".sprintf("%01.03f",getmicrotime() - $start)."</div>";
  return "<div>".sprintf($plugin_croozweb_dataset['head_msg'],htmlspecialchars($word_euc)).$data."</div>";
}

function plugin_croozweb_get($word,$do_refresh=FALSE)
{
  global $plugin_croozweb_dataset;
  
  $data = "";
  $refresh = FALSE;
  
  // キャッシュ有効時間(h)
  $cache_time = $plugin_croozweb_dataset['cache_time'];
  
  // キャッシュファイル名
  $c_file = P_CACHE_DIR.md5($word).".crw";
  
  if (!$do_refresh && file_exists($c_file))
    {
      $data = join('',file($c_file));
      if (time() - filemtime($c_file) > $cache_time * 3600)
        {
          $refresh = TRUE;
        }
    }

  
  if (!$data | $refresh)
    {
      $r_word = rawurlencode($word);
      $crooz = "http://crooz.jp";
      
      $target = $crooz."/pc/S/search.jsp?query=".$r_word."&s_career=d&drct=null";
      
      $data = http_request($target);
      if ($data['rc'] !== 200)
        {
          if (file_exists($c_file))
            $data = join('',file($c_file));
          else
            return "<div>".$plugin_croozweb_dataset['err_noconnect']."(".$data['data'].")</div>";
        }
      $data = $data['data'];
      $data = preg_replace("/\x0D\x0A|\x0D|\x0A/","\n",$data);
      
      // 抽出
      $data = (preg_match("/".preg_quote("<table width=\"100%\">","/")."(.+)".preg_quote("</td>","/")."/s",$data,$match)) ?
        $match[1] : "";
      $data = mb_convert_encoding( $data, "EUC-JP", "SJIS" );

      $result = "";
      $desclimit = 150;

      $count = 0;
      $max_limit = $plugin_croozweb_dataset['max_limit'];

      while(preg_match("/<LI><font size=\"3\">.*?url=(http.*?)&query=.*?&s_type=s_site'\">(.*?)<\/a>.*?<LI>(.*?)<br>.*?(http.*?)<\/font>/s",$data,$match))
        
        {
          
          $url = urldecode($match[1]);
          $name = $match[2];
          $desc = mb_strimwidth($match[3], 0, $desclimit, "...");
          
          $result .= 
            '<a href="' . $url . '">' . $name . '</a><br />'.
            htmlspecialchars($desc) . '<br />' .
//            $url . 
            '<br />';
          
          $data = str_replace($match[0],"",$data);
          $count += 1;
          if ($count >= $max_limit) break;
        }
      
      //trim -> last
      $data = trim($result);
      if (!$data)
        $data = "<ul><li>".str_replace("%s",htmlspecialchars($word),$plugin_croozweb_dataset['err_noresult'])."</li></ul>";

      
      // キャッシュ保存
      $fp = fopen($c_file, "wb");
      fwrite($fp, $data);
      fclose($fp);
    }
  
  return array($data,$refresh);
}
?>