<?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.
**/

global $DIR_ADMIN;
if (!is_dir($DIR_ADMIN)) die('System is not configured properly - NP_PDF.php');
include ( substr($DIR_ADMIN,0,strpos($DIR_ADMIN,'admin'))."photo".DIRECTORY_SEPARATOR."includes".DIRECTORY_SEPARATOR."user.class.php");

if (!is_callable("pun_hash")) {
	function pun_hash($str) {
			return md5($str);
	}
}

class NP_UserSharing extends NucleusPlugin {

	function getNAME() { return 'UserSharing';  }
	function getAuthor()  { return 'Radek HULAN';  }
	function getURL() {  return 'http://hulan.cz/blog/'; }
	function getVersion() { return '1.0'; }
	function getDescription() { 
		return 'This plugin will create new Weblog users also in PunBB Forum and Fotogalery, Change Passwords, Login / Logout to all areas and Delete Members in all areas.';
	}
	
   	function install() { 
      $this->createOption('forum','Syncronize users between Weblog and Forum?','yesno','yes'); 
      $this->createOption('photo','Syncronize users between Weblog and Photo Gallery?','yesno','yes'); 
    }

   	function init() { 
   		$this->forum = ($this->getOption('forum') == 'yes');
   		$this->photo = ($this->getOption('photo') == 'yes');
	}
	
	function getEventList() { 
		return array(
			'PostRegister',
			'PostChangePassword',
			'LoginSuccess',
			'Logout',
			'PostDeleteMember',
			'PostAuthentication',
			'QuickMenu'
		);
	}	
	
	function supportsFeature($feature) {
		switch($feature) {
			case 'SqlTablePrefix':
				return 1;
			default:
				return 0;
		}
	}
	
	function event_QuickMenu(&$data) {
		global $member, $CONF;
		if ($member->isAdmin()) {
			array_push(
				$data['options'], 
				array(
					'title' => 'FORUM admin',
					'url' => $CONF['IndexURL'].'forum/admin_index.php',
					'tooltip' => 'Manage Forum'
				)
			);
			array_push(
				$data['options'], 
				array(
					'title' => 'PHOTO admin',
					'url' => $CONF['IndexURL'].'photo/admin.php',
					'tooltip' => 'Manage Photo Gallery'
				)
			);
		}
	}

	function setGlobalDir(){
		$this->GLOBAL_DIR = dirname(__FILE__);
		if (substr($this->GLOBAL_DIR,-1,1)!=DIRECTORY_SEPARATOR)
			$this->GLOBAL_DIR .= DIRECTORY_SEPARATOR;
		$this->GLOBAL_DIR = substr($this->GLOBAL_DIR,0,strpos($this->GLOBAL_DIR,'admin'.DIRECTORY_SEPARATOR));
	}

	function connectPunBB(){
		if (!$this->forum)
			return false;
		$this->setGlobalDir();
		if (!$this->GLOBAL_DIR)
			return;
		// connect to PunBB database
		global $pun_root, $cookie_name, $cookie_path, $cookie_domain, $cookie_secure, $cookie_seed, $db_type;
		$pun_root = $this->GLOBAL_DIR.'forum'.DIRECTORY_SEPARATOR;
		if (is_file($pun_root."config.php")) {
			@require ($pun_root."config.php");
			if (empty($pun_root))
				return false;
			switch ($db_type) {
				case 'mysql':
					require ($pun_root.'include'.DIRECTORY_SEPARATOR.'dblayer'.DIRECTORY_SEPARATOR.'mysql.php');
					break;
				case 'mysqli':
					require ($pun_root.'include'.DIRECTORY_SEPARATOR.'dblayer'.DIRECTORY_SEPARATOR.'mysqli.php');
					break;
				case 'pgsql':
					require ($pun_root.'include'.DIRECTORY_SEPARATOR.'dblayer'.DIRECTORY_SEPARATOR.'pgsql.php');
					break;
				case 'sqlite':
					require ($pun_root.'include'.DIRECTORY_SEPARATOR.'dblayer'.DIRECTORY_SEPARATOR.'sqlite.php');
					break;
				default:
					return false;
			}
			if (!defined('PUN_ROOT'))
				define('PUN_ROOT',$pun_root);
			$this->punbb = new DBLayer($db_host, $db_username, $db_password, $db_name, $db_prefix, false);
			return true;
		}
		return false;
	}
	
	
	function event_PostDeleteMember(&$data) {
		if ($this->forum) {
			/* **********************
			  forum user delete
			 ***********************/
			$this->connectPunBB();
			if (!isset($this->punbb))
				return;
			// get user data
			$result = $this->punbb->query('SELECT num_posts FROM '.$this->punbb->prefix.'users WHERE username=\''.$this->punbb->escape($data['member']->displayname).'\'');
			list($num_posts) = $this->punbb->fetch_row($result);
			// delete the user if there are no posts
			if (intval($num_posts)==0)
				$result = $this->punbb->query('DELETE FROM '.$this->punbb->prefix.'users WHERE username=\''.$this->punbb->escape($data['member']->displayname).'\'');
		}
		if ($this->photo){
			/* **********************
			  photo user delete
			 ***********************/
			$file=$this->GLOBAL_DIR.DIRECTORY_SEPARATOR.str_replace('|',DIRECTORY_SEPARATOR,'photo|data|users.csv.php');
			$content = array();
			$len = strlen($data['member']->displayname)+1;
			if ($fp = @fopen($file, "r")) {
				while (!feof($fp)) {
					$buffer = fgets($fp, 4096);
					if ( strcmp(substr($buffer,0,$len),$data['member']->displayname.',') != 0)
						$content[] = $buffer;
				}
				@fclose($fp);
				if ($fp = @fopen($file, "w")) {
					foreach ($content as $line) {
						@fputs($fp,$line);
					}
					@fclose($fp);
				}
			}
		}
	}
	
