#!/usr/bin/env php
<?php

	/**
	 * HTML Parser (stripped to needs)
	 * @author Ciprian Mocanu <http://mbe.ro/> <ciprian@mbe.ro>
	 * Class that transforms html to array as best as it's able
	 */
	class htmlParser {
		//your very own separator
		//do not enter characters such as < or >
		private $separator = '-{}-'; 
		//the tags that don't have any innerHTML in them
		//feel free to add some if I missed any
		private $singleTags = 'meta|img|hr|br|link|!--|!DOCTYPE|input';
		private $html,$level;
		public $levelArray;
		function __construct($html='') {
			$this->html=$this->removeWhiteSpace($html);
			$this->level=-1;
			$this->levelArray=array();
		}
		function __destruct() {
			//nothing yet;
		}
		private function getElement($value) {
			$ar = explode($this->separator,$value);
			$ar = explode('-',$ar[1]);
			return $this->levelArray[$ar[0]][$ar[1]];
		}
		private function parseToHTML($str,$level) {
			$ar=$this->getArrayOfReplacements($str);
			foreach ($ar as $item) {
				$elem = $this->getElement($item);
				$str=str_replace($item,($level==0?$elem['htmlText']:'<'.$elem['tag'].$elem['attr'].'>'.$elem['htmlText'].'</'.$elem['tag'].'>'),$str);
			}
			return $str;
		}
		private function replaceSingleTags() {
			//tags like img, input etc
			$result=preg_match_all('/<('.$this->singleTags.')(.[^><]*)?>/is', $this->html, $m);
			if ($result>0) {
				foreach ($m[0] as $id => $value)
					$this->html = str_replace($value,'',$this->html);
			}
		}
		private function replaceSimpleTags() {
			//tags that only have text in them (no other content)
			$result=preg_match_all('/<(.[^\s]*)(.[^><]*)?>(.[^<]*)?<\/\1>/is', $this->html, $m);
			if ($result>0) {
				$this->level++;
				$oneLevel=array();
				foreach ($m[0] as $id => $value) {
					if ($this->level==0)
						$htmlText=$value;
					else
						$htmlText=$this->parseToHTML($m[3][$id],$this->level-1);
					$oneLevel[] = array('str' => $value, 'rep' => $this->separator.$this->level.'-'.$id.$this->separator, 'tag' => $m[1][$id], 'level' => $this->level, 'text' => $m[3][$id], 'attr' => $m[2][$id] , 'htmlText' => $htmlText);
					
					$this->html = str_replace($value,$this->separator.$this->level.'-'.$id.$this->separator,$this->html);
				}
				$this->levelArray [$this->level] = $oneLevel;
			}
		}
		private function replaceRemainingTags() {
			//tags that remain after everything
			$result=preg_match_all('/<(.[^\s]*)(.[^><]*)?>(.*)?<\/\1>/is', $this->html, $m);
			if ($result>0) {
				$this->level++;
				$oneLevel=array();
				foreach ($m[0] as $id => $value) {
					if ($this->level==0)
						$htmlText=$m[3][$id];
					else
						$htmlText=$this->parseToHTML($m[3][$id],$this->level-1);
					$oneLevel[] = array('str' => $value, 'rep' => $this->separator.$this->level.'-'.$id.$this->separator, 'tag' => $m[1][$id], 'level' => $this->level, 'text' => $m[3][$id], 'attr' => $m[2][$id] , 'htmlText' => $htmlText);
					
					$this->html = str_replace($value,$this->separator.$this->level.'-'.$id.$this->separator,$this->html);
				}
				$this->levelArray [$this->level] = $oneLevel;
			}
		}
		private function existSimpleTags() {
			$result=preg_match('/<(.[^\s]*)(.[^><]*)?>(.[^<]*)?<\/\1>/is', $this->html);
			return $result>0;
		}
		private function existSingleTags() {
			$result=preg_match('/<('.$this->singleTags.')(.[^><]*)?>/is', $this->html);
			return $result>0;
		}
		private function removeWhiteSpace ($string) {
			$string = str_replace(array("\n","\r",'&nbsp;',"\t"),'',$string);
			return preg_replace('|  +|', ' ', $string);
		}
		public function toArray($html='') {
			//first part: coding
			if ($html!='')
				$this->html = $this->removeWhiteSpace($html);
			while ($this->existSimpleTags() || $this->existSingleTags()) {
				$this->replaceSingleTags();
				$this->replaceSimpleTags();
			}
			$this->replaceRemainingTags();
			//now decoding
			$ar=$this->getArray($this->html);
			return $ar;
		}
		private function getArrayOfReplacements($str) {
			$final=array();
			$ar=explode($this->separator,$str);
			for ($i=0;$i<(count($ar)-1)/2;$i++)
				$final []= $this->separator.$ar[$i*2+1].$this->separator;
			return $final;
		}
		private function getArray($html, $father='') {
			$final=array();
			if (strpos($html,$this->separator)!==false) {
				$r=$this->getArrayOfReplacements($html);
				foreach ($r as $i) {
					$ar = explode($this->separator,$i);
					$ar = explode('-',$ar[1]);
					$elem = $this->levelArray[$ar[0]][$ar[1]];
					$this->levelArray[$ar[0]][$ar[1]]['father'] = $father;
					$final[] = array( 'tag' => $elem['tag'], 'innerHTML' => $elem['htmlText'], 'repl' => $elem['rep'],'stratr' => $elem['attr'], 'level' => $elem['level'], 'father' => $father, 'childNodes' => $this->getArray($elem['text'],$i));
				}
			}
			return $final;
		}
	}

	function merge_cidr(array $cidr_or_ipv4_list)
	{
		$valid_ip='0*?((?:0)|(?:2(?:(?:[0-4][0-9])|(?:5[0-5])))|(?:1?[0-9]{1,2}))';
		$valid_ip.=str_repeat(".$valid_ip",3);
		$valid_routing_prefix='(?:0*?((?:(?:0)|(?:3[0-2])|(?:[1-2]?[0-9]))))';
		foreach($cidr_or_ipv4_list as $a)
		{
			list($ip, $mask) = explode('/', $a);
			$c[$mask][] = ip2long($ip) & (-1 << (32 - $mask));
		}

		if ($c) // If any valid ipv4 with optional routing prefix matched
		{
			foreach($c as &$unique)
				$unique=array_unique($unique);
			$c = merge_cidr_summarize($c);
			foreach($c as $d => & $e)
			{
				$e = array_map(
					function ($a) use($d)
					{
						return [$a, $a + (1 << (32 - $d)) - 1];
					}
				, $e);
			}
			foreach($c as $f => $g)
			foreach($c as $h => $i)
			if ($f > $h)
			foreach($g as $j => $k)
			foreach($i as $l)
			if ($k[0] >= $l[0] && $k[1] <= $l[1])
			unset($c[$f][$j]);
			foreach($c as $f => $g)
			{
				usort($g,
				function (array $a, array $b)
				{
					return  $b[0]>$a[0]?1:($b[0]<$a[0]?-1:0);
				}); // Order the result "naturally" inversed
				foreach($g as $h) // For each ordered result
				$z[] = long2ip($h[0]) . '/' . $f; // Convert it to human readable
			}
			return array_reverse($z);
		}
	}

	function merge_cidr_summarize(array $a)
	{
		$b = false;
		$c = [];
		krsort($a);
		foreach($a as $d => $e)
		{
			sort($a[$d]);
			$k = count($a[$d]);
			for ($i = 0; $i < $k; $i++)
			{
				if ($a[$d][$i] == $a[$d][$i + 1])
					continue;
				elseif (($a[$d][$i] & (-1 << 33 - $d)) == ($a[$d][$i + 1] & (-1 << 33 - $d)))
				{
					$c[$d - 1][] = $a[$d][$i++] & (-1 << 33 - $d);
					$b = true;
				}
				else
					$c[$d][] = $a[$d][$i];
			}
		}
		return $b ? merge_cidr_summarize($c) : $a;
	}
	
	function ip2bin($ip) 
	{ 
		if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) 
			return ip2long($ip);
		elseif(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) 
		{
			$binNum = '';
			foreach (unpack('C*', inet_pton($ip)) as $byte)
				$binNum .= str_pad(decbin($byte), 8, '0', STR_PAD_LEFT);
			return base_convert(ltrim($binNum, '0'), 2, 10);
		}
		else
			return false; 
	}

	function nextip($ip)
	{
		if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) 
			return long2ip(ip2long($ip)+1);
		else
			return false; 
	}

	if (!isset($argv[1]) || !is_numeric($argv[1]))
		die(' Usage: '.$argv[0].' <as>'.PHP_EOL);
	$wget = @file_get_contents('https://ipinfo.io/AS'.intval($argv[1]));
	if (!$wget)
		die('Unable to fetch data'.PHP_EOL);
	$html = new htmlParser($wget);
	$doc = $html->toArray();
	$res4 = array();
	$res6 = array();
	foreach($doc[0]["childNodes"] AS $node)
	{
		if ($node['tag'] == 'table' && preg_match('/id="block.{1,}table"/', $node['stratr']))
		{
			preg_match_all('/\>([0-9a-fA-F\.:]+)\/([0-9]+)\</', $node['innerHTML'], $matches, PREG_SET_ORDER);
			if ($matches)
			{
				foreach ($matches AS $match)
				{
					$ip = $match[1];
					$mask = $match[2];
					if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4))
						$res4[] = $ip.'/'.$mask;
					elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6))
						$res6[] = ['ip'=>$ip,'mask'=>$mask,'long'=>ip2bin($ip)];
				}
			}
		}
	}
	// family/ip sorting of v6 results
	usort($res6, function($a, $b) {
		$ret = $a['long'] - $b['long'];
		return $ret;
	});
	
	print_r(merge_cidr($res4));
?>
