<?php

/********************************************************************************
	- MemHT Portal -
	
	Copyright (C) 2007-2008 by Miltenovik Manojlo
	http://www.memht.com
	
	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 opinion) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License along
	with this program; if not, see <http://www.gnu.org/licenses/> (GPLv2)
	or write to the Free Software Foundation, Inc., 51 Franklin Street,
	Fifth Floor, Boston, MA02110-1301, USA.
		
********************************************************************************/

//===========================================
//Do not show errors
//===========================================
error_reporting(E_ALL);

//===========================================
//Database: Connect
//===========================================
require_once("inc/inc_config.php");
require_once("inc/inc_database.php");

$dblink = new database();
$dblink->connect();

//===========================================
//Timezone setting
//===========================================
$timezonerow = $dblink->get_row("SELECT timezone FROM memht_config");
$siteConfig['timezone'] = intval($timezonerow['timezone']);
$tzNOW = "DATE_ADD(NOW(),INTERVAL ".$siteConfig['timezone']." HOUR)";

require_once("inc/inc_login.php");

//Check if the visitor is logged as user
function isUser($userid,$force=0) {
	global $dblink,$privs;
	
	if (memRunHooks('IsUser',array($userid,$force,&$privs))) {
		if (isset($_COOKIE['login_user'])) {
			$cookiecontent = $_COOKIE['login_user'];
			$cookieitem = explode("#",$cookiecontent);
			
			if ($privs['user']) {
				$pcookieitem = explode("#",$privs['user']);
				if ($cookieitem[0]==$pcookieitem[0] AND $cookieitem[1]==$pcookieitem[1] AND $cookieitem[2]==$pcookieitem[2]) {
					return true;
				} else {
					$privs['user'] = false;
					return false; //Error? Hack?
				}
			} else if ($force==1) {
				//Database Account Control
				if ($dblink->get_num("SELECT id FROM memht_utenti WHERE id=$userid AND pass='".inCode($cookieitem[2])."' LIMIT 1")>0) {
					$privs['user'] = $cookiecontent;
					return true; //Account Correct
				} else {
					$privs['user'] = false;
					return false; //Error? Hack?
				}
			} else {
				return false;
			}
		} else {
			return false; //Not Logged
		}
		return false;
	}
}

//Data input function (from user)
function inCode($string) {
	if (get_magic_quotes_gpc()) { $string = stripslashes($string); }
	$string = str_replace('<br type="_moz" />','',$string); //FCKeditor 2.5.1 bug fix
	if ($string=="<br />") { $string = ""; } //FCKeditor 2.5.1 bug fix
	$string = htmlentities($string,ENT_QUOTES);
	return mysql_real_escape_string($string);
}

//Data output function (from database)
function outCode($string,$html=1) {
	global $langdata;
	
	$string = ($html==1) ? unhtmlentities($string) :  stripslashes($string) ;
	$string = str_replace('\"','"',$string);
	$string = str_replace("\'","'",$string);
	return str_replace("&amp;","&",$string);
}

function unhtmlentities($string,$html=1) {
	$trans_tbl1 = get_html_translation_table(HTML_ENTITIES);
	foreach ($trans_tbl1 as $ascii => $htmlentitie) {
		$trans_tbl2[$ascii] = '&#'.ord($ascii).';';
	}
		
	$trans_tbl1 = array_flip($trans_tbl1);
	$trans_tbl2 = array_flip($trans_tbl2);
	
	$tagstostrtip = array('iframe','script','style');
	$string = strtr(strtr($string,$trans_tbl1),$trans_tbl2);
	if ($html==1) { $string = strip_selected_tags($string,$tagstostrtip); }
	return $string;
}

function strip_selected_tags($text, $tags = array()) {
	$args = func_get_args();
	$text = array_shift($args);
	$tags = func_num_args() > 2 ? array_diff($args,array($text)) : (array)$tags;
	foreach ($tags as $tag){
		if(preg_match_all('/<'.$tag.'[^>]*>([^<]*)<\/'.$tag.'>/iu',$text,$found) ){
			$text = str_replace($found[0],$found[1],$text);
		}
	}
	return @$text;
}

//===========================================
//Includes
//===========================================
require_once("inc/inc_readConfig.php");

