<?php $root=$_SERVER['DOCUMENT_ROOT'];$wroot=dirname($_SERVER['SCRIPT_NAME']);while((strlen($wroot)>1)&&(!file_exists($root.$wroot.'/main')))$wroot=dirname($wroot);if($wroot=='/')$wroot='';require_once($root.$wroot.'/main/app/App.php');
//sudo mysql -e "drop database aurarvyp_gds;drop user 'aurarvyp_gdsu'@'localhost';";sudo mysql -e "create database aurarvyp_gds;grant all on aurarvyp_gds.* to 'aurarvyp_gdsu'@'localhost' identified by 'aurarvyp_dbpass';";
//sudo mysql -e "create database aurarvyp_gds;grant all on aurarvyp_gds.* to 'aurarvyp_gdsu'@'localhost' identified by 'aurarvyp_dbpass';";
//sudo mysql -e "drop database aurarvyp_gds;drop user 'aurarvyp_gdsu'@'localhost';";
$dbOpen=(   file_exists("{$app->froot}/main/app/config.json")   &&   $app->dbInit(json_decode(file_get_contents("{$app->froot}/main/app/config.json"),true))   )?'':'open';
if (!$dbOpen&&(!$app->privileged('admin'))) $app->nopage('This page can only be accessed by admins.');
else{

	//database
	if (($app->getPost('dbSubmit'))&&($app->getPost('adUser'))&&($app->getPost('adPass'))&&($app->getPost('adPass')===$app->getPost('adConf'))){
		$config=[
			'dbHost'=>$app->getPost('dbHost'),
			'dbUser'=>$app->getPost('dbUser'),
			'dbPass'=>$app->getPost('dbPass'),
			'dbName'=>$app->getPost('dbName'),
			'dbPort'=>$app->getPost('dbPort')
		];
		if ($app->dbInit($config)){
			$app->config=$config;
			$app->createUserTable();
			file_put_contents("{$app->froot}/main/app/config.json",json_encode($app->config,true));
			if (!file_exists("{$app->froot}{$app->temp}")) $app->mkdir("{$app->froot}{$app->temp}");
			if (!file_exists("{$app->froot}/main/users")) $app->mkdir("{$app->froot}/main/users");
			$username=$app->getPost('adUser');
			$userpass=$app->getPost('adPass');
			$userhash=password_hash($userpass,PASSWORD_DEFAULT);
			if (ctype_alnum($username)){
				if (!($app->user=$app->findUser($username))) $app->addUser('superadmin',$username,$userhash);
				else{
					$app->editUser(1,['type'=>'superadmin','user'=>$username,'hash'=>$userhash]);
					if (!file_exists("{$app->froot}/main/users/$username")){
						$app->mkdir("{$app->froot}/main/users/$username",0777,true);
						copy("{$app->froot}/main/assets/anonymous.png","{$app->froot}/main/users/$username/avatar.png");
					}
				}
				$app->login($username,$userpass);
				Header("Location: {$_SERVER['REQUEST_URI']}");
			}			
			else $error="<p class='error'>Usernames must have alphanumeric characters only.</p>";
		}
	}


	//site icon
	if ($app->getPost('siteIconSubmit')){
		$icon_error=false;
		$homepath="{$app->froot}/main/assets/favicon";
		$app->mkdir($homepath,0777);
		$ext=$_FILES['siteIcon']['name'];$ext=substr($ext,strrpos($ext,'.'));
		$icon=$app->imageGDCreate($_FILES['siteIcon']['tmp_name'],$ext);
		if (!$icon) $icon_error=true;
		if (!$icon_error){
			$iconmeta='';
			$icon=$app->imageGDSquare($icon,512);
			imagepng($icon,"$homepath/favicon.png");
			$pngs=[
				['/apple-icon.png',192],['/apple-icon-180x180.png',180],['/apple-icon-152x152.png',152],['/apple-icon-144x144.png',144],['/apple-icon-120x120.png',120],['/apple-icon-114x114.png',114],['/apple-icon-76x76.png',76],['/apple-icon-72x72.png',72],['/apple-icon-60x60.png',60],['/apple-icon-57x57.png',57],
				['/apple-touch-icon.png',180],
				['/android-chrome-512x512.png',512],['/android-chrome-192x192.png',192],
				['/android-icon-192x192.png',192],['/android-icon-144x144.png',144],['/android-icon-96x96.png',96],['/android-icon-72x72.png',72],['/android-icon-48x48.png',48],['/android-icon-36x36.png',36],
				['/ms-icon-310x310.png',310],['/ms-icon-150x150.png',150],['/ms-icon-144x144.png',144],['/ms-icon-70x70.png',70],
				['/favicon-96x96.png',96],['/favicon-32x32.png',32],['/favicon-16x16.png',16]
			];
			foreach($pngs as $item){
				$x=imagescale($icon,$item[1],$item[1],IMG_BICUBIC_FIXED);
				imagepng($x,$homepath.$item[0]);
				imagedestroy($x);
				$s=substr($item[0],1);
				$s=substr($s,0,strcspn($s,'0123456789')-1);
				switch ($s){
					case 'favicon':				$iconmeta.="<link rel='icon' type='image/png' sizes='{$item[1]}x{$item[1]}' href='{$app->wroot}/main/assets/favicon{$item[0]}' />\n"; break;
					case 'apple-touch-icon':	$iconmeta.="<link rel='apple-touch-icon' type='image/png' sizes='{$item[1]}x{$item[1]}' href='{$app->wroot}/main/assets/favicon{$item[0]}' />\n"; break;
					case 'apple-icon':			$iconmeta.="<link rel='apple-icon' type='image/png' sizes='{$item[1]}x{$item[1]}' href='{$app->wroot}/main/assets/favicon{$item[0]}' />\n"; break;
					case 'ms-icon':				$iconmeta.="<meta name='msapplication-TileImage' content='{$app->wroot}/main/assets/favicon{$item[0]}' />\n"; break;
					case 'android-chrome':		$iconmeta.="<link rel='icon' type='image/png' sizes='{$item[1]}x{$item[1]}' href='{$app->wroot}/main/assets/favicon{$item[0]}' />\n"; break;
					case 'android-icon':			$iconmeta.="<link rel='icon' type='image/png' sizes='{$item[1]}x{$item[1]}' href='{$app->wroot}/main/assets/favicon{$item[0]}' />\n"; break;
				}
			}
			$iconmeta.="<meta name='msapplication-config' content='{$app->wroot}/main/assets/favicon/browserconfig.xml' /><meta name='msapplication-config' content='{$app->wroot}/main/assets/favicon/IEconfig.xml' /><link rel='manifest' href='{$app->wroot}/main/assets/favicon/manifest.json' /><link rel='manifest' href='{$app->wroot}/assets/favicon/site.webmanifest' /><meta name='msapplication-TileColor' content='#ffffff' /><meta name='theme-color' content='#ffffff' />";
			$icon_data=file_get_contents($homepath.'/favicon-16x16.png');
			$favicon=pack('vvvCCCCvvVV',0,1,1,16,16,0,0,1,0,filesize($homepath.'/favicon-16x16.png'),22).$icon_data;
			file_put_contents($homepath.'/favicon.ico',$favicon);file_put_contents($app->froot.'/favicon.ico',$favicon);
			unset($icon_data,$favicon);
			imagedestroy($icon);
			file_put_contents("{$homepath}/browserconfig.xml","<"."?xml version='1.0' encoding='utf-8'?"."><browserconfig><msapplication><tile><square70x70logo src='{$app->wroot}/main/assets/favicon/ms-icon-70x70.png'/><square144x144logo src='{$app->wroot}/main/assets/favicon/ms-icon-144x144.png'/><square150x150logo src='{$app->wroot}/main/assets/favicon/ms-icon-150x150.png'/><square310x310logo src='{$app->wroot}main/assets/favicon/ms-icon-310x310.png'/><TileColor>#ffffff</TileColor></tile></msapplication></browserconfig>\n");
			file_put_contents("{$homepath}/IEconfig.xml","<"."?xml version='1.0' encoding='utf-8'?"."><browserconfig><msapplication><tile><square70x70logo src='{$app->wroot}/main/assets/favicon/ms-icon-70x70.png'/><square144x144logo src='{$app->wroot}/main/assets/favicon/ms-icon-144x144.png'/><square150x150logo src='{$app->wroot}/main/assets/favicon/ms-icon-150x150.png'/><square310x310logo src='{$app->wroot}main/assets/favicon/ms-icon-310x310.png'/><TileColor>#ffffff</TileColor></tile></msapplication></browserconfig>\n");
			file_put_contents("{$homepath}/site.webmanifest",'{"name":"","short_name":"","icons":[{"src":"'.$app->wroot.'/main/assets/favicon/android-chrome-192x192.png","sizes":"192x192","type":"image/png"},{"src":"'.$app->wroot.'/main/assets/favicon/android-chrome-512x512.png","sizes":"512x512","type":"image/png"}],"theme_color":"#ffffff","background_color":"#ffffff","display":"standalone"}'."\n");
			file_put_contents("{$homepath}/manifest.json",'{"name":"App","icons":[{"src": "'.$app->wroot.'/main\/assets\/favicon\/android-icon-36x36.png","sizes": "36x36","type": "image\/png","density": "0.75"},{"src": "'.$app->wroot.'/main\/assets\/favicon\/android-icon-48x48.png","sizes": "48x48","type": "image\/png","density": "1.0"},{"src": "'.$app->wroot.'/main\/assets\/favicon\/android-icon-72x72.png","sizes": "72x72","type": "image\/png","density": "1.5"},{"src": "'.$app->wroot.'main\/assets\/favicon\/android-icon-96x96.png","sizes": "96x96","type": "image\/png","density": "2.0"},{"src": "'.$app->wroot.'main\/assets\/favicon\/android-icon-144x144.png","sizes": "144x144","type": "image\/png","density": "3.0"},{"src": "'.$app->wroot.'main\/assets\/favicon\/android-icon-192x192.png","sizes": "192x192","type": "image\/png","density": "4.0"}]}'."\n");
			file_put_contents("{$homepath}/iconmeta.htm",$iconmeta);
		}
	}


	//site indexes
	function getDir($dir){
		$dirs=glob($dir.'/*');
		for ($i=sizeof($dirs)-1;$i>=0;$i--){
			if (substr($dirs[$i],-5)=='/main') array_splice($dirs,$i,1);
			else
			if (substr($dirs[$i],-8)=='/cgi-bin') array_splice($dirs,$i,1);
		}
		$files=$dirs;
		$dirs=glob($dir.'/*',GLOB_ONLYDIR);
		for ($i=sizeof($dirs)-1;$i>=0;$i--){
			if (substr($dirs[$i],-5)=='/main') array_splice($dirs,$i,1);
			else
			if (substr($dirs[$i],-8)=='/cgi-bin') array_splice($dirs,$i,1);
		}
		forEach($dirs as $d) $files=array_merge($files,getDir($d));
		return $files;
	}
	if ($app->getPost('siteIndexSubmit')){
		$siteIndex='<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'."\n";
		$siteIndex.="<url><loc>{$app->fqwroot}/main/special/join.php</loc><changefreq>monthly</changefreq><priority>0.5</priority></url>\n";
		$siteIndex.="<url><loc>{$app->fqwroot}/main/special/privacy.php</loc><changefreq>yearly</changefreq><priority>0.1</priority></url>\n";
		$siteIndex.="<url><loc>{$app->fqwroot}/main/special/contact.php</loc><changefreq>yearly</changefreq><priority>0.1</priority></url>\n";
		$siteIndex.="<url><loc>{$app->fqwroot}/main/special/copyright.php</loc><changefreq>yearly</changefreq><priority>0.1</priority></url>\n";
		$files=getDir($app->froot);
		foreach($files as $file){
			$wfile=$app->fqwroot.substr($file,strlen($app->froot));
			$wfmod=date("Y-m-d",filemtime($file));
			$siteIndex.="<url><loc>$wfile</loc><lastmod>$wfmod</lastmod><changefreq>monthly</changefreq><priority>0.5</priority></url>\n";
		}
		$siteIndex.="</urlset>\n";
		file_put_contents($app->froot.'/sitemap.xml',$siteIndex);

		$robots=file_get_contents($_SERVER['DOCUMENT_ROOT'].'/robots.txt');
		$robotText="Sitemap: {$app->fqwroot}/sitemap.xml";
		if (strpos($robots,$robotText)===false){
			$robots="$robotText\n".$robots;
			file_put_contents($_SERVER['DOCUMENT_ROOT'].'/robots.txt',$robots);
		}
	}

	if ($app->getPost('erasureSubmit')){
		unlink("{$app->froot}/main/app/userlogs.csv");
		exec("rm -R {$app->froot}{$app->temp}/*");
	}

	$app->heads('Setup');
	$app->header();
?>
<section>
	<article>
		<h1 class='article'>Website Settings</h1>

		<article>
			<details class='center' <?php echo $dbOpen; ?> <?php $app->memoryDisclosure('setupDatabaseDetail'); ?>>
				<summary><h5>Database</h5></summary>
				<h3>Setup Website Database</h3>
				<form class='tall' method='post'>
					<input name='adUser' placeholder='admin username' value='admin' />
					<?php if (isset($error)) echo $error; ?>
					<input name='adPass' type='password' placeholder='admin password' value='guest777' />
					<input name='adConf' type='password' placeholder='confirm password' value='guest777' />
					<input name='dbHost' placeholder='host (localhost)' value='localhost' />
					<input name='dbPort' placeholder='port (3306)' value='3306' />
					<input name='dbName' placeholder='name (gdsdb)' value='aurarvyp_gds' />
					<input name='dbUser' placeholder='db username' value='aurarvyp_gdsu' />
					<input name='dbPass' type='password' placeholder='db password' value='aurarvyp_dbpass' />
					<input type='submit' name='dbSubmit' value='Use These Settings' />
				</form>
			</details>
		</article>

		<article>
			<details class='center' <?php $app->memoryDisclosure('setupSiteIconDetail'); ?>>
				<summary><h5>Site Icon</h5></summary>
				<h3>Create Site Favicons</h3>
				<?php $app->imageDropper('siteIcon','/main/assets/favicon/favicon.png'); ?>
			</details>
		</article>

		<article>
			<details class='center' <?php $app->memoryDisclosure('setupModuleDetail'); ?>>
				<summary><h5>Modules</h5></summary>
				<h3>Configure Modules</h3>
				<?php
					$modules=glob($app->froot.'/main/modules/*');
					foreach($modules as $module){
						$mod=basename($module);$modname=ucfirst($mod);
						echo "<p class='center'><a href='{$app->wroot}/main/modules/$mod/config.php'>$modname</a></p>";
					}
				?>
				<h3>Configure Plugins</h3>
				<?php
					$modules=glob($app->froot.'/main/plugins/*');
					foreach($modules as $module){
						$mod=basename($module);$modname=ucfirst($mod);
						echo "<p class='center'><a href='{$app->wroot}/main/plugins/$mod/config.php'>$modname</a></p>";
					}
				?>
			</details>
		</article>

		<article>
			<details class='center' <?php $app->memoryDisclosure('setupSiteIndexDetail'); ?>>
				<summary><h5>Site Indexes</h5></summary>
				<h3>Manage Site Indexes</h3>
				<a href=<?php echo "'{$app->wroot}/main/app/userlogs.csv'"; ?> download='userlogs.csv'>
					<?php $filesize=$app->readableNumber((file_exists("{$app->froot}/main/app/userlogs.csv"))?filesize("{$app->froot}/main/app/userlogs.csv"):0); ?>
					<h5>Download User Logs (<?php echo $filesize; ?> bytes)</h5>
				</a>
				<form class='block' method='post' onsubmit="return confirm('Are you sure?');">
					<input class='red' type='submit' name='erasureSubmit' value='Erase Site Data' />
				</form>
				<form class='block' method='post'>
					<input type='submit' name='siteIndexSubmit' value='Create Site Map' />
				</form>
			</details>
		</article>

	</article>
</section>
<?php
	$app->setMemoryDisclosures('setupSiteIconDetail','setupSiteIndexDetail','setupDatabaseDetail','setupModuleDetail');
	$app->footer();
	$app->tails();
}
?>
