/**
  * Test an IP address
  * @param string $ip
  * @return bool
  */
 public function checkIP($ip)
 {
     foreach ($this->ipAddresses as $range) {
         if (\IP::isInRange($ip, $range)) {
             return true;
         }
     }
     return false;
 }
Exemple #2
0
 /**
  * Checks whether a given IP is on the autoblock whitelist.
  * TODO: this probably belongs somewhere else, but not sure where...
  *
  * @param string $ip The IP to check
  * @return bool
  */
 public static function isWhitelistedFromAutoblocks($ip)
 {
     // Try to get the autoblock_whitelist from the cache, as it's faster
     // than getting the msg raw and explode()'ing it.
     $cache = ObjectCache::getMainWANInstance();
     $lines = $cache->getWithSetCallback(wfMemcKey('ipb', 'autoblock', 'whitelist'), $cache::TTL_DAY, function () {
         return explode("\n", wfMessage('autoblock_whitelist')->inContentLanguage()->plain());
     });
     wfDebug("Checking the autoblock whitelist..\n");
     foreach ($lines as $line) {
         # List items only
         if (substr($line, 0, 1) !== '*') {
             continue;
         }
         $wlEntry = substr($line, 1);
         $wlEntry = trim($wlEntry);
         wfDebug("Checking {$ip} against {$wlEntry}...");
         # Is the IP in this range?
         if (IP::isInRange($ip, $wlEntry)) {
             wfDebug(" IP {$ip} matches {$wlEntry}, not autoblocking\n");
             return true;
         } else {
             wfDebug(" No match\n");
         }
     }
     return false;
 }
	function checkAccess() {
		foreach ( $this->accessRanges as $range ) {
			if ( IP::isInRange( $_SERVER['REMOTE_ADDR'], $range ) ) {
				return true;
			}
		}
		return false;
	}
/**
 * Checks if an IP matches a proxy we've configured.
 *
 * @param string $ip
 * @return bool
 * @since 1.23 Supports CIDR ranges in $wgSquidServersNoPurge
 */
function wfIsConfiguredProxy($ip)
{
    global $wgSquidServers, $wgSquidServersNoPurge;
    // quick check of known proxy servers
    $trusted = in_array($ip, $wgSquidServers) || in_array($ip, $wgSquidServersNoPurge);
    if (!$trusted) {
        // slightly slower check to see if the ip is listed directly or in a CIDR
        // block in $wgSquidServersNoPurge
        foreach ($wgSquidServersNoPurge as $block) {
            if (strpos($block, '/') !== false && IP::isInRange($ip, $block)) {
                $trusted = true;
                break;
            }
        }
    }
    return $trusted;
}
Exemple #5
0
 /**
  * As recCheckCondition, but *not* recursive.  The only valid conditions
  * are those whose first element is APCOND_EMAILCONFIRMED/APCOND_EDITCOUNT/
  * APCOND_AGE.  Other types will throw an exception if no extension evalu-
  * ates them.
  *
  * @param $cond Array: A condition, which must not contain other conditions
  * @param $user User The user to check the condition against
  * @return bool Whether the condition is true for the user
  */
 private static function checkCondition($cond, User $user)
 {
     global $wgEmailAuthentication, $wgEnableEditCountLocal;
     if (count($cond) < 1) {
         return false;
     }
     switch ($cond[0]) {
         case APCOND_EMAILCONFIRMED:
             if (Sanitizer::validateEmail($user->getEmail())) {
                 if ($wgEmailAuthentication) {
                     return (bool) $user->getEmailAuthenticationTimestamp();
                 } else {
                     return true;
                 }
             }
             return false;
         case APCOND_EDITCOUNT:
             if (!empty($wgEnableEditCountLocal)) {
                 return $user->getEditCountLocal() >= $cond[1];
             } else {
                 return $user->getEditCount() >= $cond[1];
             }
         case APCOND_AGE:
             $age = time() - wfTimestampOrNull(TS_UNIX, $user->getRegistration());
             return $age >= $cond[1];
         case APCOND_AGE_FROM_EDIT:
             $age = time() - wfTimestampOrNull(TS_UNIX, $user->getFirstEditTimestamp());
             return $age >= $cond[1];
         case APCOND_INGROUPS:
             $groups = array_slice($cond, 1);
             return count(array_intersect($groups, $user->getGroups())) == count($groups);
         case APCOND_ISIP:
             return $cond[1] == $user->getRequest()->getIP();
         case APCOND_IPINRANGE:
             return IP::isInRange($user->getRequest()->getIP(), $cond[1]);
         case APCOND_BLOCKED:
             return $user->isBlocked();
         case APCOND_ISBOT:
             return in_array('bot', User::getGroupPermissions($user->getGroups()));
         default:
             $result = null;
             wfRunHooks('AutopromoteCondition', array($cond[0], array_slice($cond, 1), $user, &$result));
             if ($result === null) {
                 throw new MWException("Unrecognized condition {$cond[0]} for autopromotion!");
             }
             return (bool) $result;
     }
 }
