What's new

PHP [KONKURS][MODERN]Info prosto z config.lua + stages.xml

Status
Not open for further replies.

Kuzirashi

ASP.NET MVC, JS-SPA, PHP, NODE
Joined
Jul 24, 2010
Messages
772
Reaction score
157
Live demo:
Po kolei:
1. Tworzymy folder classes w /system/
2. W nim tworzymy nowy plik Info.php z kodem:
PHP:
<?php
 
class Info {
 
  private $variables;
  private $debug;

  function __construct($dbg = false){
    $this->variables = null;
    $this->debug = $dbg;
  }

	public function loadFile ($path) {
		if(!$this->open = fopen($path, 'r')) {
			throw new Exception('Failed to open ' . $path . '.');
		} else {
			if(!$this->data = fread($this->open, filesize($path))) {
				throw new Exception('Failed to bind data.');
			} else {
				if(!fclose($this->open)) {
					throw new Exception('Failed to close.');
				} else {
					return $this->data;
				}
			}
		}
	}
  
  public function convert($lua_text){
    if((explode("\n", $lua_text)) > 0){
      $result = array();
      $lua_text = preg_replace("/\ -- (.*?)\n/","\n",$lua_text);
      $lua_text =  str_replace(",\n)", "\n)",
                    str_replace("{", "array(",
                     str_replace("}", ");",
                      str_replace("},", "),",
                       str_replace("[\"", "\"",
                        str_replace("] = ", " => ",
                         str_replace("\t", "", 
                          str_replace("{\n}", "false\n", $lua_text )
                         )
                        )
                       )
                      )
                     )
                    )
                   );
      foreach(explode("\n", $lua_text) as $lua_line){
        if($this->debug){print($lua_line."\n");}
        $lua_line = chop($lua_line);
        if(preg_match("/^[a-z]/", $lua_line)){
          if(is_numeric($lua_line[strlen($lua_line)-1]) || $lua_line[strlen($lua_line)-1] == "\""){
            $lua_line.=";";
          }
          if($this->debug){print("variable start: $lua_line\n");}
 
          $result[] = $lua_line;
          $this->variables[] = substr($lua_line, 0, strpos($lua_line, " "));
        }else{
          $result[] = $lua_line;
        }
      }
    }
	$wynik = array();
	$i = 0;
	foreach ($result as $row) {
		$mhm = explode(' =', $row);
		$wynik[$mhm[0]] = $mhm[1];
	}
    return $wynik;
  }
 
  public function getVariables(){
    return $this->variables;
  }
 
  public function variableCount(){
    return(count($this->variables));
  }
  
  public function clean($str) {
	$result = preg_replace('/;/', '', $str);
	return $result;
  }
} 
?>
3. Tworzymy nowy plik Xml.php (r?wnie? w classes) z kodem:
PHP:
<?php
/**
 * XML2Array: A class to convert XML to array in PHP
 * It returns the array which can be converted back to XML using the Array2XML script
 * It takes an XML string or a DOMDocument object as an input.
 *
 * See Array2XML: http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes
 *
 * Author : Lalit Patel
 * Website: http://www.lalit.org/lab/convert-xml-to-array-in-php-xml2array
 * License: Apache License 2.0
 *          http://www.apache.org/licenses/LICENSE-2.0
 * Version: 0.1 (07 Dec 2011)
 * Version: 0.2 (04 Mar 2012)
 * 			Fixed typo 'DomDocument' to 'DOMDocument'
 *
 * Usage:
 *       $array = XML2Array::createArray($xml);
 */

class Xml {

    private static $xml = null;
	private static $encoding = 'UTF-8';

    /**
     * Initialize the root XML node [optional]
     * @param $version
     * @param $encoding
     * @param $format_output
     */
    public static function init($version = '1.0', $encoding = 'UTF-8', $format_output = true) {
        self::$xml = new DOMDocument($version, $encoding);
        self::$xml->formatOutput = $format_output;
		self::$encoding = $encoding;
    }

