<?php
require ('authentication_member.php');
?>
<?php

/* 编辑文章 */
/* 162100源码 - 162100.com */


if (POWER == 0) {
  err('请<a href="./login.php" target="_blank">登陆</a>。');
}
if (!isset($_GET['id'])) {
  $_GET['id'] = $_POST['id'];
}
if (!isset($_GET['area_id'])) {
  $_GET['area_id'] = $_POST['area_id'];
}
if (!isset($_GET['mode'])) {
  $_GET['mode'] = $_POST['mode'];
}

if (!$_GET['id'] || !is_numeric($_GET['id'])) {
  err('文章参数出错！<br />问题分析：1、您可能未选择文章；2、参数传递出错。');
}

if ($_GET['area_id'] == '' || !preg_match('/^\d+\-\d+(\_\d+)*$/', $_GET['area_id'])) {
  err('标签参数为空或错误！请重选分类。');
}

if (!isset($sql['db_err'])) {
  db_conn();
}
if ($sql['db_err'] != '') {
  err($sql['db_err']);
}

//栏目属性
$result = @mysql_query('SELECT * FROM '.$sql['pref'].''.$sql['data']['承载版区分类的表名'].' WHERE area_id="'.get_arearoot($_GET['area_id']).'" LIMIT 1', $db);
if (!$area_power = @mysql_fetch_assoc($result)) {
  err('系统错误：标签参数不合法（数据库找不到该类别根栏目）！请重选分类。');
}
@mysql_free_result($result);

//取版区信息
$result = @mysql_query('SELECT id FROM '.$sql['pref'].''.$sql['data']['承载版区分类的表名'].' WHERE area_id="'.$_GET['area_id'].'"', $db);
if (!@mysql_num_rows($result) > 0) {
  err('系统错误：标签参数不合法（数据库找不到该类别）！请重选分类。');
}
@mysql_free_result($result);

//身份验证
$result = @mysql_query('SELECT power,point,check_reg FROM '.$sql['pref'].''.$sql['data']['承载成员档案的表名'].' WHERE username="'.$session[0].'"', $db);
if (!$row_member = @mysql_fetch_assoc($result)) {
  err('查无您的档案！您不是合法的注册成员。');
}
@mysql_free_result($result);
/*
if ($row_member['check_reg'] == '1') {
  err('您的注册尚在审核中！您不是合法的注册成员。');
}
*/
if ($row_member['check_reg'] == '2') {
  err('您的帐户已被管理员移除至<a href="list_member.php?act=punished" target="_blank">黑名单</a>。');
}


if (POWER == 1) { //不计管理员5、4、版主3、2
  if (strstr($row_member['power'].'_', 'a') || strstr($row_member['power'].'_', 't')) { //a所有，t主题。用下划线补空
    err('提交被拒绝！您已经被限制发表，具体请询问管理员，以获得发表权限。');
  }
  if (is_numeric($web['write_start']) && $row_member['point'] < $web['write_start']) {
    err('提交被拒绝！系统设置发表需积分达到'.$web['write_start'].'分。');
  }
  if (is_numeric($area_power['area_power_write']) && $row_member['point'] < $area_power['area_power_write']) {
    err('提交被拒绝！本类别发表积分需达到'.$area_power['area_power_write'].'分。');
  }
}
$linkpr = POWER > 1 ? true : ($row_member['point'] < $web['link_start'] ? false : true);
unset($row_member);

$result = @mysql_query('SELECT id,title_mark,author_ip,area_id,area_check,reward FROM '.$sql['pref'].''.$sql['data']['承载主题文章的表名'].' WHERE id="'.$_GET['id'].'"', $db); // AND author_ip="'.$session[0].'"
if (!$row_author = @mysql_fetch_assoc($result)) {
  err('数据库查不到此文章！');
}
if (POWER < 4) {
  if (POWER >= 1) {
    if ($session[0] != $row_author['author_ip']) {
      if (!strstr($session[4].'_', '('.get_arearoot($row_author['area_id']).')')) {
        err('您'.$session[4].'没有编辑此栏目（'.$row_author['area_id'].'）文章的权力！');
      }
      err('你与该文作者不符！');
    }
  }
  if (strstr($row_author['reward'], '（已兑现）')) {
    err('该文已经兑现悬赏，不允再编辑。');
  }
}
@mysql_free_result($result);


/* 过滤、检测 */
@ require ('inc/function/filter.php');
$subject = filter1($_POST['subject'], true);
server_sbj($subject); //主题检测
$content = filter2($_POST['content']);
server_chk($content, $web['list_wordcount']); //内容检测
//$topdate=gmdate('YmdHis',time()+(floatval($web['time_pos'])*3600));
//$date=get_date($topdate,10);