Exemple #6
0
 /**
  * Check if the IP is allowed to skip captchas
  */
 function isIPWhitelisted()
 {
     if ($this->IPWhitelist) {
         $ip = wfGetIp();
         foreach ($this->IPWhitelist as $range) {
             if (IP::isInRange($ip, $range)) {
                 return true;
             }
         }
     }
     return false;
 }
 /**
  * Autoblocks the given IP, referring to this Block.
  * @param string $autoblockip The IP to autoblock.
  * @param bool $justInserted The main block was just inserted
  * @return bool Whether or not an autoblock was inserted.
  */
 function doAutoblock($autoblockip, $justInserted = false)
 {
     # If autoblocks are disabled, go away.
     if (!$this->mEnableAutoblock) {
         return;
     }
     # Check for presence on the autoblock whitelist
     # TODO cache this?
     $lines = explode("\n", wfMsgForContentNoTrans('autoblock_whitelist'));
     $ip = $autoblockip;
     wfDebug("Checking the autoblock whitelist..\n");
     foreach ($lines as $line) {
         # List items only
         if (substr($line, 0, 1) !== '*') {
             continue;
         }
         $wlEntry = substr($line, 1);
         $wlEntry = trim($wlEntry);
         wfDebug("Checking {$ip} against {$wlEntry}...");
         # Is the IP in this range?
         if (IP::isInRange($ip, $wlEntry)) {
             wfDebug(" IP {$ip} matches {$wlEntry}, not autoblocking\n");
             #$autoblockip = null; # Don't autoblock a whitelisted IP.
             return;
             #This /SHOULD/ introduce a dummy block - but
             # I don't know a safe way to do so. -werdna
         } else {
             wfDebug(" No match\n");
         }
     }
     # It's okay to autoblock. Go ahead and create/insert the block.
     $ipblock = Block::newFromDB($autoblockip);
     if ($ipblock) {
         # If the user is already blocked. Then check if the autoblock would
         # exceed the user block. If it would exceed, then do nothing, else
         # prolong block time
         if ($this->mExpiry && $this->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp)) {
             return;
         }
         # Just update the timestamp
         if (!$justInserted) {
             $ipblock->updateTimestamp();
         }
         return;
     } else {
         $ipblock = new Block();
     }
     # Make a new block object with the desired properties
     wfDebug("Autoblocking {$this->mAddress}@" . $autoblockip . "\n");
     $ipblock->mAddress = $autoblockip;
     $ipblock->mUser = 0;
     $ipblock->mBy = $this->mBy;
     $ipblock->mReason = wfMsgForContent('autoblocker', $this->mAddress, $this->mReason);
     $ipblock->mTimestamp = wfTimestampNow();
     $ipblock->mAuto = 1;
     $ipblock->mCreateAccount = $this->mCreateAccount;
     # Continue suppressing the name if needed
     $ipblock->mHideName = $this->mHideName;
     # If the user is already blocked with an expiry date, we don't
     # want to pile on top of that!
     if ($this->mExpiry) {
         $ipblock->mExpiry = min($this->mExpiry, Block::getAutoblockExpiry($this->mTimestamp));
     } else {
         $ipblock->mExpiry = Block::getAutoblockExpiry($this->mTimestamp);
     }
     # Insert it
     return $ipblock->insert();
 }
