User:Merge bot/proposedmergers.php

<?php
/** proposedmergers.php - To generate lists of proposed page mergers on Wikipedia
 *
 *  (c) 2009 James Hare - http://en.wikipedia.org/wiki/User:Harej
 *  (c) 2013-2022 Bill  - http://en.wikipedia.org/wiki/User:wbm1058
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *   
 *  Developers (add your self here if you worked on the code):
 *    James Hare - [[User:Harej]] - Wrote everything
 *    WBM - [[User:Wbm1058]] - March/April 2013 updates
 **/
ini_set("display_errors", 1);
error_reporting(E_ALL ^ E_NOTICE);
require_once 'botclasses.php';  // Botclasses.php was written by User:Chris_G and is available under the GNU General Public License
include("logininfo.php");

const bot_version = "1.110";
const botuser = "Merge bot";

function templateprocess($processed) {
	echo " :: " . $processed;
	$processed = preg_replace("/\s?\|\s?/", "|", $processed);
	$processed = preg_replace("/\{{2}\s?/", "", $processed);
	$processed = preg_replace("/\s?\}{2}/", "", $processed);
	$processed = preg_replace("/\s?=\s?/", "=", $processed);

#				Redirects to {{Merge}} (14 aliases)
	$processed = preg_replace("/^(Mergewith|Merge with|Merge_with|MergeVfD|Mergesplit|MergeSplit|Merge)/i", "merge", $processed);
	$processed = preg_replace("/^(Mergedisputed|MergeDisputed|Merge-disputed|Merge disputed|Merge_disputed)/i", "merge", $processed);
	$processed = preg_replace("/^(Merge-multiple|Mergemulti|Mergetomultiple-with|Multimerge)/i", "merge", $processed);
	$processed = preg_replace("/^(Proposed merge|Proposed_merge)/i", "merge", $processed);

#				{{Merging}}
	$processed = preg_replace("/^(Mergingsectionto|Merging|Merging to|Merging_to)(.*)\|\s*dir\s*\=\s*from/i", "mergefrom$2", $processed);
	$processed = preg_replace("/^(Mergingsectionto|Merging|Merging to|Merging_to)/i", "merge", $processed);

#				Redirects to {{Merge from}} (11 aliases)
	$processed = preg_replace("/^(Merge from|Merge_from|Merge-from|Include|Mergrefrom|Mergefrom-category|MergeFrom|Mergefrom)/i", "mergefrom", $processed);
	$processed = preg_replace("/^(Mergefrom-multiple|Multiplemergefrom|Mergefrommultiple|Mergefrommulti|Multimergefrom)/i", "mergefrom", $processed);

#				{{Afd-merge from}}, {{Merging from}}
	$processed = preg_replace("/^(Afd-merge from|Afd-merge_from|Afd-mergefrom|Afdmergefrom|Merging from|Merging_from|Mergingfrom)/i", "mergefrom", $processed);

#				Redirects to {{Merge to}} (15 aliases) and {{Merge school}} (1 alias)
	$processed = preg_replace("/^(Merge to|Merge_to|Merge-to|Mergeinto|MergetoCat|Mergelist|Mergeto-disputed)/i", "mergeto", $processed);
	$processed = preg_replace("/^(MergePartial|Merge-multiple-to|Merge to article|Merge_to_article)/i", "mergeto", $processed);
	$processed = preg_replace("/^(Mergeto-multiple|Multiplemergeto|Multiplemergeinto|Merge into|Merge_into|Merge-into|MergeTo|Mergeto|Merge2)/i", "mergeto", $processed);
	$processed = preg_replace("/^(Merge school|Merge_school|Merge-school)/i", "mergeto", $processed);

#				{{Afd-merge to}}
	$processed = preg_replace("/^(Afd-merge to|Afd-merge_to|Afd-mergeto|Afdmergeto|AfD-merge to|AfD-merge_to)/i", "afd-mergeto", $processed);

#				{{Merge portions from}}  // This is really a splitting template, not a merging template
	$processed = preg_replace("/^(Merge portions from|Merge_portions_from|Move portions from|Move_portions_from)/i", "false-positive", $processed);

	return $processed;
}

