<?php
if (!defined('IN_DISCUZ')) {
	exit('Access Denied');
}
function str_replace_once_zhiwu55fun($needle, $replace, $haystack) {
    $pos = strpos($haystack, $needle);
    if ($pos === false) {
        return $haystack;
    }
    return substr_replace($haystack, $replace, $pos, strlen($needle));
}
function ext_getuserbyuid_zhiwu55fun($uid) {
    $uid = intval($uid);
    $userInfo = getuserbyuid($uid, 1);
    if (empty($userInfo['uid']) || is_numeric($userInfo['uid']) == false) {
        $userInfo = DB::fetch_first("SELECT uid,username FROM %t WHERE uid=%d",array('zhiwu55cn_reguser',$uid));
    }
    if (empty($userInfo['uid']) || is_numeric($userInfo['uid']) == false) {
        $userInfo = DB::fetch_first("SELECT uid,username FROM %t ORDER BY RAND() LIMIT 1",array('zhiwu55cn_reguser'));
    }
    return $userInfo;
}
function save_img_zhiwu55fun($imgurl,$hzw_remotefile) {
    global $_G;
	if (!isset($_G['cache']['plugin'])) {
		loadcache('plugin');
	}
    $imgurl = preg_replace('/^\/\//','http://',$imgurl);
    $filename = date('His') . strtolower(random(16));
    $dir = !getglobal('setting/attachdir') ? (DISCUZ_ROOT . './data/attachment/') : getglobal('setting/attachdir');
    $dir = $dir . 'forum';
    list($y, $m, $d) = explode('-', date('Y-m-d', time()));
    !is_dir("$dir/$y$m") && mkdir("$dir/$y$m", 0777);
    !is_dir("$dir/$y$m/$d") && mkdir("$dir/$y$m/$d", 0777);
    $savefilename = "$dir/$y$m/$d/";
    if (strpos(strtolower($imgurl), 'gif') !== false) {
        $filename = $filename . '.gif';
    } elseif (strpos(strtolower($imgurl), 'png') !== false) {
        $filename = $filename . '.png';
    } elseif (strpos(strtolower($imgurl), 'jpeg') !== false) {
        $filename = $filename . '.jpeg';
    } else {
        $filename = $filename . '.jpg';
    }
    $savefilename = $savefilename . $filename;
    $imgData = ext_dfsockopen_zhiwu55fun($imgurl);
    if (strlen($imgData) <= 4) {
        $imgData = dfsockopen($imgurl, 0, '', '', false, '', 15, true, 'URLENCODE', false);
    }
    if (strlen($imgData) <= 4 && stripos($imgurl,'https')>5) {
        $imgurl = str_ireplace('https', 'http', $imgurl);
        $imgData = dfsockopen($imgurl);
    }
    file_put_contents($savefilename, $imgData);
    require_once libfile('class/image');
    $image = new image;
    $image->Watermark($savefilename);
    $imginfo = @getimagesize($savefilename);
    if ($imginfo !== false) {
        $imgwidth = $imginfo[0];
        $imagesize = @filesize($savefilename);
    }
    if ($imagesize == 0 || is_numeric($imagesize) === false) {
        $imagesize = strlen($imgData);
    }
    if ($hzw_remotefile == 1 && $_G['setting']['ftp']['on'] == 1) {
        $ftp = &discuz_ftp::instance();
        $ftp->connect();
        $ftpfilename = "forum/$y$m/$d/" . $filename;
		$ftp->upload($savefilename, $ftpfilename);
		@unlink($savefilename);
    }
    return array("filename" => "$y$m/$d/$filename", "imagesize" => $imagesize, "imgwidth" => $imgwidth);
}
function convert_img_zhiwu55fun($tid, $pid, $uid, $message, $hzw_remotefile) {
    global $_G;
	if (!isset($_G['cache']['plugin'])) {
		loadcache('plugin');
	}
    preg_match_all('/<img[^<>]*src\s*=\s*([\'"]?)([^\'">]*)\1[^<>]*>/i', $message, $imglist, PREG_SET_ORDER);
	$HasForumThreadimage=true;
    if (count($imglist) > 0) {
        foreach ($imglist as $img) {
            $imgUrl = $img[2];
            $savefilename = save_img_zhiwu55fun($imgUrl,$hzw_remotefile);
			if($HasForumThreadimage && $savefilename['imagesize']>900)
			{
				$threadimage = array();
				$threadimage['tid'] = $tid;
				$threadimage['attachment'] = $savefilename['filename'];
				if ($hzw_remotefile == 1 && $_G['setting']['ftp']['on'] == 1) {
					$threadimage['remote'] = 1;
				} else {
					$threadimage['remote'] = 0;
				}
				DB::insert("forum_threadimage", $threadimage);
				$HasForumThreadimage=false;
			}
            $attachment = array();
            $attachment['tid'] = $tid;
            $attachment['pid'] = $pid;
            $attachment['uid'] = $uid;
            $attachment['tableid'] = getattachtableid($tid);
            $attachment['downloads'] = 0;
            $aid = DB::insert("forum_attachment", $attachment, true);
            $forum_attachment_n = array();
            $forum_attachment_n['aid'] = $aid;
            $forum_attachment_n['tid'] = $tid;
            $forum_attachment_n['pid'] = $pid;
            $forum_attachment_n['uid'] = $uid;
            $forum_attachment_n['dateline'] = time();
            $forum_attachment_n['filename'] = random(16) . '.jpg';
            $forum_attachment_n['filesize'] = $savefilename['imagesize'];
            $forum_attachment_n['attachment'] = $savefilename['filename'];
            if ($hzw_remotefile == 1 && $_G['setting']['ftp']['on'] == 1) {
                $forum_attachment_n['remote'] = 1;
            } else {
                $forum_attachment_n['remote'] = 0;
            }
            $forum_attachment_n['readperm'] = 0;
            $forum_attachment_n['price'] = 0;
            $forum_attachment_n['isimage'] = 1;
            $forum_attachment_n['width'] = $savefilename['imgwidth'];
            $forum_attachment_n['thumb'] = 0;
            $forum_attachment_n['picid'] = 0;
            C::t("forum_attachment_n")->insert("tid:" . $tid, $forum_attachment_n);
            $message = str_replace_once_zhiwu55fun($img[0], '[attach]' . $aid . '[/attach]', $message);
        }
        return $message;
    } else {
        return $message;
    }
}
if (!function_exists('portalcp_article_pre_next')) {
    function portalcp_article_pre_next($catid, $aid) {
        $data = array('preaid' => C::t('portal_article_title')->fetch_preaid_by_catid_aid($catid, $aid),
            'nextaid' => C::t('portal_article_title')->fetch_nextaid_by_catid_aid($catid, $aid),
            );
        if ($data['preaid']) {
            C::t('portal_article_title')->update($data['preaid'], array('preaid' => C::t('portal_article_title')->fetch_preaid_by_catid_aid($catid, $data['preaid']),
                    'nextaid' => C::t('portal_article_title')->fetch_nextaid_by_catid_aid($catid, $data['preaid']),
                    )
                );
        }
        return $data;
    }
}
function getclassname($typeid, $fid,$portal_catid,$forum_portal,$group_fid) {

	global $_G;
	if($forum_portal=='forum')
	{
		$restr=lang('plugin/csdn123_news', 'forum');
		$fidinfo = C::t('forum_forum')->fetch_info_by_fid($fid);
		$restr=$restr . ' -- ' . $fidinfo['name'];
		if ($typeid > 0) {
			$typeidInfo = C::t('forum_threadclass')->fetch_all_by_typeid_fid($typeid, $fid);
			if(empty($typeidInfo)==false)
			{
				$restr=$restr . ' -- ' . $typeidInfo[$typeid]['name'];
			}
		}

	} elseif($forum_portal=='portal') {

		$restr=lang('plugin/csdn123_news', 'portal');
		loadcache('portalcategory');
		$category = $_G['cache']['portalcategory'];
		if(empty($category[$portal_catid])==false)
		{
			$restr=$restr . ' -- ' . $category[$portal_catid]['catname'];
		}

	} elseif($forum_portal=='group') {

		$restr=lang('plugin/csdn123_news', 'group');
		require_once libfile('function/group');
		$groupName=grouplist('displayorder',array('name'),1,array($group_fid));
		if(count($groupName)>0)
		{
			$restr=$restr . ' -- ' . $groupName[$group_fid]['name'];
		}

	}
	return $restr;
}
function send_thread_zhiwu55fun($hzw_news) {

	global $_G;
	@set_time_limit(200);
	$zhiwu55_result=array();
	$hzw_news['title']=str_replace("'",'&#39;',$hzw_news['title']);
	$hzw_news['title']=str_replace("\'",'&#39;',$hzw_news['title']);
	$hzw_news['title']=str_replace("\&#39;",'&#39;',$hzw_news['title']);
	$hzw_news['title']=str_replace('"','&quot;',$hzw_news['title']);
	$hzw_news['title']=str_replace('\&quot;','&quot;',$hzw_news['title']);
    $zhiwu55_result['title']=$hzw_news['title'];
    $zhiwu55_result['content']=$hzw_news['firstPost0'];
	$commentArr=array();
    for($i=1;$i<$hzw_news['replayArrCount'];$i++)
	{
		$commentArr[]=$hzw_news['firstPost'.$i];
	}
	$zhiwu55_result['topHref']=$hzw_news['topHref'];
	if (empty($zhiwu55_result['title']) || empty($zhiwu55_result['content'])) {
        return lang('plugin/csdn123_news', 'zhiwu55_com_04');
    }
	$hzw_news['send_datetime']=strtotime($hzw_news['sendtime']);
	$hzw_news_chk = DB::fetch_first("SELECT * FROM %t WHERE source_link=%s",array('zhiwu55cn_news',$zhiwu55_result['topHref']));
	if (!empty($hzw_news_chk['browse_url']) && strlen($hzw_news_chk['browse_url'])>5) {
		return $hzw_news_chk['browse_url'];
	}
	if(empty($hzw_news_chk))
	{
		$addNews=array();
		$addNews['title']=daddslashes($zhiwu55_result['title']);
		$addNews['source_link']=daddslashes($zhiwu55_result['topHref']);
		DB::insert('zhiwu55cn_news',$addNews);

	} else {

		DB::update('zhiwu55cn_news',array('del'=>1,'push_date'=>time()),array('source_link'=>$zhiwu55_result['topHref']));

	}
	$post_text = $zhiwu55_result['content'];
	$post_text = str_ireplace('src="//www.zhiwu55.com','src="http://www.zhiwu55.com',$post_text);
	$post_text = str_ireplace('src=//www.zhiwu55.com','src="http://www.zhiwu55.com',$post_text);
	$post_text = str_ireplace("src='//www.zhiwu55.com",'src="http://www.zhiwu55.com',$post_text);
	$first_uid=$hzw_news['first_uid'];
	if(stripos($first_uid,',')!==false)
	{
		$first_uidArr=explode(',',$first_uid);
		shuffle($first_uidArr);
		$first_uid=$first_uidArr[0];
	}
	$UserInfo = ext_getuserbyuid_zhiwu55fun($first_uid);
	if($hzw_news['display_link']==1)
	{
		$post_text=$post_text . '<br><br><br>' . lang('plugin/csdn123_news', 'source_link') . $zhiwu55_result['topHref'];
	}
	if($hzw_news['filter_image']==1)
	{
		$post_text = preg_replace('/<img[^<>]+?>/i', '', $post_text);
	}
	if ($hzw_news['filter_image'] == 2 && $hzw_news['image_center'] == 1) {
		$post_text = preg_replace('/(<img[^<>]+?>)/i', '<div style="text-align:center">$1</div>', $post_text);
	}
	$reply_uid = $hzw_news['reply_uid'];
	if (strpos($reply_uid, ',') != false) {
		$uidArr = explode(',', $reply_uid);
	} else {
		$uidArr = array($reply_uid);
	}
	$uidCount = count($uidArr);
	$title = $zhiwu55_result['title'];
	if(dstrlen($title)>=80 && (stripos($title,'&')!==false || stripos($title,'"')!==false))
	{
		$title=cutstr($title,78,false);
		$cut_num=substr_count($title,'&');
		if(empty($cut_num))
		{
			$cut_num=substr_count($title,'"');
		}
		$cut_num=$cut_num * 6;
		$cut_num=78-$cut_num;
		$title=cutstr($title,$cut_num,false);

	} else if(dstrlen($title)>=80 && stripos($title,'&')===false) {

		$title = cutstr($title,78,false);
	}
	$forum_portal = $hzw_news['forum_portal'];
	if(!defined('DISCUZ_VERSION')) {
		require_once './source/discuz_version.php';
	}
	if ($forum_portal == 'forum' || $forum_portal=='group') {

		if($forum_portal == 'forum')
		{
			$fid = $hzw_news['fid'];
		} else {
			$fid = $hzw_news['group_fid'];
		}
		$_G['forum']['fid'] = $fid;
		$forumInfo = C::t('forum_forum')->fetch_info_by_fid($fid);
		require_once libfile('function/editor');
		if(DISCUZ_VERSION=='X2.5')
		{
				$newthread = array(
					'fid' => $fid,
					'posttableid' => 0,
					'readperm' => 0,
					'price' => 0,
					'typeid' => $hzw_news['threadtypeid'],
					'sortid' => 0,
					'author' => $UserInfo['username'],
					'authorid' => $UserInfo['uid'],
					'subject' => $title,
					'dateline' => $hzw_news['send_datetime'],
					'lastpost' => time(),
					'lastposter' =>  $UserInfo['username'],
					'displayorder' => 0,
					'digest' => 0,
					'special' => 0,
					'attachment' => 0,
					'moderated' => 0,
					'status' => 32,
					'isgroup' => 0,
					'replycredit' => 0,
					'closed' => 0
				);
				$tid = C::t('forum_thread')->insert($newthread, true);
				$pid = insertpost(array(
					'fid' => $fid,
					'tid' => $tid,
					'first' => '1',
					'author' => $UserInfo['username'],
					'authorid' => $UserInfo['uid'],
					'subject' => $title,
					'dateline' => $hzw_news['send_datetime'],
					'message' => '[Just a minute,It is loading]',
					'useip' => $_G['clientip'],
					'invisible' => 0,
					'anonymous' => 0,
					'usesig' => 1,
					'htmlon' => 0,
					'bbcodeoff' => -1,
					'smileyoff' => -1,
					'parseurloff' => 0,
					'attachment' => '0',
					'tags' => '',
					'replycredit' => 0,
					'status' => 0
				));

		}else {
			$modthread = C::m('forum_thread');
		}
		$params = array();
		if ($hzw_news['pseudo_original'] == 1) {
			$title = rep_weiyanchang_zhiwu55fun($title);
		}
		$params['subject'] = $title;
		$params['message'] = '[Just a minute,It is loading]';
		$params['typeid'] = $hzw_news['threadtypeid'];
		$params['sortid'] = 0;
		$params['special'] = 0;
		$params['publishdate'] = $hzw_news['send_datetime'];
		$params['readperm'] = 0;
		$params['allownoticeauthor'] = 1;
		$params['usesig'] = 1;
		$params['replycredit'] = 0;
		if(DISCUZ_VERSION!='X2.5')
		{
			$modthread->newthread($params);
			$tid = $modthread->tid;
			$pid = $modthread->pid;
		}
		$threadData = array();
		$threadData['author'] = $UserInfo['username'];
		$threadData['authorid'] = $UserInfo['uid'];
		$threadData['typeid'] = $hzw_news['threadtypeid'];
		$threadData['subject'] = $title;
		$icon=$_G['setting']['newbie'];
		$threadData['icon'] = -1;
		DB::update('forum_thread', $threadData, 'tid=' . $tid);
		$postData = array();
		if($hzw_news['filter_image']==2)
		{
			$post_text = convert_img_zhiwu55fun($tid, $pid, $UserInfo['uid'], $post_text, $hzw_news['hzw_remotefile']);
		}
		if ($forumInfo['allowhtml'] != 1) {
			$post_text = html2bbcode($post_text);
			$post_text = str_ireplace('&quot;','"',$post_text);
		}
		if ($hzw_news['pseudo_original'] == 1) {
			$post_text = rep_weiyanchang_zhiwu55fun($post_text);
		}
		$postData['message'] = $post_text;
		if (strpos($post_text, '[attach]') !== false) {
			$postData['attachment'] = 2;
			$threadFirstPost_attachment = 2;
			require_once libfile('function/post');
			$temp_uid = $_G['uid'];
			$temp_ismoderator = $_G['forum']['ismoderator'];
			$temp_forumpicstyle = $_G['setting']['forumpicstyle'];
			$temp_thumbwidth = $_G['setting']['forumpicstyle']['thumbwidth'];
			$temp_thumbheight = $_G['setting']['forumpicstyle']['thumbheight'];
			$_G['uid'] = $UserInfo['uid'];
			$_G['forum']['ismoderator'] = 1;
			$_G['setting']['forumpicstyle'] = array();
			$_G['setting']['forumpicstyle']['thumbwidth'] = 160;
			$_G['setting']['forumpicstyle']['thumbheight'] = 160;
			setthreadcover($pid, $tid);
			$_G['uid'] = $temp_uid;
			$_G['forum']['ismoderator'] = $temp_ismoderator;
			$_G['setting']['forumpicstyle'] = $temp_forumpicstyle;
			$_G['setting']['forumpicstyle']['thumbwidth'] = $temp_thumbwidth;
			$_G['setting']['forumpicstyle']['thumbheight'] = $temp_thumbheight;
		}
		$postData['author'] = $UserInfo['username'];
		$postData['authorid'] = $UserInfo['uid'];
		$postData['bbcodeoff'] = 0;
		if ($forumInfo['allowhtml'] == 1) {
			$postData['htmlon'] = 1;
		}
		DB::update('forum_post', $postData, 'pid=' . $pid);
		unset($postData);
		unset($params);
		if (is_numeric($UserInfo['uid'])) {
			DB::query('update %t set threads=threads+1,posts=posts+1,extcredits2=extcredits2+2 where uid=%d',array('common_member_count',$UserInfo['uid']));
			if(DISCUZ_VERSION != 'X2.5' && DISCUZ_VERSION != 'X3')
			{
				$chkNewThread = DB::fetch_first('SELECT * FROM %t WHERE tid=%d',array('forum_newthread',$tid));
				if (empty($chkNewThread)) {
					C::t('forum_newthread')->insert(array('tid' => $tid,
							'fid' => $fid,
							'dateline' => $hzw_news['send_datetime'],
							));
				}
				C::t('common_member_status')->update($UserInfo['uid'], array('lastpost' => time(),'lastip' => $_G['clientip'], 'port' => $_G['remoteport'], 'lastvisit' => TIMESTAMP, 'lastactivity' => TIMESTAMP));
			}
		}
		if(isset($commentArr) && is_array($commentArr))
		{
			$chk_intval_time=time();
			$chk_intval_time=$chk_intval_time-$hzw_news['send_datetime'];
			if($hzw_news['intval_time']>$chk_intval_time)
			{
				$hzw_news['intval_time']=$chk_intval_time;
			}
            $postitem_intval_count = count($commentArr);
			$postitem_intval = $hzw_news['intval_time'] / $postitem_intval_count;
            $postitem_intval = intval($postitem_intval);
            foreach ($commentArr as $post_k => $post_text) {
				if (empty($post_text) || $post_text == "") {
					continue;
				}
                $post_text = trim($post_text);
				if($hzw_news['filter_image']==1)
				{
					$post_text = preg_replace('/<img[^<>]+?>/i', '', $post_text);
				}
                if ($hzw_news['filter_image'] == 2 && $hzw_news['image_center'] == 1) {
                    $post_text = preg_replace('/(<img[^<>]+?>)/i', '<div align="center">$1</div>', $post_text);
                }
                if ($hzw_news['pseudo_original'] == 1) {
                    $post_text = rep_weiyanchang_zhiwu55fun($post_text);
                }
				$postData = array();
                $postUid = rand(1,999);
                $postUid = $postUid % $uidCount;
                $postUid = $uidArr[$postUid];
                $PostUserInfo = ext_getuserbyuid_zhiwu55fun($postUid);
                if (defined('DISCUZ_VERSION') && (DISCUZ_VERSION == 'X3' || DISCUZ_VERSION == 'X2.5')) {
                    $pid = insertpost(array('fid' => $hzw_news['fid'], 'tid' => $tid, 'first' => '0', 'author' => $PostUserInfo['username'], 'authorid' => $PostUserInfo['uid'], 'subject' => '', 'dateline' => getglobal('timestamp'), 'message' => '[Just a minute,It is loading]', 'useip' => getglobal('clientip'), 'invisible' => 0, 'anonymous' => 0, 'usesig' => 1, 'htmlon' => 0, 'bbcodeoff' => 0, 'smileyoff' => - 1, 'parseurloff' => 0, 'attachment' => '0', 'status' => 0));
                } else {
                    $pid = insertpost(array('fid' => $hzw_news['fid'], 'tid' => $tid, 'first' => '0', 'author' => $PostUserInfo['username'], 'authorid' => $PostUserInfo['uid'], 'subject' => '', 'dateline' => getglobal('timestamp'), 'message' => '[Just a minute,It is loading]', 'useip' => getglobal('clientip'), 'port' => getglobal('remoteport'), 'invisible' => 0, 'anonymous' => 0, 'usesig' => 1, 'htmlon' => 0, 'bbcodeoff' => 0, 'smileyoff' => - 1, 'parseurloff' => 0, 'attachment' => '0', 'status' => 0));
                }
                if ($hzw_news['filter_image'] == 2) {
                    $post_text = convert_img_zhiwu55fun($tid, $pid, $PostUserInfo['uid'], $post_text, $hzw_news['hzw_remotefile']);
                }
				if ($forumInfo['allowhtml'] != 1) {
					$post_text = html2bbcode($post_text);
					$post_text = str_ireplace('&quot;','"',$post_text);
				}
                $postData['message'] = $post_text;
				$timeDiff=$postitem_intval*($post_k+1);
				$send_datetime=$hzw_news['send_datetime']+$timeDiff;
				$timeDiffMin=time();
				$send_datetime=min($send_datetime,$timeDiffMin);
                $postData['dateline'] = $send_datetime;
                if (strpos($post_text, '[attach]') !== false) {
                    $postData['attachment'] = 2;
					if(empty($coverImg))
					{
						require_once libfile('function/post');
						$temp_uid = $_G['uid'];
						$temp_ismoderator = $_G['forum']['ismoderator'];
						$temp_forumpicstyle = $_G['setting']['forumpicstyle'];
						$temp_thumbwidth = $_G['setting']['forumpicstyle']['thumbwidth'];
						$temp_thumbheight = $_G['setting']['forumpicstyle']['thumbheight'];
						$_G['uid'] = $UserInfo['uid'];
						$_G['forum']['ismoderator'] = 1;
						$_G['setting']['forumpicstyle'] = array();
						$_G['setting']['forumpicstyle']['thumbwidth'] = 160;
						$_G['setting']['forumpicstyle']['thumbheight'] = 160;
						setthreadcover($pid, $tid);
						$_G['uid'] = $temp_uid;
						$_G['forum']['ismoderator'] = $temp_ismoderator;
						$_G['setting']['forumpicstyle'] = $temp_forumpicstyle;
						$_G['setting']['forumpicstyle']['thumbwidth'] = $temp_thumbwidth;
						$_G['setting']['forumpicstyle']['thumbheight'] = $temp_thumbheight;
					}

                }
				if ($forumInfo['allowhtml'] == 1) {
					$postData['htmlon'] = 1;
				}
                DB::update('forum_post', $postData, 'pid=' . $pid);
                updatemembercount($PostUserInfo['uid'], array('extcredits2' => 1), true, '', 0, '');
                if (is_numeric($PostUserInfo['uid'])) {
                    DB::query('UPDATE %t SET extcredits2=extcredits2+1,posts=posts+1 WHERE uid=%d',array('common_member_count',$PostUserInfo['uid']));
                }
                C::t('forum_threadpartake')->insert(array('tid' => $tid, 'uid' => $PostUserInfo['uid'], 'dateline' => $postData['dateline']));
                if(DISCUZ_VERSION != 'X2.5' && DISCUZ_VERSION != 'X3')
				{
					C::t('common_member_status')->update($PostUserInfo['uid'], array('lastip' => $_G['clientip'], 'port' => $_G['remoteport'], 'lastvisit' => TIMESTAMP, 'lastactivity' => TIMESTAMP));
                }
				if ($forum_portal == 'group') {
                    $chkGroupUser = C::t('forum_groupuser')->fetch_all_userinfo($PostUserInfo['uid'], $fid);
                    if (empty($chkGroupUser)) {
                        C::t('forum_groupuser')->insert($fid, $PostUserInfo['uid'], $PostUserInfo['username'], 4, TIMESTAMP, TIMESTAMP);
                    } else {
                        C::t('forum_groupuser')->update_counter_for_user($PostUserInfo['uid'], $fid, 0, 1);
                    }
                }
            }
        }
		$lastpostArr = array();
		if(!empty($PostUserInfo['username']))
		{
			$lastpostArr['lastpost'] = $postData['dateline'];
			$lastpostArr['lastposter'] = $PostUserInfo['username'];
		} else {
			$lastpostArr['lastpost'] = $hzw_news['send_datetime'];
			$lastpostArr['lastposter'] = $UserInfo['username'];
		}
		$lastpostArr['views'] = $hzw_news['views'];
		if ($threadFirstPost_attachment == 2) {
			$lastpostArr['attachment'] = 2;
		}
		$replies = C::t('forum_post')->count_visiblepost_by_tid($tid);
		$replies = intval($replies) - 1;
		$lastpostArr['replies'] = $replies;
		$lastpostArr['maxposition'] = $replies + 1;
		if($forum_portal=='group')
		{
			$lastpostArr['isgroup'] = 1;
			$chkGroupUser = C::t('forum_groupuser')->fetch_all_userinfo($UserInfo['uid'], $fid);
            if (empty($chkGroupUser)) {
                C::t('forum_groupuser')->insert($fid, $UserInfo['uid'], $UserInfo['username'], 4, TIMESTAMP, TIMESTAMP);
            } else {
                C::t('forum_groupuser')->update_counter_for_user($UserInfo['uid'], $fid, 1);
            }
		}
		DB::update('forum_thread', $lastpostArr, 'tid=' . $tid);
		if ($tid > 0) {

			$previewUrl=$_G['siteurl'] . 'forum.php?mod=viewthread&tid=' . $tid;
			DB::update('zhiwu55cn_news', array('tid_aid'=>$tid,'browse_url' => $previewUrl,'push_date'=>time(),'del'=>0,'title'=>$title), "source_link='".$zhiwu55_result['topHref']."'");
			DB::update('zhiwu55cn_update', array('preview_url' => $previewUrl,'push_date'=>time()), "source_link='".$zhiwu55_result['topHref']."'");
			$lastUserName = $PostUserInfo['username'];
			$lastUserName = $tid . "\t" . daddslashes($title) . "\t" . time() . "\t" . daddslashes($lastUserName);
			DB::query("update %t set threads=threads+1,posts=posts + 1,lastpost=%s,todayposts=todayposts + 1 where fid=%d",array('forum_forum',$lastUserName,$fid));
			return $previewUrl;

		} else {
			return 'send_error';
		}

	} elseif ($forum_portal=='portal') {

		if ($hzw_news['pseudo_original'] == 1) {
			$title = rep_weiyanchang_zhiwu55fun($title);
		}
		$setarr = array();
		$setarr['title'] = $title;
		if($hzw_news['display_link']==1)
		{
			$setarr['fromurl'] = daddslashes($zhiwu55_result['topHref']);
		} else {
			$setarr['fromurl'] = '';
		}
		$setarr['dateline'] = $hzw_news['send_datetime'];
		$setarr['allowcomment'] = 1;
		$zhiwu55_content = $post_text;
		if ($hzw_news['pseudo_original'] == 1) {
			$zhiwu55_content = rep_weiyanchang_zhiwu55fun($zhiwu55_content);
		}
		$summary = $zhiwu55_content;
		$summary = preg_replace('/\s+/','',$summary);
		$summary = preg_replace('/<script.+?<\/script>/i','',$summary);
		$summary = preg_replace('/<style.+?<\/style>/i','',$summary);
		$summary = cutstr(strip_tags($summary), 200);
		$summary = censor($summary);
		$setarr['summary'] = $summary;
		$setarr['catid'] = $hzw_news['portal_catid'];
		$setarr['highlight'] = '|||';
		$setarr['uid'] = $UserInfo['uid'];
		$setarr['username'] = $UserInfo['username'];
		$setarr['contents'] = 1;
		$aid = C::t('portal_article_title')->insert($setarr, 1);
		if(DISCUZ_VERSION != 'X2.5' && DISCUZ_VERSION != 'X3')
		{
			C::t('common_member_status')->update($UserInfo['uid'], array('lastip' => $_G['clientip'], 'port' => $_G['remoteport'], 'lastvisit' => TIMESTAMP, 'lastactivity' => TIMESTAMP));
        }
		C::t('portal_category')->increase($hzw_news['portal_catid'], array('articles' => 1));
		if(DISCUZ_VERSION!='X2.5')
		{
			C::t('portal_category')->update($hzw_news['portal_catid'], array('lastpublish' => time()));
		}
		C::t('portal_article_count')->insert(array('aid' => $aid, 'catid' => $hzw_news['portal_catid'], 'viewnum' => $hzw_news['views']));
		$upload = new discuz_upload();
		$arrayimageurl = $temp = $imagereplace = array();
		if($hzw_news['filter_image']==2)
		{
			preg_match_all("/\<img.+src=('|\"|)?(.*)(\\1)[^<>]*?>/ismUe", $zhiwu55_content, $temp, PREG_SET_ORDER);
		}
		if (!empty($temp) && is_array($temp)) {
			foreach ($temp as $tempvalue) {
				if (strlen($tempvalue[2])>10) {
					$arrayimageurl[] = $tempvalue[2];
				}
			}
			$arrayimageurl = array_unique($arrayimageurl);
			if (!empty($arrayimageurl)) {
				foreach ($arrayimageurl as $imageurl) {
					$attach['oldimageurl'] = $imageurl;
					$attach['ext'] = GetImgFileExt_zhiwu55fun($imageurl);
					if (!$upload->is_image_ext($attach['ext'])) {
						continue;
					}
					$zhiwu55com_imgData = '';
					$zhiwu55com_imgSrc=preg_replace('/^\/\//','http://',$imageurl);
					$zhiwu55com_imgData = dfsockopen($zhiwu55com_imgSrc);
					if (empty($zhiwu55com_imgData)) continue;
					$temp = explode('/', $imageurl);
					$attach['name'] = trim($temp[count($temp) - 1]);
					$attach['thumb'] = '';
					$attach['isimage'] = $upload->is_image_ext($attach['ext']);
					$attach['extension'] = $upload->get_target_extension($attach['ext']);
					$attach['attachdir'] = $upload->get_target_dir('portal');
					$attach['attachment'] = $attach['attachdir'] . $upload->get_target_filename('portal') . '.' . $attach['extension'];
					$attach['target'] = getglobal('setting/attachdir') . './portal/' . $attach['attachment'];
					if (!@$fp = fopen($attach['target'], 'wb')) {
						continue;
					} else {
						flock($fp, 2);
						fwrite($fp, $zhiwu55com_imgData);
						fclose($fp);
					}
					if (!$upload->get_image_info($attach['target'])) {
						@unlink($attach['target']);
						continue;
					}
					$attach['size'] = filesize($attach['target']);
					if (empty($conver_pic) && stripos($attach['attachment'], 'jp') != false && filesize($attach['target']) > 12000) {
						$conver_pic = 'portal/' . $attach['attachment'];
					}
					$attachs[] = daddslashes($attach);
				}
			}
		}
		if (is_array($attachs) && count($attachs)>0) {
			foreach ($attachs as $attach) {
				if ($attach['isimage'] && empty($_G['setting']['portalarticleimgthumbclosed'])) {
					require_once libfile('class/image');
					$image = new image();
					$thumbimgwidth = $_G['setting']['portalarticleimgthumbwidth'] ? $_G['setting']['portalarticleimgthumbwidth'] : 300;
					$thumbimgheight = $_G['setting']['portalarticleimgthumbheight'] ? $_G['setting']['portalarticleimgthumbheight'] : 300;
					$attach['thumb'] = $image->Thumb($attach['target'], '', $thumbimgwidth, $thumbimgheight, 2);
					$image->Watermark($attach['target'], '', 'portal');
				}
				if (getglobal('setting/ftp/on') && ((!$_G['setting']['ftp']['allowedexts'] && !$_G['setting']['ftp']['disallowedexts']) || ($_G['setting']['ftp']['allowedexts'] && in_array($attach['ext'], $_G['setting']['ftp']['allowedexts'])) || ($_G['setting']['ftp']['disallowedexts'] && !in_array($attach['ext'], $_G['setting']['ftp']['disallowedexts']))) && (!$_G['setting']['ftp']['minsize'] || $attach['size'] >= $_G['setting']['ftp']['minsize'] * 1024)) {
					if (ftpcmd('upload', 'portal/' . $attach['attachment']) && (!$attach['thumb'] || ftpcmd('upload', 'portal/' . getimgthumbname($attach['attachment'])))) {
						@unlink($_G['setting']['attachdir'] . '/portal/' . $attach['attachment']);
						@unlink($_G['setting']['attachdir'] . '/portal/' . getimgthumbname($attach['attachment']));
						$attach['remote'] = 1;
					} else {
						if (getglobal('setting/ftp/mirror')) {
							@unlink($attach['target']);
							@unlink(getimgthumbname($attach['target']));
							portal_upload_error(lang('portalcp', 'upload_remote_failed'));
						}
					}
				}
				$setarr = array('uid' => $UserInfo['uid'], 'filename' => random(16) . 'jpg', 'attachment' => $attach['attachment'], 'filesize' => $attach['size'], 'isimage' => $attach['isimage'], 'thumb' => $attach['thumb'], 'remote' => $attach['remote'], 'filetype' => $attach['extension'], 'dateline' => time(), 'aid' => $aid);
				C::t('portal_attachment')->insert($setarr, true);
				$attach['url'] = ($attach['remote'] ? $_G['setting']['ftp']['attachurl'] : $_G['setting']['attachurl']) . 'portal/';
				$newimageurl = $attach['url'] . $attach['attachment'];
				$zhiwu55_content = str_replace($attach['oldimageurl'], $newimageurl, $zhiwu55_content);
			}
		}
		C::t('portal_article_content')->insert(array('aid' => $aid, 'id' => 0, 'title' => '', 'content' => $zhiwu55_content, 'pageorder' => 1, 'dateline' => $hzw_news['send_datetime']));
		if (empty($conver_pic) == false && strlen($conver_pic) > 3) {
			C::t('portal_article_title')->update($aid, array('pic' => $conver_pic, 'thumb' => 1));
		}
		if(DISCUZ_VERSION!='X2.5')
		{
			portalcp_article_pre_next($hzw_news['portal_catid'],$aid);
		}
		if(isset($commentArr) && is_array($commentArr)) {
			$chk_intval_time=time();
			$chk_intval_time=$chk_intval_time-$hzw_news['send_datetime'];
			if($hzw_news['intval_time']>$chk_intval_time)
			{
				$hzw_news['intval_time']=$chk_intval_time;
			}
			$postitem_intval_count = count($commentArr);
			$postitem_intval = $hzw_news['intval_time'] / $postitem_intval_count;
            $postitem_intval = intval($postitem_intval);
            foreach ($commentArr as $post_k => $post_text) {
                if(empty($post_text) || $post_text=='') {
					continue;
				}
				$post_text = strip_tags($post_text);
                $postUid = rand(1,999);
                $postUid = $postUid % $uidCount;
                $postUid = $uidArr[$postUid];
                $PostUserInfo = ext_getuserbyuid_zhiwu55fun($postUid);
                if ($hzw_news['pseudo_original'] == 1) {
                    $post_text = rep_weiyanchang_zhiwu55fun($post_text);
                }
				$timeDiff=$postitem_intval*($post_k+1);
				$send_datetime=$hzw_news['send_datetime']+$timeDiff;
				$timeDiffMin=time();
				$dateline=min($send_datetime,$timeDiffMin);
                if (defined('DISCUZ_VERSION') && (DISCUZ_VERSION == 'X3' || DISCUZ_VERSION == 'X2.5')) {
                    $setarr = array('uid' => $PostUserInfo['uid'],
                        'username' => $PostUserInfo['username'],
                        'id' => $aid,
                        'idtype' => 'aid',
                        'postip' => $_G['clientip'],
                        'dateline' => $dateline,
                        'status' => 0,
                        'message' => $post_text
                        );
                } else {
                    $setarr = array('uid' => $PostUserInfo['uid'],
                        'username' => $PostUserInfo['username'],
                        'id' => $aid,
                        'idtype' => 'aid',
                        'postip' => $_G['clientip'],
                        'port' => $_G['remoteport'],
                        'dateline' => $dateline,
                        'status' => 0,
                        'message' => $post_text
                        );
                }

                $pcid = C::t('portal_comment')->insert($setarr, true);
                C::t('portal_article_count')->increase($aid, array('commentnum' => 1));
            }
        }
		$previewUrl=$_G['siteurl'] . 'portal.php?mod=view&aid=' . $aid;
		DB::update('zhiwu55cn_news', array('browse_url' => $previewUrl,'tid_aid'=>$aid,'push_date'=>time(),'del'=>0,'title'=>$title), "source_link='".$zhiwu55_result['topHref']."'");
		DB::update('zhiwu55cn_update', array('preview_url' => $previewUrl,'push_date'=>time()), "source_link='".$zhiwu55_result['topHref']."'");
		return $previewUrl;

	}
}
function getRndUid_zhiwu55fun($num = 80) {
    global $_G;
    $uidarray = DB::fetch_all('SELECT uid FROM %t ORDER BY RAND() LIMIT %d',array('zhiwu55cn_reguser',$num));
    foreach ($uidarray as $uidvalue) {
        $uidstr = $uidvalue['uid'] . ',' . $uidstr;
    }
    $uidstr = substr($uidstr, 0, -1);
    if ($uidstr == "" || empty($uidstr)) {
        return $_G['uid'];
    } else {
        return $uidstr;
    }
}
function getOneUid_zhiwu55fun($str) {
    if (strpos($str, ',') == false && is_numeric($str)) {
        return $str;
    } else {
        $strArr = explode(',', $str);
        shuffle($strArr);
        return $strArr[1];
    }
}
function rep_weiyanchang_zhiwu55fun($str) {
    $wordRs = DB::fetch_all("SELECT word1,word2 FROM %t",array('zhiwu55cn_weiyanchang'));
    foreach ($wordRs as $wordValue) {
        $word1 = $wordValue['word1'];
        $word2 = $wordValue['word2'];
        $word2 = preg_replace('/(.)/', '$1_hzw_', $word2);
        $str = str_replace($word1, $word2, $str);
    }
    $str = str_replace('_hzw_', '', $str);
    return $str;
}
function GetImgFileExt_zhiwu55fun($imgurl) {
    if (stripos($imgurl, 'gif') != false) {
        return 'gif';
    } elseif (stripos($imgurl, 'jpg') != false) {
        return 'jpg';
    } elseif (stripos($imgurl, 'jpeg') != false) {
        return 'jpeg';
    } elseif (stripos($imgurl, 'png') != false) {
        return 'png';
    } else {
        return 'jpg';
    }
}
function majia_chk_zhiwu55fun() {
    $chk = DB::fetch_first("SELECT * FROM %t LIMIT 1",array('zhiwu55cn_reguser'));
    if (empty($chk) || count($chk) == 0) {
        return true;
    } else {
        return false;
    }
}
function ext_dfsockopen_zhiwu55fun($url)
{
	if(function_exists('curl_init') && function_exists('curl_exec')) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_REFERER, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		if(strlen($cookie)>5) {
			curl_setopt($ch, CURLOPT_COOKIE, $cookie);
		}
		$data = curl_exec($ch);
		$status = curl_getinfo($ch);
		$errno = curl_errno($ch);
		curl_close($ch);
		if($status['http_code'] != 200 || strlen($data)<20) {
			$data = @file_get_contents($url);
			return $data ;
		} else {
			return $data;
		}
	} else {
		return 'no';
	}

}
function wwwzhiwu55com_appid($returnType=1)
{
	global $_G;
	$appid = '';
	if (!isset($_G['cache']['plugin'])) {
		loadcache('plugin');
	}
	$randNum=rand(1,20);
	$hzw_appid=getcookie('zhiwu55com_appid');
	if($returnType==1 && !empty($hzw_appid) && strlen($hzw_appid)==32 && $randNum!=5)
	{
		return $hzw_appid;
	}
	$siteurl = parse_url($_G['siteurl'],PHP_URL_HOST);
	$siteurlArr=explode('.',$siteurl);
	array_splice($siteurlArr,0,-2);
	$siteurl=implode('.',$siteurlArr);
	$appid = $siteurl.dirname(__DIR__).php_uname('s').php_uname('n');
	$appid = md5($appid);
	$appid = strtoupper($appid);
	dsetcookie('zhiwu55com_appid',$appid,86400);
	if($returnType==55 || empty($_G['cache']['plugin']['csdn123_news']['zhiwu55_appsecret']))
	{
		$dataArr = array();
		$dataArr['siteurl'] = $_G['siteurl'];
		$dataArr['savepath'] = __DIR__;
		$dataArr['system_info'] = php_uname();
		$dataArr['http_server'] = $_SERVER['SERVER_SOFTWARE'];
		$returnStr = serialize($dataArr);
		$returnStr=base64_encode($returnStr);
		$remoteUrl = array();
		$remoteUrl['zhiwu55com_appid_data'] = $returnStr;
		$remoteUrl['zhiwu55com_appid'] = $appid;
		$fetchUrl = "http://www.zhiwu55.com/authorization/wwwzhiwu55com_empowerment_202005.php";
		$htmlcode = dfsockopen($fetchUrl, 0, $remoteUrl);
		$zhiwu55_arr_Str = preg_replace('/^\s+|\s+$/','',$htmlcode);
		$zhiwu55_arr_Str = base64_decode($zhiwu55_arr_Str);
		$zhiwu55_arr = array();
		$zhiwu55_arr = dunserialize($zhiwu55_arr_Str);
		if(!empty($zhiwu55_arr) && is_array($zhiwu55_arr))
		{
			if(empty($zhiwu55_arr['hzw_appsecret']) && !empty($_G['cache']['plugin']['csdn123_news']['zhiwu55_appsecret']))
			{
				
				$zhiwu55_arr['hzw_appsecret'] = $_G['cache']['plugin']['csdn123_news']['zhiwu55_appsecret'];
				
			} elseif(empty($zhiwu55_arr['hzw_appsecret'])) {
				
				if (!isset($_G['cache']['zhiwu55com_authorization'])) {
					loadcache('zhiwu55com_authorization');
				}
				if(!empty($_G['cache']['zhiwu55com_authorization']))
				{
					$zhiwu55com_authorization_arr = $_G['cache']['zhiwu55com_authorization'];
					$zhiwu55_arr['hzw_appsecret'] = $zhiwu55com_authorization_arr['hzw_appsecret'];
				}				
				
			}
			savecache('zhiwu55com_authorization',$zhiwu55_arr);
		}
		if(!empty($zhiwu55_arr['hzw_appsecret']) && strlen($zhiwu55_arr['hzw_appsecret'])>10)
		{
			$_G['cache']['plugin']['csdn123_news']['zhiwu55_appsecret']=$zhiwu55_arr['hzw_appsecret'];
			include_once libfile('function/cache');
			$plugin = C::t('common_plugin')->fetch_by_identifier('csdn123_news');
			$pluginid = $plugin['pluginid'];
			C::t('common_pluginvar')->update_by_variable($pluginid, 'zhiwu55_appsecret', array('value'=>$zhiwu55_arr['hzw_appsecret']));
			updatecache(array('plugin', 'setting', 'styles'));
			cleartemplatecache();
		}
	}
	return $appid;

}
function hzw_sign($dataArr)
{
	if(!is_array($dataArr))
	{
		return 'no';

	} else {

		ksort($dataArr, SORT_STRING);
		$string1 = '';
		foreach ($dataArr as $k => $v) {
			$v=urlencode($v);
			$string1 .= "{$k}={$v}&";
		}
		return strtoupper(md5($string1));
	}
}