Minde/Klaidos/SmartWEB/tables.php

Iš PHP, MySQL.
Peršokti į: navigaciją, paiešką
<?php
    if(!defined('SMARTWEB'))
        define('SMARTWEB', 1);

    require_once 'system/debugger_start.php';

    require_once("system/projects.php");
    if (substr($_SERVER['HTTP_HOST'], -3) == ":80") $_SERVER['HTTP_HOST'] = str_replace(":80", "", $_SERVER['HTTP_HOST']);
    if (!isset($_projects[$_SERVER['HTTP_HOST']])) $_projects[$_SERVER['HTTP_HOST']] = $_projects["default"];
    $pnconfig['_t147Tt'] = $_projects[$_SERVER['HTTP_HOST']];
    require_once("system/config.php");
    require_once($pnconfig['_t147Tt']."/system/config.php");
    require_once($_t0577."error_handler.php");

    if (isset($_SERVER["HTTP_X_FORWARDED_FOR"]))
        $user_ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    else { $user_ip = $_SERVER['REMOTE_ADDR']; }

    if ($PHP_AUTH_USER == "" && $PHP_AUTH_PW == "" && ereg("^Basic ", $HTTP_AUTHORIZATION)) {
      list($PHP_AUTH_USER, $PHP_AUTH_PW) = explode(":", base64_decode(substr($HTTP_AUTHORIZATION, 6)));
    }

    $have_access = false;

		header('Content-Type: text/html; charset=utf-8');

            $ip_array = array('213.197.169.106', '213.197.173.18', '82.135.132.20', '213.226.142.140', '217.147.36.152', '127.0.0.1');

    if (true == in_array($user_ip, $ip_array)) {
        $have_access = true;
    } else {
    	if (!isset($_SERVER['PHP_AUTH_USER'])) {
    		authenticate();
    	} else {
	        if (true == check()) {
	            $have_access = true;
	        }
    	}
    }

    if ($have_access == false) {
        die('No access. Your IP '.$user_ip.' is logged.');
    }
   
    function  authenticate()  {
        Header("WWW-Authenticate: Basic realm=\"Some test stuff\"");
        Header("HTTP/1.0 401 Unauthorized");
        echo "Sorry, you must enter information ;)\n";
        exit;
    }

    function check(){
               
        $password = '$1$9t5.c.3.$cFeCLxH5.MhKKE1K4rV44/';
        $user = '$1$3r2.OA3.$NaCskbXYYWkH3usDpiknh.';
        if (crypt($_SERVER['PHP_AUTH_USER'],$user) == $user &&
        		crypt($_SERVER['PHP_AUTH_PW'],$password) == $password ) {
        	return TRUE;
		} else {
			return FALSE;
		}
    }


    require_once($_t12M."m_site/wfiles/prefices.php");
    require_once($_t0577."db_".$_DB_TYPE.".php");


    $db = New Database();
    $GLOBALS['db'] = $db;

    $db_type = $db->GetType();


    if ($_POST['query']) {
        $query = stripslashes(trim($_POST['query']));
    }
	$file_name = "./system/tables_sql.php";
	if(file_exists($file_name)) {
		require_once($file_name);
		$sql_name_dropdown="<select name=\"selected_sql\" onChange=\"Javascript:Exe_form()\">";
		$sql_name_dropdown.="<option value=0>Pasirinkite</option>";
		foreach ($sql_array as $key => $value) {
				$sql_name_dropdown.="<option value=\"".$value."\">".$key."</option>";
			}
			$sql_name_dropdown .= "</select>";
	}

    echo "<html>
    <head>
    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">
        <title>DB tables.</title>
    </head>

    <STYLE>
        A.link {
            font-family: arial;
            font-size:10px; color: #000000;
            font-size: 11px;
        }
        A.link:visited {
            color: #009000;
            text-decoration: underline;
        }
        A.link:hover{
            color: #003300;
            text-decoration: underline;
        }
        A.link:active {
            color: #000000;
            text-decoration: underline;
        }
    </STYLE>


    <script type=\"text/javascript\">
        function addToQuery(str){
            insertAtCaret(str);
            return false;
        }

        function insertAtCaret(myValue) {
            var qryField = document.getElementById('query');

            if (document.selection) {
                qryField.focus();
                var sel = document.selection.createRange();
                sel.text = myValue;
            }else if (qryField.selectionStart || qryField.selectionStart == '0') {
                var startPos = qryField.selectionStart;
                var endPos = qryField.selectionEnd;
                qryField.value = qryField.value.substring(0, startPos) + myValue + qryField.value.substring(endPos, qryField.value.length);
            } else {
                qryField.value += myValue;
            }

            qryField.focus();
        }

		function Exe_form() {
			document.getElementById('query').value = document.getElementById('selected_sql').value;
			document.getElementById('query').focus();
		}
    </script>
    <body>
    <a href=\"/tables.php\">Lentelių sÄ…raÅas</a>
    <form method=\"post\" action=\"\">
    <input type=\"hidden\" name=\"action\" value=\"qry\">
    <textarea name=\"query\" id=\"query\" rows=10 cols=50 style=\"width: 100%\">".$query."</textarea><br />

	<table border=0 width=100%>
		<tr>
			<td width=\"10%\">
				<input type=submit value='Vykdyti užklausą'>
			</td>
			<td width=\"80%\">
				Saugomos užklausos pavadinimas: <input type=text name=\"sql_name\" value=''>
				<input type=submit value=\"IÅsaugoti\"> IÅsaugotos: $sql_name_dropdown
			</td>
			<td width=\"10%\" align=right>
				<input type=\"submit\" value=\"PROCESSLIST\" onClick=\"document.getElementById('query').value='SHOW FULL PROCESSLIST'\">
			</td>
		</tr>
	</table>

	<br /></form>
    <hr><br />
    ";


    $t_name = (isset($_REQUEST['t_name']) ? $_REQUEST['t_name'] : '');

		if( isset($_GET['t']) && !isset($_REQUEST['action']) && !empty($_GET['t']) ) {
		$_REQUEST['action'] = 'table';
		$_REQUEST['t_name'] = $t_name = $_GET['t'];
	}

    switch ($_REQUEST['action']) {
    	case "structure":
            $qry = "SHOW FULL COLUMNS FROM ".$_REQUEST['t_name'];
            $result = $db->x5024e($qry);
            echo "<b>".$t_name."</b> (Ä®raÅų: $c_count) <a class=\"link\" href=\"tables.php?action=table&t_name=$t_name\">turinys</a><br>";
            echo '<table border="0" cellspacing="1" cellpadding="1">';
            $fc = 0;
            echo '<tr><th style="background: #DBE4F0;">'.($fc++).'</th><th style="background: #DBE4F0;">Laukelis</th><th style="background: #DBE4F0;">Tipas</th><th style="background: #DBE4F0;">Lyginimas</th><th style="background: #DBE4F0;">Raktas</th><th style="background: #DBE4F0;">Pagal nutylÄ—jimÄ…</th><th style="background: #DBE4F0;">Privilegijos</th></tr>';
            while (list($field, $type, $collation, $null, $key, $default, $extra, $privilegies, $comment ) = $db->GetRowAsList($result)) {
                echo '<tr><td style="background: #DBE4F0;">'.($fc++).'</td><td style="background: #DBE4F0;">'.$field.'</td><td style="background: #DBE4F0;">'.$type.'</td><td style="background: #DBE4F0;">'.$collation.'</td><td style="background: #DBE4F0;">'.$key.'</td><td style="background: #DBE4F0;">'.$default.'</td><td style="background: #DBE4F0;">'.$privilegies.'</td></tr>';
            }
            echo "</table>";
            break;
        case "table_str":
            $qry = "SELECT COUNT(*) FROM ".$_REQUEST['t_name'];
            $result = $db->x5024e($qry);
            list($c_count) = $db->GetRowAsList($result);

            echo "<b>".$t_name."</b> (ÄÆraÅų: $c_count) <a class=\"link\" href=\"tables.php?action=table&t_name=$t_name\">turinys</a> <a class=\"link\" href=\"tables.php?action=structure&t_name=$t_name\">struktÅ«ra</a><br>";
            echo "<table>";
            $fields = getTableFields ($db_type, $db, $t_name);
            $field_count = count($fields);
            echo '<table border="0" cellspacing="1" cellpadding="1">';
            for ($fc=0; $fc<$field_count; $fc++) {
                $field = $fields[$fc];
                echo '<tr><td style="background: #DBE4F0;">'.($fc+1).'</td><td style="background: #DBE4F0;">'.$field.'</td></tr>';
            }
            echo "</table>";
            break;
        case "table":
            echo '<b><a href="#" onClick="return addToQuery(\''.$t_name.'\');">'.$t_name.'</a></b><br>';
            echo "<table>";
            $fields = getTableFields ($db_type, $db, $t_name);
            $field_count = count($fields);
            echo '<table border="0" cellspacing="1" cellpadding="1"><tr>';
            for ($fc=0; $fc<$field_count; $fc++) {
                $field = $fields[$fc];
                echo '
                    <td style="background: #DBE4F0;">
                        <a href="#" onClick="return addToQuery(\''.$field.'\');">'.$field.'</a>  <span style="font-size: x-small;"><a href="tables.php?action=table&t_name='.$_REQUEST['t_name'].'&order='.$field.'&dir=ASC">A</a> <a href="tables.php?action=table&t_name='.$_REQUEST['t_name'].'&order='.$field.'&dir=DESC">D</a></span>
                    </td>
                ';
            }
            echo "</tr>";
            $order = (true == isset($_REQUEST['order'])) ? ' ORDER BY '.$_REQUEST['order'].' '.$_REQUEST['dir'] : '';
            $qry = 'SELECT * FROM '.$t_name.' '.$order;
            $result = $db->x5024e($qry);
            $count = $db->Count($result);
            for ($fc=0; $fc<$count; $fc++) {
                $fields = $db->GetRowAsList($result);
                echo '<tr><td style="background: #DBE4F0;">'.implode('</td><td style="background: #DBE4F0;">', $fields).'</td></tr>';
            }
            echo "</table>";
            break;
        case "drop_tables":
            if ($db_type == 'oracle')
                $qry = "SELECT table_name FROM user_tables";
            else
                $qry = "SHOW TABLES";

            $result = $db->x5024e($qry);
            $table_count = $db->Count($result);

            echo "$table_count lenteliu sk<br>";

            for ($c=0;$c<$table_count;$c++) {
                list($t_name) = $db->GetRowAsList($result);
                echo "$t_name<br>";
                $qry = "DROP TABLE $t_name";
                $db->x5024e($qry);
            }
            if ($db_type == 'oracle') {
                $qry = "SELECT SEQUENCE_NAME FROM ALL_SEQUENCES WHERE SEQUENCE_OWNER='EIC'";
                $result = $db->x5024e($qry);
                $table_count = $db->Count($result);
                echo $table_count." seku sk<br>";
                for ($c=0;$c<$table_count;$c++) {
                    list($t_name) = $db->GetRowAsList($result);
                    echo "$t_name<br>";
                    $qry = "DROP SEQUENCE $t_name";
                    $r = $db->x5024e($qry);
                }
            }
            echo "baige";
            break;
        case 'check':
        	if (!isset($_POST['x_action'])) $_POST['x_action'] = 'none';
        	if (isset($sql)) unset($sql);
        	$t_name = $_GET['t_name'];
        	$cmd = array();
        	$cmd['mysql'] = array('optimize' => "OPTIMIZE TABLE `$t_name`;",
        						  'repair' => "REPAIR TABLE `$t_name`;",
        						  'check' => "CHECK TABLE `$t_name`;");
        	if (isset($cmd[$db_type][$_POST['x_action']])) {
        		$sql = $cmd[$db_type][$_POST['x_action']];
        	}
        	if (isset($sql)){
        		if (!is_array($sql)) $sqls = array($sql);
        		foreach ($sqls as $sql) {
        			$result = $db->x5024e($sql);
        			if (is_resource($result)) {
        				echo "<table border=\"1\">";
        				$data = "";
        				$header = false;
        				$h1 = "";
        				while ($row = $db->GetRowAsArray($result)) {
        					$data .= "<tr>";
        					if (!$header) {
        						$h1 .= "<tr>";
        					}
        					foreach ($row as $name => $value) {
        						if (!$header) {
        							$h1	.= "<th>$name</th>";
        						}
        						$data .= "<td>$value</td>";
        					}
        					$data .= "</tr>";
							if (!$header) {
        						$h1 .= "</tr>";
        						$header = true;
        					}
        				}
        				echo $h1.$data;
        				echo "</table><br />";
        			} else {
        				var_dump($result);
        			}
        		}
        	}
        	echo "<form action=\"tables.php?action=check&t_name=$t_name\" method=\"post\">";
        	echo "<input type=\"submit\" name=\"x_action\" value=\"optimize\" ".(isset($cmd[$db_type]['optimize'])?'':'disabled="disabled"')."/>";
        	echo "<input type=\"submit\" name=\"x_action\" value=\"repair\" ".(isset($cmd[$db_type]['repair'])?'':'disabled="disabled"')."/>";
        	echo "<input type=\"submit\" name=\"x_action\" value=\"check\" ".(isset($cmd[$db_type]['check'])?'':'disabled="disabled"')."/>";
        	echo "</form>";
        	die();
        	break;
        case "qry":
                    		$_REQUEST['sql_name'] = trim($_REQUEST['sql_name']);
    		if (strlen($_REQUEST['sql_name']) > 2 && strlen($query) > 10) {
				if(file_exists($file_name)) {
					$fh = @fopen($file_name, 'a');
				} else {
					$fh = @fopen($file_name, 'w');
					@fwrite($fh, "<?php ");
				}
			    $sql_array[$_REQUEST['sql_name']] = $query;
			    $sql_array = array_unique($sql_array);
			    foreach ($sql_array as $r_key => $r_value) {
			   		 $stringas .= "\$sql_array['".$r_key."'] = \"$r_value\";";
			    }
			    @fwrite($fh, $stringas);
			    @fclose($fh);
    		}

                                               
            $max_rows_limit = 200;
            $supported_qry_types = array('select', 'show', 'desc', 'explain', 'update', 'delete', 'replace', 'drop', 'alter', 'create', 'insert', 'repair', 'optimize', 'check', 'set', 'kill');
            $list_qry_types = array('select', 'show', 'desc', 'explain', 'check', 'optimize', 'repair');

            $qry_for_preg = str_replace(
                array("\n", "\r"),
                array(" ",  " "),
                $query);
            $qry_for_preg = strtolower(trim($qry_for_preg));
            $is_supported_qry = preg_match('/('.implode('|', $supported_qry_types).')/i', $qry_for_preg, $matches);
            if ( $is_supported_qry ) {
                $qry_type = $matches[1];
                switch ( $qry_type ) {
                case 'select':
                    $is_matched = preg_match('/select(.*)from\s+([^; ]+)/i', $qry_for_preg, $matches);
                    if ( $is_matched ) {
                        $fields_str = str_replace('`','',$matches[1]);
                        $table_name = str_replace('`','',$matches[2]);

                        $field_list = array();
                        $initial_field_list = explode(',', $fields_str);
                        $fields_count = sizeof($initial_field_list);
                        for ( $i=0; $i<$fields_count; $i++ ) {
                            $field_str = trim($initial_field_list[$i]);
                            if ( '*' == $field_str ) {
                                                                                                                                if ( 'mysql' != $db_type ) {
                                    $field_list = null; unset($field_list);
                                    break;
                                }
                                else {
                                    $rs = $db->x5024e('DESC `'.$table_name.'`');
                                    while ( list($field_name) = $db->GetRowAsList($rs) ) {
                                        $field_list[] = $field_name;
                                    }
                                }
                            }
                            else {
                                $field_str = explode(' as ', $field_str);
                                if ( sizeof($field_str) > 1 ) {
                                    $field_list[] = $field_str[1];
                                }
                                else {
                                    $field_list[] = $field_str[0];
                                }
                            }
                        }
                    }
                }
            }
           
            if ( $is_supported_qry ) {
                if ( in_array($qry_type, $list_qry_types) ) {
                    echo '<div>';
                    if ( isset($table_name) ) {
                        echo 'LentelÄ—: <strong>'.$table_name.'</strong>; ';
                    }
                    $result = $db->x5024e($query);
                    $count = $db->Count($result);
                    if ($count == 0)
                        echo "nieko nerado</div>";
                    else {
                        echo 'Ä®raÅų skaiĨius: <strong>'.$count.'</strong></div>';
                        echo "<table border=1 cellspacing=1 cellpadding=1>";
                                                                                                if ( isset($field_list) && is_array($field_list) ) {
                            $fields_count = sizeof($field_list);
                            echo '<tr>';
                            for ( $i=0; $i<$fields_count; $i++ ) {
                                echo '<th>'.$field_list[$i].'</th>';
                            }
                            echo '</tr>';
                        }
                                                for ($c=0; $c<$count && $c<$max_rows_limit; $c++) {
                            echo "<tr>";
                            $tmp = $db->GetRowAsList($result);
                            for ($cc=0; $cc<count($tmp); $cc++) {
                                echo "<td><pre style=\"padding:0px;margin:0px;\">".$tmp[$cc]."</td>";
                            }
                            echo "</tr>";
                        }
                        echo "</table>";

                        if ( $count > $max_rows_limit ) {
                            echo '<div style="background-color:red;color:yellow;font-weight:bold;padding:4px;margin:10px;">Per daug ÄÆraÅų. Rodomi tik pirmi '.$max_rows_limit.'.<br /><small>Naudokite LIMIT, kad pamatytumÄ—te reikiamus ÄÆraÅus.</small></div>';
                        }
                    }
                    break;
                }
                else {
                    $result = $db->x5024e($query);
                                        if ( $result && $db->getType == 'mysql') {
                        $affected_rows = $db->AffectedRows();
                        printf('<div style="padding:4px;margin:10px;">Pakeistų laukų skaiĨius: <strong>%d</strong></div>', $affected_rows);
                    }
                }
            }
            else {
                echo '<div style="background-color:red;color:yellow;font-weight:bold;padding:4px;margin:10px;">Klaida! Tokia užklausa nepalaikoma.<br /><small>Palaikomos tik tokios užklausos: <span style="color:white;">'.implode(', ', $supported_qry_types).'</span></small></div>';
            }
        default:
            if ($db_type == 'oracle')
                $qry = "SELECT table_name FROM user_tables";
            else
                $qry = "SHOW TABLES";
            $result = $db->x5024e($qry);
            $table_count = $db->Count($result);
            echo "$table_count lenteliu sk<br><table>";
            for ($c=0;$c<$table_count;$c++) {
                 list($tmp) = $db->GetRowAsList($result);
                 if (strstr($tmp, '$')) continue;
                 $t_array[] = $tmp;
            }
            if ($db_type == 'mssql' || $db_type == 'oracle')
                sort($t_array);
            $table_count = count($t_array);


            for ($c=0;$c<$table_count;$c++) {
                $t_name = $t_array[$c];
                echo "
                    <tr>
                        <td><a class=\"link\" href=\"tables.php?action=table_str&t_name=$t_name\">laukai</a></td>
                        <td><a class=\"link\" href=\"tables.php?action=table&t_name=$t_name\">turinys</a></font></td>
						<td><a class=\"link\" href=\"tables.php?action=check&t_name=$t_name\">tikrinti</a></td>
                        <td><a href=\"tables.php?action=table&t_name=$t_name\">$t_name</a></td>
                ";
                $qry = "select count(*) from $t_name";
                $r = $db->x5024e($qry);
                list($count) = $db->GetRowAsList($r);
                echo "<td align=\"right\"><b>$count</b></td></tr>";
            }
            echo "</table>";

            if ($db_type == 'oracle') {

                $qry = "SELECT SEQUENCE_NAME, LAST_NUMBER FROM ALL_SEQUENCES WHERE SEQUENCE_OWNER='".strtoupper($_DB_USER)."'";
                $result = $db->x5024e($qry);
                $table_count = $db->Count($result);

                echo "<br /><br /><b>sekos</b> $table_count<br /><table>";
                for ($c=0;$c<$table_count;$c++) {
                    list($t_name, $t_number) = $db->GetRowAsList($result);
                    echo "<tr><td>$t_name </td><td align=\"right\"><b>$t_number</b></td></tr>";
                }
                echo "</table>";

                $qry = "SELECT trigger_name, status FROM all_triggers WHERE owner = '".strtoupper($_DB_USER)."'";
                $result = $db->x5024e($qry);
                $table_count = $db->Count($result);
                echo "<br /><br /><b>trigeriai</b> $table_count<br /><table>";
                for ($c=0;$c<$table_count;$c++) {
                    list($t_name, $t_status) = $db->GetRowAsList($result);
                    echo "<tr><td>$t_name </td><td align=\"right\"><b>$t_status</b></td></tr>";
                }
                echo "</table>";

            }

    }

    echo "<br /><a href=\"/tables.php\"><< pirmas</a>";

    function getTableFields ($db_type, $db, $table) {
        if ($db_type == 'oracle')
        $qry = "SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH, DATA_PRECISION, DATA_SCALE, NULLABLE,
        DATA_DEFAULT FROM ALL_TAB_COLUMNS WHERE TABLE_NAME='$table' AND OWNER='".strtoupper($GLOBALS['_DB_USER'])."'";
        else
            $qry = "SHOW FIELDS FROM $table";
        $fields_result = $db->x5024e($qry);
        $field_count = $db->Count($fields_result);
        for ($fc=0; $fc<$field_count; $fc++) {
            $tmp = $db->GetRowAsList($fields_result);
            $fields[] = $tmp[0];
        }
        return $fields;
    }

    require_once 'system/debugger_end.php';

?>
</body>
</html>