<?

function return_error_page($page_url){
    header('HTTP/1.0 404 Not Found');
    $error_page=array(
    'page_title'=>'Error 404 page cannot be found',
    'heading_1'=>'Error 404 page cannot be found',
    'content_1'=>'Sorry this page is removed or cannot be found',
    'content_2'=>'',
    'content_3'=>'',
    'content_4'=>'',
    'content_5'=>'',
    'client_content_and_location'=>'',
    'additional_pages_links'=>'',
    'error_page_links'=>'',
	'link_content'=>'',
    'box_2'=>''
    
     
    );
    $cont=DB_connect::connect_db();
    mysqli_query($cont, "INSERT INTO _logs_banned_pages_attempted (page_tried) VALUES ('$page_url')");
    DB_connect::disconnect_db($cont);
    
    return $error_page;
}


#require_once(dirloc::$dirlocation.'/get_links.php');

function error_generator($domain_in,$path_in,$extn,$site_data){

if($extn==''){
    $fulladdress=$domain_in.$path_in;
}
else{
$fulladdress=$domain_in.$path_in.'.'.$extn;
  }
$serverpath=$domain_in.$path_in;

 
#$t_r_l_n_a=array(60,15,15,10);   //0, 1, 2, 3 link chances  - must add up to 100 or it will truncate the chances

#$random_link_choice=rand(1,100);
#if($random_link_choice<=$t_r_l_n_a[1]+$t_r_l_n_a[0]+$t_r_l_n_a[2]+$t_r_l_n_a[3]){
#	$rand_link_num=3;}
#if($random_link_choice<=$t_r_l_n_a[1]+$t_r_l_n_a[0]+$t_r_l_n_a[2]){
#	$rand_link_num=2;}
#if($random_link_choice<=$t_r_l_n_a[1]+$t_r_l_n_a[0]){
#	$rand_link_num=1;}
#if($random_link_choice<=$t_r_l_n_a[0]){
#	$rand_link_num=0;}

        
/// build the error page


//  $site_data



if(substr($serverpath, -1)=='/'){
    $split_path=explode('/',$serverpath);
	end($split_path);
	$keyword=prev($split_path);
 }
 else{
    
    $keyword=basename($path_in);
 }
 
 $keyword=ucfirst(str_replace('-',' ',$keyword));
$keyword=str_replace('_',' ',$keyword);


#######################################image injection ######################################

$thiscontent='';
##Two parts@
#get images
#$thiscontent.=get_image($site_data['theme'],$site_data['subtheme'],$keyword);

#get content

#$thiscontent.=get_content($site_data['theme'],$site_data['logo'],'',$site_data['company'],$site_data['email'],$fulladdress,$keyword);

#############################################################################################



$thistitle=$site_data['logo'].' - '. $keyword;
$thisheading=$site_data['logo'].' - '. $keyword;
$thisanchor=$keyword;
 $thislinks='';

 
$cont=DB_connect::connect_db();
/* put it into the database        

$offset_result = mysqli_query($cont, "SELECT id FROM `page_data` WHERE `domain` LIKE '$domain_in';");
while($offset_rowin= mysqli_fetch_assoc( $offset_result )){
	$offset_row[]=$offset_rowin;
}

$select_random_page_offset=(array_rand($offset_row));
$select_random_page_id=$offset_row[$select_random_page_offset]['id'];

$query = mysqli_query($cont, "SELECT error_page_links, time_edit_stamp FROM `page_data` WHERE `id` LIKE '$select_random_page_id';");
$error_page_links = mysqli_fetch_assoc($query);
//print_r($error_page_links);
$time_edit_stamp=$error_page_links['time_edit_stamp'];
$error_page_links=$error_page_links['error_page_links'];

if($extn==''){$error_page_links.='<li><a href="'.$path_in.'">'.$thisanchor.'</a></li>'.PHP_EOL;}
else{
$error_page_links.='<li><a href="'.$path_in.'.'.$extn.'">'.$thisanchor.'</a></li>'.PHP_EOL;
}
$time_edit_stamp=$time_edit_stamp+1;
//echo '<br>';
*/

if($extn==''){$page_name=$path_in;}
else{
$page_name=$path_in.'.'.$extn;
}

      
#$query = mysqli_query($cont, "UPDATE `page_data` SET `error_page_links`='$error_page_links', `time_edit_stamp`='$time_edit_stamp' WHERE `id`='$select_random_page_id';");


$current_time=date('h:m d/m/y');
 
$thistitle=str_replace('\'',"\'",$thistitle);
$thisheading=str_replace('\'',"\'",$thisheading);
$thisanchor=str_replace('\'',"\'",$thisanchor);
 
mysqli_query($cont, "INSERT INTO page_data (page_url, domain, page_title, content_1, heading_1, anchor, source, active_status, time_created, linker_status) VALUES ('$path_in', '$domain_in' ,'$thistitle', '$thiscontent', '$thisheading', '$thisanchor', 'error' , '1', '$current_time', '1')");
//echo mysql_errno($cont) . ": " . mysql_error($cont) . "\n";
#$thislinks=get_links($rand_link_num,$fulladdress);
#$thislinks=str_replace("\'","\'",$thislinks);
#mysqli_query($cont, "UPDATE `page_data` SET `link_content`='$thislinks' WHERE `page_url`='$path_in' AND `domain`='$domain_in';");
$query=mysqli_query($cont, "SELECT id FROM `page_data` WHERE `page_url`='$path_in' AND `domain`='$domain_in';");
$page_id=mysqli_fetch_array($query);
$page_id=$page_id['id'];
$theme=$site_data['theme'];
$logo=$site_data['logo'];
$company=$site_data['company'];
$email=$site_data['email'];
$subtheme=$site_data['subtheme'];



############################ Menu Update#####################################
$query = mysqli_query($cont, "SELECT menu FROM `sitewide_data` WHERE `domain` = '$domain_in';");
$menu_update=mysqli_fetch_array($query);


$menu_update=$menu_update['menu'];

$menu_num=substr_count($menu_update,'<li>');
if($menu_num<=7){
$thisanchor= explode(' ',$thisanchor,3);
$thisanchor=$thisanchor[0].' '.$thisanchor[1];
if($extn==''){$menu_update.='<li><a href="'.$path_in.'">'.$thisanchor.'</a></li>'.PHP_EOL;}
else{
$menu_update.='<li><a href="'.$path_in.'.'.$extn.'">'.$thisanchor.'</a></li>'.PHP_EOL;}

}
#############################################################################



mysqli_query($cont, "INSERT INTO _logs_pages_created (pagelist) VALUES ('$fulladdress')");

$query = mysqli_query($cont, "SELECT COUNT(*) FROM page_data WHERE `domain` = '$domain_in'");

$page_count=mysqli_fetch_array($query);

$page_count=$page_count[0];

$query = mysqli_query($cont, "UPDATE `sitewide_data` SET `page_count`='$page_count', `menu`='$menu_update' WHERE `domain` = '$domain_in';");

mysqli_query($cont, "INSERT INTO create_queue (page_id, fullurl, current_theme, current_subtheme, website_title, company, email, page_title, domain, page) VALUES ('$page_id', '$fulladdress', '$theme', '$subtheme', '$logo', '$company', '$email', '$keyword', '$domain_in', '$page_name')");


DB_connect::disconnect_db($cont);

    $error_page_gen=array(
    'domain'=>$domain_in,
    'page_title'=>$thistitle,
    'heading_1'=>str_replace('\\',"",$thisheading),
    'content_1'=>$thiscontent,
    'content_2'=>'',
    'content_3'=>'',
    'content_4'=>'',
    'content_5'=>'',
    'client_content_and_location'=>'',
    'additional_pages_links'=>'',
    'error_page_links'=>'',
    'link_content'=>$thislinks,
    'box_2'=>''
    
    
    );

    return $error_page_gen;
    }