echo "PHP version: " . PHP_VERSION . "\n";
#phpinfo();
echo "Bot version: " . bot_version . "\n";

$j = 0;
$takeofflater = 0;
$maxi = 0;
$cachepage = "";
$discuss = array();
$target = array();
$section = array();
$multiplesections = array();
$reason = array();
$othernamespace = 0;
$matchfailed = 0;
$templatesplitfailed = 0;
$nopartner = 0;
$nopartners = array();
$no_direction = 0;
$no_directions = array();
$conflict = 0;
$conflicts = array();
$mismatched_date = 0;
$mismatched_dates = array();
$reason_count = 0;
$reasons = array();
$blank = 0;
$blanks = array();
$no_reciprocal = 0;
$redirects = 0;
$maybe = 0;
$maybes = array();
$diffcase = 0;
$diffcases = array();
$redir_no_reciprocal = 0;
$redir_no_reciprocals = array();
$page_moved = 0;
$pages_moved = array();
$other_redirect = 0;
$other_redirects = array();
$selfmerge = 0;
$targetself = 0;
$noname = 0;
$wikt = 0;
$mainsubmission = "";
$skipped = 0;
$counter = array();
$maxcounter = 0;
$submission = array();
$nomatches = array();
$nosplits = array();

echo "Logging in...\n";
$objwiki = new wikipedia();
$objwiki->http->useragent = '[[User:Merge bot]] php wikibot classes';
$objwiki->login($mbuser, $mbpass);
echo "...done.\n";

$mergemonths = $objwiki->categorymembers("Category:Articles to be merged");
print_r($mergemonths);

