<?php

/**
  * BLOG:CMS: PHP/MySQL Personal Content Management System (CMS)
  * http://blogcms.com/
  * ----------------------------------------------------------------
  *
  * Copyright (C) 2003-2005 Radek HULÁN
  * http://hulan.cz/contact/
  *
  * ----------------------------------------------------------------
  * This program is free software; you can redistribute it and/or
  * modify it under the terms of the GNU General Public License
  * as published by the Free Software Foundation; either version 2
  * of the License, or (at your option) any later version.
**/

class NP_PunBB extends NucleusPlugin {

 function getNAME() { return 'PunBB';  }
 function getAuthor()  { return 'Radek HULAN';  }
 function getURL() {  return 'http://hulan.cz/blog/'; }
 function getVersion() { return '1.0'; }
 function getDescription() { 
  return 'Plugin to automatically create BLOG:CMS users in PunBB user database as well. It is also able to create topics and posts when you add a new article to BLOG:CMS.';
 }
 
 function getTableList() {	return array(sql_table('plugin_punbb')); }
 
 function init(){
	 // connect to PunBB forum
	 $this->connectPunBB();
	 // date/time options
	 $this->_today = $this->getOption("today");
	 $this->_1day = $this->getOption("1day");
	 $this->_2day = $this->getOption("2day");
	 $this->_forumtime = ($this->getOption('forumtime')=='1');
 }

 function getEventList() { 
   return array(
     'PostPluginOptionsUpdate',
     'AddItemFormExtras',
     'PostAddItem',
     'EditItemFormExtras',
     'PreUpdateItem'
     ); 	
 }	

 function install() {
   $this->createOption('create','Offer option to create topic in PunBB when adding/editing article?','select','1', 'no|0|yes|1');
   $this->createOption('default','"Add Article To PunBB?" is on by default?','select','1', 'no|0|yes|1');
   $this->createOption('forum','PunBB forum number to create topics in:','text','1');
   $this->createOption('linktext','Text to post before article link:','text','Link to article: ');
   $this->createOption('link','Add article LINK to PunBB topic?','select','1', 'no|0|yes|1');
   $this->createOption('body','Add article BODY to PunBB topic?','select','1', 'no|0|yes|1');
   $this->createOption('more','Add article MORE to PunBB topic?','select','0', 'no|0|yes|1');
   $this->createOption('image','Embed images in posts?','select','1', 'no|0|yes|1');
   $this->createOption('close','Automatically close comments for articles in PunBB?','select','1', 'no|0|yes|1');
   $this->createOption('drop','Drop tables on uninstall?','select','0', 'no|0|yes|1');
   $this->createOption('copy','Copy all registered BLOG:CMS users to PunBB now?','select','0', 'no|0|yes|1');
   global $SQL_TYPE;
   switch ($SQL_TYPE){
	   case 0:
         sql_query("create table if not exists ".sql_table('plugin_punbb')." (itemid int(11) auto_increment, topicid int(11) NOT NULL, PRIMARY KEY(itemid), KEY(topicid)) Type=MyISAM COMMENT='Plugin: PunBB'");
		 break;
	   case 1:
         sql_query("create table if not exists ".sql_table('plugin_punbb')." (itemid int(11) auto_increment, topicid int(11) NOT NULL, PRIMARY KEY(itemid), KEY(topicid)) Type=MyISAM COMMENT='Plugin: PunBB'");
		 break;
	   case 2:
         sql_query("create table ".sql_table('plugin_punbb')." (itemid INTEGER PRIMARY KEY, topicid int(11))");
         sql_query("create index idx_plugin_punbb on ".sql_table('plugin_punbb')." (topicid)");
		 break;
   }
   $this->createCategoryOption('punbbtopic','Forum number in PunBB, or 0 for default one','text','0');
   // dates/times of forum replies
   $this->createOption("today", "Text for today:", "text", "<strong>today</strong>");
   $this->createOption("1day", "Text for 1 day before:", "text", "<strong>yesterday</strong>");
   $this->createOption("2day", "Text for 2 days before:", "text", "<strong>2 days ago</strong>");
   $this->createOption('forumtime','Show date/time of last forum reply?','select','1', 'no|0|yes|1');
 }
 
 function unInstall() { 
   if ($this->getOption('drop')=='1') sql_query("drop table ".sql_table('plugin_punbb'));
 }

	function supportsFeature($feature) {
    	switch($feature) {
	        case 'SqlTablePrefix':
	        	return 1;
	        default:
	    		return 0;
		}
	}

