<?php
  //grab class
  include('BasicBot.php5');

  //create bot
  $LivingBot = new phpwikibot("LivingBot", $password, "en", "5", "5");
  
  check_for_emergency();
  
  $updateonly = ($_GET['update'] == "y");
  $human = ($_GET['check'] == "y");

  //Load list of projects to check
  $handle = fopen("announcements.txt", 'r') or die("can't open file");
  //Top line as a header.
  $newfile = fgets($handle);
  while (!feof($handle)) {
	  //Whole lines:
	  $lines[] = fgets($handle);
	  //Sub-divided:
	  $projects[] = explode(",", trim($lines[(count($lines) - 1)]));
  }
  fclose($handle);
  echo "<ol>\n";
  //Loop through each project
  for ($i = 0; $i < count($projects); $i++) {
	  //Break down project info into human-readable variables
	  $project = trim($projects[$i][0]);
	  $temp = explode(":", $projects[$i][1]);
	  $namespace = trim($temp[0]);
	  $identifier = trim($temp[1]);
	  $oldcount = trim($projects[$i][2]);
	  $commas = strposall($lines[$i], ",");
	  
	  echo "<li>$identifier</li>\n";	  
	  if ($updateonly) {
		  if ($oldcount == -1) {
			  echo "Updating a new item. ";
			  $newcount = get_count($namespace, $identifier);
			  $newfile .= substr($lines[$i], 0, $commas[1]) . ", " . $newcount . substr($lines[$i], $commas[2]);
		  } else {	  
			  $newfile .= $lines[$i];
		  }
		  continue;
	  } else {
		  //Get the next milestone target
		  for ($j = (count($projects[$i]) - 1); $j > 2; $j--) {
			  if ($oldcount < $projects[$i][$j]) {
				  $nextmilestone = trim($projects[$i][$j]);
			  }
		  }
		  //If no next milestone, move on
		  if (!isset($nextmilestone)) {
			  continue;
		  }
		  //Get the new count
		  $newcount = get_count($namespace, $identifier);
		  if ($newcount > $oldcount) {
			  echo "Up from $oldcount to $newcount. \n";
		  }
		  //And compare
		  if ($newcount >= $nextmilestone) {
			  echo "<strong>This project has an announcement to make. </strong>\n";
			  $identifier = str_replace("_", " ", $identifier);
			  //Chip off a milestone from the file
			  $newfile .= substr($lines[$i], 0, $commas[1]) . ", " . $newcount . substr($lines[$i], $commas[3]);
			  //Based on namespace, write appropriate message
			  switch ($namespace) {
				  case "on-template":
					  switch(substr($identifier, 0, 2)){
						  case "FA":
							  $messages[] = "The English Wikipedia now has more than " . $nextmilestone . " [[Wikipedia:Featured articles|featured articles]].\n";
						  break;
						  case "GA":
							  $messages[] = "The English Wikipedia now has more than " . $nextmilestone . " [[Wikipedia:Good articles|good articles]].\n";
						  break;
					      default:
							  $messages[] = "The English Wikipedia now has more than " . $nextmilestone . " [[Wikipedia:" . $code . "|" . $code . "]].\n";
						  break;
					  }
				  case "total":
					  $messages[] = $project . " now covers more than " . $nextmilestone . " articles in total.\n";
					  break;
				  case "good topics":
					  $messages[] = "The English Wikipedia now has more than " . $nextmilestone . "[[Wikipedia:Good topics|good topics]].\n";
					  break;
				  case "featured topics":
					  $messages[] = "The English Wikipedia now has more than " . $nextmilestone . "[[Wikipedia:Featured topics|featured topics]].\n";
					  break;
				  case "Category":
					  $messages[] = $project . " passed " . $nextmilestone . " articles in its category [[:Category:" . $identifier . "|" . $identifier . "]].\n";
					  break;
				  case "cat-only":
					  $messages[] = "[[:Category:" . $identifier . "|" . $identifier . "]]  passed " . $nextmilestone . " articles.\n";
					  break;
				  case "Template":
					  $messages[] = "[[Wikipedia:" . $project . "|" . $project . "]] passed " . $nextmilestone . " articles using its template [[Template:" . $identifier . "|" . $identifier . "]].\n";
					  break;
				  case "good":
				  	  $messages[] = $project . " now includes more than " . $nextmilestone . " [[Wikipedia:Good topics|good topics]]. \n";
					  break;
				  case "featured":
				  	  $messages[] = $project . " now includes more than " . $nextmilestone . " [[Wikipedia:Featured articles|featured articles]]. \n";
					  break;
				  default:
					  //Mostly "A-Class", "B-Class" and so forth
					  $messages[] = $project . " now includes more than " . $nextmilestone . " " . $namespace . " articles. \n";
					  break;
			  }
		  } else {
			  //Just update the count, leave milestones intact
			  $newfile .= substr($lines[$i], 0, $commas[1]) . "," . $newcount . substr($lines[$i], $commas[2]);
		  }
	  }
  }
  echo "</ol>";
  check_for_emergency();
  
  if (!$check) {
	  //Update list of projects with new counts, ready for next time.
	  $fhupdate = fopen("announcements.txt", 'w') or die("can't open file");
	  fwrite($fhupdate, $newfile);
	  fclose($fhupdate);
  }
  if (!$updateonly) {
	  //If milestones have been passed...
	  if (count($messages) == 0) {
		  die("No project passed one of its milestones.");
	  }
	  //...update WP:ANN
	  $post = "";
	  $date = date("j F Y");
	  //Get existing page
	  $page = $LivingBot->get_page("Wikipedia:Announcements");
	  //Draw up the post
	  if (preg_match(("/===[ ]*" . $date . "[ ]*===/"), $page, $temp)) {
		  $existsat = stripos($page, $temp[0]) + strlen($temp[0]);
	  } else {
		  $post = "=== " . $date . " ===\n";
	  }
	  for ($i = 0; $i < count($messages); $i++) {
		  if (stripos($page, $messages[0]) != false || stripos($post, $messages[0]) != false) {
			  //For some reason, this post has been before
			  continue;
		  }
		  $post .= $messages[0];
	  }
	  if (strlen($post) < 3) {
		  die("Would have been a null edit.");
	  }
	  //If the date header has already been added for today
	  if (isset($existsat)) {
		  //Add below that
		  $newpage = substr($page, 0, $existsat) . "\n" . $post . substr($page, $existsat);
	  } else {
		  //Else add under the main heading
		  $existsat = stripos($page, "==Announcements==") + 17;
		  $newpage = substr($page, 0, $existsat) . "\n" . $post . substr($page, $existsat);
	  }
	  //Write changes
	  if ($human) {
		  echo "<pre>$post</pre>";
	  } else {
		  $LivingBot->put_page("Wikipedia:Announcements", $page, $newpage, "Bot adding announcement(s) from WikiProject(s). [[User_talk:LivingBot|Incorrect?]] Or do you want to [[User:LivingBot/ProjectSignup|sign up your project]]?");
	  }
  }
  
  // ******* HELPER FUNCTIONS ******* \\
  
  function get_count($namespace, $identifier) {
	  global $LivingBot;
	  //Get the new count of this category/template/whatever
	  switch ($namespace) {
		  case "on-template":
			  //This way is messier, but more reliable, than grabbing the Wiki edit page because of protection
			  $identifier = str_replace(" ", "_", $identifier);
			  $page = webpage(("http://en.wikipedia.org/wiki/Template:" . $identifier));
			  preg_match("/[^0-9a-zA-Z]p[^0-9a-zA-Z]([0-9]{4,6})[^0-9a-zA-Z!]\/p[^0-9a-zA-Z!]/", $page, $matches);
			  return $matches[1];
			  break;
		  case "Template":
			  return - 1;
			  break;
		  case "Category":
			  //fall through
		  case "total":
			  //fall through
		  default:
			  $identifier = str_replace(" ", "_", $identifier);
			  $identifier = str_replace("&", "%26", $identifier);		 
			  $page = webpage(("http://toolserver.org/~erwin85/categorycount.php?lang=en&family=wikipedia&namespaces=1&category=" . $identifier . "&subcats=1&d=10&submit=Submit"));
			  preg_match("/There are ([0-9]+) articles/", $page, $matches);
			  if (strlen($matches[1]) == 0) {
				  return -1;
			  } else {
				  return $matches[1];
			  }
	  }
  }
  function strposall($haystack, $needle) {
	  //Simple helper function for getting all occurences in string
	  $s = 0;
	  $i = 0;
	  while (is_integer($i)) {
		  $i = strpos($haystack, $needle, $s);
		  if (is_integer($i)) {
			  $aStrPos[] = $i;
			  $s = $i + strlen($needle);
		  }
	  }
	  if (isset($aStrPos)) {
		  return $aStrPos;
	  } else {
		  return false;
	  }
  }
  function check_for_emergency() {
	  //Die if an emergency shutoff initiated.
	  global $LivingBot;
	  if (stripos($LivingBot->get_page("User:LivingBot/shutoff"), "<!--Emergency shutoff-->") === false) {
		  die("Bot shut down.<br />");
	  }
  }
  function webpage($url){
	  //Returns the HTML of a page
	  $ch = curl_init();
	  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	  curl_setopt($ch, CURLOPT_URL, $url);
	  $page = curl_exec($ch);
	  curl_close($ch);
	  return $page;
  }
?>