//Use cronjobs
if ($siteConfig['usecronjobs']==1) {
	
	//===========================================
	//Maintenance
	//===========================================
	class Maintenance {
		//Override timings, forcing the execution
		var $forcedexec = false;
	
		//Call all class functions
		function All() {
			global $dblink,$siteConfig,$tzNOW;
			
			if ($dblink->get_num("SELECT last FROM memht_maintenance")==0) { $dblink->query("INSERT INTO memht_maintenance (last) VALUES ('2000-01-01 00:00:00')"); }
			if ($this->forcedexec OR $dblink->get_num("SELECT last FROM memht_maintenance WHERE (last + INTERVAL ".$siteConfig['maintenance']." MINUTE) < $tzNOW")>0) {
				$dblink->query("UPDATE memht_maintenance SET last=$tzNOW");
				
				if (memRunHooks('Maintenance',array($this->forcedexec))) {
					$this->CleanBanned();
					$this->MessageBoxFlood();
					$this->OldWaitingUsers();
					$this->OldPrivateMessages();
					$this->OldLoginAttempts();
					$this->GroupMembers();
					$this->ResetMediumLoadTime();
					$this->DeleteOldLiveData();
					$this->DeleteOldAdminData();
					$this->DeleteRssCache();
					$this->RssAggregator();
					$this->CleanStatistics();
					
					memRunHooks('MaintenanceEnd',array($this->forcedexec));
				}
			}
		}
		
		//Clean the database from extinguished temporary ban's
		function CleanBanned() {
			global $dblink,$tzNOW;
			
			$dblink->query("DELETE FROM memht_banned WHERE date < $tzNOW AND permanent=0");
		}
		
		//Clean messagemox flood data
		function MessageBoxFlood() {
			global $dblink,$siteConfig,$tzNOW;
			
			$dblink->query("DELETE FROM memht_messagebox_flood WHERE (time + INTERVAL ".$siteConfig['maintenance_mesboxflood']." MINUTE) < $tzNOW");
		}
		
		//Clean old pending user registrations
		function OldWaitingUsers() {
			global $dblink,$siteConfig,$tzNOW;	
			
			$dblink->query("DELETE FROM memht_utenti_attesa WHERE activated=0 AND (data + INTERVAL ".$siteConfig['maintenance_waitusers']." HOUR) < $tzNOW");
			$dblink->query("DELETE FROM memht_utenti_attesa WHERE activated=1 AND (data + INTERVAL 3 MONTH) < $tzNOW");
		}
		
		//Clean old private messages
		function OldPrivateMessages() {
			global $dblink,$siteConfig,$tzNOW;
			
			$dblink->query("DELETE FROM memht_pvtmsg WHERE (date + INTERVAL ".$siteConfig['maintenance_oldpm']." DAY) < $tzNOW");
		}
		
		//Clean old login attempts
		function OldLoginAttempts() {
			global $dblink,$siteConfig,$tzNOW;
			
			$dblink->query("DELETE FROM memht_login_flood WHERE (time + INTERVAL ".$siteConfig['maintenance_failedlogin']." MINUTE) < $tzNOW");
		}
		
		//Clean expired group members
		function GroupMembers() {
			global $dblink,$siteConfig,$tzNOW;
			
			$dblink->query("UPDATE memht_groups_members SET standby=1 WHERE permanent=0 AND standby=0 AND expire < $tzNOW");
			$dblink->query("DELETE FROM memht_groups_members WHERE permanent=0 AND standby=1 AND (expire + INTERVAL ".$siteConfig['maintenance_standbygroup']." DAY) < $tzNOW");
		}
		
		function DeleteOldLiveData() {
			global $dblink,$siteConfig,$tzNOW;
			
			$dblink->query("DELETE FROM memht_statistics_livedata WHERE (date + INTERVAL 12 HOUR) < $tzNOW");
		}
		
		function DeleteOldAdminData() {
			global $dblink,$siteConfig,$tzNOW;
			
			$dblink->query("DELETE FROM memht_statistics_administration WHERE (date + INTERVAL 7 DAY) < $tzNOW");
		}
		
		//Reset medium load time
		function ResetMediumLoadTime() {
			global $dblink,$siteConfig,$tzNOW;
			
			$dblink->query("DELETE FROM memht_statistics_loadtime WHERE (started + INTERVAL ".$siteConfig['maintenance_loadtime']." HOUR) < $tzNOW");
		}
		
		//Delete RSS chache
		function DeleteRssCache() {
			global $dblink;
			
			if (@count(@glob("inc/magpie/cache/*", GLOB_BRACE))>20) {
				$limit = 0;
				$over = 0;
				$handle = @opendir('inc/magpie/cache/');
				while (false !== ($file = @readdir($handle))) {
					if ($limit>20 OR $over>20) { break; }
					if ($file != "." AND $file != "..") {
						@unlink("inc/magpie/cache/$file");
						$limit++;
					}
					$over++;
				}
				@closedir($handle);
			}
		}
		
		//Rss Aggregator
		function RssAggregator() {
			global $dblink,$tzNOW;
			
			if ($dblink->get_num("SELECT id FROM memht_aggregator WHERE enabled=1")>0) {
				if ($dblink->get_num("SELECT maintenance_aggregator FROM memht_maintenance WHERE (maintenance_aggregator + INTERVAL 1 HOUR) < $tzNOW")>0) {
					$dblink->query("UPDATE memht_maintenance SET maintenance_aggregator=$tzNOW");
					$result = $dblink->get_list("SELECT * FROM memht_aggregator");
					foreach ($result as $row) {
						$whr = intval($row['whr']);
						$argument = intval($row['argument']);
						$author = outCode($row['author']);
						$rssurl = outCode($row['rssurl']);
						$numfeeds = intval($row['numfeeds']);
						if (!defined('MAGPIE_CACHE_DIR')) { define('MAGPIE_CACHE_DIR','inc/magpie/cache'); }
						require_once("inc/magpie/rss_fetch.inc");
						if ($rss = @fetch_rss($rssurl)) {
							$channel = inCode($rss->channel['title']);
							$items = array_reverse($rss->items);
							$lim = 0;
							foreach ($items as $item) {
								if ($lim>=$numfeeds) { break; }
								$link = inCode(@$item['link']);
								$title = inCode(@$item['title']);
								$description = inCode(@$item['description']);
								$encoded = inCode(@$item['content']['encoded']);
								if (strlen($link)>4 AND strlen($title)>4 AND strlen($description)>10) {
									$more = "Source: <a href=\"$link\" target=\"_blank\" title=\"$channel\"><i>$channel</i></a>";
									if ($author=="") { $author = $channel; }
									//1 = Articles, 2 = Guide, 3 = News
									switch ($whr) {
										case 1:
											if ($encoded!="") {
												$desc = $description;
												$description = $encoded;										
											} else {
												$desc = "";
											}
											$rssquery = "INSERT INTO memht_articoli (id,argomento,nome,descrizione,testo,autore,data,enabled) VALUES ";
											$rssquery .= "(null,'$argument','$title','$desc','$description<br><br>$more','$author',$tzNOW,'1')";
											$checkquery = "SELECT id FROM memht_articoli WHERE nome='$title'";
										break;
										case 2:
											if ($encoded!="") {
												$desc = $description;
												$description = $encoded;										
											} else {
												$desc = "";
											}
											$rssquery = "INSERT INTO memht_guide (id,argomento,nome,descrizione,testo,autore,data,enabled) VALUES ";
											$rssquery .= "(null,'$argument','$title','$desc','$description<br><br>$more','$author',$tzNOW,'1')";
											$checkquery = "SELECT id FROM memht_guide WHERE nome='$title'";
										break;
										case 3:
											if ($encoded=="") {
												$rssquery = "INSERT INTO memht_news (id,argomento,nome,testo_home,testo,autore,data,enabled) VALUES ";
												$rssquery .= "(null,'$argument','$title','$description','$more','$author',$tzNOW,'1')";
											} else {
												$encoded .= "<br><br>$more";
												$rssquery = "INSERT INTO memht_news (id,argomento,nome,testo_home,testo,autore,data,enabled) VALUES ";
												$rssquery .= "(null,'$argument','$title','$description','$encoded','$author',$tzNOW,'1')";
											}
											$checkquery = "SELECT id FROM memht_news WHERE nome='$title'";
										break;
									}
									if ($dblink->get_num($checkquery)==0) { $dblink->query($rssquery); $lim++; }
								}
							}
						}
					}
				}
			}
		}
		
		//Clean statistics data
		//Added in 3.8.0
		function CleanStatistics() {
			global $dblink,$tzNOW;
			
			//memht_statistics_browsers
			$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_browsers WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_browsers WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_browsers WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");
			
			//memht_statistics_domains
			$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_domains WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_domains WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_domains WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");
			
			//memht_statistics_os
			$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_os WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_os WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_os WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");
			
			//memht_statistics_pages
			$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_pages WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_pages WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_pages WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");
			
			//memht_statistics_screenres
			$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_screenres WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_screenres WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_screenres WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");
			
			//memht_statistics_searchengines
			$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_searchengines WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_searchengines WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_searchengines WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");
			
			//memht_statistics_searchkeywords
			$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_searchkeywords WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_searchkeywords WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_searchkeywords WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");
			
			//memht_statistics_users
			$row = $dblink->get_row("SELECT ROUND(MAX(hits)*0.005) AS min FROM memht_statistics_users WHERE (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_users WHERE hits < ".intval($row['min'])." AND (day + INTERVAL 1 MONTH) < $tzNOW");
			$dblink->query("DELETE FROM memht_statistics_users WHERE hits < 5 AND (day + INTERVAL 1 WEEK) < $tzNOW");
			
			//memht_statistics_spiders
			$dblink->query("DELETE FROM memht_statistics_spiders WHERE (lastvisit + INTERVAL 1 WEEK) < $tzNOW");
		}
	}
	
	//Rewritten in 4.0.5
	function sendNewsletter() {
		global $dblink,$siteConfig,$tzNOW;
		
		if (memRunHooks('SendNewsletter')) {
			if ($srow = $dblink->get_row("SELECT * FROM memht_newsletter_status")) {
				//Unfinished newsletter session
				$crow = $dblink->get_row("SELECT * FROM memht_newsletter_config");
				$aut_mailpause = intval($crow['aut_mailpause']);
				
				if ($dblink->get_num("SELECT date FROM memht_newsletter_status WHERE (date + INTERVAL $aut_mailpause MINUTE) < $tzNOW")>0) {
					//Check busy status
					$proceed = true;
					if ($dblink->get_num("SELECT busy FROM memht_newsletter_busy WHERE busy=0")==0) {
						//Busy
						$proceed = false;
						if ($dblink->get_num("SELECT busy FROM memht_newsletter_busy WHERE busy=1 AND (date + INTERVAL 5 MINUTE) < $tzNOW")>0) {
							//Stuck > Reset
							$dblink->query("TRUNCATE memht_newsletter_busy");
							$dblink->query("INSERT INTO memht_newsletter_busy (busy,date) VALUES (0,$tzNOW)");
							$dblink->query("UPDATE memht_newsletter_status SET date=$tzNOW");
						}
					}
					
					if ($proceed) {
						//Set busy
						$dblink->query("UPDATE memht_newsletter_busy SET busy=1,date=$tzNOW");
						
						//Config
						$sender_mail = outCode($crow['email_mittente']);
						$mailorsmtp = intval($crow['mailorsmtp']);
						$smtp = outCode($crow['smtp']);
						$useauth = intval($crow['useauth']);
						$smtpuser = outCode($crow['smtpuser']);
						$smtppass = outCode($crow['smtppass']);
						$aut_mailpersession = intval($crow['aut_mailpersession']);
						
						//Status
						$title = outCode($srow['title']);
						$content = outCode($srow['content']);
						$emails = intval($srow['emails']);
						
						require_once("inc/class/class.phpmailer.php");
						$mail = new PHPMailer();
						$mail->From = $sender_mail;
						$mail->FromName = $siteConfig['site_name'];
						$mail->Subject = $title;
						if ($mailorsmtp==1) {
							//Smtp
							$mail->Host = $smtp;
							$mail->Mailer = "smtp";
							if ($useauth) {
								$mail->SMTPAuth = true;
								$mail->Username = $smtpuser;
								$mail->Password = $smtppass;
							}
						} else {
							//Mail
							$mail->Mailer = "mail";
						}
						$mail->IsHTML(true);
						$mail->Body = $content;
						
						if ($result = $dblink->get_list("SELECT id,email FROM memht_newsletter WHERE sent=0 ORDER BY id LIMIT $aut_mailpersession")) {
							$count = 0;
							foreach ($result as $row) {
								$id = intval($row['id']);
								$email = outCode($row['email']);
								
								$dblink->query("UPDATE memht_newsletter SET sent=1,date=$tzNOW WHERE id=$id");
								
								$mail->AddAddress($email);
								$mail->Send();
								$mail->ClearAddresses();
								$count++;
							}
							
							//Update status
							$dblink->query("UPDATE memht_newsletter_status SET date=$tzNOW,emails=emails+$count");
						} else {
							//No more emails
							$dblink->query("TRUNCATE memht_newsletter_status");
							$dblink->query("INSERT INTO memht_newsletter_sent (title,content,date,numemails) VALUES ('".inCode($title)."','".inCode($content)."',$tzNOW,$emails)");
						}
					
						//Finished
						$dblink->query("UPDATE memht_newsletter_busy SET busy=0,date=$tzNOW");
					}
				}
			}
			
			memRunHooks('SendNewsletterEnd');
		}
	}
	
	//===========================================
	//Maintenance
	//===========================================
	$maintenance = new Maintenance();
	$maintenance->forcedexec = true;
	$maintenance->All();
	
	//===========================================
	//Newsletter
	//===========================================
	sendNewsletter();	
} else {
	echo "Cronjobs disabled";
}

//===========================================
//Database: Disconnect
//===========================================
$dblink->disconnect();

?>