<commit_before><?php

/** editor.inc.php
  *
  * All the functions used by the editor.
  */

/** @function fix_gpc_string 
  *
  * Take a string (that we got from $_REQUEST) and make it back to how the
  * user TYPED it, regardless of whether magic_quotes_gpc is turned on or off.
  *
  * @param string $input String to fix
  *
  * @returns string Fixed string
  *
  */
function fix_gpc_string($input) 
{
    if (true == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc()) {
        $input = stripslashes($input);
    }
    return ($input);
}

/**
 * Clean up URI (function taken from Cacti) to protect against XSS
 */
function wm_editor_sanitize_uri($str) {
        static $drop_char_match =   array(' ','^', '$', '<', '>', '`', '\'', '"', '|', '+', '[', ']', '{', '}', ';', '!', '%');
        static $drop_char_replace = array('', '', '',  '',  '',  '',  '',   '',  '',  '',  '',  '',  '',  '',  '',  '', '');

        return str_replace($drop_char_match, $drop_char_replace, urldecode($str));
}

// much looser sanitise for general strings that shouldn't have HTML in them
function wm_editor_sanitize_string($str) {
        static $drop_char_match =   array('<', '>' );
        static $drop_char_replace = array('', '');

        return str_replace($drop_char_match, $drop_char_replace, urldecode($str));
}

function wm_editor_validate_bandwidth($bw) {
  
    if(preg_match( "/^(\d+\.?\d*[KMGT]?)$/", $bw) ) {
	return true;
    }
    return false;
}

function wm_editor_validate_one_of($input,$valid=array(),$case_sensitive=false) {
    if(! $case_sensitive ) $input = strtolower($input);
    
    foreach ($valid as $v) {
	if(! $case_sensitive ) $v = strtolower($v);
	if($v == $input) return true;
    }
    
    return false;
}

// Labels for Nodes, Links and Scales shouldn't have spaces in
function wm_editor_sanitize_name($str) {
    return str_replace( array(" "), "", $str);
}

function wm_editor_sanitize_selected($str) {        
	$res = urldecode($str);
	
	if( ! preg_match("/^(LINK|NODE):/",$res)) {
	    return "";
	}
	return wm_editor_sanitize_name($res);
}

function wm_editor_sanitize_file($filename,$allowed_exts=array()) {
    
    $filename = wm_editor_sanitize_uri($filename);
    
    if ($filename == "") return "";
        
    $ok = false;
    foreach ($allowed_exts as $ext) {
	$match = ".".$ext;
	
	if( substr($filename, -strlen($match),strlen($match)) == $match) {
	    $ok = true;
	}
    }    
    if(! $ok ) return "";
    return $filename;
}

function wm_editor_sanitize_conffile($filename) {
    
    $filename = wm_editor_sanitize_uri($filename);
    
    # If we've been fed something other than a .conf filename, just pretend it didn't happen
    if ( substr($filename,-5,5) != ".conf" ) {
	$filename = ""; 
     }
    return $filename;
}