//FULLTEXT
$subject_fulltext = preg_replace('/[[:punct:]]/i', ' ', $subject);
$subject_fulltext = preg_replace('/\pP/u', ' ', $subject_fulltext);
$subject_fulltext = preg_replace('/[\xe0-\xef][\x80-\xbf]{2}/e', '"".toUnicode("$0").""', $subject_fulltext);

$keyword_fulltext = preg_replace('/[[:punct:]]/i', ' ', filter1($_POST['keyword'], true));
$keyword_fulltext = preg_replace('/\pP/u', ' ', $keyword_fulltext);
$keyword_fulltext = preg_replace('/[\xe0-\xef][\x80-\xbf]{2}/e', '"".toUnicode("$0").""', $keyword_fulltext);

$title_key = ''.$subject_fulltext.'|TMD| '.$keyword_fulltext;

//处理悬赏
$reward = round(floatval($_POST['reward']), 2);
if ($reward > 0) {
  if ($reward < floatval($row_author['reward'])) {
    err('悬赏值只能增加不能减少！');
  }
  if (POWER > 0 && POWER < 4) {
    //求和货币值
    $result = @mysql_query('SELECT SUM(money) AS total FROM '.$sql['pref'].''.$sql['data']['承载财务数据的表名'].' WHERE (username="'.$session[0].'" AND type="0")', $db);
    $row = @mysql_fetch_assoc($result);
    $total_funds = floatval($row['total']);
    unset($row);
    @mysql_free_result($result);

    if ($reward - floatval($row_author['reward']) > $total_funds) {
    //if ($reward > $total_funds) {
      err('余额（'.$total_funds.'）不足！你最多只能悬赏'.(floatval($row_author['reward']) + $total_funds).'货币值');
    }
    $eval_reward = '@mysql_query(\'INSERT INTO `'.$sql['pref'].''.$sql['data']['承载财务数据的表名'].'` (`username`,`type`,`description`,`money`,`date`,`other`) VALUES ("'.$session[0].'","0","悬赏","-'.($reward - floatval($row_author['reward'])).'",DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR),"文章ID：<a href=\"article.php?mode='.$web['sitemode'].'&id=\'.$_GET[\'id\'].\'\" target=\"_blank\">\'.$_GET[\'id\'].\'</a>")\', $db);
';
  }
  $title_mark_ = '<img src="inc/images/coin.gif" title="悬赏" />';
  $update_eval .= ',`reward`="'.$reward.'"';
}

if (POWER <= 1) {
  /*限制发布重复***************************************待优化*/
  if ($web['send_re'] == 1 || $web['send_re'] == 2) {
    if ($web['send_re'] == 2) {
      $ko1 = ' B.author_ip="'.$session[0].'" AND';
      $ko2 = '您所发布的';
    }
    $result = @mysql_query('SELECT COUNT(A.id) AS cf FROM '.$sql['pref'].''.$sql['data']['承载关键词的表名'].' AS A,'.$sql['pref'].''.$sql['data']['承载主题文章的表名'].' AS B WHERE'.$ko1.' B.id<>"'.$_GET['id'].'" AND A.id=B.id AND (MATCH (A.title) AGAINST (\'"'.$subject_fulltext.'|TMD|"\' IN BOOLEAN MODE))', $db);
    $row = @mysql_fetch_assoc($result);
    @mysql_free_result($result);
    if ($row['cf'] > 0) {
      err(''.$ko2.'文章库中已有相同题目的记录！禁止信息重复。');
    }
    unset($row);
  }
}

