Location: PHPKode > projects > chillyCMS > chillyCMS/admin/tools.include.php
<?php
//#################################################################################################
//	Tools helper functions
//#################################################################################################
//	chillyCMS - Content Management System
//	Copyright (C) 2008
//	Stefanie Wiegand <hide@address.com> & Johannes Cox <hide@address.com>
//	
//	This program is licensed under the GPL 3.0 license. For more information see LICENSE.txt.
//#################################################################################################
//	tools_menu($tool)
//	backup_form()
//	newsletter_form()
//	analysis_form()
//	backup_now()
//	delete_backup($name)
//	reset_stats($which)
//	send_newsletter()
//#################################################################################################
defined('DOIT') or die('Restricted access');

//Tools menu///////////////////////////////////////////////////////////////////////////////////////
function tools_menu($tool) {
	global $is_admin,$l_tools;
	$analysis=$newsletter=$backup=$update="";
	if	($tool=="backup")	{	$analysis=$newsletter=$update="_no";	}
	elseif	($tool=="newsletter")	{	$analysis=$backup=$update="_no";	}
	elseif	($tool=="update")	{	$analysis=$backup=$newsletter="_no";	} 
	else				{	$backup=$newsletter=$update="_no";	}
	$toolsmenu = "\t\t<ul class='toolsmenu'>\n".
	//analysis
	"\t\t\t<li>\n".
	"\t\t\t\t<form method='post' action='tools.site.php'>\n".
	"\t\t\t\t\t<input type='hidden' name='tool' value='analysis' />\n".
	"\t\t\t\t\t<input type='submit' class='linkbutton tools_analysis$analysis' value=''/>\n".
	"\t\t\t\t\t<span>".$l_tools["lbl_stats"]."</span>\n".
	"\t\t\t\t</form>\n".
	"\t\t\t</li>\n".
	//newsletter
	"\t\t\t<li>\n".
	"\t\t\t\t<form method='post' action='tools.site.php'>\n".
	"\t\t\t\t\t<input type='hidden' name='tool' value='newsletter' />\n".
	"\t\t\t\t\t<input type='submit' class='linkbutton tools_newsletter$newsletter' value=''/>\n".
	"\t\t\t\t\t<span>".$l_tools["lbl_newsletter"]."</span>\n".
	"\t\t\t\t</form>\n".
	"\t\t\t</li>\n";
	
	if ($is_admin) {
		//backup
		$toolsmenu .= "\t\t\t<li>\n".
		"\t\t\t\t<form method='post' action='tools.site.php'>\n".
		"\t\t\t\t\t<input type='hidden' name='tool' value='backup' />\n".
		"\t\t\t\t\t<input type='submit' class='linkbutton tools_backup$backup' value=''/>\n".
		"\t\t\t\t\t<span>".$l_tools["lbl_backup"]."</span>\n".
		"\t\t\t\t</form>\n".
		"\t\t\t</li>\n";
		//update
		$toolsmenu .= "\t\t\t<li>\n".
		"\t\t\t\t<form method='post' action='tools.site.php'>\n".
		"\t\t\t\t\t<input type='hidden' name='tool' value='update' />\n".
		"\t\t\t\t\t<input type='submit' class='linkbutton tools_update$update' value=''/>\n".
		"\t\t\t\t\t<span>".$l_tools["lbl_update"]."</span>\n".
		"\t\t\t\t</form>\n".
		"\t\t\t</li>\n";
	}
	$toolsmenu .= "\t\t</ul>\n".
	"\t\t<div class='tool'>\n";
	if	($tool=="backup")	{ $toolsmenu .= backup_form();		}
	elseif	($tool=="newsletter")	{ $toolsmenu .= newsletter_form();	}
	elseif	($tool=="update")	{ $toolsmenu .= update_form();	}
	else				{ $toolsmenu .= analysis_form();	}
	$toolsmenu .= "\t\t\t<br /><br />\n".
	"\t\t</div>\n".
	"\t\t<div class='clr'></div>\n";
	
	return $toolsmenu;	
}
//Backup tool//////////////////////////////////////////////////////////////////////////////////////
function backup_form() {
	global $is_admin,$l_tools,$l_gen,$backendstyle;
	
	$backupform = "";
	if ($is_admin) {
		$backupform .= "\t\t\t<h1>$l_tools[lbl_managebus]</h1>\n".
		//former backups:
		"\t\t\t<table class=\"realtable\" cellspacing='0' width='100%'>\n".
		"\t\t\t<thead>\n".
		"\t\t\t<tr>\n".
		"\t\t\t\t<th class='left'>$l_tools[lbl_name]</th>\n".
		"\t\t\t\t<th class='left'>$l_tools[lbl_date]</th>\n".
		"\t\t\t\t<th class='center'>$l_tools[lbl_filesize]</th>\n".
		"\t\t\t\t<th class='center'>$l_gen[lbl_download]</th>\n".
		"\t\t\t\t<th class='center'>$l_gen[lbl_delete]</th>\n".
		"\t\t\t</tr>\n".
		"\t\t\t</thead>\n".
		"\t\t\t<tbody>\n";
		$style="even";
		//read all files beginning with backup_ and ending with .zip
		$files = array();
		read_files(PATH."/backup",$files);
		//order: new to old
		rsort($files);
		foreach ($files as $file) {
			//only show real backup files
			if (substr($file["name"],0,7)=="backup_" && substr($file["name"],-4)==".zip") {
				$date=substr(substr($file["name"],-19),0,-4);
				$time=substr($date,-6);
				$hr=substr($time,0,2);
				$min=substr($time,2,2);
				$sec=substr($time,-2);
				$date=substr($date,0,-7);
				$day=substr($date,-2);
				$month=substr($date,4,2);
				$yr=substr($date,0,4);
				$filesize=round($file["size"]/1000000, 2);
				//name
				$backupform .= "\t\t\t<tr class='$style'>\n".
				"\t\t\t\t<td class='left'>$file[name]</td>\n".
				//date
				"\t\t\t\t<td class='left'>$yr/$month/$day $hr:$min:$sec</td>\n".
				//size
				"\t\t\t\t<td class='center'>$filesize MB</td>\n".
				//download button
				"\t\t\t\t<td>\n".
				"\t\t\t\t\t<form action='".URL."/backup/$file[name]'>\n".
				"\t\t\t\t\t\t<input type='submit' class='save' value=\" \" title='$l_gen[lbl_download]' />\n".
				"\t\t\t\t\t</form>\n".
				"\t\t\t\t</td>\n".
				//delete button
				"\t\t\t\t<td>\n".
				"\t\t\t\t\t<form method='post' action='tools.site.php'>\n".
				"\t\t\t\t\t\t<input type='hidden' name='tool' value='backup' />\n".
				"\t\t\t\t\t\t<input type='hidden' name='action' value='delete' />\n".
				"\t\t\t\t\t\t<input type='hidden' name='name' value='$file[name]' />\n".
				"\t\t\t\t\t\t<input type='submit' class='delete' value=\" \" title='$l_gen[lbl_delete]' ".
				js_confirm_link($file["name"].' '.$l_gen["pop_del"])." />\n".
				"\t\t\t\t\t</form>\n".
				"\t\t\t\t</td>\n".
				"\t\t\t</tr>\n";
				if ($style=="odd") { $style="even"; } else { $style="odd"; }
			}
			
		}
		$backupform .= "\t\t\t</tbody>\n".
		"\t\t\t</table><br /><br />\n";
		//backup now button
		$backupform .= "\t\t\t<form method='post' action='tools.site.php'>\n".
		"\t\t\t\t<input type='hidden' name='action' value='backupnow'></input>\n".
		"\t\t\t\t<input type='hidden' name='tool' value='backup'></input>\n".
		"\t\t\t\t<input type='submit' class=\"button\" value='$l_tools[lbl_backupnow]'></input>\n".
		"\t\t\t</form>\n";
	}
	
	return $backupform;
}
//Newsletter tool//////////////////////////////////////////////////////////////////////////////////////
function newsletter_form() {
	global $l_tools,$settings,$l_gen,$l_ugs,$l_gform,$page,$groups;
	$newsletterform = "<h1>".$l_tools["lbl_newsletter"]."</h1><br />".
	"<form method='post' action='tools.site.php'>".
	"<table class='newslettertable1' cellspacing='0'>".
	//From
	"<tr><td>$l_tools[lbl_from]</td><td>\"$settings[sitename]\" &lt;$settings[siteemail]&gt;</td></tr>".
	"<input type='hidden' name='from1' value='$settings[sitename]'></input>".
	"<input type='hidden' name='from2' value='$settings[siteemail]'></input>".
	//Subject
	"<tr><td>$l_tools[lbl_subject]</td><td><input type='text' name='subject' class=\"textinput\" /></td></tr>".
	//Message
	"<tr><td>$l_tools[lbl_message]</td><td></td></tr>".
	"</table>".
	//Extra Buttons
	"<div class='floatright'>".
	"<input class='button' type='submit' name='action' value='$l_tools[lbl_sendnl]'/></input>".
	"<input class=\"button\" type='reset' name='action' value='$l_gen[lbl_reset]'/>".
	"</div>".
	//To	//TODO: an registrierte user
	"<table class='newslettertable2 realtable' cellspacing='0'>".
	"<thead><tr><th width='20px'></th><th width='20px'></th><th width='130px'>$l_tools[lbl_to]</th></tr></thead><tbody>";

	//sort groups by name
	$mygroups = $groups;
	foreach ($mygroups as $key => $row) {
		$gid[$key]  = $row['gid'];
		$name[$key] = $row['name'];
	}
	array_multisort($name, SORT_ASC, $gid, SORT_ASC, $mygroups);
	if (is_array($mygroups)) {
		foreach ($mygroups as $g) {
			if ($g["gid"]==1) { $symbol="<a class='admin'></a>"; $g["name"]=$l_gform["lbl_admins"]; }
			elseif ($g["gid"]==2) { $symbol="<a class='user'></a>"; $g["name"]=$l_ugs["lbl_users"]; }
			else { $symbol="<a class='special'></a>"; }
			$newsletterform .= "<tr><td><input type='checkbox' class='middle' name='mailto[]' value='$g[gid]'/></td>".
			"<td>$symbol</td><td class='mailtoname'>$g[name]</td></tr>";
		}
	}
	$newsletterform .= "</tbody></table>".
	"<div class='newslettercontent'><br />".
	"<div>".
	"<textarea name='ckeditor' rows='25' style='width:95%'></textarea>".
	"<div class='clr'></div>".
	"<a class='editorswitch' href='javascript:;'". 
	"onmousedown=\"CKEDITOR.replace('ckeditor');\">WYSIWYG</a>".
	"<a class='editorswitch' href='javascript:;' onmousedown=\"CKEDITOR.instances.".
	"ckeditor.destroy();\">HTML</a>".
	"<br />".
	"</div><br />".
	"</div>".
	"<script type='text/javascript'>".
		"CKEDITOR.replace( 'ckeditor', {".
			"toolbar : 'Newsletter' }".
		");".
	"</script>".
	"<input type='hidden' name='tool' value='newsletter'></input>".
	"</form>";
	
	return $newsletterform;
}
//Analysis tool//////////////////////////////////////////////////////////////////////////////////////
function analysis_form() {
	global $l_tools,$l_uform,$l_edit,$is_admin,$l_ctr,$l_gen,$page;
	$analysisform = "<h1>$l_tools[lbl_stats]</h1>".
	//Top 10 Contents
	"<div class='analysis_left'>".
	"<h2 style='float:left'>$l_tools[lbl_top10a]</h2>";
	//reset
	if ($is_admin) {
		$analysisform .= "<form method='post' action='tools.site.php?tool=analysis'>".
		"<input type='hidden' name='action' value='reset' />".
		"<input type='hidden' name='table' value='content' />".
		"<input type='submit' class='floatright button' value='$l_gen[lbl_reset]' /></form>";
	}
	$analysisform .= "<br />".
	"<table class=\"realtable\" cellspacing='0' width='100%' style='float:left'><tr>".
	"<th class='center'>#</th>".
	"<th class='left'>$l_edit[lbl_name]</th>".
	"<th class='center'>$l_tools[lbl_views]</th></tr><br>";
	
	$page->query("select name,views from site_content where depth>0 and views>0 order by views desc limit 10");
	$result = $page->db->getdata_array();
	
	$style="odd";
	$i=0;
	if (is_array($result) && !empty($result)) {
		foreach ($result as $row) {
			$i++;
			$analysisform .= "<tr class='$style'><td>$i</td><td class='left'>$row[name]</td><td>$row[views]</td></tr>";
			if ($style=="odd") { $style="even"; } else { $style="odd"; }
		}
	}
	$analysisform .= "</table></div>";
	if ($is_admin) {
		//Top 10 Most active Users
		$analysisform .= "<div class='analysis_right'>".
		"<h2 style='float:left'>$l_tools[lbl_top10u]</h2>".
		"<form method='post' action='tools.site.php?tool=analysis'>".
		"<input type='hidden' name='action' value='reset' />".
		"<input type='hidden' name='table' value='users' />".
		"<input type='submit' class='floatright button' value='$l_gen[lbl_reset]' /></form>".
		"<br />".
		"<table class=\"realtable\" cellspacing='0' width='100%' style='float:left'><tr>".
		"<th class='center'>#</th>".
		"<th class='left'>$l_uform[lbl_uname]</th>".
		"<th class='left'>$l_uform[lbl_name]</th>".
		"<th class='center'>$l_uform[lbl_logins]</th></tr><br>";
		
		$page->query("select user,name,logins from system_users where logins>0 order by logins desc limit 10");
		$result = $page->db->getdata_array();
	
		$style="odd";
		$i=0;
		foreach ($result as $row) {
			$i++;
			$analysisform .= "<tr class='$style'><td>$i</td><td class='left'>$row[user]</td>".
			"<td class='left'>$row[name]</td><td>$row[logins]</td></tr>";
			if ($style=="odd") { $style="even"; } else { $style="odd"; }
		}
		$analysisform .= "</table></div>";
	}
	$analysisform .= "<div class='clr'></div>";
	//Webstats
	$page->query("select * from site_visitors");
	$allwebstats = $page->db->getdata_array();
	$visits = 0;
	$browsers = $oss = $countries = array();
	foreach($allwebstats as $ws) {
		//--visits
		$visits+=$ws["visits"];
		//--browsers
		$monthbrowsers=explode(",",$ws["browsers"]);
		foreach($monthbrowsers as $mb) {
			$var=explode(":",$mb);
			if ($var[0]!="") {
				if (isset($browsers[$var[0]])) {
					$browsers[$var[0]]+=intval($var[1]);
				} else {
					$browsers[$var[0]]=intval($var[1]);
				}
			}
		}
		//--oss
		$monthoss=explode(",",$ws["oss"]);
		foreach($monthoss as $mo) {
			$var=explode(":",$mo);
			if ($var[0]!="") {
				if (isset($oss[$var[0]])) {
					$oss[$var[0]]+=intval($var[1]);
				} else {
					$oss[$var[0]]=intval($var[1]);
				}
			}
		}
		//--countries
		$monthc=explode(",",$ws["countries"]);
		foreach($monthc as $mc) {
			$var=explode(":",$mc);
			if ($var[0]!="") {
				if (isset($countries[$var[0]])) {
					$countries[$var[0]]+=intval($var[1]);
				} else {
					$countries[$var[0]]=intval($var[1]);
				}
			}
		}
	}
	//sort results
	arsort($browsers, SORT_NUMERIC);
	arsort($oss, SORT_NUMERIC);
	arsort($countries, SORT_NUMERIC);
	//output
	//--visits
	$analysisform .= "<div class='analysis_left'><h2 class='floatleft'>$l_tools[lbl_visits]<br /><br />$visits</h2>";
	//reset
	if ($is_admin) {
		$analysisform .= "<form method='post' action='tools.site.php?tool=analysis'>".
		"<input type='hidden' name='action' value='reset' />".
		"<input type='hidden' name='table' value='visits' />".
		"<input type='submit' class='floatright button' value='$l_gen[lbl_reset]' /></form>";
	}
	$analysisform .= "</div>".
	//--browsers
	"<div class='analysis_right'><h2 class='floatleft'>$l_tools[lbl_browsers]</h2>".
	"<br /><table class=\"realtable\" cellspacing='0' width='100%'>".
	"<tr><th class='left'>$l_tools[lbl_browser]</th>".
	"<th class='center'>$l_tools[lbl_amount]</th>".
	"<th class='center'>$l_tools[lbl_percent]</th></tr>";
	$style="odd";
	$counter=0;
	foreach ($browsers as $browser=>$amount) {
		if ($counter==9) { break; } else { $counter++; }
		$analysisform .= "<tr class='$style'><td class='left'>".ucfirst($browser)."</td><td>$amount</td><td>".
		round($amount/$visits*100,1)."%</td></tr>";
		if ($style=="odd") { $style="even"; } else { $style="odd"; }
	}
	$analysisform .= "</table></div>".
	"<div class='clr'></div>";
	//--oss
	$analysisform .= "<div class='analysis_right'><h2 class='floatleft'>$l_tools[lbl_oss]</h2>".
	"<br /><table class=\"realtable\" cellspacing='0' width='100%'>".
	"<tr><th class='left'>$l_tools[lbl_os]</th>".
	"<th class='center'>$l_tools[lbl_amount]</th>".
	"<th class='center'>$l_tools[lbl_percent]</th></tr>";
	$style="odd";
	$counter=0;
	foreach ($oss as $os=>$amount) {
		if ($counter==9) { break; } else { $counter++; }
		$analysisform .= "<tr class='$style'><td class='left'>$os</td><td>$amount</td><td>".round($amount/$visits*100,1)."%</td></tr>";
		if ($style=="odd") { $style="even"; } else { $style="odd"; }
	}
	$analysisform .= "</table></div>".
	//--countries
	"<div class='analysis_left'><h2 class='floatleft'>$l_tools[lbl_countries]</h2>".
	"<br /><table class=\"realtable\" cellspacing='0' width='100%'>".
	"<tr><th class='left'>$l_tools[lbl_country]</th>".
	"<th class='center'>$l_tools[lbl_amount]</th>".
	"<th class='center'>$l_tools[lbl_percent]</th></tr>";
	$style="odd";
	$counter=0;
	foreach ($countries as $c=>$amount) {
		if ($counter==9) { break; } else { $counter++; }
		$analysisform .= "<tr class='$style'><td class='left'>$l_ctr[$c]</td><td>$amount</td><td>".
		round($amount/$visits*100,1)."%</td></tr>";
		if ($style=="odd") { $style="even"; } else { $style="odd"; }
	}
	$analysisform .= "</table></div>".
	"<div class='clr'></div>";
	//--Feedback about chillyCMS
	$showfeedback=false;
	$page->query("select settings from site_modules where modid=3");
	$loginmods = $page->db->getdata_array();
	
	foreach ($loginmods as $l) {
		$settings=explode(",",$l["settings"]);
		if ($settings[4]==1) { $showfeedback=true; }
	}
	//show only if there is at least one login module with activated feedback
	if ($showfeedback) {
		//Calculation of the amount of positive feedback, negative feedback and overall feedback:
		$negative_amount=0;
		$page->query("select * from mod_login");
		$result = $page->db->getdata_array();
	
		if ($result) {
			foreach ($result as $row) {
				if ($row["type"]==0) {
					$positive_amount=intval($row["feedback"]);	
				} else {
					$negative_amount++;
				}
			}
		}
		$complete_amount=$positive_amount+$negative_amount;
		//Is there a feedback at all?...
		//...yes, then display the result-area:
		if ($complete_amount>0) {
			$positive_width=(($positive_amount*100)/$complete_amount);
			$negative_width=100-$positive_width;
			$pw_rounded=round($positive_width, 2);
			$nw_rounded=round($negative_width, 2);
			$feedbackinfo=$l_tools["lbl_feedbacknum"].$complete_amount;
			$display_or_not="display: block;";
		//...no, then hide the result-area:
		} else {
			$pw_rounded=$nw_rounded=$positive_width=0;
			$feedbackinfo=$l_tools["lbl_nofbyet"];
			$display_or_not="display: none;";
		}
		//build up the result-area:
		$analysisform .= "<div class='analysis_left'><h2 class='floatleft'>$l_tools[lbl_feedback]</h2>";
		//reset
		if ($is_admin) {
			$analysisform .= "<form method='post' action='tools.site.php?tool=analysis'>".
			"<input type='hidden' name='action' value='reset' />".
			"<input type='hidden' name='table' value='feedback' />".
			"<input type='submit' class='floatright button' value='$l_gen[lbl_reset]' /></form>";
		}
		$analysisform .= "<br /><br /><br /><p class='left'>".$feedbackinfo."</p><br />".
		"<div class='allocation' style='".$display_or_not."'>".
		"<span class='floatleft'>".$pw_rounded."% $l_tools[lbl_pos]</span>".
		"<span class='floatright'>".$nw_rounded."% $l_tools[lbl_neg]</span><br />".
		"<div class='complete_feedback' style='background-color: red;'>".
		"<div class='positive_feedback' style='width: ".$positive_width."%; background-color: green;'></div>".
		"</div>".
		"</div>".
		"</div><br />";
	}
	
	return $analysisform;
}
//Update form//////////////////////////////////////////////////////////////////////////////////////
function update_form() {
	global $l_tools,$is_admin,$l_gen,$page,$settings;
	$updateform = "";
	if ($is_admin) {
	
		//check if curl is installed
		$curlerr = false;
		if (!function_exists("curl_init")) { $curlerr = true; }
		if (!function_exists("curl_setopt")) { $curlerr = true; }
		if (!function_exists("curl_exec")) { $curlerr = true; }
		if (!function_exists("curl_close")) { $curlerr = true; }

		$updateform = "<h1>$l_tools[lbl_update]</h1>".
		"<div class='update'>".
		//TODO: remove notice
		'<p><strong>Please note:</strong><br />This feature is still highly experimental. If any error occurs, you can also upgrade by downloading the current version of chillyCMS and overriding the old files on your webserver with the new ones from the archive.<br /><strong>Thank you for your understanding!</strong></p>';

		//curl exists
		if (!$curlerr) {
			//do the update
			if (isset($_POST["updatenow"]) && $_POST["updatenow"]=="updatenow") {
				$error = false;
				//look at each version to update, old ones first so old files are overwritten
				$toversion = explode(",",escape_html($_POST["toversion"]));
				while(!empty($toversion)) {
					$version = array_pop($toversion);
					//$serverfile = "http://chillycms.bplaced.net/CHILLYUPDATE/".$version.".zip"; TODO
					$serverfile = "http://localhost/CHILLYUPDATE/".$version.".zip";
					$localfile = fopen(PATH."/update/".$version.".zip", 'w');
					$page->debug("Trying to get chillyCMS $version...");

					//get zip file from server
					if ($localfile){
						$ch = curl_init();
						curl_setopt($ch, CURLOPT_FILE, $localfile);
						curl_setopt($ch, CURLOPT_HEADER, 0);
						curl_setopt($ch, CURLOPT_URL, $serverfile);
						curl_setopt($ch, CURLOPT_FAILONERROR, 1);      
						curl_exec($ch);
						if (curl_error($ch)) {
							$error = true;
							$page->debug("Error getting file from server",'error');
						} else {
							$page->debug("Success",'success');
						}
						curl_close($ch);
						fclose($localfile);
					
						//extract zipfile
						$zip=new Zipper();
						$zip->open(PATH."/update/".$version.".zip");
						$zip->extractTo(PATH."/tmp/update/");
						$zip->close();
					} else {
						$error = true;
					}
				}

				//see whats inside the update
				$filestobackup = array();
				$newfiles = array();
				$contents = array();
				$updateupdater = false;
				read_files(PATH."/tmp/update",$contents,true);
				if ($contents && is_array($contents) && !empty($contents) && sizeof($contents)>0) {
					$page->debug("Searching for updated files...");
					parsecontents($contents,$filestobackup,$newfiles,$updateform,$updateupdater);
				} else {
					$page->debug("Error unpacking updated files",'error');
					$error = true;
				}
				
				//updating updater
				if ($updateupdater) {
					//backup old updater files
					make_dir(PATH."/tmp/","oldupdater");
					$file1 = PATH."/admin/tools.site.php";
					$file2 = PATH."/admin/tools.include.php";
					$newfile1 = PATH."/tmp/oldupdater/tools.site.php";
					$newfile2 = PATH."/tmp/oldupdater/tools.include.php";
					
					if (!copy($file1, $newfile1)) { $error = true; }
					if (!copy($file2, $newfile2)) { $error = true; }
					
					//get new updater files
					make_dir(PATH."/tmp/","newupdater");
				
				}
			
				//backup old files in update folder
				make_dir(PATH."/tmp/","oldversion");
				
				$backuperror = false;
				foreach ($filestobackup as $bf) {
					$bf2 = explode(DIRECTORY_SEPARATOR,$bf);
					if (sizeof($bf2)>1) {
						array_pop($bf2);
						$newdirname = array_pop($bf2);
						$newparent = PATH."/tmp/oldversion/".implode("/",$bf2);
						$newdir = PATH."/tmp/oldversion/".implode("/",$bf2)."/".$newdirname;
						
						if (!is_dir($newdir)) {
							make_dir($newparent,$newdirname);
						}
					}
					$file = PATH."/".$bf;
					$newfile = PATH."/tmp/oldversion/".$bf;

					if (!copy($file, $newfile)) {
						$error = true;
						$backuperror = true;
						$page->debug('Error backuping old files','error');
						break;
					}
				}
				if (!$backuperror) { $page->debug('Success backuping old files','success'); }
			
				//copy new files in real folder
				$copyerror = false;
				if (!copyfiles_r($contents)) {
					$copyerror = true; $error = true;
					$page->debug('Error overwriting old files','error');
				} else {
					$page->debug('Success overwriting old files','success');
				}

				//delete all files from tmp folder (just keep zipfile)
				delete_recursively(PATH."/tmp/update/");
				if (!$error) {
					//update version number in db
					$page->query("update site_settings set `value`='$version' where `key`='version'");
					delete_recursively(PATH."/tmp/oldversion/");
					$updateform .= "<br /><br /><p><a class=\"tick floatleft\"></a>".$l_tools["msg_update_ok"]."</p>";
				} else {
					//TODO: restore original files
					$updateform .= "<br /><br /><p><a class=\"delete floatleft\"></a>".$l_tools["msg_update_err"]."</p>";
				}			

			//check for updates
			} else {
				//$path = "http://chillycms.bplaced.net/CHILLYUPDATE/INSTALL";
				$path = "http://localhost/CHILLYUPDATE/INSTALL";
				$ch = curl_init($path);
				curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt($ch, CURLOPT_FAILONERROR, 1);
				$result = curl_exec($ch);
				curl_close($ch);
				if ($result==false) { $newestversion = "1.0.0"; }
				
				$versions = array();
				$allversions = explode("\n",$result);
				foreach($allversions as $version) {
					$version = explode("\t",$version);
					$versions[] = $version;
				}
				$update = array();
				$newestversion = $versions[0][0];
				foreach($versions as $v) {
					if (version_compare($v[0], $settings["version"]) > 0) {
						$update[] = $v[0];
					}
				}
				$updateform .= "<br /><br /><p>";
				if (!empty($update)) {
					$num = sizeof($update);
					$updateform .= "<a class=\"update_yes\"></a>";
					if ($num==1) {
						$updateform .= $l_tools["msg_found1"];
					} else {
						$updateform .= $num.$l_tools["msg_foundmore"];
					}
					$postvalues = array("tool"=>"update","updatenow"=>"updatenow",
					"toversion"=>implode(",",$update));
					
	    				$updateform .= "<br /><br /><br />".
	    				postlink($l_tools["lbl_updatenow"], $postvalues,"",true)."</p>";
				} else {
					$updateform .= "<a class=\"update_no\"></a>".$l_tools["lbl_noupdate"]."</p>";
				}
				
			}
		//curl does not exist
		} else {
			$updateform .= "<p>".$l_tools["msg_curl"]."</p>";
		}
		$updateform .= "</div>";
	}
	return $updateform;
}
//Parse contents///////////////////////////////////////////////////////////////////////////////////
function parsecontents($contents,&$filestobackup,&$newfiles,&$updateform,&$updateupdater,$parent="") {
	global $page;
	if ($contents && is_array($contents) && !empty($contents) && sizeof($contents)>0) {
		foreach ($contents as $file) {
			if (is_array($file) && isset($file["dir"])) {
				parsecontents($file[0],$filestobackup,$newfiles,$updateform,$updateupdater,$file["dir"]."/");
			} else {
				$fullfilename = substr($file['path'],strlen(PATH)+12).'/'.$file["name"];
				//new version of existing file
				if (file_exists($file['path'].'/'.$file['name'])) {
					if ($file['name']=='tools.include.php' or $file['name']=='tools.site.php') {
						$page->debug('Updating updater!');
						$updateupdater = true;
					} else {
						$page->debug("Found new version of ".$fullfilename);
						$filestobackup[] = $fullfilename;
					}
				//completely new file
				} else {
					$page->debug("Found new file ".$fullfilename);
					$newfiles[] = $fullfilename;
				}
			}
		}
	}
}
//Backup function//////////////////////////////////////////////////////////////////////////////////
function backup_now() {
	global $is_admin,$l_tools,$page;
	if ($is_admin) {
		//copy backup.zip and rename it to newly generated filename
		$myurl=no_colons(DB_HOST);
		$date=date("_Ymd_Gis");
		//if the hour begins with a zero (which is left out) insert that zero
		if (strlen($date)<16) { $date=date("_Ymd_0Gis"); }
		$file_dest=PATH."/backup/backup_".$myurl.$date.".zip";
		//make db backup
		$drop="";
		$allqueries="";
		$coretables=array("system_users","system_groups","system_modules","site_settings",
		"site_content","site_modules","site_visitors");
		//get ALL tables
		
		$page->query("select TABLE_NAME from information_schema.TABLES ".
		"where TABLE_SCHEMA='".$page->db->database."' order by CREATE_TIME,TABLE_NAME;");
		$alltables=$page->db->getdata_array();
		
		foreach ($alltables as $t) {
			$table = $t["TABLE_NAME"];
			$page->query("select * from $table");
			$tablecontent = $page->db->getdata_array();
			
			$page->query("show create table $table");
			$createtable = $page->db->getdata();
			
			//first add "drop if exists"-part of all tables except coretables (are deleted separately in a special order)
			if (!in_array($table,$coretables)) {
				$drop.="drop table if exists $table;\n";
			}
			//then add create table part
			$allqueries .= $createtable["Create Table"].";\n";
			//go through each table
			if (!empty($tablecontent)) {
				$tablequery = array();
				$tablecolumns = array();
				$counter = 0;
				foreach ($tablecontent as $row) {
					//get column names of the table
					if ($counter==0) { 
						foreach ($row as $k=>$v) { $tablecolumns[]=$k; }
						$counter++;
					}
					//collect each row
					$insertvalues = array_map('mysql_escape_string',$row);
					$tablequery[] = "('".implode("','",$insertvalues)."')";
				}
				//make insertstring for this table
				$tablequery="insert into $table (`".implode("`,`",$tablecolumns)."`) values\n".implode(",\n",$tablequery).";\n\n";
				$allqueries.=$tablequery;
			}
		}
		//make the insert script
		$zip = new Zipper();
		$open = $zip->open($file_dest, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE);
		if ($open===true) {
			//save the script inside the zip file's installation folder
			if (!$zip->addFromString("installation/database.sql", $allqueries)) {
				return array("could not create insert-script", "bad");
			}
			if (!$zip->addFromString("installation/drop1.sql", $drop)) {
				return array("could not create drop-script", "bad");
			}
		} else {
			return array($l_tools["msg_accessbu"], "bad");
		}
		//copy all folders in CMSFOLDER into the zip file
		$error=false;
		$zip->addDir(PATH."/admin", "admin");
		$zip->addDir(PATH."/core", "core");
		$zip->addDir(PATH."/languages", "languages");
		$zip->addDir(PATH."/media", "media");
		$zip->addDir(PATH."/modules", "modules");
		$zip->addDir(PATH."/scripts", "scripts");
		$zip->addDir(PATH."/style", "style");
		$zip->addDir(PATH."/templates", "templates");
		$zip->addDir(PATH."/tmp", "tmp");
		$zip->addDir(PATH."/update", "update");
		//make new backup and installation folder
		$zip->addDir(PATH."/backup/files", "backup/files");
		$zip->addDir(PATH."/backup/files/installation", "installation");
		//copy files to cms root folder that MUST exist
		if (!$zip->addFile(PATH."/backup/files/config.php", "config.php")) { $error=true; }
		if (!$zip->addFile(PATH."/index.php", "index.php")) { $error=true; }
		//copy files to cms root folder that MIGHT exist
		if (file_exists(PATH."/description.txt")) {
			$zip->addFile(PATH."/description.txt", "description.txt");
		}
		if (file_exists(PATH."/htaccess.txt")) {
			$zip->addFile(PATH."/htaccess.txt", "htaccess.txt");
		} elseif (file_exists(PATH."/.htaccess")) {
			$zip->addFile(PATH."/.htaccess", ".htaccess");
		}
		if (file_exists(PATH."/LICENSE.txt")) {
			$zip->addFile(PATH."/LICENSE.txt", "LICENSE.txt");
		}
		if (file_exists(PATH."/README")) {
			$zip->addFile(PATH."/README", "README");
		}
		if (file_exists(PATH."/CHANGELOG.txt")) {
			$zip->addFile(PATH."/CHANGELOG.txt", "CHANGELOG.txt");
		}
		//close zipfile and save
		if (!$zip->close()) { $error=true; }
		if (!$error) {
			return array($l_tools["msg_backup_ok"], "good");
		} else {
			return array($l_tools["msg_backup_err"], "bad");
		}
	}
}
//Delete a backup file/////////////////////////////////////////////////////////////////////////////
function delete_backup($name) {
	global $is_admin,$l_tools;
	if ($is_admin) {
		$name=cut_doubledots($name);
		if (@unlink(PATH."/backup/".$name)) {
			return array($l_tools["msg_delbu_ok"]." $name", "good");
		} else {
			return array($l_tools["msg_delbu_err"]." $name", "bad");
		}
	}
}
//Reset statistics/////////////////////////////////////////////////////////////////////////////////
function reset_stats($which) {
	global $l_tools,$is_admin,$page;
	$error=false;
	if ($is_admin) {
		if (!$page->query("start transaction")) { $error=true; }
		if ($which=="content") {
			if (!$page->query("update site_content set views=0")) { $error=true; }
		} elseif ($which=="users") {
			$sql="update system_users set logins=0,lastlogin='0000-00-00 00:00:00'";
			if (!$page->query($sql)) { $error=true; }
		} elseif ($which=="visits") {
			$sql = "update site_visitors set `visits`=0, `browsers`=null,`oss`=null,`countries`=null";
			if (!$page->query($sql)) { $error=true; }
		} elseif ($which=="feedback") {
			if (!$page->query("update mod_login set feedback=0 where id=1")) { $error=true; }
			if (!$page->query("delete from mod_login where id>1")) { $error=true; }
		}
		if (!$error) {
			$msg = array($l_tools["msg_reset_ok"],"good");
			$sql="commit";
		} else {
			$msg = array($l_tools["msg_reset_err"],"bad");
			$sql="rollback";
		}
		while(1) {
			if ($page->query($sql)) { break; }
		}
	}
	return $msg;
}
//Send a newsletter////////////////////////////////////////////////////////////////////////////////
function send_newsletter() {
	global $l_tools,$page;
	//from
	$from = "\"".$_POST["from1"]."\" <".email_chars($_POST["from2"]).">";

	//recipients:
	//--members of a group who want to get the newsletter
	$groups=$_POST["mailto"];
	$bcc=array();
	if (is_array($groups) && !empty($groups)) {
		$page->query("select `email`,`gids` from system_users where `getnewsletter`=1");
		$allusers = $page->db->getdata_array();
		if (!empty($allusers)) {
			foreach ($allusers as $u) {
				$gids=explode(",",$u["gids"]);
				foreach ($groups as $g) {
					if (in_array($g,$gids)) { $bcc[] = $u["email"]; }
				}
			}
			
		}
	}
	$bcc=implode(", ",$bcc);
	$recipient = email_chars($_POST["from2"]);
	//--guests who registered for the newsletter	TODO

	//subject
	$subject = $_POST["subject"];
	if ($subject=="") { $subject=$l_tools["lbl_newsletter"]; }

	//message			TODO insert images button
	//--make absolute urls
	$content = str_replace("../media",URL."/media",$_POST["ckeditor"]);
	$message = "<html>\n".
	"<head><title>$subject</title></head>\n".
	"<body>\n".$content."\n</body>\n".
	"</html>";

	//html mail header
	$header = "MIME-Version: 1.0\r\n";
	$header.= "Content-type: text/html; charset=utf-8\r\n";
	if (!empty($bcc)) { $header.= "Bcc: $bcc\r\n"; }
	$header.= "From: $from"."\r\n";

	//send mail
	if (mail($recipient, $subject, $message, $header)) {
		return array($l_tools["msg_nl_ok"], "good");
	} else {
		return array($l_tools["msg_nl_err"], "bad");
	}
}
?>
Return current item: chillyCMS