Exemple #8
0
 /**
  * Checks whether a given IP is on the autoblock whitelist.
  * TODO: this probably belongs somewhere else, but not sure where...
  *
  * @param string $ip The IP to check
  * @return bool
  */
 public static function isWhitelistedFromAutoblocks($ip)
 {
     global $wgMemc;
     // Try to get the autoblock_whitelist from the cache, as it's faster
     // than getting the msg raw and explode()'ing it.
     $key = wfMemcKey('ipb', 'autoblock', 'whitelist');
     $lines = $wgMemc->get($key);
     if (!$lines) {
         $lines = explode("\n", wfMessage('autoblock_whitelist')->inContentLanguage()->plain());
         $wgMemc->set($key, $lines, 3600 * 24);
     }
     wfDebug("Checking the autoblock whitelist..\n");
     foreach ($lines as $line) {
         # List items only
         if (substr($line, 0, 1) !== '*') {
             continue;
         }
         $wlEntry = substr($line, 1);
         $wlEntry = trim($wlEntry);
         wfDebug("Checking {$ip} against {$wlEntry}...");
         # Is the IP in this range?
         if (IP::isInRange($ip, $wlEntry)) {
             wfDebug(" IP {$ip} matches {$wlEntry}, not autoblocking\n");
             return true;
         } else {
             wfDebug(" No match\n");
         }
     }
     return false;
 }
Exemple #9
0
 /**
  * Check if the IP is allowed to skip captchas
  */
 public function isIPWhitelisted()
 {
     if ($this->wg->CaptchaWhitelistIP) {
         $ip = $this->wg->Request->getIP();
         foreach ($this->wg->CaptchaWhitelistIP as $range) {
             if (\IP::isInRange($ip, $range)) {
                 return true;
             }
         }
     }
     return false;
 }
	public static function checkWhitelist( $ip ) {
		global $wgMemc;
		
		$whitelist = self::loadWhitelist();
		
		$memcKey = wfMemcKey( 'whitelisted', $ip );
		$data = $wgMemc->get( $memcKey );
		
		if( $data != '' ) {
			return ( $data === 'ok' ) ? true : false;
		}
		
		if( is_array( $whitelist ) ) {
			foreach( $whitelist as $entry ) {
				if( IP::isInRange( $ip, $entry ) ) {
					$wgMemc->set( $memcKey, 'ok', 86400 );
					return true;
				}
			}
		}
		
		$wgMemc->set( $memcKey, 'not', 86400 );
		return false;
	}
Exemple #11
0
function ScanNetwork($RuleID, $RuleName, $network, $basePath, $QuotaSizeBytes, $FileAcls)
{
    events("[INFO]: Scanning {$network}", __LINE__);
    $acls_content = array();
    $NOTIF_TEXT = array();
    $basePath = $basePath . "/IPADDR";
    $unix = new unix();
    $dirs = $unix->dirdir($basePath);
    $FileAclsMD5_start = md5_file($FileAcls);
    $IP = new IP();
    $f = array();
    while (list($fullpath, $none) = each($dirs)) {
        $addr = basename($fullpath);
        if (!$IP->isInRange($addr, $network)) {
            continue;
        }
        if (!Scan_IpAddr($RuleID, $RuleName, $addr, $basePath, $QuotaSizeBytes, $FileAcls)) {
            continue;
        }
        $f[] = $addr;
    }
    @file_put_contents($FileAcls, @implode("\n", $f));
    $FileAclsMD5_end = md5_file($FileAcls);
    if ($FileAclsMD5_end != $FileAclsMD5_start) {
        squid_admin_mysql(1, "{$RuleName}: Quota changed", @implode("\n", $GLOBALS["NOTIF_TEXT"]), __FILE__, __LINE__);
        $GLOBALS["MUST_RELOAD_SQUID"] = true;
    }
}
Exemple #12
0
 /**
  * As recCheckCondition, but *not* recursive.  The only valid conditions
  * are those whose first element is APCOND_EMAILCONFIRMED/APCOND_EDITCOUNT/
  * APCOND_AGE.  Other types will throw an exception if no extension evalu-
  * ates them.
  *
  * @param $cond Array: A condition, which must not contain other conditions
  * @param $user The user to check the condition against
  * @return bool Whether the condition is true for the user
  */
 private static function checkCondition($cond, User $user)
 {
     if (count($cond) < 1) {
         return false;
     }
     switch ($cond[0]) {
         case APCOND_EMAILCONFIRMED:
             if (User::isValidEmailAddr($user->getEmail())) {
                 global $wgEmailAuthentication;
                 if ($wgEmailAuthentication) {
                     return (bool) $user->getEmailAuthenticationTimestamp();
                 } else {
                     return true;
                 }
             }
             return false;
         case APCOND_EDITCOUNT:
             return $user->getEditCount() >= $cond[1];
         case APCOND_AGE:
             $age = time() - wfTimestampOrNull(TS_UNIX, $user->getRegistration());
             return $age >= $cond[1];
         case APCOND_AGE_FROM_EDIT:
             $age = time() - wfTimestampOrNull(TS_UNIX, $user->getFirstEditTimestamp());
             return $age >= $cond[1];
         case APCOND_INGROUPS:
             $groups = array_slice($cond, 1);
             return count(array_intersect($groups, $user->getGroups())) == count($groups);
         case APCOND_ISIP:
             return $cond[1] == wfGetIP();
         case APCOND_IPINRANGE:
             return IP::isInRange(wfGetIP(), $cond[1]);
         default:
             $result = null;
             wfRunHooks('AutopromoteCondition', array($cond[0], array_slice($cond, 1), $user, &$result));
             if ($result === null) {
                 throw new MWException("Unrecognized condition {$cond[0]} for autopromotion!");
             }
             return $result ? true : false;
     }
 }
 /**
  * Check if an IP address is in a whitelisted range.
  *
  * @param  string  $ipAddress IP address to whitelist
  * @return boolean
  */
 public function isWhiteListedIP($ipAddress)
 {
     $ipAddress = \IP::sanitizeIP($ipAddress);
     $whitelistRanges = $this->getWhitelistRanges();
     $isWhitelisted = false;
     foreach ($whitelistRanges as $range) {
         if (\IP::isInRange($ipAddress, $range)) {
             $isWhitelisted = true;
             break;
         }
     }
     return $isWhitelisted;
 }