    /**
     * Convert an XML to Array
     * @param string $node_name - name of the root node to be converted
     * @param array $arr - aray to be converterd
     * @return DOMDocument
     */
    public static function &createArray($input_xml) {
        $xml = self::getXMLRoot();
		if(is_string($input_xml)) {
			$parsed = $xml->loadXML($input_xml);
			if(!$parsed) {
				throw new Exception('[XML2Array] Error parsing the XML string.');
			}
		} else {
			if(get_class($input_xml) != 'DOMDocument') {
				throw new Exception('[XML2Array] The input XML object should be of type: DOMDocument.');
			}
			$xml = self::$xml = $input_xml;
		}
		$array[$xml->documentElement->tagName] = self::convert($xml->documentElement);
        self::$xml = null;    // clear the xml node in the class for 2nd time use.
        return $array;
    }

    /**
     * Convert an Array to XML
     * @param mixed $node - XML as a string or as an object of DOMDocument
     * @return mixed
     */
    private static function &convert($node) {
		$output = array();

		switch ($node->nodeType) {
			case XML_CDATA_SECTION_NODE:
				$output['@cdata'] = trim($node->textContent);
				break;

			case XML_TEXT_NODE:
				$output = trim($node->textContent);
				break;

			case XML_ELEMENT_NODE:

				// for each child node, call the covert function recursively
				for ($i=0, $m=$node->childNodes->length; $i<$m; $i++) {
					$child = $node->childNodes->item($i);
					$v = self::convert($child);
					if(isset($child->tagName)) {
						$t = $child->tagName;

						// assume more nodes of same kind are coming
						if(!isset($output[$t])) {
							$output[$t] = array();
						}
						$output[$t][] = $v;
					} else {
						//check if it is not an empty text node
						if($v !== '') {
							$output = $v;
						}
					}
				}

				if(is_array($output)) {
					// if only one node of its kind, assign it directly instead if array($value);
					foreach ($output as $t => $v) {
						if(is_array($v) && count($v)==1) {
							$output[$t] = $v[0];
						}
					}
					if(empty($output)) {
						//for empty nodes
						$output = '';
					}
				}

				// loop through the attributes and collect them
				if($node->attributes->length) {
					$a = array();
					foreach($node->attributes as $attrName => $attrNode) {
						$a[$attrName] = (string) $attrNode->value;
					}
					// if its an leaf node, store the value in @value instead of directly storing it.
					// if(!is_array($output)) {
						// $output = array('@value' => $output);
					// }
					$output['@attributes'] = $a;
				}
				break;
		}
		return $output;
    }

    /*
     * Get the root XML node, if there isn't one, create it.
     */
    private static function getXMLRoot(){
        if(empty(self::$xml)) {
            self::init();
        }
        return self::$xml;
    }
}
?>
5. Tworzymy plik /system/pages/info.php z kodem:
PHP:
<?PHP
/* - - KUZIRASHI'S DYNAMIC INFO	*
 * - - - SCRIPT FOR MEMSORIA.PL	*
 * - - - - -  PROVIDES DYNAMIC:	*
 * -  SKILLS, FRAGS, EXP STAGES	*
 */
 
// CONFIG
$classes_path 	= 'xxx/system/classes/'; // ZAMIE?
$config_path 	= 'xxx/config.lua'; // ZAMIE?
$stages_path 	= 'xxx/data/XML/stages.xml'; // ZAMIE?
$free_vip 		= 150; // ZAMIE?

// HELPERS
function clean ($str, $length) {
	$lua = new Info();
	$res = $lua->clean($str);
	if (isset($length['first'])) {
		return substr($res, $length['first'], $length['second']);
	} else {
		return $res;
	}
}

function loadClass ($name, $path) {
	require $path . $name . '.php';
}

// REQUIRE CLASS
loadClass('Info', $classes_path);
loadClass('Xml', $classes_path);

// TRY TO LOAD CONFIG
try {
	$lua 			= new Info();
	$loaded 		= $lua->loadFile($config_path);
} catch (Exception $e) {
	echo 'B??d: ' . $e->getMessage();
}