?><?
function create_new_site($domain,$path){
	
	#### the themes database connect####
	$themes=array();
$cont_data=DB_connect::connect_content_db();
	$results = mysqli_query($cont_data, "select theme, subtheme from themes;");
	while($offset_rowin= mysqli_fetch_assoc( $results )){
	$themes[]=$offset_rowin;
}
	DB_connect::disconnect_content_db($cont_data);


$newarray=array();
foreach($themes as $item){
		if(!in_array($item['theme'],$newarray)){
			$newarray[$item['theme']]=array();
		}
}

foreach($themes as $item){
		if(array_key_exists($item['theme'],$newarray)){
		$newarray[$item['theme']][]=$item['subtheme'];
		}
}

$options=array_keys($newarray);
$select='';
$java_opts="{";
foreach($options as $opt){
	$select.='<option value="'.$opt.'">'.$opt.'</option>';
	
	$java_opts.='"'.$opt.'":[';
	$java_opts.='{text:"Please Select",value:""},';
		$java_opts.='{text:"Generic",value:""},';
	foreach($newarray[$opt] as $value){
		$java_opts.='{text:"'.$value.'",value:"'.$value.'"},';
		
	}
	$java_opts=rtrim($java_opts, ",");
	$java_opts.='],';
	
}
$java_opts=rtrim($java_opts, ",");
$java_opts.='}';

####################
### the themes header part###
$new_site['content_1']='<script type="text/javascript">

var opts = '. $java_opts .';


function changeOther(sel) {
    var selbox = document.getElementById("find"+sel.id.replace("field",""));
    console.log(selbox.id)
      selbox.options.length = 0;
      var val = sel.value;
      if (val=="") {
        selbox.options[selbox.options.length] = new Option(\'Please select one of the options to the left first\',\'\');
        return;
      }
      for (var opt = opts[val],i=0; i<opt.length;i++) {
         selbox.options[selbox.options.length] = new Option(opt[i].text,opt[i].value);
      }

}

window.onload=function() {
    document.getElementById("fieldone").onchange=function() {
        changeOther(this);
   }      
}
</script>
<script type="text/javascript" src="http://www.mm-hmm.co.uk/tinymce/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
    selector: "textarea",
 plugins: [
        "advlist autolink lists link image charmap preview anchor",
        "searchreplace visualblocks code wordcount",
        "insertdatetime media table contextmenu paste"
    ],
    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image"

});
</script>