for ($a = 0; $a < count($mergemonths); $a++) { // for each month
	#if (preg_match("/Category:Articles to be merged/", $mergemonths[$a])) {
	if (preg_match("/Category:Articles to be merged from/", $mergemonths[$a])) {
		echo "\n__________\n" . $a . ": " . $mergemonths[$a] . "\n";
		$transcludes = $objwiki->categorymembers($mergemonths[$a]);
		#print_r($transcludes);

		$monthyear = str_replace("Category:Articles to be merged from ", "", $mergemonths[$a], $repcount);
		if ($repcount == 0) {
			$monthyear = str_replace("Category:", "", $mergemonths[$a]);
		}

		for ($i = 0; $i < count($transcludes); $i++) { // for each page in the category
	
			if ($i > $maxi) {
				$maxi = $i;
			}

			if (preg_match("/^((User|Wikipedia|File|MediaWiki|Template|Help|Category|Portal|Draft)(( |_)talk)?|Talk):/", $transcludes[$i])) {
				echo "\n\n?? Other namespace: " . $transcludes[$i] . "\n\n";
				$others[$othernamespace] = $transcludes[$i];
				$othernamespace += 1;
				continue;
			}

			$getpagefailed = 0;
			do {
				if ($transcludes[$i] == $cachepage) {
					echo "getpage 1: $transcludes[$i]|from cache\n";
					$contents = $cachecontents;
				}
				else {
					echo "getpage 1: $transcludes[$i]|";
					$contents = $objwiki->getpage($transcludes[$i]);
				}
				if ($contents == FALSE) {
					echo "\n\n?? getpage failed: " . $transcludes[$i] . "\n\n";
					$getpagefailed += 1;
					if ($getpagefailed == 5) {
						die("getpage Error");
					}
					sleep(10);
					continue;
				}
			} while ($contents == FALSE);

			if (preg_match_all("/\{{2}\s?(merge|proposed merge|afd-merge|merging|move section)[^}]*\}{2}/i", $contents, $raw1) == 0) {
				#echo "contents:\n";
        			#echo "$contents";
        			#echo "\n";
				unset($contents);
				echo "\n\n?? Match failed: " . $transcludes[$i] . "\n\n";
				$nomatches[$matchfailed] = $transcludes[$i];
				$matchfailed += 1;
				continue;
			}

			$mergetemplates = count($raw1[0]);
			if ($mergetemplates > 1) {
				echo "$mergetemplates merge templates on $transcludes[$i]\n";
				print_r($raw1[0]);
			}
			$takeofflater = 0;

			for ($j = 0; $j < $mergetemplates; $j++) { // for each merge template on the page
				$key = $a . "-" . $i . "-" . $j;
			
				$pagename[$key] = $transcludes[$i];
				echo $key . ">> " . $pagename[$key];
				$template = templateprocess($raw1[0][$j]);
				#echo " § " . $template . " §";

				$ptemplate = $raw1[0][$j];
				if (isset($contents)) $pcontents = $contents;
				else $pcontents = "";
				unset($contents);
			
				$templatesplit = array_map('trim',explode("|", $template));
				echo " " . $templatesplit[0];

				switch ($templatesplit[0]) {
					case "mergefrom":
						$type[$key] = "into";
						break;
					case "merge":
						$type[$key] = "with";
						break;
					case "mergeto":
						$type[$key] = "to";
						break;
					case "afd-mergeto":
					case "false-positive":
						echo " [unset: " . $pagename[$key] . "]\n";
						unset($pagename[$key]);
						$takeofflater += 1;
						continue 2;
					default:
						echo "*** templatesplitfailed: " . $template . "\n";
						print_r($templatesplit);
						$nosplits[$templatesplitfailed] = $transcludes[$i];
						$templatesplitfailed += 1;
						echo " [unset: " . $pagename[$key] . "]\n";
						unset($pagename[$key]);
						$takeofflater += 1;
						continue 2;
				}
			
				$otherpage[$key] = "{{pagelist|nspace=|";
				unset($otherpages);
				$otherpages = array();
				$otherpage_count = 0;

				for ($para = 1; $para < count($templatesplit); $para++) {
					#echo "\n" . $para . ") " . $templatesplit[$para] . "\n";
					if (preg_match("/^date\s*=/i", $templatesplit[$para])) {
						$date[$key] = str_replace("date=", "", $templatesplit[$para]);
						$date[$key] = str_replace("_", " ", $date[$key]);

						if ($date[$key] != $monthyear) {
							if (in_array($transcludes[$i], $mismatched_dates) == FALSE) {
								$mismatched_dates[$mismatched_date] = $transcludes[$i];
								$mismatched_date += 1;
							}
							echo " Another date: " . $date[$key] . " not " . $monthyear;
							echo " [unset=> " . $date[$key] . "]\n";
							unset($pagename[$key]);
							unset($type[$key]);
							unset($date[$key]);
							unset($discuss[$key]);
							unset($target[$key]);
							unset($section[$key]);
							unset($multiplesections[$key]);
							unset($reason[$key]);
							$takeofflater += 1;
							continue 2;
						}
					}
					elseif (preg_match("/^(discuss|discussion|talk)\s*=/i", $templatesplit[$para])) {
						$discuss[$key] = str_replace("discuss=", "", $templatesplit[$para]);
						$discuss[$key] = str_replace("discussion=", "", $discuss[$key]);
						$discuss[$key] = str_replace("talk=", "", $discuss[$key]);
					}
					elseif (preg_match("/^target\s*=/i", $templatesplit[$para])) {
						$target[$key] = str_replace("target=", "", $templatesplit[$para]);

						if ($target[$key] == $transcludes[$i]) {
							echo "\n** error ** Page " . $transcludes[$i] . " proposed merge target is itself\n";
							$targetself += 1;
						}

						if (in_array($target[$key], $pagename)) {
							echo " [unset=> " . $target[$key] . "]\n";
							unset($pagename[$key]);
							unset($type[$key]);
							unset($date[$key]);
							unset($discuss[$key]);
							unset($target[$key]);
							unset($section[$key]);
							unset($multiplesections[$key]);
							unset($reason[$key]);
							$takeofflater += 1;
							continue 2;
						}
					}
					elseif (preg_match("/^section\s*=/i", $templatesplit[$para])) {
						$section[$key] = str_replace("section=", "", $templatesplit[$para]);
					}
					elseif (preg_match("/^multiplesections\s*=/i", $templatesplit[$para])) {
							// Template:Mergefrom uses parameter multiplesections; Merge and Mergeto do not
						$multiplesections[$key] = str_replace("multiplesections=", "", $templatesplit[$para]);
					}
					elseif (preg_match("/^dir\s*=/i", $templatesplit[$para])) { // Template:Merging
					}
					elseif (preg_match("/^(reason|comment)\s*=/i", $templatesplit[$para])) {
						$reason[$key] = str_replace("reason=", "", $templatesplit[$para]);
						$reasons[$reason_count] = $pagename[$key] . " …… " . $reason[$key];
						$reason_count += 1;
					}
					else {
						if (in_array($templatesplit[$para], $pagename)) {
							echo " [unset-> " . $templatesplit[$para] . "]\n";
							unset($pagename[$key]);
							unset($type[$key]);
							unset($date[$key]);
							unset($discuss[$key]);
							unset($target[$key]);
							unset($section[$key]);
							unset($multiplesections[$key]);
							unset($reason[$key]);
							$takeofflater += 1;
							continue 2;
						}
						else {
							if (preg_match("/^(1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20)=/i", $templatesplit[$para])) {
								echo "\nNumbered parameter(s):" . $templatesplit[$para];
								$templatesplit[$para] = preg_replace("/(1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20)=/", "", $templatesplit[$para]);
							}
							$otherpage[$key] .= $templatesplit[$para] . "|";
							$otherpages[$otherpage_count] = $templatesplit[$para];
							$otherpage_count += 1;
						}
					}
				}

				$otherpage[$key] .= "}}";
				echo " -- " . $otherpage[$key] . "\n";
				#print_r($otherpages);

				for ($ii = 0; $ii < count($otherpages); $ii++) {
					$break = 0;
					$pagecontents = "";

					if (str_replace ("_"," ",$otherpages[$ii]) != $otherpages[$ii]) {
						echo "\n$otherpages[$ii] has underscores\n";
						$pos = strpos($ptemplate, $otherpages[$ii]);
						$otherpages[$ii] = str_replace ("_"," ",$otherpages[$ii]);
						if ($pos !== false) {
					            $new_template = substr_replace($ptemplate, $otherpages[$ii], $pos, strlen($otherpages[$ii]));
					            $pcontents = str_replace($ptemplate,$new_template,$pcontents);
					            if ($pcontents == "") {
					                echo "\n??Problem replacing underscores with spaces in merge template\n";
					            }
					            else if ($objwiki->nobots($transcludes[$i],botuser,$pcontents) == true) {
					                echo "\nReplacing underscores with spaces in merge template\n";
					                $objwiki->edit($transcludes[$i],$pcontents,"Replace underscores with spaces in merge template",true,true);
					            }
						}

					}

					if (strpos($otherpages[$ii],"#") !== false) {
						$len = strpos($otherpages[$ii],"#");
						if ($len == 0) $mp = $pagename[$key];
						else $mp = substr($otherpages[$ii],0,$len); // strip section links
					}
					else $mp = $otherpages[$ii];

					if ($pagename[$key] == $mp) {
						echo "\n***** PAGE " . $mp . " PROPOSED FOR SELF-MERGE *****\n\n";
						$selfmerge += 1;
					}
					else if ($mp == "") {
						echo "\n**** Pagename not specified ****" . $ptemplate . "\n\n";
						$noname += 1;
						$new_template = str_replace ("||","|",$ptemplate);
						if ($new_template !== $ptemplate) {
						    	$pcontents = str_replace($ptemplate,$new_template,$pcontents);
						    	if ($pcontents == "") {
						    	    echo "\n??Problem removing redundant pipe in merge template\n";
						    	}
						    	else if ($objwiki->nobots($transcludes[$i],botuser,$pcontents) == true) {
						    	    echo "\nRemoving redundant pipe in merge template\n";
						    	    $objwiki->edit($transcludes[$i],$pcontents,"Remove redundant pipe in merge template",true,true);
						    	}
						}
					}
					else if (preg_match("/^(Wiktionary|Wikt):/i",$otherpages[$ii])) {
						echo "\n*** Wiktionary merge: " . $otherpages[$ii] . " ***\n\n";
						$wikt += 1;
						$otherpage[$key] = preg_replace("/nspace=/", "nspace=wikt", $otherpage[$key]);
					}
					else {
					    while ($pagecontents == "") {
					        if ($break == 5) {
					            echo "\n*** " . $pagename[$key] . ": PAGE " . $otherpages[$ii] . " IS BLANK OR DOES NOT EXIST ***\n\n";
					            $blanks[$blank] = $pagename[$key] . ":: " . $otherpages[$ii];
					            unset($pagecontents);
					            $blank += 1;
					            break;
					        }
					        else {
					            if (preg_match("/^((User|Wikipedia|File|MediaWiki|Template|Help|Category|Portal|Draft)(( |_)talk)?|Talk):/", $otherpages[$ii])
					                and $break == 0) {
					            	    echo "\n\n? Other namespace: " . $otherpages[$ii] . "\n\n";
					            	    $others[$othernamespace] = $otherpages[$ii];
					            	    $othernamespace += 1;
					            }
					            echo "getpage 2: $otherpages[$ii]|";
					            $pagecontents = $objwiki->getpage($otherpages[$ii]);
					            if (preg_match_all("/\{{2}\s?(merge|afd-merge|merging|move section)[^}]*\}{2}/i", $pagecontents, $raw2) == 0 and $break == 0) {
					                echo "*** Merge tag not found on " . $otherpages[0] . " *2*\n";
					                $no_reciprocal += 1;
					            }
					            $cachepage = $otherpages[$ii];
					            if (isset($pagecontents)) $cachecontents = $pagecontents;
						    else $cachecontents = "";
					            $break += 1;
					        }
					    }

					    if (isset($pagecontents) and preg_match("/^\#REDIRECT(\s*|:)\[{2}.*\]{2}/i", $pagecontents, $redirect)) {
					        echo "\n*** " . $pagename[$key]. ": PAGE " . $otherpages[$ii] . " IS A REDIRECT!! ***\n";
					        echo $pagecontents . "\n\n";
					        $redirects += 1;
					        preg_match("/(?<=\[{2}).+(?=(\]{2}))/i", $redirect[0], $target);
					        echo "Target: " . $target[0] . "\n";
					        $target[0] = ucfirst($target[0]);
					        $target[0] = str_replace ("_"," ",$target[0]);
					        $target[0] = trim($target[0]);

					        if (strpos($target[0],"#") !== false) {
					            $len = strpos($target[0],"#");
					            if ($len == 0) $targetpage = $target[0];
					            else $targetpage = substr($target[0],0,$len); // strip section links
					        }
					        else $targetpage = $target[0];

					        if ($targetpage == $pagename[$key]) {
					            echo $otherpages[$ii] . " redirects to " . $target[0] . " -- may have been merged\n\n";
					            $maybes[$maybe] = $pagename[$key] . ":: " . $otherpages[$ii];
					            $maybe +=1;
					        }
					        else if (strtoupper($otherpages[$ii]) == strtoupper($target[0])) {
					            echo "Case difference\n";
					            $diffcases[$diffcase] =  $pagename[$key] . ":: " . $otherpages[$ii] . " vs. " . $target[0];
					            $diffcase += 1;
					            $pos = strpos($ptemplate, $otherpages[$ii]);
					            if ($pos !== false) {
					                $new_template = substr_replace($ptemplate, $target[0], $pos, strlen($otherpages[$ii]));
					                $pcontents = str_replace($ptemplate,$new_template,$pcontents);
					                if ($pcontents == "") {
					                    echo "\n??Problem bypassing redirect in merge template – DIFFCAPS\n";
						    	}
					                else if ($objwiki->nobots($transcludes[$i],botuser,$pcontents) == true) {
					                    echo "\nBypassing redirect in merge template – DIFFCAPS\n";
					                    $objwiki->edit($transcludes[$i],$pcontents,"Bypass redirect in merge template – DIFFCAPS",true,true);
					                }
					            }
					        }
					        else {
					            echo "getpage 4: $targetpage|";
					            $pagecontents = $objwiki->getpage($targetpage);
					            if (preg_match_all("/\{{2}\s?(merge|afd-merge|merging|move section)[^}]*\}{2}/i", $pagecontents, $raw4) == 0) {
					                echo "*** Merge tag not found on target page " . $targetpage. " *4*\n";
					                $redir_no_reciprocals[$redir_no_reciprocal] = $pagename[$key] . ":: " . $otherpages[$ii];
					                $redir_no_reciprocal += 1;
					            }
					            else {
					                echo "*** Merge tag found on target page " . $targetpage. " *4* " . $raw4[0][0] . "\n";
					                $pos = stripos($raw4[0][0],$pagename[$key]);
					                if ($pos === false) {
					                    echo " ** " . $pagename[$key] . " not found!\n";
					                    $other_redirects[$other_redirect] = $pagename[$key] . ":: " . $otherpages[$ii];
					                    $other_redirect += 1;
					                }
					                else {
					                    echo " ** found " . $pagename[$key] . "\n";
					                    $pages_moved[$page_moved] = $pagename[$key] . ":: " . $otherpages[$ii];
					                    $page_moved += 1;
					                    $pos = strpos($ptemplate, $otherpages[$ii]);
					                    if ($pos !== false) {
					                        $new_template = substr_replace($ptemplate, $target[0], $pos, strlen($otherpages[$ii]));
					                        $pcontents = str_replace($ptemplate,$new_template,$pcontents);
					                        echo "\n$pcontents\n";
					                        if ($pcontents == "") {
					                            echo "\n??Problem bypassing redirect in merge template – apparently " . $otherpages[$ii] .
					                                " moved to " . $target[0] . "\n";
					                        }
					                        else if ($objwiki->nobots($transcludes[$i],botuser,$pcontents) == true) {
					                            echo "\nBypassing redirect in merge template – apparently " . $otherpages[$ii] . " moved to " . $target[0] . "\n";
					                            $objwiki->edit($transcludes[$i],$pcontents,"Bypass redirect in merge template – apparently " .
					                                $otherpages[$ii] . " moved to " . $target[0],true,true);
					                        }
					                    }
					                }
					            }
					        }
					    }
					}
				}

				if ($otherpage[$key] == "{{pagelist|nspace=|}}") {
					$nopartners[$nopartner] = $transcludes[$i];
					$nopartner += 1;
					if ($templatesplit[0] == "mergeto") $type[$key] = "to ?";
				}
				else if (substr($otherpage[$key],0,22) == "{{pagelist|nspace=wikt") {
					#echo "\nwikt:\n";
				}
				else if ($templatesplit[0] == "mergeto") {
					$break = 0;
					$pagecontents = "";

					while ($pagecontents == "") {
						if ($break == 5) {
							echo "\n*** " . $pagename[$key] . ": PAGE " . $otherpages[0] . " is BLANK or DOES NOT EXIST ***\n\n";
							unset($pagecontents);
							break;
						}
						else {
							if ($otherpages[0] == $cachepage) {
								echo "getpage 3: $otherpages[0]|from cache\n";
								$pagecontents = $cachecontents;
							}
							else {
								echo "getpage 3: $otherpages[0]|";
								$pagecontents = $objwiki->getpage($otherpages[0]);
								if (preg_match_all("/\{{2}\s?(merge|afd-merge|merging|move section)[^}]*\}{2}/i", $pagecontents, $raw3) == 0) {
									echo "*** Merge tag not found on " . $otherpages[0]. " *3*\n";
									$no_reciprocal += 1;
								}
							}
							$break += 1;
						}
					}

					if (isset($pagecontents) and preg_match_all("/\{{2}\s?(merge|afd-merge|merging|move section)[^}]*\}{2}/i", $pagecontents, $raw) !== 0) {
						$reciprocal = FALSE;
						for ($jraw = 0; $jraw < count($raw[0]); $jraw++) {
							echo "(" . $jraw . ") " . $raw[0][$jraw];
							$pos = stripos($raw[0][$jraw],$pagename[$key]);
							if ($pos === false) {
								echo " ** " . $pagename[$key] . " not found!";
							}
							else {
								echo " ** found " . $pagename[$key];
								$reciprocal_template = templateprocess($raw[0][$jraw]);
								echo "\n§ " . $reciprocal_template . " § ";
								$reciprocal_templatesplit = array_map('trim',explode("|", $reciprocal_template));
								echo $reciprocal_templatesplit[0];
								switch ($reciprocal_templatesplit[0]) {
									case "merge":
										echo "\n% Reciprocal direction not specified\n";
										$no_directions[$no_direction] = $pagename[$key] . " ==> " . $otherpages[0];
										$no_direction += 1;
									case "mergefrom":
									case "false-positive":
										$reciprocal = TRUE;
										break;
									case "mergeto":
										echo "\n!! Conflicting tags !!\n";
										$conflicts[$conflict] = $pagename[$key] . " <===> " . $otherpages[0];
										$conflict += 1;
										break;
									default:
										echo "\n!! Unexpected: " . $templatesplit[0];
								}
							}
						}
						if ($reciprocal == FALSE) {
							echo "\n*** Reciprocal merge tag not found on " . $otherpages[0]. " ***\n";
							$no_reciprocal += 1;
						}
						else {
							echo "\n";
							echo "mergeto target: " . $otherpage[$key] . " ◆ " . $otherpages[0];
							echo " [unset: " . $pagename[$key] . "]\n";
							unset($pagename[$key]);
							unset($type[$key]);
							$takeofflater += 1;
							continue;
						}
					}
				}

				if (!array_key_exists($key, $discuss)) { // ($discuss[$key] == "")
					if (preg_match("/^(User|Wikipedia|Image|File|MediaWiki|Template|Help|Category|Portal):/i",$transcludes[$i],$m)) {
						$discuss[$key] = str_replace($m[1],$m[1].' talk',$transcludes[$i]);
					}
					else {
						$discuss[$key] = "Talk:" . $transcludes[$i];
					}
				}
			}
		}

		$j = $j - $takeofflater;

		if (count($transcludes) > 0) {
			$mainsubmission .= "* [[Wikipedia:Proposed mergers/Log/" . $monthyear . "|" . $monthyear . "]]\n";
		}
		else {
			echo "\n*** Category is empty ***\n\n";
		}
	}
	else {
		echo "\n" . $a . ": Skipped: " . $mergemonths[$a] . "\n";
		$skipped += 1;
	}
}

