<?php
if (!defined('_GNUBOARD_'))
  exit;

function autolink($str, $bo_table, $stx = '')
{
  $str = ' ' . $str;
  $str = strtr($str, ["&#039;" => "'", "&#034;" => "&quot;"]);

  $str = preg_replace(
    '`<a href="([^"]*)"[^>]*>\S*</a>`i',
    '<a href="$1" target="_blank" class="other-site-link">Link URL</a>',
    $str
  );

  $str = substr($str, 1);

  $str = preg_replace(
    "/\\#([0-9a-zA-Z가-힣_])([0-9a-zA-Z가-힣_]*)/",
    '<a href="?bo_table=' . $bo_table . '&amp;sfl=hash&amp;stx=%23$1$2" class="link_hash_tag">&#35;$1$2</a>',
    $str
  );

  $str = preg_replace(
    "/\\@([0-9])([0-9]*)/",
    '<a href="?bo_table=' . $bo_table . '&amp;sfl=log&amp;stx=$1$2&amp;single=Y" target="_blank" class="log_link_tag">$1$2</a>',
    $str
  );

  return strtr($str, ["[[" => "<span class='member_call'>", "]]" => "</span>"]);
}

function get_sql_search_mmb($search_ca_name, $search_field, $search_text, $search_operator = 'and', $single_use = '')
{
  global $g5;

  $str = $search_ca_name ? "ca_name = '$search_ca_name'" : "";

  $search_text = trim(strip_tags($search_text));

  if (!$search_text) {
    return $search_ca_name ? $str : '0';
  }

  $str = $str ? "$str and " : "";

  $tmp = explode(",", trim($search_field));
  $field = explode("||", $tmp[0]);
  $not_comment = !empty($tmp[1]) ? $tmp[1] : "";

  $search_parts = [];
  foreach (explode(" ", $search_text) as $search_str) {
    if ($search_str === "")
      continue;

    insert_popular($field, $search_str);

    $field_parts = [];
    foreach ($field as $f) {
      $f = preg_match("/^[\w,|]+$/", $f) ? $f : "wr_subject";

      switch ($f) {
        case "mb_id":
        case "wr_name":
          $field_parts[] = "$f = '$search_str'";
          break;
        case "wr_hit":
        case "wr_good":
        case "wr_nogood":
          $field_parts[] = "$f >= '$search_str'";
          break;
        case "wr_num":
          $field_parts[] = "$f = " . ((-1) * $search_str);
          break;
        case "wr_ip":
        case "wr_password":
          $field_parts[] = "1=0";
          break;
        case "hash":
          $field_parts[] = "wr_content like '%$search_str%'";
          break;
        case "log":
          $log_condition = "wr_num >= " . ($search_str * -1);
          if ($single_use) {
            $log_condition .= " and wr_num < " . (($search_str * -1) + 1);
          }
          $field_parts[] = $log_condition;
          break;
        default:
          $field_parts[] = preg_match("/[a-zA-Z]/", $search_str)
            ? "INSTR(LOWER($f), LOWER('$search_str'))"
            : "INSTR($f, '$search_str')";
          break;
      }
    }
    $search_parts[] = "(" . implode(" or ", $field_parts) . ")";
  }

  $str .= "(" . implode(" $search_operator ", $search_parts) . ")";

  if ($not_comment) {
    $str .= " and wr_is_comment = '0'";
  }

  return $str;
}