Exemple #14
0
 /**
  * Check if the IP is allowed to skip captchas
  */
 function isIPWhitelisted()
 {
     global $wgCaptchaWhitelistIP;
     if ($wgCaptchaWhitelistIP) {
         global $wgRequest;
         // Compat: WebRequest::getIP is only available since MW 1.19.
         $ip = method_exists($wgRequest, 'getIP') ? $wgRequest->getIP() : wfGetIP();
         foreach ($wgCaptchaWhitelistIP as $range) {
             if (IP::isInRange($ip, $range)) {
                 return true;
             }
         }
     }
     return false;
 }
Exemple #15
0
 /**
  * Checks whether a given IP is on the autoblock whitelist.
  * TODO: this probably belongs somewhere else, but not sure where...
  *
  * @param $ip String: The IP to check
  * @return Boolean
  */
 public static function isWhitelistedFromAutoblocks($ip)
 {
     global $wgMemc;
     // Try to get the autoblock_whitelist from the cache, as it's faster
     // than getting the msg raw and explode()'ing it.
     $key = wfMemcKey('ipb', 'autoblock', 'whitelist');
     $lines = $wgMemc->get($key);
     if (!$lines) {
         $lines = explode("\n", wfMsgForContentNoTrans('autoblock_whitelist'));
         $wgMemc->set($key, $lines, 3600 * 24);
     }
     /** Wikia Change start **/
     global $wgGlobalWhitelistedFromAutoblocks;
     if (!empty($wgGlobalWhitelistedFromAutoblocks) && is_array($wgGlobalWhitelistedFromAutoblocks)) {
         if (empty($lines)) {
             $lines = array();
         }
         foreach ($wgGlobalWhitelistedFromAutoblocks as $val) {
             $lines[] = '*' . $val;
         }
     }
     /** Wikia Change end **/
     wfDebug("Checking the autoblock whitelist..\n");
     foreach ($lines as $line) {
         # List items only
         if (substr($line, 0, 1) !== '*') {
             continue;
         }
         $wlEntry = substr($line, 1);
         $wlEntry = trim($wlEntry);
         wfDebug("Checking {$ip} against {$wlEntry}...");
         # Is the IP in this range?
         if (IP::isInRange($ip, $wlEntry)) {
             wfDebug(" IP {$ip} matches {$wlEntry}, not autoblocking\n");
             return true;
         } else {
             wfDebug(" No match\n");
         }
     }
     return false;
 }