function show_editor_startpage()
{
	global $mapdir, $WEATHERMAP_VERSION, $config_loaded, $cacti_found, $ignore_cacti,$configerror;

	$fromplug = false;
	if (isset($_REQUEST['plug']) && (intval($_REQUEST['plug'])==1) ) { 
	    $fromplug = true; 
	}

	$matches=0;

	print '<html xmlns="http://www.w3.org/1999/xhtml"><head><link rel="stylesheet" type="text/css" media="screen" href="editor-resources/oldeditor.css" /><script type="text/javascript" src="editor-resources/jquery-latest.min.js"></script><script src="editor-resources/editor.js" type="text/javascript"></script><title>PHP Weathermap Editor ' . $WEATHERMAP_VERSION
		. '</title></head><body>';

	print '<div id="nojs" class="alert"><b>WARNING</b> - ';
	print 'Sorry, it\'s partly laziness on my part, but you really need JavaScript enabled and DOM support in your browser to use this editor. It\'s a visual tool, so accessibility is already an issue, if it is, and from a security viewpoint, you\'re already running my ';
	print 'code on your <i>server</i> so either you trust it all having read it, or you\'re already screwed.<P>';
	print 'If it\'s a major issue for you, please feel free to complain. It\'s mainly laziness as I said, and there could be a fallback (not so smooth) mode for non-javascript browsers if it was seen to be worthwhile (I would take a bit of convincing, because I don\'t see a benefit, personally).</div>';
	
	$errormessage = "";

    if ($configerror!='') {
        $errormessage .= $configerror.'<p>';
    }
		
	if ( !$librenms_found && !$ignore_librenms) {
		//$errormessage .= '$cacti_base is not set correctly. Cacti integration will be disabled in the editor.';
		//$errormessage .= "$librenms_found and $ignore_librenms";
		//if ($config_loaded != 1) { 
            	//$errormessage .= " You might need to copy editor-config.php-dist to editor-config.php and edit it."; 
        	//}
	}
	
	if ($errormessage != '') {
		print '<div class="alert" id="nocacti">'.htmlspecialchars($errormessage).'</div>';
	}

	print '<div id="withjs">';
	print '<div id="dlgStart" class="dlgProperties" ><div class="dlgTitlebar">Welcome</div><div class="dlgBody">';
	print 'Welcome to the PHP Weathermap '.$WEATHERMAP_VERSION.' editor.<p>';
	print '<div style="border: 3px dashed red; background: #055; padding: 5px; font-size: 90%;"><b>NOTE:</b> This editor is not finished! There are many features of ';
	print 'Weathermap that you will be missing out on if you choose to use the editor only.';
	print 'These include: curves, node offsets, font definitions, colour changing, per-node/per-link settings and image uploading. You CAN use the editor without damaging these features if you added them by hand, however.</div><p>';
	
	print 'Do you want to:<p>';
	print 'Create A New Map:<br>';
	print '<form method="GET">';
	print 'Named: <input type="text" name="mapname" size="20">';

	print '<input name="action" type="hidden" value="newmap">';
	print '<input name="plug" type="hidden" value="'.$fromplug.'">';

	print '<input type="submit" value="Create">';
	print '</form>';

	$titles = array();

	$errorstring="";

	if (is_dir($mapdir)) {
		$n=0;
		$dh=opendir($mapdir);

		if ($dh) {
		    while (false !== ($file = readdir($dh))) {
			$realfile=$mapdir . DIRECTORY_SEPARATOR . $file;
			$note = "";
	
			// skip directories, unreadable files, .files and anything that doesn't come through the sanitiser unchanged
			if ( (is_file($realfile)) && (is_readable($realfile)) && (!preg_match("/^\./",$file) )  && ( wm_editor_sanitize_conffile($file) == $file ) ) {
				if (!is_writable($realfile)) {
					$note .= "(read-only)";
				}
				$title='(no title)';<commit_msg>Added error checking for files missing .conf<commit_after><?php

/** editor.inc.php
  *
  * All the functions used by the editor.
  */

/** @function fix_gpc_string 
  *
  * Take a string (that we got from $_REQUEST) and make it back to how the
  * user TYPED it, regardless of whether magic_quotes_gpc is turned on or off.
  *
  * @param string $input String to fix
  *
  * @returns string Fixed string
  *
  */
function fix_gpc_string($input) 
{
    if (true == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc()) {
        $input = stripslashes($input);
    }
    return ($input);
}

/**
 * Clean up URI (function taken from Cacti) to protect against XSS
 */
function wm_editor_sanitize_uri($str) {
        static $drop_char_match =   array(' ','^', '$', '<', '>', '`', '\'', '"', '|', '+', '[', ']', '{', '}', ';', '!', '%');
        static $drop_char_replace = array('', '', '',  '',  '',  '',  '',   '',  '',  '',  '',  '',  '',  '',  '',  '', '');

        return str_replace($drop_char_match, $drop_char_replace, urldecode($str));
}

// much looser sanitise for general strings that shouldn't have HTML in them
function wm_editor_sanitize_string($str) {
        static $drop_char_match =   array('<', '>' );
        static $drop_char_replace = array('', '');

        return str_replace($drop_char_match, $drop_char_replace, urldecode($str));
}

function wm_editor_validate_bandwidth($bw) {
  
    if(preg_match( "/^(\d+\.?\d*[KMGT]?)$/", $bw) ) {
	return true;
    }
    return false;
}

function wm_editor_validate_one_of($input,$valid=array(),$case_sensitive=false) {
    if(! $case_sensitive ) $input = strtolower($input);
    
    foreach ($valid as $v) {
	if(! $case_sensitive ) $v = strtolower($v);
	if($v == $input) return true;
    }
    
    return false;
}

// Labels for Nodes, Links and Scales shouldn't have spaces in
function wm_editor_sanitize_name($str) {
    return str_replace( array(" "), "", $str);
}

function wm_editor_sanitize_selected($str) {        
	$res = urldecode($str);
	
	if( ! preg_match("/^(LINK|NODE):/",$res)) {
	    return "";
	}
	return wm_editor_sanitize_name($res);
}

function wm_editor_sanitize_file($filename,$allowed_exts=array()) {
    
    $filename = wm_editor_sanitize_uri($filename);
    
    if ($filename == "") return "";
        
    $ok = false;
    foreach ($allowed_exts as $ext) {
	$match = ".".$ext;
	
	if( substr($filename, -strlen($match),strlen($match)) == $match) {
	    $ok = true;
	}
    }    
    if(! $ok ) return "";
    return $filename;
}

function wm_editor_sanitize_conffile($filename) {
    
    $filename = wm_editor_sanitize_uri($filename);
    
    # If we've been fed something other than a .conf filename, just pretend it didn't happen
    if ( substr($filename,-5,5) != ".conf" ) {
	$filename = ""; 
     }
    return $filename;
}

function show_editor_startpage()
{
	global $mapdir, $WEATHERMAP_VERSION, $config_loaded, $cacti_found, $ignore_cacti,$configerror, $action;

	$fromplug = false;
	if (isset($_REQUEST['plug']) && (intval($_REQUEST['plug'])==1) ) { 
	    $fromplug = true; 
	}

	$matches=0;

	print '<html xmlns="http://www.w3.org/1999/xhtml"><head><link rel="stylesheet" type="text/css" media="screen" href="editor-resources/oldeditor.css" /><script type="text/javascript" src="editor-resources/jquery-latest.min.js"></script><script src="editor-resources/editor.js" type="text/javascript"></script><title>PHP Weathermap Editor ' . $WEATHERMAP_VERSION
		. '</title></head><body>';

	print '<div id="nojs" class="alert"><b>WARNING</b> - ';
	print 'Sorry, it\'s partly laziness on my part, but you really need JavaScript enabled and DOM support in your browser to use this editor. It\'s a visual tool, so accessibility is already an issue, if it is, and from a security viewpoint, you\'re already running my ';
	print 'code on your <i>server</i> so either you trust it all having read it, or you\'re already screwed.<P>';
	print 'If it\'s a major issue for you, please feel free to complain. It\'s mainly laziness as I said, and there could be a fallback (not so smooth) mode for non-javascript browsers if it was seen to be worthwhile (I would take a bit of convincing, because I don\'t see a benefit, personally).</div>';
	
	$errormessage = "";

    if ($configerror!='') {
        $errormessage .= $configerror.'<p>';
    }
		
	if ( !$librenms_found && !$ignore_librenms) {
		//$errormessage .= '$cacti_base is not set correctly. Cacti integration will be disabled in the editor.';
		//$errormessage .= "$librenms_found and $ignore_librenms";
		//if ($config_loaded != 1) { 
            	//$errormessage .= " You might need to copy editor-config.php-dist to editor-config.php and edit it."; 
        	//}
	}
	
	if ($errormessage != '') {
		print '<div class="alert" id="nocacti">'.htmlspecialchars($errormessage).'</div>';
	}

	print '<div id="withjs">';
	print '<div id="dlgStart" class="dlgProperties" ><div class="dlgTitlebar">Welcome</div><div class="dlgBody">';
	print 'Welcome to the PHP Weathermap '.$WEATHERMAP_VERSION.' editor.<p>';
	print '<div style="border: 3px dashed red; background: #055; padding: 5px; font-size: 90%;"><b>NOTE:</b> This editor is not finished! There are many features of ';
	print 'Weathermap that you will be missing out on if you choose to use the editor only.';
	print 'These include: curves, node offsets, font definitions, colour changing, per-node/per-link settings and image uploading. You CAN use the editor without damaging these features if you added them by hand, however.</div><p>';
	
	print 'Do you want to:<p>';
	print 'Create A New Map:<br>';
    if($action == 'newmap') {
      print "<b>Error creating map, the filename needs to end in .conf</b>";
    }
	print '<form method="GET">';
	print 'Named: <input type="text" name="mapname" size="20">';

	print '<input name="action" type="hidden" value="newmap">';
	print '<input name="plug" type="hidden" value="'.$fromplug.'">';

	print '<input type="submit" value="Create">';
	print '</form>';

	$titles = array();

	$errorstring="";

	if (is_dir($mapdir)) {
		$n=0;
		$dh=opendir($mapdir);

		if ($dh) {
		    while (false !== ($file = readdir($dh))) {
			$realfile=$mapdir . DIRECTORY_SEPARATOR . $file;
			$note = "";
	
			// skip directories, unreadable files, .files and anything that doesn't come through the sanitiser unchanged
			if ( (is_file($realfile)) && (is_readable($realfile)) && (!preg_match("/^\./",$file) )  && ( wm_editor_sanitize_conffile($file) == $file ) ) {
				if (!is_writable($realfile)) {
					$note .= "(read-only)";
				}
				$title='(no title)';
{'fraction_non_alphanumeric': 0.17361271010822013, 'fraction_numerical': 0.0032235781717706653, 'mean_word_length': 3.8492742835876443, 'pattern_counts': {'":': 0, '<': 91, '<?xml version=': 0, '>': 89, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1024313', 'n_tokens_mistral': 4530, 'n_tokens_neox': 4347, 'n_words': 1173}