if (count($pagename) < 1) {
	echo "No pagenames! Exiting.";
	die();
}

echo "\n*** Preparing Updates ***\n\n";
print_r($pagename);

foreach ($pagename as $key => $title) {
	if (array_key_exists($date[$key], $counter) and $counter[$date[$key]] > $maxcounter) {
		$maxcounter = $counter[$date[$key]];
	}
	if (!array_key_exists($date[$key], $submission)) $submission[$date[$key]] = "";
	if (!array_key_exists($key, $reason)) $reason[$key] = "";
	
	switch ($type[$key]) {
		case "with":  // regular merge
			if (array_key_exists($key, $target)) { // ($target[$key] != "")
				$submission[$date[$key]] .=
					"{{merge log entry|1=[[$title]]|2=$otherpage[$key]|3=[[$target[$key]]]|talk=$discuss[$key]|type=with|reason=$reason[$key]}}\n";
			}
			else {
				$submission[$date[$key]] .= "{{merge log entry|1=[[$title]]|2=$otherpage[$key]|talk=$discuss[$key]|type=with|reason=$reason[$key]}}\n";
			}
			break;
		case "into":  // merge-from
			$submission[$date[$key]] .= "{{merge log entry|1=$otherpage[$key]|2=[[$title]]|talk=$discuss[$key]|type=into|reason=$reason[$key]}}\n";
			break;
		case "to":  // merge-to
			$submission[$date[$key]] .= "{{merge log entry|1=[[$title]]|2=$otherpage[$key]|talk=$discuss[$key]|type=into|reason=$reason[$key]}}\n";
			break;
		case "to ?":  // no partner
			$submission[$date[$key]] .= "{{merge log entry|1=[[$title]]|2=?|talk=$discuss[$key]|type=into|reason=$reason[$key]}}\n";
			break;
		default:
			echo "\n*error* " . $type[$key] . "\n";
			break; // use "continue 2"?
	}

	if (array_key_exists($date[$key], $counter)) $counter[$date[$key]] += 1;
	else $counter[$date[$key]] = 1;
	echo $date[$key] . " | " . $counter[$date[$key]] . ") " . $key . " ++ " . $title. "\n";
}