Exemple #16
0
 /**
  * Check if the IP is allowed to skip captchas
  */
 function isIPWhitelisted()
 {
     global $wgCaptchaWhitelistIP;
     if ($wgCaptchaWhitelistIP) {
         global $wgRequest;
         $ip = $wgRequest->getIP();
         foreach ($wgCaptchaWhitelistIP as $range) {
             if (IP::isInRange($ip, $range)) {
                 return true;
             }
         }
     }
     return false;
 }
Exemple #17
0
function CheckAutousers()
{
    include_once "auto-account.php";
    include_once "ressources/class.tcpip.inc";
    $account = new AutoUsers();
    $chckip = false;
    if ($account->AutoCreateAccountEnabled == 0) {
        writelogs("auto-account is disabled", __FUNCTION__, __FILE__);
        return false;
    }
    $ip = new IP();
    $list = $account->AutoCreateAccountIPArray;
    if (is_array($list)) {
        while (list($num, $val) = each($list)) {
            if ($ip->isInRange($_SERVER['REMOTE_ADDR'], trim($val))) {
                writelogs("{$_SERVER['REMOTE_ADDR']} against {$val}=TRUE", __FUNCTION__, __FILE__);
                return true;
                break;
            }
        }
    } else {
        writelogs("{$_SERVER['REMOTE_ADDR']} IP List is null", __FUNCTION__, __FILE__);
        return false;
    }
    return false;
}
 /**
  * @param EditPage $editPage
  * @param string $newtext
  * @param string $section
  * @return bool true if the captcha should run
  */
 function shouldCheck(&$editPage, $newtext, $section, $merged = false)
 {
     $this->trigger = '';
     $title = $editPage->mArticle->getTitle();
     global $wgUser;
     if ($wgUser->isAllowed('skipcaptcha')) {
         wfDebug("ConfirmEdit: user group allows skipping captcha\n");
         return false;
     }
     global $wgCaptchaWhitelistIP;
     if (!empty($wgCaptchaWhitelistIP)) {
         $ip = wfGetIp();
         foreach ($wgCaptchaWhitelistIP as $range) {
             if (IP::isInRange($ip, $range)) {
                 return false;
             }
         }
     }
     global $wgEmailAuthentication, $ceAllowConfirmedEmail;
     if ($wgEmailAuthentication && $ceAllowConfirmedEmail && $wgUser->isEmailConfirmed()) {
         wfDebug("ConfirmEdit: user has confirmed mail, skipping captcha\n");
         return false;
     }
     if ($this->captchaTriggers($editPage, 'edit')) {
         // Check on all edits
         global $wgUser;
         $this->trigger = sprintf("edit trigger by '%s' at [[%s]]", $wgUser->getName(), $title->getPrefixedText());
         $this->action = 'edit';
         wfDebug("ConfirmEdit: checking all edits...\n");
         return true;
     }
     if ($this->captchaTriggers($editPage, 'create') && !$editPage->mTitle->exists()) {
         //Check if creating a page
         global $wgUser;
         $this->trigger = sprintf("Create trigger by '%s' at [[%s]]", $wgUser->getName(), $title->getPrefixedText());
         $this->action = 'create';
         wfDebug("ConfirmEdit: checking on page creation...\n");
         return true;
     }
     if ($this->captchaTriggers($editPage, 'addurl')) {
         // Only check edits that add URLs
         if ($merged) {
             // Get links from the database
             $oldLinks = $this->getLinksFromTracker($title);
             // Share a parse operation with Article::doEdit()
             $editInfo = $editPage->mArticle->prepareTextForEdit($newtext);
             $newLinks = array_keys($editInfo->output->getExternalLinks());
         } else {
             // Get link changes in the slowest way known to man
             $oldtext = $this->loadText($editPage, $section);
             $oldLinks = $this->findLinks($oldtext);
             $newLinks = $this->findLinks($newtext);
         }
         $unknownLinks = array_filter($newLinks, array(&$this, 'filterLink'));
         $addedLinks = array_diff($unknownLinks, $oldLinks);
         $numLinks = count($addedLinks);
         if ($numLinks > 0) {
             global $wgUser;
             $this->trigger = sprintf("%dx url trigger by '%s' at [[%s]]: %s", $numLinks, $wgUser->getName(), $title->getPrefixedText(), implode(", ", $addedLinks));
             $this->action = 'addurl';
             return true;
         }
     }
     global $wgCaptchaRegexes;
     if (!empty($wgCaptchaRegexes)) {
         // Custom regex checks
         $oldtext = $this->loadText($editPage, $section);
         foreach ($wgCaptchaRegexes as $regex) {
             $newMatches = array();
             if (preg_match_all($regex, $newtext, $newMatches)) {
                 $oldMatches = array();
                 preg_match_all($regex, $oldtext, $oldMatches);
                 $addedMatches = array_diff($newMatches[0], $oldMatches[0]);
                 $numHits = count($addedMatches);
                 if ($numHits > 0) {
                     global $wgUser;
                     $this->trigger = sprintf("%dx %s at [[%s]]: %s", $numHits, $regex, $wgUser->getName(), $title->getPrefixedText(), implode(", ", $addedMatches));
                     $this->action = 'edit';
                     return true;
                 }
             }
         }
     }
     return false;
 }
	function execute() {
		global $wgRequest, $wgContLanguageCode;

		if ( !$this->scalerAccessRanges ) {
			$this->htmlError( 403, 'inplace_access_disabled' );
			return false;
		}

		/**
		 * Run access checks against REMOTE_ADDR rather than wfGetIP(), since we're not
		 * giving access even to trusted proxies, only direct clients.
		 */
		$allowed = false;
		foreach ( $this->scalerAccessRanges as $range ) {
			if ( IP::isInRange( $_SERVER['REMOTE_ADDR'], $range ) ) {
				$allowed = true;
				break;
			}
		}

		if ( !$allowed ) {
			$this->htmlError( 403, 'inplace_access_denied' );
			return false;
		}

		if ( !$wgRequest->wasPosted() ) {
			echo $this->dtd();
?>
<html>
<head><title>inplace-scaler.php Test Interface</title></head>
<body>
<form method="post" action="inplace-scaler.php" enctype="multipart/form-data" >
<p>File: <input type="file" name="data" /></p>
<p>Width: <input type="text" name="width" /></p>
<p>Page: <input type="page" name="page" /></p>
<p><input type="submit" value="OK" /></p>
</form>
</body>
</html>
<?php
			return true;
		}

		$tempDir = $this->tmpDir . '/' . gmdate( self::$tempDirFormat );
		if ( !is_dir( $tempDir ) ) {
			if ( !wfMkdirParents( $tempDir, null, __METHOD__ ) ) {
				$this->htmlError( 500, 'inplace_scaler_no_temp' );
				return false;
			}
		}

		$name = $wgRequest->getFileName( 'data' );
		$srcTemp = $wgRequest->getFileTempname( 'data' );

		$params = $_REQUEST;
		unset( $params['file'] );
		if ( get_magic_quotes_gpc() ) {
			$params = array_map( 'stripslashes', $params );
		}

		$i = strrpos( $name, '.' );
		$ext = File::normalizeExtension( $i ? substr( $name, $i + 1 ) : '' );

		$magic = MimeMagic::singleton();
		$mime = $magic->guessTypesForExtension( $ext );

		$image = UnregisteredLocalFile::newFromPath( $srcTemp, $mime );

		$handler = $image->getHandler();
		if ( !$handler ) {
			$this->htmlError( 400, 'inplace_scaler_no_handler' );
			return false;
		}

		if ( !isset( $params['page'] ) ) {
			$params['page'] = 1;
		}
		$srcWidth = $image->getWidth( $params['page'] );
		$srcHeight = $image->getHeight( $params['page'] );
		if ( $srcWidth <= 0 || $srcHeight <= 0 ) {
			$this->htmlError( 400, 'inplace_scaler_invalid_image' );
			return false;
		}

		list( $dstExt, $dstMime ) = $handler->getThumbType( $ext, $mime );
		if ( preg_match( '/[ \\n;=]/', $name ) ) {
			$dstName = "thumb.$ext";
		} else {
			$dstName = $name;
		}
		if ( $dstExt != $ext ) {
			$dstName = "$dstName.$dstExt";
		}

		$dstTemp = tempnam( $tempDir, 'mwimg' );

		$thumb = $handler->doTransform( $image, $dstTemp, false, $params );
		if ( !$thumb || $thumb->isError()  ) {
			$error = $thumb ? $thumb->getHtmlMsg() : '';
			$this->htmlErrorReal( 500, 'inplace_scaler_failed', array(''), $error );
			unlink( $dstTemp );
			return false;
		}
		$stat = stat( $dstTemp );
		if ( !$stat  ) {
			$this->htmlError( 500, 'inplace_scaler_no_output' );
			return false;
		}

		if ( $stat['size'] == 0 ) {
			$this->htmlError( 500, 'inplace_scaler_no_output' );
			unlink( $dstTemp );
			return false;
		}

		wfDebug( __METHOD__.": transformation completed successfully, streaming output...\n" );
		header( "Content-Type: $dstMime" );
		header( "Content-Disposition: inline;filename*=utf-8'$wgContLanguageCode'" . urlencode( $dstName ) );
		readfile( $dstTemp );
		unlink( $dstTemp );
	}