	function event_PostAuthentication($loginOk) {
		if (strpos($_SERVER['REQUEST_URI'],'/photo/')===false)
		if ($loginOk && $this->photo) {
			global $member;
			/* **********************
			  gallery login
			 ***********************/
			if (isset($member))
			if ($member->isAdmin()) {
				if (!session_id()) {
					ini_set("arg_separator.output", "&amp;");			
					session_name("PHPSESSID");
					session_start();
				}
				$user = new sgUser($member->getDisplayName(),$member->getPassword());
				$user->check = md5($_SERVER["REMOTE_ADDR"]);
				$user->ip = $_SERVER["REMOTE_ADDR"];
				$user->loginTime = time();
				$user->permissions = 1024;
				$_SESSION["sgUser"] = $user;
			}
		}
	}
	
	function event_LoginSuccess(&$data) {
		global $member;
		if (!isset($member))
			$member = MEMBER::createFromName($data['displayname']);
		if ($member->isAdmin() && $this->forum) {
			/* **********************
			  forum login
			 ***********************/
			if (!$this->connectPunBB())
				return;
			// get user data
			$query = 'SELECT id, group_id, password, save_pass FROM '.$this->punbb->prefix.'users WHERE username=\''.$this->punbb->escape($data['member']->displayname).'\'';
			$result = $this->punbb->query($query);
			list($user_id, $group_id, $db_password_hash, $save_pass) = $this->punbb->fetch_row($result);
			// set login cookie
			if ($user_id>0) {
				global $cookie_name, $cookie_path, $cookie_domain, $cookie_secure, $cookie_seed;
				$expire = ($save_pass == '1') ? time() + 31536000 : 0;
				setcookie($cookie_name, serialize(array($user_id, $cookie_seed.pun_hash($data['member']->password) )), $expire, $cookie_path, $cookie_domain, $cookie_secure);
			}
		}
		if ($member->isAdmin() && $this->photo) {
			/* **********************
			  gallery login
			 ***********************/
			if (!session_id()) {
				ini_set("arg_separator.output", "&amp;");			
				session_name("PHPSESSID");
				session_start();
			}
			$user = new sgUser($data['member']->displayname,postVar('password'));
			$user->check = md5($_SERVER["REMOTE_ADDR"]);
			$user->ip = $_SERVER["REMOTE_ADDR"];
			$user->loginTime = time();
			$_SESSION["sgUser"] = $user;
		}
	}
	
	function event_Logout($data){
		if ($this->forum) {
			$member = MEMBER::createFromName($data['username']);
			/* **********************
		  	  forum logout
		 	***********************/
			$this->connectPunBB();
			if (!isset($this->punbb))
				return;
			// get user data
			$result = $this->punbb->query('SELECT id, group_id, password, save_pass FROM '.$this->punbb->prefix.'users WHERE username=\''.$this->punbb->escape($member->displayname).'\'');
			list($user_id, $group_id, $db_password_hash, $save_pass) = $this->punbb->fetch_row($result);
			// set login cookie
			global $cookie_name, $cookie_path, $cookie_domain, $cookie_secure, $cookie_seed;
			$expire = ($save_pass == '1') ? time() + 31536000 : 0;
			setcookie($cookie_name, '', $expire, $cookie_path, $cookie_domain, $cookie_secure);
		}
		if ($this->photo){
			/* **********************
		  	 gallery logout
		 	***********************/
			if (!session_id()) {
				ini_set("arg_separator.output", "&amp;");			
				session_name("PHPSESSID");
				session_start();
			}
			$_SESSION["sgUser"] = null;
		}
	}