echo "\n\n*** Posting Updates ***\n\n";

foreach ($submission as $log => $content) {
	if ($log != "") {
		echo "Updating> " . $log. "\n";
		#echo $content . "\n";
		$objwiki->edit("Wikipedia:Proposed mergers/Log/" . $log,$content,"Updating list of proposed mergers",false,true);
	}
	else echo "\n? Error, null log specification: " . $content . "\n\n";
}

echo "Updating Wikipedia:Proposed mergers/Log\n";
$objwiki->edit("Wikipedia:Proposed mergers/Log",$mainsubmission,"Updating list of logs",true,true);
echo "done.\n";

echo "\nCategory members skipped: " . $skipped;
echo "\nMaximum pages in a category: " . $maxi;
echo "\nMaximum items on a report page: " . $maxcounter;
echo "\nOther namespaces skipped: " . $othernamespace . "\n";
print_r($others);
echo "\nPattern match failed: " . $matchfailed . "\n";
print_r($nomatches);
echo "\nTemplatesplit failed: " . $templatesplitfailed . "\n";
print_r($nosplits);
echo "\nNo partner: " . $nopartner . "\n";
if ($nopartner > 0) print_r($nopartners);
echo "\nReciprocal direction not specified: " . $no_direction . "\n";
if ($no_direction > 0) print_r($no_directions);
echo "\nConflicting tags: " . $conflict . "\n";
if ($conflict > 0) print_r($conflicts);
echo "\nPages with multiple proposal dates: " . $mismatched_date . "\n";
if ($mismatched_date > 0) print_r($mismatched_dates);
echo "\nPages where reasons are given in the template: " . $reason_count . "\n";
if ($reason_count > 0) print_r($reasons);
echo "\nOther pages which are blank or don't exist: " . $blank . "\n";
if ($blank > 0) print_r($blanks);
echo "\nOther pages which are redirects: " . $redirects;
echo "\n  Maybe merged: " . $maybe . "\n";
if ($maybe > 0) print_r($maybes);
echo "\n  Cases differ: " . $diffcase . "\n";
if ($diffcase > 0) print_r($diffcases);
echo "\n  Pages moved: " . $page_moved . "\n";
if ($page_moved > 0) print_r($pages_moved);
echo "\n  Other redirects: " . $other_redirect . "\n";
if ($other_redirect > 0) print_r($other_redirects);
echo "\n  Redirect with no reciprocal tags: " . $redir_no_reciprocal . "\n";
print_r($redir_no_reciprocals);
echo "\nMerge-to targets without reciprocal merge tags: " . $no_reciprocal . "\n";
echo "\nSelf-merges: " . $selfmerge . "\n";
echo "\nSpecified |target is the page itself: " . $targetself . "\n";
echo "\nNo name specified: " . $noname . "\n";
echo "\nWiktionary merges: " . $wikt . "\n";
echo "\nMission accomplished.\n\n";

?>