<?php
function calculatePageRank($linkGraph, $dampingFactor = 0.15) {
        $pageRank = array();
        $tempRank = array();
        $nodeCount = count($linkGraph);

        // initialise the PR as 1/n
        foreach($linkGraph as $node => $outbound) {
                $pageRank[$node] = 1/$nodeCount;
                $tempRank[$node] = 0;
        }

        $change = 1;
        $i = 0;
        while($change > 0.00005 && $i < 100) {
                $change = 0;
                $i++;

                // distribute the PR of each page
                foreach($linkGraph as $node => $outbound) {
                        $outboundCount = count($outbound);
                        foreach($outbound as $link) {
                                $tempRank[$link] += $pageRank[$node] / $outboundCount;
                        }
                }
               
                $total = 0;
                // calculate the new PR using the damping factor
                foreach($linkGraph as $node => $outbound) {
                        $tempRank[$node]  = ($dampingFactor / $nodeCount)
                                                + (1-$dampingFactor) * $tempRank[$node];
                        $change += abs($pageRank[$node] - $tempRank[$node]);
                        $pageRank[$node] = $tempRank[$node];
                        $tempRank[$node] = 0;
                        $total += $pageRank[$node];
                }

                // Normalise the page ranks so it's all a proportion 0-1
                foreach($pageRank as $node => $score) {
                        $pageRank[$node] /= $total;
                }
        }
       
        return $pageRank;
}

//create adjiacency array, if it's not there, there is no link between the two pages
$fp = fopen('adj_list', 'r');
/**
adj_list file format:

page_number: linked_page1 linked_pagen -1

example:
0: 1 2 -1
1: -1
2: 0 -1

**/
$links = array();
do{
	$line=fgets($fp);
	if($line===FALSE)break;
	//get linked pages list
	$exploded=explode(':', $line);
	//put linked pages list in an array
	$explodedlinks=explode(' ', $exploded[1]);
	$array=array();
	foreach($explodedlinks as $e){
		//if there's no link, go to next line
		if(intval($e)==-1)break;
		//first value is always null, skip it
		if($e == NULL)continue;
		else array_push($array, intval($e));
	}
	array_push($links, $array);
}while(TRUE);
fclose($fp);

$p=calculatePageRank($links);
//show PR
print_r($p);
?>