	function event_PostChangePassword(&$data) {
		if ($data['member']->installprocess)
			return;		
		if ($this->forum) {
			/* **********************
			  change forum user pwd
			 ***********************/
			$this->connectPunBB();
			if (!isset($this->punbb))
				return;
			$query=$this->punbb->query("update ".$this->punbb->prefix."users set password='".$this->punbb->escape($data['member']->password)."'where username='".$this->punbb->escape($data['member']->displayname)."'",false);
			// relogin to forum - get user data
			$result = $this->punbb->query('SELECT id, group_id, password, save_pass FROM '.$this->punbb->prefix.'users WHERE username=\''.$this->punbb->escape($data['member']->displayname).'\'');
			list($user_id, $group_id, $db_password_hash, $save_pass) = $this->punbb->fetch_row($result);
			// set login cookie
			global $cookie_name, $cookie_path, $cookie_domain, $cookie_secure, $cookie_seed;
			$expire = ($save_pass == '1') ? time() + 31536000 : 0;
			setcookie($cookie_name, serialize(array($user_id, $cookie_seed.pun_hash($data['member']->password))), $expire, $cookie_path, $cookie_domain, $cookie_secure);
		}
		if ($this->photo){
			/* **********************
			  change photo user pwd
			 ***********************/
			$file=$this->GLOBAL_DIR.DIRECTORY_SEPARATOR.str_replace('|',DIRECTORY_SEPARATOR,'photo|data|users.csv.php');
			$content = array();
			$len = strlen($data['member']->displayname)+1;
			if ($fp = @fopen($file, "r")) {
				while (!feof($fp)) {
					$buffer = fgets($fp, 4096);
					if ( strcmp(substr($buffer,0,$len),$data['member']->displayname.',') == 0) {
						if ($data['member']->isBlogAdmin(intval($data['member']->blogid)))
							$rights = 1024;
						else
							$rights = 0;
						$buffer = $data['member']->displayname.','.$data['member']->password.','.$rights.',"",'.$data['member']->email.',"'.addslashes($data['member']->realname).'","Regular user account",""'."\n"; 
					}
					$content[] = $buffer;
				}
				@fclose($fp);
				if ($fp = @fopen($file, "w")) {
					foreach ($content as $line) {
						@fputs($fp,$line);
					}
					@fclose($fp);
				}
			}
		}
	}
		
	function event_PostRegister(&$data) {
		if ($data['member']->installprocess)
			return;		
			
		if ($this->forum){
			/* **********************
			  create forum user
			 ***********************/
			$this->connectPunBB();
			if (!isset($this->punbb))
				return;
			// user already exists?
			$query=$this->punbb->query("select id from ".$this->punbb->prefix."users where username='".$this->punbb->escape($data['member']->displayname)."'",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,'".$this->punbb->escape($data['member']->displayname)."',".
					" '".$this->punbb->escape($data['member']->realname)."',".
					" '".$this->punbb->escape($data['member']->password)."',".
					" '".$this->punbb->escape($data['member']->email)."',".
					" 1,1,1,1,1,1,".
					" 1,'PHPbb',".strval(time()).",'English'".
					")";
				$this->punbb->query($query,false);
			}
		}
		if ($this->photo){
			/* **********************
			  create photo user
			 ***********************/
			$file=$this->GLOBAL_DIR.DIRECTORY_SEPARATOR.str_replace('|',DIRECTORY_SEPARATOR,'photo|data|users.csv.php');
			@chmod($file,0777);
			if ( $fp = @fopen($file, 'a') ) {
				$data = $data['member']->displayname.','.addslashes($data['member']->password).',0,"",'.$data['member']->email.',"'.$data['member']->realname.'","User account",""'."\n";
				@fputs($fp, $data, strlen($data));
				fclose($fp);
			}
		}
	}

	function doSkinVar($skinType, $type, $pre = '', $post = '') {
		/* **********************
		  print member forum page
		 ***********************/
		global $blog, $blogid, $memberid;
		if (isset($blogid) && $skinType=='member') {
			if ($type == 'memberlink') {
				$this->connectPunBB();
				$mem = MEMBER::createFromID($memberid);
				$query = "select id from ".$this->punbb->prefix."users where username='".$this->punbb->escape($mem->getDisplayName())."'";
				$result = $this->punbb->query($query);
				list ($id) = $this->punbb->fetch_row($result);
				if (intval($id)>0)
					echo $pre.$blog->getURL()."forum/profile.php?id=$id".$post;
			}
			if ($type == 'memberarticles') {
				echo $pre;
				$query = sql_query('select inumber, ititle from '.sql_table('item').' where iauthor='.$memberid.' and iblog='.$blogid.' order by itime desc');
				echo '<ul>';
				while ($row = sql_fetch_object($query))
					echo '<li><a href="'.fancyLink($row->inumber).'">'.htmlspecialchars($row->ititle).'</a></li>';
				echo '</ul>'.$post;
			}
		}
	}
}
?>