@ require ('inc/function/write_file.php');
$up_arr = array();
//图
if (preg_match('/<img [^>]*src[\s\r\n]*=(?![\s\r\n]*\"?inc\/images\/)[^>]*>/i', $content, $mi)) {
  $title_mark .= '<img src="inc/images/picye.gif" title="文中含图" />';
  @ require ('inc/function/img.php');
/*
  @ob_flush();
  @flush();
  echo '<span class="grayword">正在处理缩略图…</span>';
*/
  //处理缩略图
  $temp_thumb = 'thuml';
  $thumb = urldecode(preg_replace('/.+src[\s\r\n]*=[\s\r\n]*(\"|\')?([^\"\>\s]+\.(gif|jpg|png)).+/i', '$2', $mi[0]));
  $thumb_format = strtolower(ltrim(strrchr($thumb, '.'), '.'));
  $thumb_here = '__temp__/temp/'.$temp_thumb.'-'.$_GET['id'].'.'.$thumb_format.'';

  if (substr($thumb, 0, 14) == 'obj.php?title=') {
    $result = @mysql_query('SELECT `text` FROM '.$sql['pref'].''.$sql['data']['承载上传数据的表名'].' WHERE title="'.substr($thumb, 14).'" LIMIT 1', $db);
    if ($row_t = @mysql_fetch_assoc($result)) {
      $thumb_contents = $row_t['text'];
    }
    unset($row_t);
    @mysql_free_result($result);
  } else {
    $thumb_contents = @file_get_contents($thumb);
  }
  if ($thumb_contents) {
    write_file($thumb_here, $thumb_contents);
    //if (run_img_resize($thumb_here, $thumb_here, 120, false, 75)) {
    run_img_resize($thumb_here, $thumb_here, 120, false, 75);
      $thumb_here = typeto($thumb_here, 'jpg');
      if ($thumb_content = @file_get_contents($thumb_here)) {
        $up_arr[$thumb_here] = '
      @mysql_query(\'REPLACE INTO `'.$sql['pref'].''.$sql['data']['承载上传数据的表名'].'` (`title`,`text`,`type`,`username`,`date`) VALUES ("'.basename($thumb_here).'","\'.mysql_real_escape_string($thumb_content).\'","image/jpeg","'.$row_author['author_ip'].'",DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR))\', $db);
        unlink($thumb_content);
      ';
      }
    //}
  }
/*
  echo '√<br />';
*/
} else {
  $index_e = '
    @mysql_query(\'DELETE FROM '.$sql['pref'].''.$sql['data']['承载上传数据的表名'].' WHERE title LIKE "info-'.$_GET['id'].'.%" OR title LIKE "thumb-'.$_GET['id'].'.%" OR title LIKE "thuml-'.$_GET['id'].'.%"\', $db);
    if ($lost_img = @glob("__temp__/temp/info-'.$_GET['id'].'-*")) {
      foreach ($lost_img as $i_img) {
        @unlink($i_img);
      }
    }
    unset($lost_img, $i_img);
    @unlink("__temp__/temp/thumb-'.$_GET['id'].'.jpg");
    @unlink("__temp__/temp/thuml-'.$_GET['id'].'.jpg");
  ';
}

if (preg_match('/<embed [^>]*src[\s\r\n]*=[^>]+>|<object [^>]*><param [^>]*value[\s\r\n]*=[^>]+>/i', $content)) {
  $title_mark .= '<img src="inc/images/picfil.gif" title="文中含影辑" />';
}
if (preg_match('/<a [^>]*href[\s\r\n]*=[^\>]+\.('.$web['_18_type'].')[^>]*>/i', $content)) {
  $title_mark .= '<img src="inc/images/picenc.gif" title="文中含附件" />';
}
$title_mark .= $title_mark_;

$content = preg_replace('/(<[^>]+)(__temp__\/temp\/\d+-[^\/\"\s]+)/ie', '"$1".cha_up("$2").""', $content);

function cha_up($file) {
  global $web, $sql, $up_arr, $session, $up_arr_lost;
  $filename = urldecode(basename($file));
  $format = strtolower(ltrim(strrchr($filename, '.'), '.'));
  $title = 'info-'.$_GET['id'].'-'.substr($filename, 0, 14).'.'.$format;
  if ($GLOBALS['ofile'] != $filename) {
    if (file_exists('__temp__/temp/'.$filename)) {
      $mime = preg_replace('/^.+--/i', '', $filename);
      $mime = preg_replace('/\.'.$format.'$/i', '', $mime);
      $up_arr['__temp__/temp/'.$filename] = $web['uploadto'] == 1 ? '
      if ($obj_contents = @file_get_contents($k)) {
        @mysql_query(\'REPLACE INTO `'.$sql['pref'].''.$sql['data']['承载上传数据的表名'].'` (`title`,`text`,`type`,`username`,`date`) VALUES ("'.$title.'","\'.mysql_real_escape_string($obj_contents).\'","'.urldecode($mime).'","'.$row_author['author_ip'].'",DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR))\', $db);
        unset($obj_contents);
      }
      '.($web['temp'] == 1 ? '@rename($k, \'__temp__/temp/'.$title.'\');' : '@unlink($k);').'' : '@rename($k, \'__temp__/temp/'.$title.'\');';
      $GLOBALS['ofile'] = $filename;

    } else {
      err('转移上传文件出错！上传源文件已经不存在，可能是重复提交造成。');
    }
  } else {
    $GLOBALS['ofile'] = $filename;
  }
  return 'obj.php?title='.$title;
}

//print_r($up_arr);print_r($up_arr_lost);die;



//过滤链接
if ($linkpr == false) {
  $content = preg_replace('/<a [^>]*>|<\/a\s*>/i', '', $content);
}


if (!empty($area_power['area_check'])) {
  if (POWER > 1) {
    $update_output = '编辑完毕。';
  } else {
    if ($row_author['area_check'] == '') {
      @mysql_query('UPDATE `'.$sql['pref'].''.$sql['data']['承载成员档案的表名'].'` SET point=IF(point-'.abs($web['writeadd']).'>0,point-'.abs($web['writeadd']).',"0"),writecount=IF(writecount-1>0,writecount-1>0,"0") WHERE username="'.$session[0].'"', $db);
    }
    $update_eval .= ',area_check="1"';
    $update_eval .= ',topdate=IF(topdate<DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR),DATE_ADD(UTC_TIMESTAMP(), INTERVAL '.floatval($web['time_pos']).' HOUR),topdate)';
    $update_output = '已提交管理员审核，请待候。';
  }
}



@mysql_query('UPDATE `'.$sql['pref'].''.$sql['data']['承载主题文章的表名'].'` SET title="'.mysql_real_escape_string($subject).'",`text`="'.mysql_real_escape_string($content).'",title_mark="'.mysql_real_escape_string(preg_replace('/^(\[荐\])?.*$/' , '$1'.$title_mark, $row_author['title_mark'])).'",area_id="'.$_GET['area_id'].'"'.$update_eval.' WHERE id="'.$_GET['id'].'"', $db); // AND author_ip="'.$session[0].'"

$edit_result_1 = @mysql_affected_rows();
@mysql_query('REPLACE INTO `'.$sql['pref'].''.$sql['data']['承载关键词的表名'].'` (`id`,`title`) VALUES ("'.$_GET['id'].'","'.$title_key.'")', $db);
$edit_result_2 = @mysql_affected_rows();

if ($edit_result_1 > 0 || $edit_result_2 > 0) {

  preg_match_all('/<[^>]+(src|href)[\s\r\n]*=[\s\r\n]*"?obj\.php\?title\=([^\/\"\s\&\=]+)/i', $content, $matcher_upload);
  if (count($matcher_upload[2]) > 0) {
    $matcher_upload[2] = array_unique($matcher_upload[2]);    
    @mysql_query('DELETE FROM '.$sql['pref'].''.$sql['data']['承载上传数据的表名'].' WHERE title LIKE "info-'.$_GET['id'].'-%" AND (title<>"'.implode('" AND title<>"', $matcher_upload[2]).'")', $db);
    if ($lost_img = @glob('__temp__/temp/info-'.$_GET['id'].'-*')) {
      foreach ($lost_img as $i_img) {
        if (!in_array(basename($i_img), $matcher_upload[2])) {
          @unlink($i_img);
        }
      }
    }
    unset($lost_img, $i_img);
  } else {
    @mysql_query('DELETE FROM '.$sql['pref'].''.$sql['data']['承载上传数据的表名'].' WHERE title LIKE "info-'.$_GET['id'].'-%"', $db);
    if ($lost_img = @glob('__temp__/temp/info-'.$_GET['id'].'-*')) {
      foreach ($lost_img as $i_img) {
        @unlink($i_img);
      }
    }
    unset($lost_img, $i_img);
  }
  if (isset($index_e)) {
    eval($index_e);
  }

  if (count($up_arr) > 0) {
    foreach ($up_arr as $k => $s) {
      eval($s);
    }
  }


  del_uploadfiles();

  $sitemode = (!empty($_GET['mode']) && file_exists('inc/css/'.$_GET['mode'].'/article.php')) ? $_GET['mode'] : $web['sitemode'];
  $article_url = $web['url_html_article'] == 1 ? 'article.'.$sitemode.'.'.$_GET['id'].'.1.html' : 'article.php?mode='.$sitemode.'&id='.$_GET['id'].'';




  if (file_exists('get_newinfo_for162100_run.php')) {
    include ('get_newinfo_for162100_run.php');
  }



  if ($_POST['m']==1) {
    err('
<script>
  if (parent.$("submit_safe_in")!=null) parent.$("submit_safe_in").innerHTML="编辑成功！";
  parent.runReset();
  setTimeout("parent.location.href=\''.$article_url.'\';", 1000);
</script>编辑成功！', 'ok');
    
  }



  alert('编辑成功！'.$update_output, $article_url);
} else {
  del_uploadfiles();
  err('编辑数据不成功！（原因：1、您可能未做修改 2、或者错误：'.mysql_errno().':'.mysql_error().'）。');
}

@mysql_close();


?>