Exemple #20
0
function matches_src($gpid, $negation)
{
    $ip = new IP();
    $q = new mysql_squid_builder();
    pack_debug("Checks \"{$gpid}\" Negation \"{$negation}\"", __FUNCTION__, __LINE__);
    $sql = "SELECT pattern FROM webfilters_sqitems WHERE gpid={$gpid} AND enabled=1";
    $results = $q->QUERY_SQL($sql);
    $exclam = null;
    if (!$q->ok) {
        writelogs("{$gpid} {$q->mysql_error}", __FUNCTION__, __FILE__, __LINE__);
        return false;
    }
    if (mysql_num_rows($results) == 0) {
        pack_debug("No item associated to this group {$gpid}", __FUNCTION__, __LINE__);
        return false;
    }
    if ($negation == 1) {
        $exclam = "!";
    }
    while ($ligne = mysql_fetch_assoc($results)) {
        $pattern = trim($ligne["pattern"]);
        if ($pattern == null) {
            return;
        }
        pack_debug("Checks \"{$pattern}\" against \"{$GLOBALS["IPADDR"]}\"", __FUNCTION__, __LINE__);
        if (preg_match("#^[0-9\\.]+\\/[0-9]+\$#", $pattern, $re)) {
            if ($negation == 1) {
                if (!$ip->isInRange($GLOBALS["IPADDR"], $pattern)) {
                    pack_debug("Checks \"{$GLOBALS["IPADDR"]}\" not in range \"{$pattern}\" WON", __FUNCTION__, __LINE__);
                    return true;
                }
            }
            if ($ip->isInRange($GLOBALS["IPADDR"], $pattern)) {
                pack_debug("Checks \"{$GLOBALS["IPADDR"]}\" is in range \"{$pattern}\" WON", __FUNCTION__, __LINE__);
                return true;
            }
            pack_debug("Checks \"{$GLOBALS["IPADDR"]}\" range \"{$pattern}\" NO MATCH", __FUNCTION__, __LINE__);
            continue;
        }
        if (preg_match("#^[0-9\\.]+-[0-9\\.]+\$#", $pattern, $re)) {
            if ($negation == 1) {
                if (!$ip->isInRange($GLOBALS["IPADDR"], $pattern)) {
                    pack_debug("Checks \"{$GLOBALS["IPADDR"]}\" not in range \"{$pattern}\" WON", __FUNCTION__, __LINE__);
                    return true;
                }
            }
            if ($ip->isInRange($GLOBALS["IPADDR"], $pattern)) {
                pack_debug("Checks \"{$GLOBALS["IPADDR"]}\" is in range \"{$pattern}\" WON", __FUNCTION__, __LINE__);
                return true;
            }
            pack_debug("Checks \"{$GLOBALS["IPADDR"]}\" range \"{$pattern}\" NO MATCH", __FUNCTION__, __LINE__);
            continue;
        }
        if ($ip->isIPAddress($pattern)) {
            if ($negation == 1) {
                if ($GLOBALS["IPADDR"] != $pattern) {
                    pack_debug("Checks \"{$GLOBALS["IPADDR"]}\" IP NOT \"{$pattern}\" WON", __FUNCTION__, __LINE__);
                    return true;
                }
            }
            if ($GLOBALS["IPADDR"] == $pattern) {
                pack_debug("Checks \"{$GLOBALS["IPADDR"]}\" IP IS \"{$pattern}\" WON", __FUNCTION__, __LINE__);
                return true;
            }
            pack_debug("Checks \"{$GLOBALS["IPADDR"]}\" == \"{$pattern}\" NO MATCH", __FUNCTION__, __LINE__);
            continue;
        }
        pack_debug("Not supported pattern {$pattern}", __FUNCTION__, __LINE__);
    }
    pack_debug("Group {$gpid}, nothing match", __FUNCTION__, __LINE__);
    return false;
}
 protected function funcIPInRange($args)
 {
     if (count($args) < 2) {
         throw new AFPUserVisibleException('notenoughargs', $this->mCur->pos, array('ip_in_range', 2, count($args)));
     }
     $ip = $args[0]->toString();
     $range = $args[1]->toString();
     $result = IP::isInRange($ip, $range);
     return new AFPData(AFPData::DBool, $result);
 }