 // connect to PunBB database
 function connectPunBB(){
  global $pun_root, $db_type, $DIR_ADMIN;
	if (!is_dir($DIR_ADMIN)) die('System is not configured properly');
  $pun_root=$DIR_ADMIN;
  if ( (substr($pun_root,-1)=='/') || (substr($pun_root,-1)=="\\") ) $pun_root=substr($pun_root,0,strlen($pun_root)-1);
  $pos = strrpos($pun_root,"\\");
  if ($pos===false) $pos = strrpos($pun_root,'/');
  if ($pos!==false) $pun_root=substr($pun_root,0,$pos);
  $pun_root.="/forum/";
  if (!file_exists($pun_root."config.php")) doError("Cannot read $pun_root"."config.php. PunBB is probably not installed.");
  require_once($pun_root."config.php");
  switch ($db_type) {
	case 'mysql':
		require $pun_root.'include/dblayer/mysql.php';
		break;
	case 'mysqli':
		require $pun_root.'include/dblayer/mysqli.php';
		break;
	case 'pgsql':
		require $pun_root.'include/dblayer/pgsql.php';
		break;
	case 'sqlite':
		require $pun_root.'include/dblayer/sqlite.php';
		break;
	default:
		die('Invalid PunBB Forum configuration');
		break;
  }
  $this->punbb = new DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, false);
 }

 function event_PostPluginOptionsUpdate(&$data) {
	if ($this->getOption('copy')=='1') {
     $this->setOption('copy','0');
     $users=array();
     $query=sql_query("SELECT mname as username, mrealname as realname, mpassword as password, memail as email FROM ".sql_table('member'));
     while ($arr=sql_fetch_array($query)) $users[]=$arr;
     global $db;
     foreach ($users as $user){
        // user already exists?
        $query=$this->punbb->query("select id from ".$this->punbb->prefix."users where username='".$this->punbb->escape($user['username'])."'",false);
        // username still does not exists
        if ($this->punbb->num_rows($query)==0) {
          $query="insert into ".$this->punbb->prefix."users"." (".
                 " group_id,".
				 " username,".
                 " realname,".
                 " password,".
                 " email,".
                 " email_setting,save_pass,notify_with_post,show_img,show_avatars,show_sig,".
                 " timezone,style,registered,language)".
                 " values(".
				 " 4,".
                 " '".$user['username']."',".
                 " '".$user['realname']."',".
                 " '".$user['password']."',".
                 " '".$user['email']."',".
                 " 1,1,1,1,1,1,".
                 " 1,'Oxygen',".strval(time()).",'English'".
                 ")";
           $this->punbb->query($query,false);
        }
     }
	}
 }

	function event_AddItemFormExtras($data) {
	  if ($this->getOption('create')=='1'){
   	  echo '<table><tr><td><h3>Create topic in PunBB?</h3>';
   	  $s1=''; $s2='';
   	  if ($this->getOption('default')=='1') $s1='checked="checked"'; else $s2='checked="checked"';
   	  echo '<input name="punbbtopiccreate" type="radio" value="1" id="punbb1" '.$s1.' /><label for="punbb1">yes</label> ';
   	  echo '<input name="punbbtopiccreate" type="radio" value="0" id="punbb2" '.$s2.' /><label for="punbb1">no</label>';
   	  echo '</td><td><h3>Copy article text as well?</h3>';
   	  echo '<input name="punbbcopy" type="radio" value="1" id="punbb3" checked="checked"  /><label for="punbb3">yes</label> ';
   	  echo '<input name="punbbcopy" type="radio" value="0" id="punbb4" /><label for="punbb4">no</label></td></tr></table>';
 	  }
	}

	function event_EditItemFormExtras($data) {
	  if ($this->getOption('create')!='1') return;
	  $query=sql_query('select topicid from '.sql_table('plugin_punbb').' where itemid='.strval($data['itemid']));
	  if ($msg=sql_fetch_array($query)) $s=strval($msg['topicid']); else $s='';
   	  echo '<h3>PunBB</h3><p><label for="punbb1">PunBB Topic Number:</label> <input name="punbbtopicnumber" type="text" value="'.$s.'" id="punbb1" /></p>';
	}
  
  /**************************************/
  /* create new topic in PunBB database */
  /**************************************/
  function event_PostAddItem(&$data) { 
	  if ($this->getOption('create')!='1') return;
	  
	  if (isset($_POST['punbbtopiccreate']) && ($_POST['punbbtopiccreate']=='1') ) {
		$myitemid=strval(intval($data['itemid']));
		global $CONF;
		$myurl=$CONF['IndexURL'].fancyLink($myitemid);
		$pos=strpos($myurl,'&');
		if ($pos!==false) $myurl=substr($myurl,0,$pos);
		$topicid=0;
		
		// get options
		$body=$this->getOption('body');
		$more=$this->getOption('more');
		$link=$this->getOption('link');
		$image=$this->getOption('image');
		
		// category -- forum id
		$q=sql_query('select icat from '.sql_table('item').' where inumber='.$myitemid);
		$r=sql_fetch_object($q);
		$forum = $this->getCategoryOption(intval($r->icat),'punbbtopic');
		if (intval($forum)==0) $forum = $this->getOption('forum');
		unset($q);
		
		// get article
		$query=sql_query('select ititle as title, ibody as body, imore as more, iauthor as member from '.sql_table('item').' where inumber='.$myitemid);
		if (!($msg_item=sql_fetch_array($query))) return;
		$query=sql_query('select mname as name from '.sql_table('member').' where mnumber='.strval($msg_item['member']));
		if (!($msg_member=sql_fetch_array($query))) return;
		
		// insert topic to PunBB
		$query = $this->punbb->query("select id from ".$this->punbb->prefix."users where username='".$msg_member['name']."'");
		if ( !($msg_user = $this->punbb->fetch_assoc($query)) ) {
		  doError("User ".$msg_member['name']." does NOT exists in PunBB user database!");
		  return;
		}
		$query= $this->punbb->query("select id from ".$this->punbb->prefix."forums where id=".$forum);
		if ( !($temp = $this->punbb->fetch_assoc($query)) ) {
		  doError("Forum number ".$forum." does NOT exists in PunBB database!");
		  return;
		}
		
		
		/* ------- TOPICS ------- */
		$query="insert into ".$this->punbb->prefix."topics".
		   " ( poster,".
		   "   subject,".
		   "   num_views,num_replies,closed,sticky,".
		   "   forum_id".
		   ") values ('".$msg_member['name']."',".
		   " '".$this->punbb->escape(strip_tags(sql_unescape($msg_item['title'])))."',".
		   " 0,0,0,0,".
		   " ".$forum.
		   " )";
		$this->punbb->query($query,false);
		$topicid = $this->punbb->insert_id();
		// insert full post?
		if ( intval($_POST['punbbcopy'])==1 ) {
			$article='';
			if (intval($body)==1) $article.=sql_unescape($msg_item['body'])."\n\n";
			if (intval($more)==1) $article.=sql_unescape($msg_item['more'])."\n\n";
			if (intval($link)==1) $article.=$this->getOption('linktext')." [b][url]".$myurl."[/url][/b]";
			
			// convert links into bbCode
			$article=preg_replace('/<a(.*?)href=[\'|\"](.*?)[\'|\"]>(.*?)<\/a>/','[url=$2]$3[/url]',$article);
			// convert images into bbCode
			if ($image=='1') 
			  $article=preg_replace('/<%image\((.*?)\|(.*?)\|(.*?)\|(.*?)\)%>/','[img]'.$CONF['MediaURL'].strval($msg_item['member']).'/'.'$1[/img]',$article);
			else
			  $article=preg_replace('/<%image\((.*?)\|(.*?)\|(.*?)\|(.*?)\)%>/','($4): [url]'.$CONF['MediaURL'].strval($msg_item['member']).'/'.'$1[/url]',$article);
			// convert popups into bbCode        
			$article=preg_replace('/<%popup\((.*?)\|(.*?)\|(.*?)\|(.*?)\)%>/','$4: [url]'.$CONF['MediaURL'].strval($msg_item['member']).'/'.'$1[/url]',$article);
			// remove other BLOG:CMS pseudo-tags
			$article=preg_replace('/<%(.*?)%>/','',$article);
			// pre/code into bbCode
			$article=str_replace('<pre>',"[code]",$article);
			$article=str_replace('</pre>',"[/code]",$article);
			// ending tags into line breaks
			$article=str_replace('</p>',"\n\n",$article);
			$article=str_replace('<br />',"\n",$article);
			$article=str_replace('<br>',"\n",$article);
			$article=str_replace('</li>',"\n",$article);
			// lists
			$article=str_replace('<li>',"* ",$article);
			// headlines in bold
			$article=preg_replace('/<h(.*?)>(.*?)<\/h(.*?)>/',"[b]$2[/b]\n",$article);
			// triple line breaks into double
			$article=str_replace("\r","",$article);
			$article=str_replace("\n\n\n","\n\n",str_replace("\n\n\n","\n\n",$article));
			$article=str_replace("\r","",$article);
			$article=str_replace("\t","",$article);
			// strip all other tags
			$article=$this->punbb->escape(trim(strip_tags($article)));
		} 
		// no article text?
		if (empty($article)) 
		  $article=$this->punbb->escape($this->getOption('linktext')." [url]".$myurl."[/url]");
		
		/* ------- POSTS ------- */
		$query="insert into ".$this->punbb->prefix."posts ".
		   " ( poster,".
		   "   poster_id,".
		   "   message,".
		   "   posted,".
		   "   topic_id,".
		   "   poster_ip".
		   " ) values ( ".
		   " '".$this->punbb->escape(sql_unescape($msg_member['name']))."',".
		   " ".strval($msg_user['id']).",".
		   " '".$this->punbb->escape($article)."',".
		   " ".strval(time()).",".
		   " ".strval($topicid).",".
		   " '".$this->punbb->escape(serverVar("REMOTE_ADDR"))."'".
		   " )";
		$this->punbb->query($query,false);
		$post_id = $this->punbb->insert_id();
		
		/* ------- TOPICS NUMBER ------- */
		$query="update ".
			 $this->punbb->prefix."topics set".
			 " last_post=".strval(time()).
			 ",last_post_id=".strval($post_id).
			 ",last_poster='".$this->punbb->escape(sql_unescape($msg_member['name'])).
			 "',num_replies=0 ".
			 "where id=".strval($topicid);
		$this->punbb->query($query,false);
		
		/* ------- USERS POST NUMBER ------- */
		$query="update ".
			 $this->punbb->prefix.
			 "users set last_post=".strval(time()).
			 ",num_posts=num_posts+1 ".
			 "where id=".strval($msg_user['id']);
		$this->punbb->query($query,false);
		
		/* ------- FORUMS POST NUMBER ------- */
		$query="update ".
			 $this->punbb->prefix.
			 "forums set last_post=".strval(time()).
			 ",num_posts=num_posts+1 ".
			 ",num_topics=num_topics+1 ".
			 ",last_post_id=".strval($post_id).
			 ",last_poster='".$this->punbb->escape(sql_unescape($msg_member['name']))."'".
			 "where id=".$forum;
		$this->punbb->query($query,false);
		
		// close comment for this article?
		if ($this->getOption('close')=='1') {
		$query="update ".sql_table('item')." set iclosed=1 where inumber=".$myitemid;
		sql_query($query);
		}
		// save relation between an article and topic id
		if ($topicid>0){
		$query="insert into ".sql_table('plugin_punbb')."(itemid,topicid) values ($myitemid,$topicid)";
		sql_query($query);
		}
    }
  }

  function event_PreUpdateItem($data) {		
	  if ($this->getOption('create')!='1') return;
	  if ( isset($_POST['punbbtopicnumber']) && (strlen($_POST['punbbtopicnumber'])>0) ) {
	    $query=sql_query('select topicid from '.sql_table('plugin_punbb').' where itemid='.strval($data['itemid']));
	    if ($row=sql_fetch_array($query)) 
	      $query='update '.sql_table('plugin_punbb').' set topicid='.undoMagic($_POST['punbbtopicnumber']).' where itemid='.strval($data['itemid']);
	    else
	      $query='insert into '.sql_table('plugin_punbb').' (itemid,topicid) values ('.strval($data['itemid']).','.undoMagic($_POST['punbbtopicnumber']).')';
	    sql_query($query);
	  }
  }
  
  /**
   * Shows link to a forum post
  **/
  function doTemplateVar(&$item,$text_pre='',$text_post='') {
	  global $CONF;
      $id=intval($item->itemid);
	  $query=sql_query('select topicid from '.sql_table('plugin_punbb').' where itemid='.$id);
	  if ($msg=sql_fetch_array($query)) {
		  $query=$this->punbb->query("select num_replies, last_post from ".$this->punbb->prefix."topics where id=".intval($msg['topicid']),false);
		  if ( !($data = $this->punbb->fetch_assoc($query)) ) return;
		  echo $text_pre;
		  echo "<a href='";
		  echo $CONF['IndexURL']."forum/viewtopic.php?id=".$msg['topicid'];
		  echo "'> ".$data['num_replies']." </a>";
		  echo $text_post;
		  if ($this->_forumtime) {
		   $today=date('d.m.y',time());
		   $onedaybefore=date('d.m.y',strtotime ("-1 day",time()));
		   $twodaysbefore=date('d.m.y',strtotime ("-2 days",time()));
		   $_date = date('d.m.y',intval($data['last_post']));
		   $r= '[' . date("d.m.y H:i",intval($data['last_post'])) . ']';
		   if ($_date==$today) $r='['.$this->_today.', '.date("H:i",intval($data['last_post'])).']';
		   if ($_date==$onedaybefore) $r='['.$this->_1day.', '.date("H:i",intval($data['last_post'])).']';
		   if ($_date==$twodaysbefore) $r='['.$this->_2day.', '.date("H:i",intval($data['last_post'])).']';
		   echo $r;
		  }
	  }
  }

}
?>