public function testBogusIPs() { $invalid = array('www.xn--var-xla.net', '216.17.184.G', '216.17.184.1.', '216.17.184', '216.17.184.', '256.17.184.1'); foreach ($invalid as $i) { $this->assertFalse(IP::isValid($i), "{$i} is an invalid IPv4 address"); } }
public function execute($sub) { global $wgOut, $wgRequest; global $wgLandingPageBase, $wgChapterLandingPages, $wgLandingPageDefaultTarget; $lang = preg_match('/^[A-Za-z-]+$/', $wgRequest->getVal('lang')) ? $wgRequest->getVal('lang') : 'en'; $utm_source = $wgRequest->getVal('utm_source'); $utm_medium = $wgRequest->getVal('utm_medium'); $utm_campaign = $wgRequest->getVal('utm_campaign'); $referrer = $wgRequest->getHeader('referer'); $target = $wgRequest->getVal('target', null); if (!$target) { $target = $wgLandingPageDefaultTarget; } $tracking = '?' . wfArrayToCGI(array('utm_source' => "{$utm_source}", 'utm_medium' => "{$utm_medium}", 'utm_campaign' => "{$utm_campaign}", 'referrer' => "{$referrer}", 'target' => "{$target}")); $ip = $wgRequest->getVal('ip') ? $wgRequest->getVal('ip') : wfGetIP(); if (IP::isValid($ip)) { $country = geoip_country_code_by_name($ip); if (is_string($country) && array_key_exists($country, $wgChapterLandingPages)) { $wgOut->redirect($this->getDestination($utm_source) . '/' . $wgChapterLandingPages[$country] . $tracking); return; } } // No valid IP or chapter page - let's just go for the passed in url or our fallback if (Http::isValidURI($target)) { $wgOut->redirect($target . '/' . $lang . $tracking); return; } else { $wgOut->redirect($wgLandingPageBase . $target . '/' . $lang . $tracking); } }
function save() { $_POST["mac"] = str_replace("-", ":", $_POST["mac"]); $_POST["mac"] = strtolower($_POST["mac"]); $ipClass = new IP(); if (!$ipClass->IsvalidMAC($_POST["mac"])) { echo "MAC: {$_POST["mac"]} Invalid!\n"; return; } if (!$ipClass->isValid($_POST["ipaddr"])) { echo "MAC: {$_POST["ipaddr"]} Invalid!\n"; return; } $cmp = new computers(); $uid = $cmp->ComputerIDFromMAC($_POST["mac"]); if ($uid != null) { $cmp = new computers($uid); } if ($uid == null) { $uid = "{$_POST["hostname"]}\$"; } $cmp->uid = $uid; $cmp->ComputerIP = $_POST["ipaddr"]; $cmp->ComputerMacAddress = $_POST["mac"]; $cmp->ComputerRealName = $_POST["hostname"]; if ($cmp->Add()) { echo $cmp->ldap_error; } }
function execute($par) { global $wgRequest, $wgOut, $wgFundraiserLPDefaults; // Set the country parameter $country = $wgRequest->getVal('country'); // If no country was passed do a GeoIP lookup if (!$country) { if (function_exists('geoip_country_code_by_name')) { $ip = wfGetIP(); if (IP::isValid($ip)) { $country = geoip_country_code_by_name($ip); } } } // If country still isn't set, set it to the default if (!$country) { $country = $wgFundraiserLPDefaults['country']; } $params = array('country' => $country); // Pass any other params that are set $excludeKeys = array('country', 'title'); foreach ($wgRequest->getValues() as $key => $value) { // Skip the required variables if (!in_array($key, $excludeKeys)) { $params[$key] = $value; } } // Redirect to FundraiserLandingPage $wgOut->redirect($this->getTitleFor('FundraiserLandingPage')->getLocalUrl($params)); }
function dns_add(){ $_POST["nameserver"]=trim($_POST["nameserver"]); $IPClass=new IP(); if(!$IPClass->isValid($_POST["nameserver"])){ echo "{$_POST["nameserver"]} invalid\n"; return; } $nameserver[$_POST["nameserver"]]=true; $q=new mysql_squid_builder(); $q->QUERY_SQL("INSERT INTO dns_servers (dnsserver,zOrder) VALUES ('{$_POST["nameserver"]}','1')"); if(!$q->ok){echo $q->mysql_error;} }
function enable_popup(){ $page=CurrentPageName(); $tpl=new templates(); $sock=new sockets(); $UtDNSEnable=$sock->GET_INFO("UtDNSEnable"); if(!is_numeric($UtDNSEnable)){$UtDNSEnable=0;} $UtDNSIPAddr=$sock->GET_INFO("UtDNSIPAddr"); $ip=new IP(); if(!$ip->isValid($UtDNSIPAddr)){$UtDNSIPAddr=$_SERVER["REMOTE_ADDR"];} $t=time(); $html=" <div style='width:98%' class=form> ".Paragraphe_switch_img("{enable_disable_cloud_protection}", "{enable_disable_cloud_protection_explain}","UtDNSEnable-$t",$UtDNSEnable,null,450)." <table style='width:100%'> <tr> <td class=legend style='font-size:16px'>{redirect_ip_address}:</td> <td>". Field_text("UtDNSIPAddr",$UtDNSIPAddr,"font-size:16px;")."</td> </tr> </table> <div style='width:99%;text-align:right;margin-top:20px'><hr>". button("{apply}","Save$t()",32)."</div> </div> <script> var xSave$t= function (obj) { var results=obj.responseText; if(results.length>5){alert(results);} CacheOff(); Loadjs('squid.restart.php?ApplyConfToo=yes&ask=yes'); } function Save$t(){ var XHR = new XHRConnection(); XHR.appendData('UtDNSEnable',document.getElementById('UtDNSEnable-$t').value); XHR.appendData('UtDNSIPAddr',document.getElementById('UtDNSIPAddr-$t').value); XHR.sendAndLoad('$page', 'POST',xSave$t); } </script> "; echo $tpl->_ENGINE_parse_body($html); }
public function execute() { $lb = wfGetLB(); if ($lb->getServerCount() == 1) { $this->error("This script dumps replication lag times, but you don't seem to have\n" . "a multi-host db server configuration."); } else { $lags = $lb->getLagTimes(); foreach ($lags as $n => $lag) { $host = $lb->getServerName($n); if (IP::isValid($host)) { $ip = $host; $host = gethostbyaddr($host); } else { $ip = gethostbyname($host); } $starLen = min(intval($lag), 40); $stars = str_repeat('*', $starLen); $this->output(sprintf("%10s %20s %3d %s\n", $ip, $host, $lag, $stars)); } } }
public function execute($sub) { global $wgRequest, $wgPriorityCountries; // Pull in query string parameters $language = $wgRequest->getVal('language', 'en'); $this->basic = $wgRequest->getBool('basic'); $country = $wgRequest->getVal('country'); // If no country was passed, try to do GeoIP lookup // Requires php5-geoip package if (!$country && function_exists('geoip_country_code_by_name')) { $ip = wfGetIP(); if (IP::isValid($ip)) { $country = geoip_country_code_by_name($ip); } } if (!$country) { $country = 'US'; // Default } // determine if we are fulfilling a request for a priority country $priority = in_array($country, $wgPriorityCountries); // handle the actual redirect $this->routeRedirect($country, $language, $priority); }
/** * Show the footer section of an ordinary page view */ public function showViewFooter() { global $wgOut, $wgUseTrackbacks; # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page if ($this->mTitle->getNamespace() == NS_USER_TALK && IP::isValid($this->mTitle->getText())) { $wgOut->addWikiMsg('anontalkpagetext'); } # If we have been passed an &rcid= parameter, we want to give the user a # chance to mark this new article as patrolled. $this->showPatrolFooter(); # Trackbacks if ($wgUseTrackbacks) { $this->addTrackbacks(); } }
function postfix_add_network_v2_save() { $tpl = new templates(); if ($_GET["ip_addr"] == null) { echo $tpl->_ENGINE_parse_body('{error} :{address} -> Null! '); return null; } if ($_GET["ip_addr2"] == null) { echo $tpl->_ENGINE_parse_body('{error} :{address} -> Null! '); return null; } include_once 'ressources/class.tcpip.inc'; $ip = new IP(); if (!$ip->isValid($_GET["ip_addr"])) { echo $tpl->_ENGINE_parse_body('{error} :{address} {bad_format} -> ' . $_GET["ip_addr"]); return null; } $cdir = $ip->ip2cidr($_GET["ip_addr"], $_GET["ip_addr2"]); if ($cdir == null) { echo $tpl->_ENGINE_parse_body('{error} :{address} {bad_format} -> ' . $_GET["ip_addr"] . "/" . $_GET["ip_addr2"]); return null; } $main = new main_cf(); writelogs("save new {$cdir} for mynetwork settings", __FUNCTION__, __FILE__); $response = $main->add_my_networks($cdir); if ($response != null) { echo $tpl->_ENGINE_parse_body("{error} :{$response}"); return null; } writelogs("save postfix configuration", __FUNCTION__, __FILE__); $main->save_conf(); writelogs("save postfix configuration done", __FUNCTION__, __FILE__); echo $tpl->_ENGINE_parse_body('{success}'); }
/** * Show the footer section of an ordinary page view */ public function showViewFooter() { # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page if ($this->getTitle()->getNamespace() == NS_USER_TALK && IP::isValid($this->getTitle()->getText())) { $this->getContext()->getOutput()->addWikiMsg('anontalkpagetext'); } # If we have been passed an &rcid= parameter, we want to give the user a # chance to mark this new article as patrolled. $this->showPatrolFooter(); wfRunHooks('ArticleViewFooter', array($this)); }
/** * From an existing Block, get the target and the type of target. * Note that, except for null, it is always safe to treat the target * as a string; for User objects this will return User::__toString() * which in turn gives User::getName(). * * @param string|int|User|null $target * @return array( User|String|null, Block::TYPE_ constant|null ) */ public static function parseTarget($target) { # We may have been through this before if ($target instanceof User) { if (IP::isValid($target->getName())) { return array($target, self::TYPE_IP); } else { return array($target, self::TYPE_USER); } } elseif ($target === null) { return array(null, null); } $target = trim($target); if (IP::isValid($target)) { # We can still create a User if it's an IP address, but we need to turn # off validation checking (which would exclude IP addresses) return array(User::newFromName(IP::sanitizeIP($target), false), Block::TYPE_IP); } elseif (IP::isValidBlock($target)) { # Can't create a User from an IP range return array(IP::sanitizeRange($target), Block::TYPE_RANGE); } # Consider the possibility that this is not a username at all # but actually an old subpage (bug #29797) if (strpos($target, '/') !== false) { # An old subpage, drill down to the user behind it $parts = explode('/', $target); $target = $parts[0]; } $userObj = User::newFromName($target); if ($userObj instanceof User) { # Note that since numbers are valid usernames, a $target of "12345" will be # considered a User. If you want to pass a block ID, prepend a hash "#12345", # since hash characters are not valid in usernames or titles generally. return array($userObj, Block::TYPE_USER); } elseif (preg_match('/^#\\d+$/', $target)) { # Autoblock reference in the form "#12345" return array(substr($target, 1), Block::TYPE_AUTO); } else { # WTF? return array(null, null); } }
function import_file() { $q = new mysql_squid_builder(); $filename = "/usr/share/artica-postfix/ressources/logs/web/nginx.import"; if (!is_file($filename)) { echo "{$filename} no such file\n"; return; } $f = explode("\n", @file_get_contents($filename)); $IpClass = new IP(); while (list($index, $line) = each($f)) { if (trim($line) == null) { continue; } if (strpos($line, ",") == 0) { continue; } $tr = explode(",", $line); if (count($tr) < 2) { continue; } $sourceserver = trim($tr[0]); $sitename = trim($tr[1]); if (!isset($tr[2])) { $tr[2] = 0; } if (!isset($tr[3])) { $tr[3] = null; } $ssl = $tr[2]; $forceddomain = $tr[3]; if (!preg_match("#(.+?):([0-9]+)#", $sourceserver, $re)) { if ($ssl == 1) { $sourceserver_port = 443; } if ($ssl == 0) { $sourceserver_port = 80; } } else { $sourceserver = trim($re[1]); $sourceserver_port = $re[2]; } if (!preg_match("#(.+?):([0-9]+)#", $sitename, $re)) { if ($ssl == 1) { $sitename_port = 443; } if ($ssl == 0) { $sitename_port = 80; } } else { $sitename = trim($re[1]); $sitename_port = $re[2]; } if ($forceddomain != null) { $title_source = $forceddomain; } else { $title_source = $sourceserver; } echo "Importing {$sitename} ({$sitename_port}) -> {$sourceserver} ({$sourceserver_port})\n"; // On cherche la source: if ($sitename == null) { echo "Local sitename is null\n"; continue; } if ($sourceserver == null) { echo "Source is null\n"; continue; } if (!$IpClass->isValid($sourceserver)) { $tcp = gethostbyname($sourceserver); if (!$IpClass->isValid($tcp)) { echo "Source {$sourceserver} cannot be resolved\n"; continue; } } $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT ID FROM reverse_sources WHERE ipaddr='{$sourceserver}' AND `port`='{$sourceserver_port}'")); $IDS = intval($ligne["ID"]); if ($IDS == 0) { $sql = "INSERT IGNORE INTO `reverse_sources` (`servername`,`ipaddr`,`port`,`ssl`,`enabled`,`forceddomain`)\n\t\t\tVALUES ('{$title_source}','{$sourceserver}','{$sourceserver_port}','{$ssl}',1,'{$forceddomain}')"; $q->QUERY_SQL($sql); $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT ID FROM reverse_sources WHERE ipaddr='{$sourceserver}' AND `port`='{$sourceserver_port}'")); $IDS = intval($ligne["ID"]); } if ($IDS == 0) { echo "Failed to add {$sourceserver}/{$sourceserver_port}/{$forceddomain}\n"; continue; } // On attaque le site web: $ligne = mysql_fetch_array($q->QUERY_SQL("SELECT servername,cache_peer_id FROM reverse_www WHERE servername='{$sitename}'")); if (trim($ligne["servername"] != null)) { echo "{$sitename} already exists on cache ID : {$ligne["cache_peer_id"]}/{$IDS}\n"; if ($ligne["cache_peer_id"] != $IDS) { $q->QUERY_SQL("UPDATE reverse_www SET `cache_peer_id`={$IDS} WHERE servername='{$sitename}'"); } continue; } $sql = "INSERT IGNORE INTO `reverse_www` (`servername`,`cache_peer_id`,`port`,`ssl`) VALUES\n\t\t('{$sitename}','{$IDS}','{$sitename_port}','{$ssl}')"; $q->QUERY_SQL($sql); if (!$q->ok) { echo $q->mysql_error; continue; } } $unix = new unix(); $nohup = $unix->find_program("nohup"); $php5 = $unix->LOCATE_PHP5_BIN(); shell_exec("{$nohup} {$php5} " . __FILE__ . " --restart >/dev/null 2>&1 &"); }
/** * Show the footer section of an ordinary page view */ public function showViewFooter() { # check if we're displaying a [[User talk:x.x.x.x]] anonymous talk page if ($this->getTitle()->getNamespace() == NS_USER_TALK && IP::isValid($this->getTitle()->getText())) { $this->getContext()->getOutput()->addWikiMsg('anontalkpagetext'); } // Show a footer allowing the user to patrol the shown revision or page if possible $patrolFooterShown = $this->showPatrolFooter(); Hooks::run('ArticleViewFooter', array($this, $patrolFooterShown)); }
function instances_duplicate_perform(){ $tpl=new templates(); $tcp=new IP(); $q=new mysql(); $sock=new sockets(); $instance_hostname=$_GET["hostname"]; $instance_src_hostname=$_GET["src"]; $main=new maincf_multi($instance_src_hostname); $novirtual=false; $instance_ip=$_GET["ip"]; $instance_ip_src=$main->ip_addr; if($instance_ip_src==null){echo $tpl->javascript_parse_text("\"$instance_src_hostname\" No such instance");return;} $organization=$_GET["ou"]; if($organization==null){ echo $tpl->javascript_parse_text("{error_choose_organization}");return;} if(trim($instance_hostname)==null){echo $tpl->javascript_parse_text("{instance_server_name}: NULL");return;} if(!$tcp->isValid($instance_ip)){echo $tpl->javascript_parse_text("{ipaddr}: \"$instance_ip\" Invalid");return;} if(!$tcp->isValid($instance_ip_src)){echo $tpl->javascript_parse_text("{ipaddr}: \"$instance_ip_src\" Invalid");return;} $main=new maincf_multi(null,null,$instance_ip); if($main->myhostname<>null){echo $tpl->javascript_parse_text("{ipaddr}: \"$instance_ip\" {already_used} -> $main->myhostname");return;} $main=new maincf_multi($instance_hostname,null,null); if($main->ip_addr<>null){echo $tpl->javascript_parse_text("{hostname}: \"$instance_hostname\" {already_used} -> $main->ip_addr");return;} $sql="SELECT ipaddr FROM nics_virtuals WHERE ipaddr='$instance_ip'"; $ligne=mysql_fetch_array($q->QUERY_SQL($sql,"artica_backup")); if($ligne["ipaddr"]<>null){echo $tpl->javascript_parse_text("{ipaddr}: \"$instance_ip\" {already_used} -> {virtual_interfaces}");return;} $sql="SELECT ipaddr FROM nics_vlan WHERE ipaddr='$instance_ip'"; $ligne=mysql_fetch_array($q->QUERY_SQL($sql,"artica_backup")); if($ligne["ipaddr"]<>null){ writelogs("Associated to a vlan -> unset Contruct virtuals addresses",__FUNCTION__,__FILE__,__LINE__); $novirtual=true; } $PING=trim($sock->getFrameWork("cmd.php?ping=".urlencode($instance_ip))); if($PING=="TRUE"){ echo $tpl->javascript_parse_text("$instance_ip:\n{ip_already_exists_in_the_network}"); return; } if(!$novirtual){ writelogs("No virtual: FALSE",__FUNCTION__,__FILE__,__LINE__); $instance_ip_tbl=explode(".",$instance_ip); unset($instance_ip_tbl[count($instance_ip_tbl)-1]); $net=@implode(".",$instance_ip_tbl); writelogs("virtual: net -> $net",__FUNCTION__,__FILE__,__LINE__); $sql="SELECT * FROM nics_virtuals WHERE ipaddr LIKE '$net.%' ORDER BY ID DESC LIMIT 0,1"; $ligne=mysql_fetch_array($q->QUERY_SQL($sql,"artica_backup")); if($ligne["ipaddr"]==null){echo $tpl->javascript_parse_text("{ipaddr}: \"$net*\" {no_such_interfaces} -> {virtual_interfaces}\n{you_need_to_create_virtual_ip_first}");return;} writelogs("$net.* {$ligne["nic"]} -> $instance_ip/{$ligne["netmask"]}",__FUNCTION__,__FILE__,__LINE__); $sql="INSERT INTO nics_virtuals (nic,org,ipaddr,netmask,cdir,gateway) VALUES('{$ligne["nic"]}','$organization','$instance_ip','{$ligne["netmask"]}','{$ligne["cdir"]}','{$ligne["gateway"]}');"; $q=new mysql(); $q->QUERY_SQL($sql,"artica_backup"); if(!$q->ok){ writelogs("virtual:ERROR $q->mysql_error",__FUNCTION__,__FILE__,__LINE__); echo $q->mysql_error; return; } } writelogs("All are OK -> starting importation",__FUNCTION__,__FILE__,__LINE__); $sql="SELECT `key`,`value`,`ValueTEXT`,`uuid` FROM `postfix_multi` WHERE `ip_address`='$instance_ip_src'"; $results=$q->QUERY_SQL($sql,"artica_backup"); while($ligne=@mysql_fetch_array($results,MYSQL_ASSOC)){ $key=$ligne["key"]; $value=$ligne["value"]; $ValueTEXT=$ligne["ValueTEXT"]; $uuid=$ligne["uuid"]; if($key=="inet_interfaces"){continue;} if($key=="myhostname"){continue;} $value=addslashes($value); $ValueTEXT=addslashes($ValueTEXT); $sql="INSERT INTO `postfix_multi` (`key`,`value`,`ValueTEXT`,`uuid`,`ou`,`ip_address`) VALUES('$key','$value','$ValueTEXT','$uuid','$organization','$instance_ip')"; writelogs($sql,__FUNCTION__,__FILE__,__LINE__); $q->QUERY_SQL($sql,"artica_backup"); if(!$q->ok){ echo $q->mysql_error; FailedIP($instance_ip); return; } } $sql="INSERT INTO `postfix_multi` (`key`,`value`,`uuid`,`ou`,`ip_address`) VALUES('inet_interfaces','$instance_ip','$uuid','$organization','$instance_ip')"; writelogs($sql,__FUNCTION__,__FILE__,__LINE__); $q->QUERY_SQL($sql,"artica_backup"); if(!$q->ok){echo $q->mysql_error;FailedIP($instance_ip);return;} $sql="INSERT INTO `postfix_multi` (`key`,`value`,`uuid`,`ou`,`ip_address`) VALUES('myhostname','$instance_hostname','$uuid','$organization','$instance_ip')"; writelogs($sql,__FUNCTION__,__FILE__,__LINE__); $q->QUERY_SQL($sql,"artica_backup"); if(!$q->ok){echo $q->mysql_error;FailedIP($instance_ip);return;} $main=new maincf_multi(null,null,$instance_ip); $main->SET_VALUE("VirtualHostNameToChange",$instance_hostname); }
/** * @param TemporaryPasswordAuthenticationRequest $req * @return \Status */ protected function sendPasswordResetEmail(TemporaryPasswordAuthenticationRequest $req) { $user = User::newFromName($req->username); if (!$user) { return \Status::newFatal('noname'); } $userLanguage = $user->getOption('language'); $callerIsAnon = \IP::isValid($req->caller); $callerName = $callerIsAnon ? $req->caller : User::newFromName($req->caller)->getName(); $passwordMessage = wfMessage('passwordreset-emailelement', $user->getName(), $req->password)->inLanguage($userLanguage); $emailMessage = wfMessage($callerIsAnon ? 'passwordreset-emailtext-ip' : 'passwordreset-emailtext-user')->inLanguage($userLanguage); $emailMessage->params($callerName, $passwordMessage->text(), 1, '<' . \Title::newMainPage()->getCanonicalURL() . '>', round($this->newPasswordExpiry / 86400)); $emailTitle = wfMessage('passwordreset-emailtitle')->inLanguage($userLanguage); return $user->sendMail($emailTitle->text(), $emailMessage->text()); }
function GET_CATEGORIES($sitename, $nocache = false, $nok9 = false, $noheuristic = false, $noArticaDB = false) { $pagename = null; if (function_exists("CurrentPageName")) { $pagename = CurrentPageName(); } $t = time(); if ($pagename == 'exec.cleancloudcatz.php') { $noArticaDB = true; } if (trim($sitename) == null) { return; } $sitename = strtolower(trim($sitename)); if (preg_match("#^www\\.(.+)#", $sitename, $re)) { $sitename = $re[1]; } if (preg_match("#^\\.(.+)#", $sitename, $re)) { $sitename = $re[1]; } if (preg_match("#^\\*\\.(.+)#", $sitename, $re)) { $sitename = $re[1]; } if (substr($sitename, 0, 1) == ".") { $sitename = substr($sitename, 1, strlen($sitename)); } if (trim($sitename) == null) { return; } if (preg_match("#^www[0-9]+\\.(.+)#", $sitename, $re)) { $sitename = $re[1]; } $IpClass = new IP(); if ($IpClass->isValid($sitename)) { if (isset($GLOBALS["IPCACHE"][$sitename])) { $sitename = gethostbyaddr($sitename); $GLOBALS["IPCACHE"][$sitename] = $sitename; } } $sitename = trim(strtolower($sitename)); if (function_exists("idn_to_ascii")) { $sitename = @idn_to_ascii($sitename, "UTF-8"); } if (!isset($GLOBALS["BlueCoatKey"])) { $sock = new sockets(); $GLOBALS["BlueCoatKey"] = trim($sock->GET_INFO("BlueCoatKey")); } $GLOBALS["CATEGORIZELOGS"] = array(); if (isset($GLOBALS["GET_CATEGORIES_MEMORY"][$sitename])) { return $GLOBALS["GET_CATEGORIES_MEMORY"][$sitename]; } $cat = array(); $cattmp = array(); if (!isset($GLOBALS["getpartOnly"])) { $GLOBALS["getpartOnly"] = $this->GetFamilySitestt(null, true); } if (isset($GLOBALS["getpartOnly"][$sitename])) { if ($GLOBALS["getpartOnly"][$sitename]) { return null; } } if (strpos(" {$sitename}", ".") == 0) { $this->categorize_reaffected($sitename); $GLOBALS["CATEGORIZELOGS-COUNT"]++; $GLOBALS["GET_CATEGORIES_MEMORY"][$sitename] = "reaffected"; $this->categorize_temp($sitename, "reaffected"); return "reaffected"; } if ($cat != null) { if ($cat == "unknown") { return null; } return $cat; } $familysite = $this->GetFamilySites($sitename); if (!$noArticaDB) { $t1 = time(); if ($GLOBALS["VERBOSE"]) { echo " ********* GET_CATEGORIES_DB ( {$sitename} ) *********\n"; } if ($GLOBALS["OUTPUT"]) { echo date("H:i:s") . " {$sitename} -> GET_CATEGORIES_DB({$sitename})\n"; } $cat = $this->GET_CATEGORIES_DB($sitename); if ($cat != null) { if (isset($_REQUEST["WEBTESTS"])) { echo "ArticaDB: "; } $this->categorize_temp($sitename, $cat); return $cat; } if ($GLOBALS["VERBOSE"]) { echo " ********* GET_CATEGORIES_DB ( {$sitename} ) " . distanceOfTimeInWords($t1, time(), true) . "\n"; } } if (!$noheuristic) { $t1 = time(); if ($GLOBALS["VERBOSE"]) { echo " ********* GET_CATEGORIES_HEURISTICS ( {$sitename} ) *********\n"; } if ($GLOBALS["OUTPUT"]) { echo date("H:i:s") . " {$sitename} -> GET_CATEGORIES_HEURISTICS({$sitename})\n"; } if (!isset($GLOBALS["SquidAppendDomain"])) { $sock = new sockets(); $SquidAppendDomain = trim($sock->GET_INFO("SquidAppendDomain")); $GLOBALS["SquidAppendDomain"] = trim($sock->GET_INFO("SquidAppendDomain")); if ($GLOBALS["SquidAppendDomain"] == null) { $MainArray = unserialize(base64_decode($sock->GET_INFO("resolvConf"))); $GLOBALS["SquidAppendDomain"] = trim($MainArray["DOMAINS1"]); if ($GLOBALS["SquidAppendDomain"] == null) { $GLOBALS["SquidAppendDomain"] = "localhost.local"; } } } if ($GLOBALS["SquidAppendDomain"] != null) { $domain = str_replace(".", "\\.", $GLOBALS["SquidAppendDomain"]); if (preg_match("#\\.{$domain}\$#", $GLOBALS["SquidAppendDomain"])) { return "internal"; } } $cat = $this->GET_CATEGORIES_HEURISTICS($sitename); if ($cat != null) { $this->categorize_temp($sitename, $cat); return $cat; } if ($GLOBALS["VERBOSE"]) { echo " ********* GET_CATEGORIES_HEURISTICS ( {$sitename} ) " . distanceOfTimeInWords($t1, time(), true) . "\n"; } } if ($GLOBALS["OUTPUT"]) { echo date("H:i:s") . " {$sitename} -> GET_CATEGORIES_GOOGLE_SAFE({$sitename})\n"; } $t1 = time(); $cat = $this->GET_CATEGORIES_GOOGLE_SAFE($sitename); if ($cat != null) { if (isset($_REQUEST["WEBTESTS"])) { echo "Google: "; } $this->categorize($sitename, $cat); $this->categorize_temp($sitename, $cat); return $cat; } if (!$nok9) { if ($GLOBALS["OUTPUT"]) { echo date("H:i:s") . " {$sitename} -> GET_CATEGORIES_K9({$sitename})\n"; } $cat = $this->GET_CATEGORIES_K9($sitename); if ($cat != null) { $this->categorize($sitename, $cat); $this->categorize_temp($sitename, $cat); return $cat; } } if ($IpClass->isValid($sitename)) { $this->categorize_temp($sitename, null); return null; } if ($GLOBALS["OUTPUT"]) { echo date("H:i:s") . " {$sitename} -> GET_CATEGORIES_K9({$sitename})\n"; } $cat = $this->GET_CATEGORIES_REAFFECTED($sitename); $this->categorize_temp($sitename, $cat); $this->cloudlogs("Cannot categorize {$sitename} / {$cat}"); if ($GLOBALS["VERBOSE"]) { $took = distanceOfTimeInWords($t, time(), true); echo "GET_CATEGORIES({$sitename}) {$took}<br>\n"; } return $cat; }
/** * Roughly increments the cache misses in the last hour by unique visitors * @param WebRequest $request * @return void */ public function incrMissesRecent(WebRequest $request) { if (mt_rand(0, self::MISS_FACTOR - 1) == 0) { $cache = ObjectCache::getLocalClusterInstance(); # Get a large IP range that should include the user even if that # person's IP address changes $ip = $request->getIP(); if (!IP::isValid($ip)) { return; } $ip = IP::isIPv6($ip) ? IP::sanitizeRange("{$ip}/32") : IP::sanitizeRange("{$ip}/16"); # Bail out if a request already came from this range... $key = wfMemcKey(get_class($this), 'attempt', $this->mType, $this->mKey, $ip); if ($cache->get($key)) { return; // possibly the same user } $cache->set($key, 1, self::MISS_TTL_SEC); # Increment the number of cache misses... $key = $this->cacheMissKey(); if ($cache->get($key) === false) { $cache->set($key, 1, self::MISS_TTL_SEC); } else { $cache->incr($key); } } }
/** * @return bool */ public function submit() { $this->parent->setVarsFromRequest(array('_RightsProfile', '_LicenseCode', 'wgEnableEmail', 'wgPasswordSender', 'wgEnableUploads', 'wgLogo', 'wgEnableUserEmail', 'wgEnotifUserTalk', 'wgEnotifWatchlist', 'wgEmailAuthentication', 'wgMainCacheType', '_MemCachedServers', 'wgUseInstantCommons', 'wgDefaultSkin')); $retVal = true; if (!array_key_exists($this->getVar('_RightsProfile'), $this->parent->rightsProfiles)) { reset($this->parent->rightsProfiles); $this->setVar('_RightsProfile', key($this->parent->rightsProfiles)); } $code = $this->getVar('_LicenseCode'); if ($code == 'cc-choose') { if (!$this->getVar('_CCDone')) { $this->parent->showError('config-cc-not-chosen'); $retVal = false; } } elseif (array_key_exists($code, $this->parent->licenses)) { // Messages: // config-license-cc-by, config-license-cc-by-sa, config-license-cc-by-nc-sa, // config-license-cc-0, config-license-pd, config-license-gfdl, config-license-none, // config-license-cc-choose $entry = $this->parent->licenses[$code]; if (isset($entry['text'])) { $this->setVar('wgRightsText', $entry['text']); } else { $this->setVar('wgRightsText', wfMessage('config-license-' . $code)->text()); } $this->setVar('wgRightsUrl', $entry['url']); $this->setVar('wgRightsIcon', $entry['icon']); } else { $this->setVar('wgRightsText', ''); $this->setVar('wgRightsUrl', ''); $this->setVar('wgRightsIcon', ''); } $skinsAvailable = $this->parent->findExtensions('skins'); $skinsToInstall = array(); foreach ($skinsAvailable as $skin) { $this->parent->setVarsFromRequest(array("skin-{$skin}")); if ($this->getVar("skin-{$skin}")) { $skinsToInstall[] = $skin; } } $this->parent->setVar('_Skins', $skinsToInstall); if (!$skinsToInstall && $skinsAvailable) { $this->parent->showError('config-skins-must-enable-some'); $retVal = false; } $defaultSkin = $this->getVar('wgDefaultSkin'); $skinsToInstallLowercase = array_map('strtolower', $skinsToInstall); if ($skinsToInstall && array_search($defaultSkin, $skinsToInstallLowercase) === false) { $this->parent->showError('config-skins-must-enable-default'); $retVal = false; } $extsAvailable = $this->parent->findExtensions(); $extsToInstall = array(); foreach ($extsAvailable as $ext) { $this->parent->setVarsFromRequest(array("ext-{$ext}")); if ($this->getVar("ext-{$ext}")) { $extsToInstall[] = $ext; } } $this->parent->setVar('_Extensions', $extsToInstall); if ($this->getVar('wgMainCacheType') == 'memcached') { $memcServers = explode("\n", $this->getVar('_MemCachedServers')); if (!$memcServers) { $this->parent->showError('config-memcache-needservers'); $retVal = false; } foreach ($memcServers as $server) { $memcParts = explode(":", $server, 2); if (!isset($memcParts[0]) || !IP::isValid($memcParts[0]) && gethostbyname($memcParts[0]) == $memcParts[0]) { $this->parent->showError('config-memcache-badip', $memcParts[0]); $retVal = false; } elseif (!isset($memcParts[1])) { $this->parent->showError('config-memcache-noport', $memcParts[0]); $retVal = false; } elseif ($memcParts[1] < 1 || $memcParts[1] > 65535) { $this->parent->showError('config-memcache-badport', 1, 65535); $retVal = false; } } } return $retVal; }
/** * Process the form. At this point we know that the user passes all the criteria in * userCanExecute(), and if the data array contains 'Username', etc, then Username * resets are allowed. * @param $data array * @return Bool|Array */ public function onSubmit(array $data) { global $wgAuth; if (isset($data['Domain'])) { if ($wgAuth->validDomain($data['Domain'])) { $wgAuth->setDomain($data['Domain']); } else { $wgAuth->setDomain('invaliddomain'); } } if (isset($data['Username']) && $data['Username'] !== '') { $method = 'username'; $users = array(User::newFromName($data['Username'])); } elseif (isset($data['Email']) && $data['Email'] !== '' && Sanitizer::validateEmail($data['Email'])) { $method = 'email'; $res = wfGetDB(DB_SLAVE)->select('user', '*', array('user_email' => $data['Email']), __METHOD__); if ($res) { $users = array(); foreach ($res as $row) { $users[] = User::newFromRow($row); } } else { // Some sort of database error, probably unreachable throw new MWException('Unknown database error in ' . __METHOD__); } } else { // The user didn't supply any data return false; } // Check for hooks (captcha etc), and allow them to modify the users list $error = array(); if (!wfRunHooks('SpecialPasswordResetOnSubmit', array(&$users, $data, &$error))) { return array($error); } if (count($users) == 0) { if ($method == 'email') { // Don't reveal whether or not an email address is in use return true; } else { return array('noname'); } } $firstUser = $users[0]; if (!$firstUser instanceof User || !$firstUser->getID()) { return array(array('nosuchuser', $data['Username'])); } // Check against the rate limiter if ($this->getUser()->pingLimiter('mailpassword')) { throw new ThrottledError(); } // Check against password throttle foreach ($users as $user) { if ($user->isPasswordReminderThrottled()) { global $wgPasswordReminderResendTime; # Round the time in hours to 3 d.p., in case someone is specifying # minutes or seconds. return array(array('throttled-mailpassword', round($wgPasswordReminderResendTime, 3))); } } global $wgNewPasswordExpiry; // All the users will have the same email address if ($firstUser->getEmail() == '') { // This won't be reachable from the email route, so safe to expose the username return array(array('noemail', $firstUser->getName())); } // We need to have a valid IP address for the hook, but per bug 18347, we should // send the user's name if they're logged in. $ip = wfGetIP(); if (!$ip) { return array('badipaddress'); } $caller = $this->getUser(); wfRunHooks('User::mailPasswordInternal', array(&$caller, &$ip, &$firstUser)); $username = $caller->getName(); $msg = IP::isValid($username) ? 'passwordreset-emailtext-ip' : 'passwordreset-emailtext-user'; // Send in the user's language; which should hopefully be the same $userLanguage = $firstUser->getOption('language'); $passwords = array(); foreach ($users as $user) { $password = $user->randomPassword(); $user->setNewpassword($password); $user->saveSettings(); $passwords[] = wfMessage('passwordreset-emailelement', $user->getName(), $password)->inLanguage($userLanguage)->plain(); // We'll escape the whole thing later } $passwordBlock = implode("\n\n", $passwords); $body = wfMessage($msg)->inLanguage($userLanguage); $body->params($username, $passwordBlock, count($passwords), Title::newMainPage()->getCanonicalUrl(), round($wgNewPasswordExpiry / 86400)); $title = wfMessage('passwordreset-emailtitle'); $result = $firstUser->sendMail($title->text(), $body->text()); if ($result->isGood()) { return true; } else { // @todo FIXME: The email didn't send, but we have already set the password throttle // timestamp, so they won't be able to try again until it expires... :( return array(array('mailerror', $result->getMessage())); } }
function build() { $sock = new sockets(); $unix = new unix(); $nohup = $unix->find_program("nohup"); $php5 = $unix->LOCATE_PHP5_BIN(); $q = new mysql(); $DisablePowerDnsManagement = $sock->GET_INFO("DisablePowerDnsManagement"); if (!is_numeric($DisablePowerDnsManagement)) { $DisablePowerDnsManagement = 0; } if ($DisablePowerDnsManagement == 1) { return; } @mkdir("/etc/powerdns/pdns.d", 0755, true); $PowerDNSLogLevel = $sock->GET_INFO("PowerDNSLogLevel"); $PowerDNSMySQLEngine = $sock->GET_INFO("PowerDNSMySQLEngine"); $PowerUseGreenSQL = $sock->GET_INFO("PowerUseGreenSQL"); $PowerDisableDisplayVersion = $sock->GET_INFO("PowerDisableDisplayVersion"); $PowerChroot = $sock->GET_INFO("PowerChroot"); $PowerActHasMaster = $sock->GET_INFO("PowerActHasMaster"); $PowerDNSDNSSEC = $sock->GET_INFO("PowerDNSDNSSEC"); $PowerDNSDisableLDAP = $sock->GET_INFO("PowerDNSDisableLDAP"); $PowerDNSPublicMode = $sock->GET_INFO("PowerDNSPublicMode"); $PowerActAsSlave = $sock->GET_INFO("PowerActAsSlave"); $PdnsNoWriteConf = $sock->GET_INFO("PdnsNoWriteConf"); $PowerSkipCname = $sock->GET_INFO("PowerSkipCname"); $PDSNInUfdb = $sock->GET_INFO("PDSNInUfdb"); $SquidActHasReverse = $sock->GET_INFO("SquidActHasReverse"); $EnableUfdbGuard = $sock->GET_INFO("EnableUfdbGuard"); $PowerDNSMySQLType = $sock->GET_INFO("PowerDNSMySQLType"); $PowerDNSMySQLRemotePort = $sock->GET_INFO("PowerDNSMySQLRemotePort"); $EnablePDNSRecurseRestrict = $sock->GET_INFO("EnablePDNSRecurseRestrict"); $PdnsHotSpot = $sock->GET_INFO("PdnsHotSpot"); $PowerDNSMySQLRemoteServer = $sock->GET_INFO("PowerDNSMySQLRemoteServer"); $PdnsHotSpot = $sock->GET_INFO("PdnsHotSpot"); $PowerDNSMySQLRemoteAdmin = $sock->GET_INFO("PowerDNSMySQLRemoteAdmin"); $PowerDNSMySQLRemotePassw = $sock->GET_INFO("PowerDNSMySQLRemotePassw"); if (!is_numeric($PowerDNSLogLevel)) { $PowerDNSLogLevel = 1; } if (!is_numeric($PowerDNSMySQLEngine)) { $PowerDNSMySQLEngine = 1; } if (!is_numeric($PowerUseGreenSQL)) { $PowerUseGreenSQL = 0; } if (!is_numeric($PowerDisableDisplayVersion)) { $PowerDisableDisplayVersion = 0; } if (!is_numeric($PowerChroot)) { $PowerChroot = 0; } if (!is_numeric($PowerActHasMaster)) { $PowerActHasMaster = 0; } if (!is_numeric($PowerDNSDNSSEC)) { $PowerDNSDNSSEC = 0; } if (!is_numeric($PowerDNSDisableLDAP)) { $PowerDNSDisableLDAP = 1; } if (!is_numeric($PowerDNSPublicMode)) { $PowerDNSPublicMode = 0; } if (!is_numeric($PowerActAsSlave)) { $PowerActAsSlave = 0; } if (!is_numeric($PdnsNoWriteConf)) { $PdnsNoWriteConf = 0; } if (!is_numeric($PowerSkipCname)) { $PowerSkipCname = 0; } if (!is_numeric($PDSNInUfdb)) { $PDSNInUfdb = 0; } if (!is_numeric($SquidActHasReverse)) { $SquidActHasReverse = 0; } if (!is_numeric($EnableUfdbGuard)) { $EnableUfdbGuard = 0; } if (!is_numeric($PowerDNSMySQLType)) { $PowerDNSMySQLType = 1; } if (!is_numeric($PowerDNSMySQLRemotePort)) { $PowerDNSMySQLRemotePort = 3306; } if (!is_numeric($EnablePDNSRecurseRestrict)) { $EnablePDNSRecurseRestrict = 0; } $LaunchPipe = 0; $pipe = ''; if ($SquidActHasReverse == 1) { $PDSNInUfdb = 0; } if ($EnableUfdbGuard == 0) { $PDSNInUfdb = 0; } if (!is_file("/usr/bin/ufdbgclient")) { $PDSNInUfdb = 0; } $q = new mysql(); $database_admin = $q->mysql_admin; $database_password = $q->mysql_password; if ($database_admin == null) { $database_admin = 'root'; } if ($PDSNInUfdb == 1) { $LaunchPipe = 1; } if ($PdnsHotSpot == 1) { $LaunchPipe = 1; } if ($LaunchPipe == 1) { $launch[] = 'pipe'; } $recursor = "127.0.0.1:1553"; $recursor_bin = $unix->find_program("pdns_recursor"); if (!is_file($recursor_bin)) { $resolv = new resolv_conf(); $IpClass = new IP(); $rr = array(); if ($resolv->MainArray["DNS1"] == "127.0.0.1") { $resolv->MainArray["DNS1"] = null; } if ($resolv->MainArray["DNS2"] == "127.0.0.1") { $resolv->MainArray["DNS2"] = null; } if ($resolv->MainArray["DNS3"] == "127.0.0.1") { $resolv->MainArray["DNS3"] = null; } if (!$IpClass->isValid($resolv->MainArray["DNS1"])) { $resolv->MainArray["DNS1"] = null; } if (!$IpClass->isValid($resolv->MainArray["DNS2"])) { $resolv->MainArray["DNS2"] = null; } if (!$IpClass->isValid($resolv->MainArray["DNS3"])) { $resolv->MainArray["DNS3"] = null; } if ($resolv->MainArray["DNS1"] != null) { $rr[] = $resolv->MainArray["DNS1"]; } if ($resolv->MainArray["DNS2"] != null) { $rr[] = $resolv->MainArray["DNS2"]; } if ($resolv->MainArray["DNS3"] != null) { $rr[] = $resolv->MainArray["DNS3"]; } $recursor = $rr[0]; } // PowerSkipCname: Do not perform CNAME indirection for each query if ($PdnsNoWriteConf == 1) { if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} PdnsNoWriteConf is enabled, skip the config and aborting pdns.conf\n"; } return; } $pdnssec_bin = $unix->find_program("pdnssec"); if (!is_file($pdnssec_bin)) { $PowerDNSDNSSEC = 0; } $PowerDNSListenAddrDefault = true; $cdirlist[] = '127.0.0.0/8'; $cdirlist[] = '127.0.0.1'; $PowerDNSListenAddr = $sock->getFrameWork("PowerDNSListenAddr"); $t = array(); $ipA = explode("\n", $PowerDNSListenAddr); while (list($line2, $ip) = each($ipA)) { if (trim($ip) == null) { continue; } if (!$unix->isIPAddress($ip)) { continue; } $t[$ip] = $ip; } if (count($t) == 0) { $ips = new networking(); $ipz = $ips->ALL_IPS_GET_ARRAY(); while (list($ip, $line2) = each($ipz)) { $t[$ip] = $ip; } } $LOCAL_ADDRESSES = array(); unset($t["127.0.0.1"]); while (list($a, $b) = each($t)) { if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} listen: {$a}\n"; } $LOCAL_ADDRESSES[] = $a; $cdirlist[] = $a; } $iplistV6 = array(); $RecursoriplistV6 = array(); $RecursoripAllowFrom = array(); $PowerDNSListenAddrV6 = explode("\n", $sock->GET_INFO("PowerDNSListenAddrV6")); while (list($field, $value) = each($PowerDNSListenAddrV6)) { if (trim($value) == null) { continue; } $iplistV6[] = $value; $RecursoriplistV6[] = "[" . $value . "]"; $RecursoripAllowFrom[] = $value; } $launch[] = 'gmysql'; if ($PowerDNSDisableLDAP == 0) { $launch[] = 'ldap'; } $f = array(); if ($EnablePDNSRecurseRestrict == 1) { $t = array(); $sql = "SELECT * FROM pdns_restricts"; $results = $q->QUERY_SQL($sql, "artica_backup"); while ($ligne = mysql_fetch_assoc($results)) { $addr = trim($ligne["address"]); if ($addr == null) { continue; } $t[] = $addr; } if (count($t) > 0) { $f[] = "allow-recursion=" . @implode(",", $t); } } $f[] = "#allow-recursion=0.0.0.0/0 "; $f[] = "#allow-recursion-override=on"; $f[] = "cache-ttl=20"; if ($PowerChroot == 1) { if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} is chrooted\n"; } $f[] = "chroot=./"; } if ($PowerActHasMaster == 1) { if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} Act has master\n"; } $f[] = "master=yes"; } if ($PowerActAsSlave == 1) { if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} Act has Slave\n"; } $f[] = "slave=yes"; } $f[] = "config-dir=/etc/powerdns"; $f[] = "# config-name="; $f[] = "# control-console=no"; $f[] = "daemon=yes"; $f[] = "# default-soa-name=a.misconfigured.powerdns.server"; $f[] = "disable-axfr=no"; $f[] = "# disable-tcp=no"; $f[] = "# distributor-threads=3"; $f[] = "# fancy-records=no"; $f[] = "guardian=yes"; $f[] = "launch=" . @implode(",", $launch); if ($PDSNInUfdb == 1) { @chmod("/usr/share/artica-postfix/exec.pdns.pipe.php", 0777); $f[] = "pipe-command=/usr/share/artica-postfix/exec.pdns.pipe.php"; $f[] = "pipebackend-abi-version=2"; $f[] = "distributor-threads=2"; } if ($PdnsHotSpot == 1) { if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} HotSpot engine...\n"; } @chmod("/usr/share/artica-postfix/exec.pdns.pipe.php", 0777); $f[] = "pipe-command=/usr/share/artica-postfix/exec.pdns.pipe.php"; $f[] = "pipebackend-abi-version=2"; $f[] = "distributor-threads=2"; } //$f[]="lazy-recursion=yes"; $f[] = "#local-address=0.0.0.0"; $f[] = "local-address=" . @implode(",", $LOCAL_ADDRESSES); if (count($iplistV6) > 0) { $iplistV6[] = "::1"; $f[] = "local-ipv6=" . @implode(",", $iplistV6); } //$f[]="query-local-address6=::1"; $f[] = "local-port=53"; $f[] = "log-dns-details=on"; //$f[]="logfile=/var/log/pdns.log"; $f[] = "# logging-facility="; $f[] = "loglevel={$PowerDNSLogLevel}"; $f[] = "# max-queue-length=5000"; $f[] = "# max-tcp-connections=10"; $MODULES_DIR = MODULES_DIR(); if ($MODULES_DIR != null) { $f[] = "module-dir={$MODULES_DIR}"; } $f[] = "# negquery-cache-ttl=60"; $f[] = "out-of-zone-additional-processing=yes"; $f[] = "# query-cache-ttl=20"; $f[] = "query-logging=yes"; $f[] = "# queue-limit=1500"; $f[] = "# receiver-threads=1"; $f[] = "# recursive-cache-ttl=10"; $f[] = "recursor={$recursor}"; // $f[] = "#setgid=pdns"; $f[] = "#setuid=pdns"; //$f[]="skip-cname=yes"; $f[] = "# slave-cycle-interval=60"; $f[] = "# smtpredirector=a.misconfigured.powerdns.smtp.server"; $f[] = "# soa-minimum-ttl=3600"; $f[] = "# soa-refresh-default=10800"; $f[] = "# soa-retry-default=3600"; $f[] = "# soa-expire-default=604800"; $f[] = "# soa-serial-offset=0"; $f[] = "socket-dir=/var/run/pdns"; $f[] = "# strict-rfc-axfrs=no"; $f[] = "# urlredirector=127.0.0.1"; //$f[]="use-logfile=yes"; $f[] = "webserver=yes"; $f[] = "webserver-address=127.0.0.1"; $f[] = "webserver-password="******"webserver-port=8081"; $f[] = "webserver-print-arguments=no"; //if PowerSkipCname=0 then $f[]="skip-cname=no') else $f[]="skip-cname=yes"; $f[] = "# wildcard-url=no"; $f[] = "# wildcards="; if ($PowerDisableDisplayVersion == 0) { $f[] = "version-string=powerdns"; } else { $f[] = "version-string=nope"; } if ($PowerDNSMySQLType == 1) { if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} MySQL /var/run/mysqld/mysqld.sock@{$database_admin}\n"; } $G[] = "gmysql-socket=/var/run/mysqld/mysqld.sock"; $G[] = "gmysql-user={$database_admin}"; if ($database_password != null) { $G[] = "gmysql-password={$database_password}"; } $G[] = "gmysql-dbname=powerdns"; shell_exec("{$nohup} {$php5} /usr/share/artica-postfix/exec.pdns.php --mysql >/dev/null 2>&1 &"); } if ($PowerDNSMySQLType == 2) { if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} MySQL {$PowerDNSMySQLRemoteServer}@{$PowerDNSMySQLRemoteAdmin}\n"; } $G[] = "gmysql-host={$PowerDNSMySQLRemoteServer}"; $G[] = "gmysql-port={$PowerDNSMySQLRemotePort}"; $G[] = "gmysql-user={$PowerDNSMySQLRemoteAdmin}"; if ($PowerDNSMySQLRemotePassw != null) { $G[] = "gmysql-password={$PowerDNSMySQLRemotePassw}"; } $G[] = "gmysql-dbname=powerdns"; } if ($PowerDNSMySQLType == 3) { $mysql_server = $q->mysql_server; if ($mysql_server == 'localhost' or $mysql_server == "127.0.0.1") { $mysql_server = "127.0.0.1"; } $mysql_port = $q->mysql_port; if ($PowerUseGreenSQL == 1) { shell_exec("{$php5} /usr/share/artica-postfix/exec.greensql.php --sets"); $GreenPort = @file_get_contents("/etc/artica-postfix/settings/Mysql/GreenPort"); if (!is_numeric($GreenPort)) { $GreenPort = 3305; } $mysql_port = $GreenPort; } if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} MySQL {$mysql_server}:{$mysql_port}@{$database_admin}\n"; } $G[] = "gmysql-host={$mysql_server}"; $G[] = "gmysql-port={$mysql_port}"; $G[] = "gmysql-user={$database_admin}"; if ($database_password != null) { $G[] = "gmysql-password={$database_password}"; } $G[] = "gmysql-dbname=powerdns"; } $f[] = @implode("\n", $G); if ($PowerDNSDNSSEC == 1) { $f[] = "gmysql-dnssec"; } if ($PowerDNSDisableLDAP == 0) { $ldap = new clladp(); $f[] = "ldap-host={$ldap->ldap_host}:{$ldap->ldap_port}"; $f[] = "ldap-basedn=ou=dns,{$ldap->suffix}"; $f[] = "ldap-binddn=cn={$ldap->ldap_admin},{$ldap->suffix}"; $f[] = "ldap-secret={$ldap->ldap_password}"; $f[] = "ldap-method=simple"; } @mkdir("/etc/powerdns/pdns.d", 0755, true); if (is_file("/etc/pdns/pdns.conf")) { @file_put_contents("/etc/pdns/pdns.conf", @implode("\n", $f)); } @file_put_contents("/etc/powerdns/pdns.conf", @implode("\n", $f)); if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} pdns.conf done...\n"; } $f[] = array(); if ($PowerDNSDisableLDAP == 0) { $f[] = "ldap-host={$ldap->ldap_host}:{$ldap->ldap_port}"; $f[] = "ldap-basedn=ou=dns,{$ldap->suffix}"; $f[] = "ldap-binddn=cn={$ldap->ldap_admin},{$ldap->suffix}"; $f[] = "ldap-secret={$ldap->ldap_password}"; $f[] = "ldap-method=simple"; } $f[] = "recursor={$recursor}"; $f[] = @implode("\n", $G); @file_put_contents("/etc/powerdns/pdns.d/pdns.local", @implode("\n", $f)); if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} pdns.local done...\n"; } $f = array(); $CDIR = $cdirlist; if (count($RecursoripAllowFrom) > 0) { while (list($field, $value) = each($RecursoripAllowFrom)) { $CDIR[] = $value; } } while (list($field, $value) = each($CDIR)) { $AA[$value] = $value; } while (list($field, $value) = each($AA)) { $ALLOW[] = $field; } if (is_file('/etc/powerdns/forward-zones-file')) { $f[] = "forward-zones-file=/etc/powerdns/forward-zones-file"; } if (is_file('/etc/powerdns/forward-zones-recurse')) { $f[] = "forward-zones-recurse=" . trim(@file_get_contents('/etc/powerdns/forward-zones-recurse')); } $f[] = "local-address=127.0.0.1"; $f[] = "quiet=no"; $f[] = "config-dir=/etc/powerdns/"; $f[] = "daemon=yes"; $f[] = "local-port=1553"; $f[] = "log-common-errors=yes"; $f[] = "allow-from=" . @implode(",", $ALLOW); $f[] = "socket-dir=/var/run/pdns"; //$f[]="query-local-address6="; @file_put_contents("/etc/powerdns/recursor.conf", @implode("\n", $f)); if ($GLOBALS["OUTPUT"]) { echo "Starting......: " . date("H:i:s") . " [INIT]: {$GLOBALS["TITLENAME"]} recursor.conf done...\n"; } if ($PowerDNSDNSSEC == 1) { shell_exec("{$php5} /usr/share/artica-postfix/exec.pdns.php --dnsseck"); } }
/** * @param int $id * @param string $text * @param string $indent Default to six spaces * @return string */ function writeContributor($id, $text, $indent = " ") { $out = $indent . "<contributor>\n"; if ($id || !IP::isValid($text)) { $out .= $indent . " " . Xml::elementClean('username', null, strval($text)) . "\n"; $out .= $indent . " " . Xml::element('id', null, strval($id)) . "\n"; } else { $out .= $indent . " " . Xml::elementClean('ip', null, strval($text)) . "\n"; } $out .= $indent . "</contributor>\n"; return $out; }
function whitelist_destination($hostname, $port = 0) { $ipClass = new IP(); $unix = new unix(); $iptables = $unix->find_program("iptables"); $squid_http_port = @file_get_contents("/etc/artica-postfix/settings/Daemons/ArticaHotSpotPort"); $squid_ssl_port = @file_get_contents("/etc/artica-postfix/settings/Daemons/ArticaSSLHotSpotPort"); if ($ipClass->isValid($hostname)) { $ip = $hostname; } else { $ip = gethostbyname($hostname); } if (!$ipClass->isValid($ip)) { if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["SERVICE_NAME"]} unable to resolve {$hostname}\n"; } return; } $md5key = md5($ip); $suffixTables = "-m comment --comment \"ArticaHotSpot-{$md5key}\""; if ($GLOBALS["OUTPUT"]) { echo "Stopping......: " . date("H:i:s") . " [INIT]: {$GLOBALS["SERVICE_NAME"]} {$hostname} -> {$ip} whitelist 80/433\n"; } if (!$GLOBALS["EBTABLES"]) { $f[] = "{$iptables} -t mangle -I PREROUTING -p tcp -m tcp -d {$ip} --dport 80 -j internet -m comment --comment ArticaHotSpot-{$md5key}"; } $f[] = "{$iptables} -t nat -I PREROUTING -p tcp {$GLOBALS["MARKHTTP"]} -m tcp -d {$ip} --dport 80 -j REDIRECT --to-port {$squid_http_port} -m comment --comment ArticaHotSpot-{$md5key}"; if (!$GLOBALS["EBTABLES"]) { $f[] = "{$iptables} -t mangle -I PREROUTING -p tcp -m tcp -d {$ip} --dport 443 -j internssl -m comment --comment ArticaHotSpot-{$md5key}"; } $f[] = "{$iptables} -t nat -I PREROUTING -p tcp {$GLOBALS["MARKHTTPS"]} -m tcp -d {$ip} --dport 443 -j REDIRECT --to-port {$squid_ssl_port} -m comment --comment ArticaHotSpot-{$md5key}"; return @implode("\n", $f); }
public function free_categorizeSave($PostedDatas = null, $category, $ForceCat = 0, $ForceExt = 0) { include_once dirname(__FILE__) . "/class.html2text.inc"; $sock = new sockets(); if (!isset($GLOBALS["uuid"])) { $sock = new sockets(); $GLOBALS["uuid"] = base64_decode($sock->getFrameWork("cmd.php?system-unique-id=yes")); } $uuid = $GLOBALS["uuid"]; $f = array(); $ExtractAllUris = $this->ExtractAllUris($PostedDatas); if (count($ExtractAllUris) > 0) { while (list($num, $ligne) = each($ExtractAllUris)) { $f[] = $num; } $PostedDatas = null; } $h2t = new html2text($PostedDatas); $h2t->get_text(); while (list($num, $ligne) = each($h2t->_link_array)) { if (trim($ligne) == null) { continue; } $ligne = strtolower($ligne); $ligne = str_replace("(whois)", "", $ligne); $ligne = str_replace("||", "", $ligne); $ligne = str_replace("^", "", $ligne); $ligne = trim($ligne); if (preg_match("#^([0-9\\.]+):[0-9]+#", $ligne, $re)) { $websitesToscan[] = $re[1]; continue; } if (strpos(" {$ligne}", "http") == 0) { $ligne = "http://{$ligne}"; } $hostname = parse_url($ligne, PHP_URL_HOST); if (preg_match("#^www\\.(.+)#", $hostname, $re)) { $hostname = $re[1]; } if (preg_match("#^\\.(.+)#", $hostname, $re)) { $hostname = $re[1]; } if (preg_match("#^\\*\\.(.+)#", $hostname, $re)) { $hostname = $re[1]; } writelogs("{$ligne} = {$hostname}", __FUNCTION__, __FILE__, __LINE__); $websitesToscan[] = $ligne; } $PostedDatas = str_replace("<", "\n<", $PostedDatas); $PostedDatas = str_replace(' rel="nofollow"', "", $PostedDatas); $PostedDatas = str_replace("\r", "\n", $PostedDatas); $PostedDatas = str_replace("https:", "http:", $PostedDatas); if ($PostedDatas != null) { $f = explode("\n", $PostedDatas); } if (!is_numeric($ForceExt)) { $ForceExt = 0; } if (!is_numeric($ForceCat)) { $ForceCat = 0; } $ipClass = new IP(); while (list($num, $www) = each($f)) { $www = trim($www); if ($www == null) { continue; } if (preg_match("#--------------#", $www)) { continue; } if (preg_match("#No extension#", $www)) { continue; } if (preg_match("#no website#i", $www)) { continue; } if (preg_match("#^analyze\\s+[0-9]+\\s+#", $www)) { continue; } if (preg_match("#(false|true):\\s+(.+?)\\s+already#i", $www, $re)) { $www = $re[2]; } writelogs("Scanning {$www}", __FUNCTION__, __FILE__, __LINE__); if (preg_match("#^(.+?)\"\\s+#", $www, $re)) { $www = $re[1]; } if (preg_match("#^([0-9\\.]+):[0-9]+#", $www, $re)) { $www = $re[1]; } $www = str_replace("(whois)", "", $www); $www = str_replace("\r", "", $www); $www = str_replace("||", "", $www); $www = str_replace("^", "", $www); $www = trim(strtolower($www)); if ($ipClass->isValid($www)) { $www = ip2long($www) . ".addr"; $websitesToscan[] = $www; continue; } if ($www == null) { continue; } $www = stripslashes($www); if (preg_match("#href=\"(.+?)\">#", $www, $re)) { $www = $re[1]; } if (preg_match('#<a rel=.+?href="(.+?)"#', $www, $re)) { $www = $re[1]; } if (preg_match("#<a href.*?http://(.+?)([\\/\"'>])#i", $www, $re)) { $www = $re[1]; } if (preg_match("#<span>www\\.(.+?)\\.([a-z]+)</span>#i", $www, $re)) { $www = $re[1] . "." . $re[2]; } $www = str_replace("http://", "", $www); if (preg_match("#\\/\\/.+?@(.+)#", $www, $re)) { $websitesToscan[] = $re[1]; } if (preg_match("#http.*?:\\/\\/(.+?)[\\/\\s]+#", $www, $re)) { $websitesToscan[] = $re[1]; continue; } if (preg_match("#^www\\.(.+)#", $www, $re)) { $www = $re[1]; } $www = str_replace("<a href=", "", $www); $www = str_replace("<img src=", "", $www); $www = str_replace("title=", "", $www); if (preg_match("#^(.*?)\\/#", $www, $re)) { $www = $re[1]; } if (preg_match("#\\.php\$#", $www, $re)) { echo "{$www} php script...\n"; continue; } $www = str_replace("/", "", $www); $www = trim($www); if ($ForceExt == 0) { if (!preg_match("#\\.([a-z0-9]+)\$#", $www, $re)) { echo "`{$www}` No extension !!?? \n"; continue; } if (strlen($re[1]) < 2) { if (!is_numeric($re[1])) { echo "{$www} bad extension `.{$re[1]}` [{$ForceExt}]\n"; continue; } } } $www = str_replace('"', "", $www); writelogs("Success pass {$www}", __FUNCTION__, __FILE__, __LINE__); $websitesToscan[] = $www; } while (list($num, $www) = each($websitesToscan)) { $cleaned[$www] = $www; } $websitesToscan = array(); while (list($num, $www) = each($cleaned)) { $websitesToscan[] = $www; } while (list($num, $www) = each($websitesToscan)) { writelogs("Scanning {$www}", __FUNCTION__, __FILE__, __LINE__); $www = strtolower($www); $www = replace_accents($www); if ($www == "www") { continue; } if ($www == "ssl") { continue; } $www = str_replace("http://", "", $www); $www = str_replace("https://", "", $www); $www = str_replace("ftp://", "", $www); $www = str_replace("ftps://", "", $www); if (preg_match("#.+?@(.+)#", $www, $ri)) { $www = $ri[1]; } if (preg_match("#^www\\.(.+?)\$#i", $www, $ri)) { $www = $ri[1]; } if ($ForceCat == 0) { if ($this->already_Cats($www)) { continue; } } if (strpos($www, '"') > 0) { $www = substr($www, 0, strpos($www, '"')); } if (strpos($www, "'") > 0) { $www = substr($www, 0, strpos($www, "'")); } if (strpos($www, ">") > 0) { $www = substr($www, 0, strpos($www, ">")); } if (strpos($www, "?") > 0) { $www = substr($www, 0, strpos($www, "?")); } if (strpos($www, "\\") > 0) { $www = substr($www, 0, strpos($www, "\\")); } if (strpos($www, "/") > 0) { $www = substr($www, 0, strpos($www, "/") - 1); } if (preg_match("#^\\.(.+)#", $www, $re)) { $www = $re[1]; } if (preg_match("#^\\*\\.(.+)#", $www, $re)) { $www = $re[1]; } if (preg_match("#\\.html\$#i", $www, $re)) { continue; } if (preg_match("#\\.htm\$#i", $www, $re)) { continue; } if (preg_match("#\\.gif\$#i", $www, $re)) { continue; } if (preg_match("#\\.png\$#i", $www, $re)) { continue; } if (preg_match("#\\.jpeg\$#i", $www, $re)) { continue; } if (preg_match("#\\.jpg\$#i", $www, $re)) { continue; } if (preg_match("#\\.php\$#i", $www, $re)) { continue; } if (preg_match("#\\.js\$#i", $www, $re)) { continue; } if ($ForceExt == 0) { if (!preg_match("#\\.[a-z0-9]+\$#", $www, $re)) { echo "{$www} bad extension `{$www}` \n"; continue; } } if (strpos(" ", trim($www)) > 0) { continue; } $sites[$www] = $www; } $this->CheckTable_dansguardian(); if (count($sites) == 0) { echo "NO websites\n"; return; } echo "\n----------------\nanalyze " . count($sites) . " websites into {$category}\n"; while (list($num, $www) = each($sites)) { $www = trim($www); if ($www == null) { continue; } if (preg_match("#^www\\.(.+?)\$#", $www, $re)) { $www = $re[1]; } writelogs("Analyze {$www}", __FUNCTION__, __FILE__, __LINE__); $md5 = md5($category . $www); if ($ForceCat == 0) { $cats = $this->GET_CATEGORIES($www, true, true, true); if ($cats != null) { echo "FALSE: {$www} already categorized ({$cats})\n"; continue; } } $category_table = "category_" . $this->category_transform_name($category); $this->CreateCategoryTable($_POST["category"]); $this->QUERY_SQL("INSERT IGNORE INTO {$category_table} (zmd5,zDate,category,pattern,uuid) VALUES('{$md5}',NOW(),'{$category}','{$www}','{$uuid}')"); if (!$this->ok) { echo "categorize {$www} failed {$this->mysql_error} line " . __LINE__ . " in file " . __FILE__ . "\n"; continue; } $this->categorize_logs($category, "{add}", $www); echo "TRUE: {$www} Added\n"; $this->QUERY_SQL("INSERT IGNORE INTO categorize (zmd5,zDate,category,pattern,uuid) VALUES('{$md5}',NOW(),'{$category}','{$www}','{$uuid}')"); if (!$this->ok) { echo $this->mysql_error . "\n"; } } $sock = new sockets(); $sock->getFrameWork("cmd.php?export-community-categories=yes"); }
/** * @covers IP::isValid */ public function testInvalidIPs() { // Out of range... foreach (range(256, 999) as $i) { $a = sprintf("%03d", $i); $b = sprintf("%02d", $i); $c = sprintf("%01d", $i); foreach (array_unique(array($a, $b, $c)) as $f) { $ip = "{$f}.{$f}.{$f}.{$f}"; $this->assertFalse(IP::isValid($ip), "{$ip} is not a valid IPv4 address"); } } foreach (range('g', 'z') as $i) { $a = sprintf("%04s", $i); $b = sprintf("%03s", $i); $c = sprintf("%02s", $i); foreach (array_unique(array($a, $b, $c)) as $f) { $ip = "{$f}:{$f}:{$f}:{$f}:{$f}:{$f}:{$f}:{$f}"; $this->assertFalse(IP::isValid($ip), "{$ip} is not a valid IPv6 address"); } } // Have CIDR $ipCIDRs = array('212.35.31.121/32', '212.35.31.121/18', '212.35.31.121/24', '::ff:d:321:5/96', 'ff::d3:321:5/116', 'c:ff:12:1:ea:d:321:5/120'); foreach ($ipCIDRs as $i) { $this->assertFalse(IP::isValid($i), "{$i} is an invalid IP address because it is a block"); } // Incomplete/garbage $invalid = array('www.xn--var-xla.net', '216.17.184.G', '216.17.184.1.', '216.17.184', '216.17.184.', '256.17.184.1'); foreach ($invalid as $i) { $this->assertFalse(IP::isValid($i), "{$i} is an invalid IP address"); } }
public function parseLine($line, array $wikis = array()) { wfProfileIn(__METHOD__); if (empty($wikis)) { wfProfileOut(__METHOD__); return false; } if (empty($line)) { wfProfileOut(__METHOD__); throw new PathFinderNoDataToParseException('Line is empty'); } $tokens = explode("&", $line); //4 is the total number of tokens we're interested in, avoid going further if there aren't enough to save time if (count($tokens) < 4) { wfProfileOut(__METHOD__); throw new PathFinderNoDataToParseException('Line doesn\'t contain enough data'); } $data = new stdClass(); /** * @see extensions/wikia/WikiaStats/WikiaWebStats.php for OneDot data definition */ foreach ($tokens as $param) { list($name, $value) = explode('=', $param); switch ($name) { case 'event': //event name from tracking //we take into consideration only pure pageviews, no events tracking requests //this avoids duplicated data popping up and screw the stats wfProfileOut(__METHOD__); throw new PathFinderNoDataToParseException('Line refers to an event tracking call.'); break; case 'n': //article namespace //in OneDot NS_MAIN is "n=" (empty), the int cast will fix it anyways if (in_array((int) $value, $this->app->wg->PathFinderExcludeNamespaces)) { wfProfileOut(__METHOD__); throw new PathFinderNoDataToParseException('Line refers to an article in an excluded namespace.'); } break; case 'c': //cityId $data->cityId = (int) $value; break; case 'a': //article ID $data->targetId = (int) $value; break; /*case 'u': //User ID (if logged in) $data->userId = (int) $value; break;*/ /*case 'u': //User ID (if logged in) $data->userId = (int) $value; break;*/ case 'x': //Wiki DB name $data->dbName = urldecode($value); break; case 'r': //referrer URL $data->referrer = urldecode($value); break; } } if (!empty($data->cityId) && !empty($data->dbName) && !empty($data->targetId) && !empty($data->referrer) && array_key_exists($data->cityId, $wikis)) { $wiki = $wikis[$data->cityId]; $urlData = parse_url($data->referrer); unset($data->referrer); if (empty($urlData['host'])) { wfProfileOut(__METHOD__); throw new PathFinderNoDataToParseException('Line contains a malformed referrer URL.'); } else { //TODO: check if is IP or dev/verify/preview if (IP::isValid($urlData['host']) || preg_match('/^(verify|preview)(\\..*)?\\.wikia\\.com/', $urlData['host']) || preg_match('/\\.wikia-dev\\.com/', $urlData['host'])) { wfProfileOut(__METHOD__); throw new PathFinderNoDataToParseException('Line contains an IP or a dev-server as the referrer.'); } } if (empty($urlData['path'])) { $urlData['path'] = ''; } if (empty($urlData['query'])) { $urlData['query'] = ''; } if ($urlData['host'] == $wiki->domain) { $urlData['path'] = $this->removeWikiPrefix($urlData['path'], true); $articleName = !in_array($urlData['path'], array('/index.php', '/api.php', '/wikia.php', '/', '')) ? urldecode(substr($urlData['path'], 1)) : null; if (!empty($articleName)) { $data->internalReferrer = $articleName; } else { wfProfileOut(__METHOD__); throw new PathFinderNoDataToParseException('Missing referrer article name'); } } else { $data->externalReferrer = $this->identifyExternalReferrer($urlData['host'], $urlData['path'], $urlData['query']); } } else { return false; } wfProfileOut(__METHOD__); return $data; }
/** * Handler for the BeforePageDisplay hook * * @param $out OutputPage * @param $text String * @return bool */ public function beforePageDisplayHTML(&$out, &$text) { global $wgRequest, $wgConf, $wgEnableZeroRatedMobileAccessTesting; wfProfileIn(__METHOD__); $DB = wfGetDB(DB_MASTER); $DBName = $DB->getDBname(); list($site, $lang) = $wgConf->siteFromDB($DBName); if ($site == 'wikipedia' || $wgEnableZeroRatedMobileAccessTesting) { $xDevice = isset($_SERVER['HTTP_X_DEVICE']) ? $_SERVER['HTTP_X_DEVICE'] : ''; self::$useFormat = $wgRequest->getText('useformat'); if (self::$useFormat !== 'mobile' && self::$useFormat !== 'mobile-wap' && !$xDevice) { wfProfileOut(__METHOD__); return true; } $output = ''; self::$renderZeroRatedLandingPage = $wgRequest->getFuzzyBool('renderZeroRatedLandingPage'); self::$renderZeroRatedBanner = $wgRequest->getFuzzyBool('renderZeroRatedBanner'); self::$renderZeroRatedRedirect = $wgRequest->getFuzzyBool('renderZeroRatedRedirect'); self::$forceClickToViewImages = $wgRequest->getFuzzyBool('forceClickToViewImages'); self::$acceptBilling = $wgRequest->getVal('acceptbilling'); self::$title = $out->getTitle(); $carrier = $wgRequest->getHeader('HTTP_X_CARRIER'); if ($carrier !== '(null)' && $carrier) { self::$renderZeroRatedBanner = true; } if (self::$title->getNamespace() == NS_FILE) { self::$isFilePage = true; } if (self::$acceptBilling === 'no') { $targetUrl = $wgRequest->getVal('returnto'); $out->redirect($targetUrl, '301'); $out->output(); } if (self::$acceptBilling === 'yes') { $targetUrl = $wgRequest->getVal('returnto'); if ($targetUrl) { $out->redirect($targetUrl, '301'); $out->output(); } } if (self::$isFilePage && self::$acceptBilling !== 'yes') { $acceptBillingYes = Html::rawElement('a', array('href' => $wgRequest->appendQuery('renderZeroRatedBanner=true&acceptbilling=yes')), wfMsg('zero-rated-mobile-access-banner-text-data-charges-yes')); $referrer = $wgRequest->getHeader('referer'); $acceptBillingNo = Html::rawElement('a', array('href' => $wgRequest->appendQuery('acceptbilling=no&returnto=' . urlencode($referrer))), wfMsg('zero-rated-mobile-access-banner-text-data-charges-no')); $bannerText = Html::rawElement('h3', array('id' => 'zero-rated-banner-text'), wfMsg('zero-rated-mobile-access-banner-text-data-charges', $acceptBillingYes, $acceptBillingNo)); $banner = Html::rawElement('div', array('style' => 'display:none;', 'id' => 'zero-rated-banner-red'), $bannerText); $output .= $banner; $out->clearHTML(); $out->setPageTitle(null); } elseif (self::$renderZeroRatedRedirect === true) { $returnto = $wgRequest->getVal('returnto'); $acceptBillingYes = Html::rawElement('a', array('href' => $wgRequest->appendQuery('renderZeroRatedBanner=true&acceptbilling=yes&returnto=' . urlencode($returnto))), wfMsg('zero-rated-mobile-access-banner-text-data-charges-yes')); $referrer = $wgRequest->getHeader('referer'); $acceptBillingNo = Html::rawElement('a', array('href' => $wgRequest->appendQuery('acceptbilling=no&returnto=' . urlencode($referrer))), wfMsg('zero-rated-mobile-access-banner-text-data-charges-no')); $bannerText = Html::rawElement('h3', array('id' => 'zero-rated-banner-text'), wfMsg('zero-rated-mobile-access-banner-text-data-charges', $acceptBillingYes, $acceptBillingNo)); $banner = Html::rawElement('div', array('style' => 'display:none;', 'id' => 'zero-rated-banner-red'), $bannerText); $output .= $banner; $out->clearHTML(); $out->setPageTitle(null); } elseif (self::$renderZeroRatedBanner === true) { self::$carrier = $this->lookupCarrier($carrier); if (isset(self::$carrier['name'])) { $html = $out->getHTML(); $parsedHtml = $this->parseLinksForZeroQueryString($html); $out->clearHTML(); $out->addHTML($parsedHtml); $carrierLink = isset(self::$carrier['link']) ? self::$carrier['link'] : ''; $bannerText = Html::rawElement('span', array('id' => 'zero-rated-banner-text'), wfMsg('zero-rated-mobile-access-banner-text', $carrierLink)); $banner = Html::rawElement('div', array('style' => 'display:none;', 'id' => 'zero-rated-banner'), $bannerText); $output .= $banner; } } if (self::$renderZeroRatedLandingPage === true) { $out->clearHTML(); $out->setPageTitle(null); $output .= wfMsg('zero-rated-mobile-access-desc'); $languageNames = Language::getLanguageNames(); $country = $wgRequest->getVal('country'); $ip = $wgRequest->getVal('ip', wfGetIP()); // Temporary hack to allow for testing on localhost $countryIps = array('GERMANY' => '80.237.226.75', 'MEXICO' => '187.184.240.247', 'THAILAND' => '180.180.150.104', 'FRANCE' => '90.6.70.28'); $ip = strpos($ip, '192.168.') === 0 ? $countryIps['THAILAND'] : $ip; if (IP::isValid($ip)) { // If no country was passed, try to do GeoIP lookup // Requires php5-geoip package if (!$country && function_exists('geoip_country_code_by_name')) { $country = geoip_country_code_by_name($ip); } self::addDebugOutput($country); } $languageOptions = $this->createLanguageOptionsFromWikiText(); // self::$displayDebugOutput = true; $languagesForCountry = isset($languageOptions[self::getFullCountryNameFromCode($country)]) ? $languageOptions[self::getFullCountryNameFromCode($country)] : null; self::addDebugOutput(self::getFullCountryNameFromCode($country)); self::addDebugOutput($languagesForCountry); self::writeDebugOutput(); if (is_array($languagesForCountry)) { $sizeOfLanguagesForCountry = sizeof($languagesForCountry); for ($i = 0; $i < $sizeOfLanguagesForCountry; $i++) { $languageName = $languageNames[$languagesForCountry[$i]['language']]; $languageCode = $languagesForCountry[$i]['language']; $output .= Html::element('hr'); $output .= Html::element('h3', array('id' => 'lang_' . $languageCode), $languageName); if ($i == 0) { $output .= self::getSearchFormHtml($languageCode); } else { $languageUrl = sprintf(self::$formatMobileUrl, $languageCode); $output .= Html::element('a', array('id' => 'lang_' . $languageCode, 'href' => $languageUrl), wfMessage('zero-rated-mobile-access-home-page-selection', $languageName)->inLanguage($languageCode)); $output .= Html::element('br'); } } } $output .= Html::element('hr'); $output .= wfMsg('zero-rated-mobile-access-home-page-selection-text'); $output .= Html::openElement('select', array('id' => 'languageselection', 'onchange' => 'javascript:window.location = this.options[this.selectedIndex].value;')); $output .= Html::element('option', array('value' => ''), wfMsg('zero-rated-mobile-access-language-selection')); foreach ($languageNames as $languageCode => $languageName) { $output .= Html::element('option', array('value' => sprintf(self::$formatMobileUrl, $languageCode)), $languageName); } $output .= Html::closeElement('select'); } if ($output) { $output = Html::openElement('div', array('id' => 'zero-landing-page')) . $output . Html::closeElement('div'); $out->addHTML($output); } } wfProfileOut(__METHOD__); return true; }
function events_search() { $page = CurrentPageName(); $tpl = new templates(); $sock = new sockets(); $q = new mysql_squid_builder(); $sock = new sockets(); $sock->getFrameWork("squid.php?rttlogs-parse=yes"); $GLOBALS["Q"] = $q; $table = "squidhour_" . date("YmdH"); if (isset($_POST['page'])) { $page = $_POST['page']; } if (isset($_POST['rp'])) { $rp = $_POST['rp']; } $searchstring = string_to_flexquery(); if ($searchstring != null) { $sql = "SELECT COUNT(*) as TCOUNT FROM `{$table}` WHERE 1 {$searchstring}"; $ligne = mysql_fetch_array($q->QUERY_SQL($sql)); $total = $ligne["TCOUNT"]; } else { $total = $q->COUNT_ROWS($table); } if (!is_numeric($rp)) { $rp = 50; } $pageStart = ($page - 1) * $rp; $limitSql = "LIMIT {$pageStart}, {$rp}"; if (isset($_POST["sortname"])) { if ($_POST["sortname"] != null) { $ORDER = "ORDER BY {$_POST["sortname"]} {$_POST["sortorder"]}"; } } $sql = "SELECT * FROM `{$table}` WHERE 1 {$searchstring} {$ORDER} {$limitSql}"; $results = $q->QUERY_SQL($sql); if (!$q->ok) { json_error_show($q->mysql_error); } if (mysql_num_rows($results) == 0) { json_error_show("no data - {$table}", 2); } $data = array(); $data['page'] = $page; $data['total'] = $total; $data['rows'] = array(); $today = date("Y-m-d"); $tcp = new IP(); $cachedT = $tpl->_ENGINE_parse_body("{cached}"); $c = 0; while ($ligne = mysql_fetch_assoc($results)) { $color = "black"; $return_code_text = null; $ff = array(); $color = "black"; $uri = $ligne["uri"]; $date = $ligne["zDate"]; $mac = $ligne["MAC"]; $ip = $ligne["CLIENT"]; $user = $ligne["uid"]; $dom = $ligne["sitename"]; $cached = $ligne["cached"]; $return_code = $ligne["TYPE"]; $size = $ligne["QuerySize"]; $category = $ligne["category"]; $ident = array(); $md = md5(serialize($ligne)); $today = date("Y-m-d"); $date = str_replace($today, "", $date); $ident[] = "<a href=\"javascript:blur()\"\n\t\tOnClick=\"javascript:Loadjs('squid.nodes.php?node-infos-js=yes&ipaddr={$ip}',true);\"\n\t\tstyle='text-decoration:underline;color:{$color}'>{$ip}</a>"; $spanON = "<span style='color:{$color}'>"; $spanOFF = "</span>"; $cached_text = null; $size = FormatBytes($size / 1024); if ($return_code == "Not Found") { $color = "#BA0000"; } if ($return_code == "Service Unavailable") { $color = "#BA0000"; } if ($return_code == "Bad Gateway") { $color = "#BA0000"; } $return_code_text = "<div style='color:{$color};font-size:11px'><i>«{$return_code}»{$cached_text} - {$size}</i></div>"; if ($user != null) { $GLOBALS["IPUSERS"][$ip] = $user; } else { if (isset($GLOBALS["IPUSERS"][$ip])) { $ident[] = "<i>{$GLOBALS["IPUSERS"][$ip]}</i>"; } } if ($user != null) { if ($tcp->isValid($user)) { $ident[] = "<a href=\"javascript:blur()\"\n\t\t\t\tOnClick=\"javascript:Loadjs('squid.nodes.php?node-infos-js=yes&ipaddr={$user}',true);\"\n\t\t\t\tstyle='text-decoration:underline;color:{$color}'>{$user}</a>"; } else { $ident[] = "<a href=\"javascript:blur()\"\n\t\t\t\tOnClick=\"javascript:Loadjs('squid.nodes.php?node-infos-js=yes&uid={$user}',true);\"\n\t\t\t\tstyle='text-decoration:underline;color:{$color}'>{$user}</a>"; } } if ($mac != null) { $ident[] = "<a href=\"javascript:blur()\"\n\t\t\tOnClick=\"javascript:Loadjs('squid.nodes.php?node-infos-js=yes&MAC={$mac}',true);\"\n\t\t\tstyle='text-decoration:underline;color:{$color}'>{$mac}</a>"; } $colorDiv = $color; if ($colorDiv == "black") { $colorDiv = "transparent"; } $identities = @implode(" | ", $ident); if ($cached == 1) { $cached_text = " - {$cachedT}"; $colorDiv = "#00B954"; } $www = $q->PostedServerToHost($uri); $time = time(); $uri = str_replace($www, "<a href=\"javascript:blur();\" OnClick=\"javascript:Loadjs('squid.website-zoom.php?js=yes&sitename={$www}&xtime={$time}')\"\r\n\t\tstyle='text-decoration:underline;color:{$color};font-weight:bold'>{$www}</a>", $uri); if ($category != null) { $category = "<strong style=color:#D2904A>« {$category} »</strong>"; } $data['rows'][] = array('id' => $md, 'cell' => array("<div style='background-color:{$colorDiv};margin-top:-5px;margin-left:-5px;margin-right:-5px;margin-bottom:-5px;'> </div>", "{$spanON}{$date}{$spanOFF}", "{$spanON}{$uri}.{$return_code_text}{$category}{$spanOFF}", "{$spanON}{$identities}{$spanOFF}")); } echo json_encode($data); }
function hosts_save() { $ID = $_POST["ID"]; $ipClass = new IP(); if (!$ipClass->isValid($_POST["ipaddr"])) { echo "Invalid IP address:{$_POST["ipaddr"]}\n"; return; } $ip2Long2 = ip2Long2($_POST["ipaddr"]); if ($ID > 0) { $sql = "UPDATE dnsmasq_records SET `hostname`='{$_POST["hostname"]}',`ipaddr`='{$_POST["ipaddr"]}',`ipaddrton`='{$ip2Long2}' WHERE ID='{$ID}'"; } else { $sql = "INSERT IGNORE INTO dnsmasq_records(`hostname`,`ipaddr`,`ipaddrton`)\n\t\tVALUES ('{$_POST["hostname"]}',\t'{$_POST["ipaddr"]}','{$ip2Long2}');\n\t\t"; } $q = new mysql_squid_builder(); $q->QUERY_SQL($sql); if (!$q->ok) { echo $q->mysql_error . "\n***{$sql}\n****\n"; } }
/** * Import an client IP address, HTTP headers, user ID, and session ID * * This sets the current session, $wgUser, and $wgRequest from $params. * Once the return value falls out of scope, the old context is restored. * This method should only be called in contexts where there is no session * ID or end user receiving the response (CLI or HTTP job runners). This * is partly enforced, and is done so to avoid leaking cookies if certain * error conditions arise. * * This is useful when background scripts inherit context when acting on * behalf of a user. In general the 'sessionId' parameter should be set * to an empty string unless session importing is *truly* needed. This * feature is somewhat deprecated. * * @note suhosin.session.encrypt may interfere with this method. * * @param array $params Result of RequestContext::exportSession() * @return ScopedCallback * @throws MWException * @since 1.21 */ public static function importScopedSession(array $params) { if (strlen($params['sessionId']) && MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent()) { // Sanity check to avoid sending random cookies for the wrong users. // This method should only called by CLI scripts or by HTTP job runners. throw new MWException("Sessions can only be imported when none is active."); } elseif (!IP::isValid($params['ip'])) { throw new MWException("Invalid client IP address '{$params['ip']}'."); } if ($params['userId']) { // logged-in user $user = User::newFromId($params['userId']); $user->load(); if (!$user->getId()) { throw new MWException("No user with ID '{$params['userId']}'."); } } else { // anon user $user = User::newFromName($params['ip'], false); } $importSessionFunc = function (User $user, array $params) { global $wgRequest, $wgUser; $context = RequestContext::getMain(); // Commit and close any current session if (MediaWiki\Session\PHPSessionHandler::isEnabled()) { session_write_close(); // persist session_id(''); // detach $_SESSION = []; // clear in-memory array } // Get new session, if applicable $session = null; if (strlen($params['sessionId'])) { // don't make a new random ID $manager = MediaWiki\Session\SessionManager::singleton(); $session = $manager->getSessionById($params['sessionId'], true) ?: $manager->getEmptySession(); } // Remove any user IP or agent information, and attach the request // with the new session. $context->setRequest(new FauxRequest([], false, $session)); $wgRequest = $context->getRequest(); // b/c // Now that all private information is detached from the user, it should // be safe to load the new user. If errors occur or an exception is thrown // and caught (leaving the main context in a mixed state), there is no risk // of the User object being attached to the wrong IP, headers, or session. $context->setUser($user); $wgUser = $context->getUser(); // b/c if ($session && MediaWiki\Session\PHPSessionHandler::isEnabled()) { session_id($session->getId()); MediaWiki\quietCall('session_start'); } $request = new FauxRequest([], false, $session); $request->setIP($params['ip']); foreach ($params['headers'] as $name => $value) { $request->setHeader($name, $value); } // Set the current context to use the new WebRequest $context->setRequest($request); $wgRequest = $context->getRequest(); // b/c }; // Stash the old session and load in the new one $oUser = self::getMain()->getUser(); $oParams = self::getMain()->exportSession(); $oRequest = self::getMain()->getRequest(); $importSessionFunc($user, $params); // Set callback to save and close the new session and reload the old one return new ScopedCallback(function () use($importSessionFunc, $oUser, $oParams, $oRequest) { global $wgRequest; $importSessionFunc($oUser, $oParams); // Restore the exact previous Request object (instead of leaving FauxRequest) RequestContext::getMain()->setRequest($oRequest); $wgRequest = RequestContext::getMain()->getRequest(); // b/c }); }