// CONVERT CONFIG
$config = $lua->convert($loaded);

// GET STAGES
try {
	$stages_xml = $lua->loadFile($stages_path);
	$stages 	= Xml::createArray($stages_xml);
} catch (Exception $e) {
	echo 'B??d: ' . $e->getMessage();
}

// USER INTERFACE
echo '<img alt="Memsoria Baner" id="__icon" src="/baner2" />
<br>
 <div align="center"><font size="1">Memsoria & Evolife - online <span lang="en">since August</span> 04, 2010</b></font>
 <br />  <br /> 
</div>
<font size="2">
<div class="header"><span lang="en">Server Information</span><span lang="en">&nbsp&nbsp&nbsp</span><a href="#pl" onclick="window.lang.change(\'pl\');"><img src="http://memsoria.pl//templates/united/images/pl.png"/></a>&nbsp<a href="#eng" onclick="window.lang.change(\'en\');"><img src="http://memsoria.pl//templates/united/images/gb.png"/></a></div>
<ul>
	<li>IP:	<b>memsoria.pl</b></li>
	<li>Port:	' . clean($config['loginPort'], NULL) . '</li>
	<li><span lang="en">Client</span>	<a href="/memsoria86">8.6 (<span lang="en">download here</span>)</a></li>
</ul>

<div class="header"><span lang="en">Memsoria Features</span></div> 
<ul>
	<li>Uptime 24/7</li> 
	<li>PvP</li>
	<li><span lang="en">Custom Addon Bonus system</span>
	<li><span lang="en">New Autostack has been added</span>
	<li><span lang="en">The attack/follow cancel attack is working</span>
	<li><span lang="en">Balanced vocations</span>
	<li><span lang="en">Real guild war system</span>
	<li><span lang="en">Raid system and Boss spawns</span>
	<li><span lang="en">No overpowered donation items</span>
	<li><span lang="en">All Monsters with their respective loot</span>
	<li><span lang="en">New monsters</span>
	<li><span lang="en">Own Map</span>
	<li><u><span lang="en">Free VIP from ' . $free_vip . ' level</span></u>
	<li><span lang="en">All real tibia features such as all houses and npcs</span>.</li> 
</ul>
<div class="header"><span lang="en">Rates</span></div> 
<table cellspacing="0" cellpadding="5" border="0" style="margin-bottom: 10px;">
<ul>
	<li><span lang="en">Skills</span>: 		' . clean($config['rateSkill'], array('first' => 0, 'second' => 3)) . 'x</li>
	<li><span lang="en">Magic</span>:  		' . clean($config['rateMagic'], array('first' => 0, 'second' => 3)) . 'x</li>
	<li>Loot:   		' . clean($config['rateLoot'], array('first' => 0, 'second' => 2)) . 'x</li>
	<li><span lang="en">Protection level</span>:	' . clean($config['protectionLevel'], NULL) . '</li>
</ul>
</table>
<div class="header"><span lang="en">Frags</span></div> 
<ul>
	<li><span lang="en">Daily frags to</span> Red Skull:	' . clean($config['dailyFragsToRedSkull'], NULL) . '</li>
	<li><span lang="en">Weekly frags to</span> Red Skull:	' . clean($config['weeklyFragsToRedSkull'], NULL) . '</li>
	<li><span lang="en">Monthly frags to</span> Red Skull:	' . clean($config['monthlyFragsToRedSkull'], NULL) . '</li>

	<li><span lang="en">Daily frags to</span> Black Skull:	' . clean($config['dailyFragsToBlackSkull'], NULL) . '</li>
	<li><span lang="en">Weekly frags to</span> Black Skull:	' . clean($config['weeklyFragsToBlackSkull'], NULL) . '</li>
	<li><span lang="en">Monthly frags to</span> Black Skull:	' . clean($config['monthlyFragsToBlackSkull'], NULL) . '</li>