Exemple #22
0
 /**
  * Issues there are most probably from IP::toHex() or IP::parseRange()
  * @covers IP::isInRange
  * @dataProvider provideIPsAndRanges
  */
 public function testIPIsInRange($expected, $addr, $range, $message = '')
 {
     $this->assertEquals($expected, IP::isInRange($addr, $range), $message);
 }
	private function shouldCheck( $title, $newText, $oldText = null ) {
		global $wgUser, $wgCaptchaWhitelistIP, $wgCaptchaRegexes;
		global $wgEmailAuthentication, $ceAllowConfirmedEmail;

		if ( $wgUser->isAllowed( 'skipcaptcha' ) ) {
			wfDebug( "WlCaptchaAdapter: user group allows skipping captcha\n" );
			return false;
		}

		if ( !empty( $wgCaptchaWhitelistIP ) ) {
			$ip = wfGetIp();
			foreach ( $wgCaptchaWhitelistIP as $range ) {
				if ( IP::isInRange( $ip, $range ) ) {
					return false;
				}
			}
		}

		if ( $wgEmailAuthentication && $ceAllowConfirmedEmail &&
			$wgUser->isEmailConfirmed() ) {
			wfDebug( "WlCaptchaAdapter: user has confirmed mail, skipping captcha\n" );
			return false;
		}

		if ( $this->captchaTriggers( $title, 'edit' ) ) {
			$this->mCaptcha->trigger = sprintf( "Edit trigger by '%s' at [[%s]]",
				$wgUser->getName(), $title->getPrefixedText() );
			$this->mCaptcha->action = 'edit';
			wfDebug( "WlCaptchaAdapter: checking all edits...\n" );
			return true;
		}

		if ( $this->captchaTriggers( $title, 'create' ) && is_null( $oldText ) ) {
			$this->mCaptcha->trigger = sprintf( "Create trigger by '%s' at [[%s]]",
				$wgUser->getName(), $title->getPrefixedText() );
			$this->mCaptcha->action = 'create';
			wfDebug( "WlCaptchaAdapter: checking on page creation...\n" );
			return true;
		}

		if ( $this->captchaTriggers( $title, 'addurl' ) ) {
			$oldLinks = $this->findLinks( $title, $oldText );
			$newLinks = $this->findLinks( $title, $newText );
			$unknownLinks = array_filter( $newLinks, array( &$this->mCaptcha, 'filterLink' ) );
			$addedLinks = array_diff( $unknownLinks, $oldLinks );
			$numLinks = count( $addedLinks );
			if ( $numLinks > 0 ) {
				$this->mCaptcha->trigger = sprintf( "%dx url trigger by '%s' at [[%s]]: %s",
					$numLinks, $wgUser->getName(), $title->getPrefixedText(),
					implode( ", ", $addedLinks ) );
				$this->mCaptcha->action = 'addurl';
				return true;
			}
		}

		if ( !empty( $wgCaptchaRegexes ) ) {
			foreach ( $wgCaptchaRegexes as $regex ) {
				$newMatches = array();
				if ( preg_match_all( $regex, $newtext, $newMatches ) ) {
					$oldMatches = array();
					preg_match_all( $regex, $oldtext, $oldMatches );
					$addedMatches = array_diff( $newMatches[0], $oldMatches[0] );
					$numHits = count( $addedMatches );
					if ( $numHits > 0 ) {
						$this->mCaptcha->trigger = sprintf( "%dx %s trigger by '%s' at [[%s]]: %s",
							$numHits, $regex, $wgUser->getName(), $title->getPrefixedText(),
							implode( ", ", $addedMatches ) );
						$this->mCaptcha->action = 'edit';
						return true;
					}
				}
			}
		}

		return false;
	}