';
##########################                                           ##################
###The themes form part:  
##########################                                           ##################

	
	
    if($path=='/create_new_site'){
        if(isset($_POST['site_info'])){
            $server_name_path=dirloc::$dirlocation."server_name.txt";
            $handle = fopen($server_name_path, "r");
            $server_name=fread($handle,filesize($server_name_path));
            fclose($handle);
            $fulladdress=$domain.$path; 
            $site_logo=$_POST['sitelogo'];
		$site_logo=str_replace('\'',"\'",$site_logo);
		$slogan=$_POST['slogan'];
		$slogan=str_replace('\'',"\'",$slogan);
            $site_company=$_POST['company'];
		$site_company=str_replace('\'',"\'",$site_company);
            $site_email=$_POST['email_bit'];
		$site_email=str_replace('\'',"\'",$site_email);
            $site_sidebar=$_POST['side_bar_1'];
		$site_sidebar=str_replace('\'',"\'",$site_sidebar);
		// this is for the homepage content
		    $site_title=$_POST['title'];
		$site_title=str_replace('\'',"\'",$site_title);
		    $site_heading=$_POST['heading'];
		$site_heading=str_replace('\'',"\'",$site_heading);
		    $site_content=$_POST['content_1'];
			$theme=$_POST['fieldone'];
			$subtheme=$_POST['findone'];
		$site_content=str_replace('\'',"\'",$site_content);
		
           # $leftfooter1='<p>2016 &copy; Copyright '.$site_logo.' - '.$domain.' All rights reserved. | </p>'.PHP_EOL;
			$leftfooter1='<p>&copy;  '.$site_logo.' 2016 | www.'.$domain.' |  Email: <a href="mailto:'.$site_email.'@'.$domain.'">'.$site_email.'@'.$domain.'</a> | Privacy | Terms & Conditions | Cookie Policy | All rights reserved. Contact: <a href="mailto:'.$site_email.'@'.$domain.'">'.$site_email.'@'.$domain.'</a>.</p>'.PHP_EOL;
			
            $menu='<li><a href="/">Home</a></li>'.PHP_EOL;
            $thistitle=$site_title;
            $thiscontent=$site_content;
            $thisheading=$site_heading;
            $thisanchor='Home';
            $thisbox='';
            //$rand_link_num=rand(0,3);
            $thislinks='';
            $path_page='/';
            $email=$site_email.'@'.$domain;
            $current_time=date('h:m d/m/y');
			
			
			$rich_bit='<style>
.review_hide{display:none}
</style>
<div class="review_hide" itemtype="http://data-vocabulary.org/Review-aggregate">
    <span itemprop="itemreviewed">[domain]</span>
    
    <span itemprop="rating" itemscope itemtype="http://data-vocabulary.org/Rating">
      <span itemprop="average">[average]</span>
      out of <span itemprop="best">5</span>
    </span>
    based on <span itemprop="votes">[ratings]</span> ratings.
    <span itemprop="count">[reviews]</span> user reviews.
  </div>  ';
  			$average=rand(30,50)/10;
			$rating=rand(1,100);
			$reviews=rand(1,$rating);
			
			$rich_bit=str_replace('[domain]',$domain,$rich_bit);
			$rich_bit=str_replace('[average]',$average,$rich_bit);
			$rich_bit=str_replace('[ratings]',$rating,$rich_bit);
			$rich_bit=str_replace('[reviews]',$reviews,$rich_bit);
			
			
			
			
			
             $cont=DB_connect::connect_db();
            
             	mysqli_query($cont,"INSERT INTO sitewide_data (domain, server_location, logo, menu, company, side_bar_1, footer_left_1, footer_wide_2, email, theme, subtheme, slogan) VALUES ('$domain', '$server_name', '$site_logo', '$menu','$site_company' , '$site_sidebar', '$leftfooter1', '$rich_bit', '$email', '$theme', '$subtheme', '$slogan');");
             	mysqli_query($cont, "INSERT INTO page_data (page_url, domain, page_title, content_1, heading_1, anchor, box_2, link_content, active_status, time_created) VALUES ('$path_page', '$domain' ,'$thistitle', '$thiscontent', '$thisheading', '$thisanchor', '$thisbox', '$thislinks', '1', '$current_time')");
                
                
             
             DB_connect::disconnect_db($cont);
            sleep(1);
            header('Location: /');
            
            
            
            }
			
			$server_name_path=dirloc::$dirlocation."server_name.txt";
            $handle = fopen($server_name_path, "r");
            $server_name=fread($handle,filesize($server_name_path));
            fclose($handle);
			
		$site_title='Welcome to '.$site_logo.'';
		$site_heading='Welcome to '.$site_logo.'';
      $new_site['heading_1']='Welcome to new site creation';
      $new_site['page_title']='Welcome to new site creation';     
      $new_site['content_2']='This website is on: '.$server_name.'
      <br>
      <br>
      <form method="POST" name="contact_form">
      <strong>Enter the site logo: Must have!</strong>
      <br>
      <input name="sitelogo" size="50" style="color:#FFF; background-color:#000;" type="text" value="'.$site_logo.'">
      <br><br>
	  <strong> Slogan:</strong>
      <br>
      <input name="slogan" size="50" style="color:#FFF; background-color:#000;" type="text" value="'.$slogan.'">
	  <br><br>
     <strong> Enter Company Name:</strong>
      <br>
      <input name="company" size="50" style="color:#FFF; background-color:#000;" type="text" value="'.$site_company.'">
      <br><br>
      <strong>Enter website email: Must have!</strong>
      <br>
      <input name="email_bit" size="50" style="color:#FFF; background-color:#000;" type="text" value="'.$site_email.'">@'.$domain.'
      <br><br>
	  <strong>Select the theme | subtheme:</strong>
	  <br>

    <select name="fieldone" id="fieldone">
      <option value="" selected="selected">Please select</option>
'.$select.'
    </select>
    <select name="findone" id="findone" />
    <option value="" selected="selected">Please select the category on the left first.</option>
    </select>
<br />

    <br />
	Image finder (you can use the themes found above or search for a more specific image):
	<br>
	 <iframe src="http://dev.mm-hmm.co.uk/image-reader.php" width="100%" height="400px;"></iframe>

	  
      
      <br><br>
      <strong>Enter the sidebar content:  Must have!</strong>
      <br>
      <textarea name="side_bar_1" style="color:#FFF; background-color:#000; width:100%" rows=20 cols=50>'.$site_sidebar.'</textarea>
	  <br><br>
	
     <strong> Enter Home page meta title:</strong>
      <br>
      <input name="title" size="50" style="color:#FFF; background-color:#000; " type="text" value="'.$site_title.'">
	  <br><br>
     <strong> Enter Home page Heading:</strong>
      <br>
      <input name="heading" size="50" style="color:#FFF; background-color:#000;" type="text" value="'.$site_heading.'">
	  <br><br>
	 <strong> Enter the homepage content:  Must have!</strong>
      <br>
      <textarea name="content_1" style="color:#FFF; background-color:#000; width:100%" rows=25 cols=50>'.$site_content.'</textarea>
      <br>
      <input type="submit" style="color:#FFF; background-color:#000;" value="Save Site Info" name="site_info">
      </form>
      
      ';  
        
      //  $leftfooter1='<p>2013 &copy; Copyright '.$sitelogo.' - '.$domain.' All rights reserved. Email: <a href="mailto:'.$email.'">'.$email.'</a></p>'.PHP_EOL;
        
        
        
    }
    
    else{
        $new_site['heading_1']='Welcome to '.$domain;
        $new_site['content_1']='Welcome to '.$domain.'. The new website is in the process of being created so please bookmark us or add us to Google+. Dont forget to check back later!';
        
        
    }
	$returnarray=array();
	$returnarray[]=$new_site;
	$returnarray[]=$new_head;
    return $returnarray;
    }
    
?>