</ul>
<div class="header"><span lang="en">The experience stages</span></div>
        <div class="message">
        <div class="content">
        <TR><TD><TABLE BORDER=0 CELLPADDING=2 CELLSPACING=1 WIDTH=100%>	
	<tr class="tableheader"> 
		<td align="center"><strong><span lang="en">From</span>:</strong></td>
		<td align="center"><strong><span lang="en">To</span>:</strong></td>
		<td align="center"><strong><span lang="en">Multiplier</span>:</strong></td>
	</tr>';
	
// LIST STAGES
foreach ($stages['stages']['world']['stage'] as $stage) {
	echo '
	<tr class="tablerow">
		<td align="center">' . $stage['@attributes']['minlevel'] . ' lvl</td>
		<td align="center">' . $stage['@attributes']['maxlevel'] . ' lvl</td>
		<td align="center">' . $stage['@attributes']['multiplier'] . 'x</td>
	</tr>';
}
echo '
</table>
</font>
</div></div>';
// END FILE
?>
6. Zast?pujemy config na samej g?rze pliku, oraz edytujemy wedle naszych potrzeb plik, poniewa? domy?lnie zawiera on informacje statyczne na o serwerze memsoria.pl

Reput mile widziany.

Zabraniam kopiowania zawarto?ci na inne fora/serwisy.

Notka moderatorska:
+40pkt do konkursu!
 

SanninStory

https://www.twitch.tv/sdrn
Joined
Oct 13, 2012
Messages
1,778
Reaction score
119
Odp: [KONKURS][MODERN]Info prosto z config.lua + stages.xml

No no, w?a?nie chcia?em aby? udost?pni? ten skrypt.

Pozdrawiam i leci reput.
 

Xart Irok

Senior User
Joined
Sep 7, 2008
Messages
2,925
Reaction score
419
Age
32
Odp: [KONKURS][MODERN]Info prosto z config.lua + stages.xml

To teraz ?adnie przegi??e? po tyle pisania nie potrzebnego kodu jak istnieje taka ?adna funkcja
PHP:
simplexml_load_file
a potem to ju? tylko u?y? na pliku p?tli dla wszystkich rekord?w. Dawno temu napisane:
PHP:
        $rateExperience .= '<table  style="width: 100%">';
        foreach($stages as $exp1)
        {
                        $i = 0;
                        $ots = (int) $exp1["id"];
                        if($ots > 0)
                                $rateExperience .= '<tr align="center" bgcolor="'.$config['site']['vdarkborder'].'"><td colspan="3"><strong>Experience Stages on '.$config['site']['worlds'][$ots].'</strong></td></tr>';
                        $rateExperience .= '<tr align="center" bgcolor="'.$config['site']['vdarkborder'].'"><td class="white">From Level</td><td class="white">To Level</td><td class="white">Rate</td></tr>';
                        foreach($exp1 as $exp)
            {
                                if(isset($exp["maxlevel"]))
                                        $max = $exp["maxlevel"];
                                else
                                        $max = "-";
                                if(is_int($i/2))
                                        $bgcolor=$config['site']['lightborder'];
                                else
                                        $bgcolor=$config['site']['darkborder'];
                                $rateExperience .= '<tr align="center" bgcolor="'.$bgcolor.'"><td>'.$exp["minlevel"].'</td><td>'.$max.'</td><td>'.$exp["multiplier"].'x</td></tr>';
                                $i++;
                        }
        }
        $rateExperience .= '</table>';
Tylko to jest napisane pod starego gesiora, ale dla chc?cego nic trudnego przerobi? by to pod Moderna.

Moim zdaniem ocena jest zbyt wysoka, jak na takie kiepskie rozwi?zanie.
 
Last edited:

Kuzirashi

ASP.NET MVC, JS-SPA, PHP, NODE
Joined
Jul 24, 2010
Messages
772
Reaction score
157
Odp: [KONKURS][MODERN]Info prosto z config.lua + stages.xml

Okej, dzi?kuj? za feedback. Kiedy b?d? si? za to bra? nast?pnym razem postaram si? pami?ta?. Mi?ego dnia.
 
Status
Not open for further replies.
Top