How to get all php member variables with phpcs - php

I am trying to get a list of class variables using phpcs but can only get a list of all variables in the file. Has anyone got any ideas on achieving this?
Sniff Code
for ($i = $stackPtr; $i < count ($tokens); $i++) {
$variable = $phpcsFile->findNext(T_VARIABLE, ($i));
if ($variable !== false) {
print ($variable);
} else {
break;
}
}
File to analyse
<?PHP
/**
* #package xxxx
* #subpackage Pro/System/Classes
* #copyright
* #author
* #link
*/
class Test_Class_AAA {
const CONSTANT = 'constant value';
public $var1 = 12;
const CONSTANT2 = 'constant value 2';
/**
* Return record schema details given a LabelIndentifier/LabelNumber or
* TransactionCode.
*
* #param string $type record type
* #param string $myextralongparam record type
* #return array record schema details (or null)
*/
private function func ($type,$myextralongparam) {
if (true) {
$x = 10;
$y = 11;
$z = $x + $y;
$f = $x - $y
$f = $x * $t;
$f = $x / $y;
$f = $x % $y;
$f = $x ** $y;
$f += 1;
$f -= 1;
$f *= 1;
$f /= 1;
$f %= 1;
if ($x === $y) {
}
if ($x !== $y) {
}
if ($x < $y) {
}
if ($x > $y) {
}
if ($x <= $y) {
}
if ($x >= $y) {
}
++$x;
} else {
}
while (true) {
}
do {
} while (true);
for ($i = 0; $i < 5; $i++) {
}
};
/**
* Return record schema details given a LabelIndentifier/LabelNumber or
* TransactionCode.
*
* #return array record schema details (or null)
*/
public function __construct () {
print "In BaseClass constructor\n";
}
}

I have made ClassWrapper exactly for these use cases.
You can find inspiration here, in getPropertyNames() method:
/**
* Inspired by #see TokensAnalyzer.
*
* #return string[]
*/
public function getPropertyNames(): array
{
if ($this->propertyNames) {
return $this->propertyNames;
}
$classOpenerPosition = $this->classToken['scope_opener'] + 1;
$classCloserPosition = $this->classToken['scope_closer'] - 1;
$propertyTokens = $this->findClassLevelTokensType($classOpenerPosition, $classCloserPosition, T_VARIABLE);
$this->propertyNames = $this->extractPropertyNamesFromPropertyTokens($propertyTokens);
$this->propertyNames = array_merge($this->propertyNames, $this->getParentClassPropertyNames());
return $this->propertyNames;
}

Related

PHP - Location inside multiple polygons

How can i turn this in to supporting more polygons than just this one? I think of something with arrays but I’m lost this code works with one polygon but just can’t get any further this is what I got:
I would like it to check if the point is in polygon A or B or C and so on depending on how many polygons I got right now it only checking if point is inside polygon A.
class Point {
public $lat;
public $long;
function Point($lat, $long) {
$this->lat = $lat;
$this->long = $long;
}
}
//the Point in Polygon function
function pointInPolygon($p, $polygon) {
//if you operates with (hundred)thousands of points
set_time_limit(60);
$c = 0;
$p1 = $polygon[0];
$n = count($polygon);
for ($i=1; $i<=$n; $i++) {
$p2 = $polygon[$i % $n];
if ($p->long > min($p1->long, $p2->long)
&& $p->long <= max($p1->long, $p2->long)
&& $p->lat <= max($p1->lat, $p2->lat)
&& $p1->long != $p2->long) {
$xinters = ($p->long - $p1->long) * ($p2->lat - $p1->lat) / ($p2->long - $p1->long) + $p1->lat;
if ($p1->lat == $p2->lat || $p->lat <= $xinters) {
$c++;
}
}
$p1 = $p2;
}
// if the number of edges we passed through is even, then it's not in the poly.
return $c%2!=0;
}
$polygon = array(
new Point(54.992883, -9.860767),
new Point(54.992775, -9.860289),
new Point(54.992236,- 9.861030),
new Point(54.992473, -9.862007)
);

Rewrite a PHP function with arrays instead

Is there any way I could rewrite this function with an array instead of all these if statements? Could i maybe use some for loop together with an array? How would that look like? Any suggestions of simpler code?
Here is my php function:
function to_next_level($point) {
/*
**********************************************************************
*
* This function check how much points user has achievents and how much procent it is until next level
*
**********************************************************************
*/
$firstlevel = "3000";
$secondlevel = "7000";
$thirdlevel = "15000";
$forthlevel = "28000";
$fifthlevel = "45000";
$sixthlevel = "80000";
if($point <= $firstlevel) {
$total = ($point/$firstlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
} elseif ($point <= $secondlevel) {
$total = ($point/$secondlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
} elseif ($point <= $thirdlevel) {
$total = ($point/$thirdlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
} elseif ($point <= $forthlevel) {
$total = ($point/$forthlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
} elseif ($point <= $fifthlevel) {
$total = ($point/$fifthlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
} elseif ($point <= $sixthlevel) {
$total = ($point/$sixthlevel) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
}
}
Try this:
function to_next_level($point) {
/*
**********************************************************************
*
* This function check how much points user has achievents and how much procent it is until next level
*
**********************************************************************
*/
$levelArray = array(3000, 7000, 15000, 28000, 45000, 80000);
foreach ($levelArray as $level)
{
if ($point <= $level) {
$total = ($point/$level) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
}
}
}
Start using OOP programming style. This is the perfect opportunity since it is a task without much complexity. Create a class that acts as central authority. That class can receive more methods over time. That way your code stays easy to maintain since all those functions are kept inside a class.
<?php
class levelAuthority
{
public static $thresholds = [ 3000, 7000, 15000, 28000, 45000, 80000 ];
public static function getDistanceToNextlevel($points)
{
foreach (self::$thresholds as $threshold) {
if ($points <= $threshold) {
$total = ($points/$threshold) * 100;
$remaining = round($total);
return $remaining;
}
}
}
}
// in the calling scope:
$points = 5000;
echo levelAuthority::getDistanceToNextlevel($points);
lots of answers to this!!
here is mine using a while loop - single exit point outside the loop:
function to_next_level($point) {
/*
**********************************************************************
*
* This function check how much points user has achievements and how much percent it is until next level
*
**********************************************************************
*/
$arr_level = array(3000,15000,28000,45000,80000);
$remaining = false;
while (!$remaining and list($key,$level) = each($arr_level)) {
if ($point <= $level) {
$total = ($point/$level) * 100;
$remaining = round($total);
}
}
// will return false if $point is greater than highest value in $arr_level
return $remaining;
}
You could write an additional function, that does the calculations and trigger it from the if/else if/else blocks.
function calculate_remaining($points, $level) {
$total = ($point/$level) * 100;
$remaining = round($total);
return $remaining;
}
You'd trigger this like:
if($point <= $firstlevel) {
return $calculate_remaining($point, $firstlevel);
} elseif ($point <= $secondlevel) {
return $calculate_remaining($point, $secondlevel);
} etc.
What about something like this?
function to_next_level($point)
{
$levels = array(
3000,
7000,
15000,
28000,
45000,
80000
);
foreach ($levels as $level)
{
if ($point <= $level)
{
$total = ($point / $level) * 100;
$remaining = round($total);
//echo number_format($remaining, 0, '.', ' ');
return $remaining;
}
}
}
The point levels are in order in the array, so [0] is $firstlevel, and so on. You simply iterate through the array and return whenever we reach the condition where $point is <= to the the $level.
Also, since $levels is static, it can be defined outside of the function.
simple:
<?php
$point = 100;
$remaining = 0;
$data = [
'firstlevel' => 3000,
'secondlevel' => 7000,
'thirdlevel' => 15000,
'forthlevel' => 28000,
'fifthlevel' => 45000,
'sixthlevel' => 80000
];
foreach($data as $item)
{
if($point <= $item)
{
$remaining = round(($point / $item ) * 100); //or return val
}
}
How about putting your variable into array and loop it?
function to_next_level($point) {
$data[0] = "3000";
$data[1] = "7000";
$data[2] = "15000";
$data[3] = "28000";
$data[4] = "45000";
$data[5] = "80000";
foreach ($data as $key => $value) {
if($point <= $value) {
$total = ($point/$value) * 100;
$remaining = round($total);
return $remaining;
}
}
}
I haven't try it. But it might work for you.

Refactoring comparision/operators blocks to DRY up and reduce C.R.A.P level

I set out to make a small project around a bounch of classes that return generators (php 5.5).
The main motivation for the small project was to expand on my TDD journey, fiddle with generators and have a package I could throw on packagist for later use.
The current state of the whole "project" can be found at Github
All tests are green, the methods does what I want. Now I want to refactor as I there is lots of dublication.
/**
* Returns a Generator with a even range.
*
* getEven(10); // 10,12,14,16,18,20,22 ...
* getEven(null, 10); // 10,8,6,4,2,0,-2,-4 ...
* getEven(10, null, 2); // 10,6,2, -2 ...
* getEven(10,20); // 10,12,14,16,18,20
* getEven(20,10); // 20,18,16,14,12,10
* getEven(10,20,2); // 10,14,18
*
* #param int|null $start
* #param int|null $end
* #param int $step
* #throws InvalidArgumentException|LogicException
* #return Generator
*/
public function getEven( $start = null, $end = null, $step = 1 )
{
// Throws LogicException
$this->throwExceptionIfAllNulls( [$start, $end] );
$this->throwExceptionIfInvalidStep($step);
// Throws InvalidArgumentException
$this->throwExceptionIfNotNullOrInt( [$start, $end] );
// infinite increase range
if(is_int($start) && is_null($end))
{
// throw LogicException
$this->throwExceptionIfOdd($start);
$Generator = function() use ($start, $step)
{
for($i = $start; true; $i += $step * 2)
{
yield $i;
}
};
}
// infinite decrease range
elseif(is_int($end) && is_null($start))
{
// throws LogicException
$this->throwExceptionIfUneven($end);
$Generator = function() use ($end, $step)
{
for($i = $end; true; $i -= $step * 2)
{
yield $i;
}
};
}
// predetermined range
else
{
// throws LogicException
$this->throwExceptionIfUneven($start);
$this->throwExceptionIfUneven($end);
// decrease
if($start >= $end)
{
$Generator = function() use ($start, $end, $step)
{
for($i = $start; $i >= $end; $i -= $step * 2)
{
yield $i;
}
};
}
// increase
else
{
$Generator = function() use ($start, $end, $step)
{
for($i = $start; $i <= $end; $i += $step * 2)
{
yield $i;
}
};
}
}
return $Generator();
}
The class also has a method named getOdd (and yes it looks alot like it ;) )
The main dublication is the closures $Generator = function() ... and the difference is mostly operators such as + - * / and arguments in the for loop. This is mainly the same in the rest of th class.
I read Dynamic Comparison Operators in PHP and come to the conclusion that there is no native method like compare(...)
Should I make a private/protected method for comparison. If so should I make a new class/function for this? I do not think it belongs in the current class.
Is it something else I am missing, I am unsure on how to DRY this up, in a proper way?
Btw. iknow a getEven, getOdd is kinda silly when i got a getRange With step function, but it is a more general refactoring / pattern question.
Update
#github the getEven and getOdd are now removed...
The code below has not been tested or verified to work, but I have faith in it and at least it shows one possible way of removing the multiple generator functions.
As you state yourself, the duplication you are trying to remove is mainly in the generator function. If you look into this you can see that every generator function you have can be written as this:
function createGenerator($index, $limit, $step) {
return function() use($index, $limit, $step) {
$incrementing = $step > 0;
for ($i = $index; true; $i += 2 * $step) {
if (($incrementing && $i <= $limit) || (!$incrementing && $i >= $limit)) {
yield $i;
}else {
break;
}
}
};
}
In order to utilize this you need to do some magic with the input arguments and it helps (at least makes it pretty) to define some constants. PHP allready got a PHP_INT_MAX constant holding the greatest value possible for an integer, however it does not got a PHP_INT_MIN. So I would define that as a constant of its own.
define('PHP_INT_MIN', ~PHP_INT_MAX);
Now lets take a look at the four cases in your function.
1) Infinite increase range
Infinte is a rather bold claim here, if we change it to "greatest value possible given the constraints of an int" we get a finite range from $index to PHP_INT_MAX, hence by setting $limit = PHP_INT_MAX; the above mentioned generator function will still be the same.
//$limit = PHP_INT_MAX;
createGenerator($index, PHP_INT_MAX, $step);
2) Infinite decrease range
The same argument as above can again be used here, but with a negativ $step and swapping $index and $limit;
//$index = $limit;
//$limit = PHP_INT_MIN;
//$step *= -1;
createGenerator($limit, PHP_INT_MIN, -1 * $step);
3) Predetermined decreasing range
Swap and negate once again.
//$temp = $index;
//$index = $limit;
//$limit = $temp;
//$step *= -1;
createGenerator($limit, $index, -1 * $step);
4) Predetermined increasing range
Well this is just the default case, where all arguments are given. And nothing needs to change.
createGenerator($index, $limit, $step);
The revised code
public function getEven($index = null, $limit = null, $step = 1) {
// Throws LogicException
$this->throwExceptionIfAllNulls([$index, $limit]);
$this->throwExceptionIfInvalidStep($step);
// Throws InvalidArgumentException
$this->throwExceptionIfNotNullOrInt([$index, $limit]);
//Generator function
function createGenerator($index, $limit, $step) {
return function() use($index, $limit, $step) {
$incrementing = $step > 0;
for ($i = $index; true; $i += 2 * $step) {
if (($incrementing && $i <= $limit) || (!$incrementing && $i >= $limit)) {
yield $i;
}else {
break;
}
}
};
}
// infinite increase range
if (is_int($index) && is_null($limit)) {
// throw LogicException
$this->throwExceptionIfodd($index);
return createGenerator($index, PHP_INT_MAX, $step);
}
// infinite decrease range
elseif (is_int($limit) && is_null($index)) {
// throws LogicException
$this->throwExceptionIfodd($limit);
return createGenerator($limit, PHP_INT_MIN, -1*$step);
}
// predetermined range
else {
// throws LogicException
$this->throwExceptionIfodd($index);
$this->throwExceptionIfodd($limit);
// decrease
if ($index >= $limit) {
return createGenerator($limit, $index, -1 * $step);
}
return createGenerator($index, $limit, $step);
}
}

Implementation of Rabin-Karp Algorithm with PHP

Hi I am writing a PHP class to implement Rabin-Karp algorithm. I have issue with re-hashing part. This code doesn't include matching part of the characters. I had to stop since it never matching hash codes due to the issue with re-hashing. Someone please help me to figure it out.
<?php
class RabinKarp
{
/**
* #var String
*/
private $pattern ;
private $patternHash ;
private $text ;
private $previousHash ;
/**
* #var Integer
*/
private $radix ;
private $prime ;
private $position ;
/**
* Constructor
*
* #param String $pattern - The pattern
*
*/
public function __construct($pattern)
{
$this->pattern = $pattern;
$this->radix = 256;
$this->prime = 100007;
$this->previousHash = "";
$this->position = 0;
$this->patternHash = $this->generateHash($pattern);
}
private function generateHash($key)
{
$charArray = str_split($key);
$hash = 0;
foreach($charArray as $char)
{
$hash = ($this->radix * $hash + ord($char)) % $this->prime;
}
return $hash;
}
public function search($character)
{
$this->text .= $character;
if(strlen($this->text) < strlen($this->pattern))
{
return false;
}
else
{
$txtHash = 0;
echo $this->previousHash . "<br/>";
if(empty($this->previousHash))
{
$txtHash = $this->generateHash($this->text);
$this->previousHash = $txtHash;
$this->position = 0;
}
else
{
// The issue is here
$charArray = str_split($this->text);
$txtHash = (($txtHash + $this->prime) - $this->radix * strlen($this->pattern) * ord($charArray[$this->position]) % $this->prime) % $this->prime;
$txtHash = ($txtHash * $this->radix + ord($character)) % $this->prime;
$this->previousHash = $txtHash;
}
if($txtHash == $this->patternHash)
{
echo "Hash Match found";
}
}
}
}
$x = new RabinKarp("ABC");
$x->search("Z");
$x->search("A");
$x->search("B");
$x->search("C");
?>
Thank you.
The value contributed to the hash by the character (c for shortness) you're removing is
ord(c) * radix^(length(pattern)-1)
since a character contributes ord(c) when it first enters the matching window, and the hash - therefore also its contribution - is multiplied with radix for each of the length(pattern)-1 characters entering the matching window until c finally leaves it.
But you're subtracting ord(c) * radix * length(pattern)
$charArray = str_split($this->text);
$txtHash = (($txtHash + $this->prime)
- $this->radix * strlen($this->pattern)
* ord($charArray[$this->position]) % $this->prime)
% $this->prime;
$txtHash = ($txtHash * $this->radix + ord($character)) % $this->prime;
Additionally, in the calculation you're using the variable $txtHash, which you've set to 0, that should be $this->previousHash, and you must increment the text position.
In principle,
$charArray = str_split($this->text);
$txtHash = (($this->previousHash + $this->prime)
- pow($this->radix, strlen($this->pattern)-1)
* ord($charArray[$this->position]) % $this->prime)
% $this->prime;
$txtHash = ($txtHash * $this->radix + ord($character)) % $this->prime;
$this->previousHash = $txtHash;
$this->position += 1;
is what you have to do.
But unless the pattern is very short, pow($this->radix,strlen($this->pattern)-1) will overflow, so you have to replace pow($this-radix, strlen($this->pattern)-1) with a modular exponentiation function
function mod_pow($base,$exponent,$modulus)
{
$aux = 1;
while($exponent > 0) {
if ($exponent % 2 == 1) {
$aux = ($aux * $base) % $modulus;
}
$base = ($base * $base) % $modulus;
$exponent = $exponent/2;
}
return $aux;
}
(this can still overflow if $modulus, that is $this->prime here, is too large). The relevant line of code becomes
$txtHash = (($this->previousHash + $this->prime)
- mod_pow($this->radix, strlen($this->pattern)-1, $this->prime)
* ord($charArray[$this->position]) % $this->prime)
% $this->prime;
Then you have a potentially huge inefficiency
$this->text .= $character;
...
$charArray = str_split($this->text);
If the string becomes long, the concatenation and the splitting may take a lot of time (not sure how PHP implements strings and string operations, but they're likely not constant time). You should probably keep only the relevant part of the string, i.e. drop the first character after recalculating the hash.

Scrambled PHP code needs some fixing

I was adding a modification for my phpBB3 discussion board and one of the steps was to add a line of code to includes/functions.php
So when I copied that file and opened in wordpad I saw that it looked all scrambled. Here is how it looks partly:
<?php /** * * #package phpBB3 * #version $Id$ * #copyright (c) 2005 phpBB Group * #license http://opensource.org/licenses/gpl-license.php GNU Public License * */ /** * #ignore */ if (!defined('IN_PHPBB')) { exit; } // Common global functions /** * set_var * * Set variable, used by {#link request_var the request_var function} * * #access private */ function set_var(&$result, $var, $type, $multibyte = false) { settype($var, $type); $result = $var; if ($type == 'string') { $result = trim(htmlspecialchars(str_replace(array("\r\n", "\r", "\0"), array("\n", "\n", ''), $result), ENT_COMPAT, 'UTF-8')); if (!empty($result)) { // Make sure multibyte characters are wellformed if ($multibyte) { if (!preg_match('/^./u', $result)) { $result = ''; } } else { // no multibyte, allow only ASCII (0-127) $result = preg_replace('/[\x80-\xFF]/', '?', $result); } } $result = (STRIP) ? stripslashes($result) : $result; } } /** * request_var * * Used to get passed variable */ function request_var($var_name, $default, $multibyte = false, $cookie = false) { if (!$cookie && isset($_COOKIE[$var_name])) { if (!isset($_GET[$var_name]) && !isset($_POST[$var_name])) { return (is_array($default)) ? array() : $default; } $_REQUEST[$var_name] = isset($_POST[$var_name]) ? $_POST[$var_name] : $_GET[$var_name]; } $super_global = ($cookie) ? '_COOKIE' : '_REQUEST'; if (!isset($GLOBALS[$super_global][$var_name]) || is_array($GLOBALS[$super_global][$var_name]) != is_array($default)) { return (is_array($default)) ? array() : $default; } $var = $GLOBALS[$super_global][$var_name]; if (!is_array($default)) { $type = gettype($default); } else { list($key_type, $type) = each($default); $type = gettype($type); $key_type = gettype($key_type); if ($type == 'array') { reset($default); $default = current($default); list($sub_key_type, $sub_type) = each($default); $sub_type = gettype($sub_type); $sub_type = ($sub_type == 'array') ? 'NULL' : $sub_type; $sub_key_type = gettype($sub_key_type); } } if (is_array($var)) { $_var = $var; $var = array(); foreach ($_var as $k => $v) { set_var($k, $k, $key_type); if ($type == 'array' && is_array($v)) { foreach ($v as $_k => $_v) { if (is_array($_v)) { $_v = null; } set_var($_k, $_k, $sub_key_type, $multibyte); set_var($var[$k][$_k], $_v, $sub_type, $multibyte); } } else { if ($type == 'array' || is_array($v)) { $v = null; } set_var($var[$k], $v, $type, $multibyte); } } } else { set_var($var, $var, $type, $multibyte); } return $var; } /** * Set config value. Creates missing config entry. */ function set_config($config_name, $config_value, $is_dynamic = false) { global $db, $cache, $config; $sql = 'UPDATE ' . CONFIG_TABLE . " SET config_value = '" . $db->sql_escape($config_value) . "' WHERE config_name = '" . $db->sql_escape($config_name) . "'"; $db->sql_query($sql); if (!$db->sql_affectedrows() && !isset($config[$config_name])) { $sql = 'INSERT INTO ' . CONFIG_TABLE . ' ' . $db->sql_build_array('INSERT', array( 'config_name' => $config_name, 'config_value' => $config_value, 'is_dynamic' => ($is_dynamic) ? 1 : 0)); $db->sql_query($sql); } $config[$config_name] = $config_value; if (!$is_dynamic) { $cache->destroy('config'); } } /** * Set dynamic config value with arithmetic operation. */ function set_config_count($config_name, $increment, $is_dynamic = false) { global $db, $cache; switch ($db->sql_layer) { case 'firebird': case 'postgres': $sql_update = 'CAST(CAST(config_value as DECIMAL(255, 0)) + ' . (int) $increment . ' as VARCHAR(255))'; break; // MySQL, SQlite, mssql, mssql_odbc, oracle default: $sql_update = 'config_value + ' . (int) $increment; break; } $db->sql_query('UPDATE ' . CONFIG_TABLE . ' SET config_value = ' . $sql_update . " WHERE config_name = '" . $db->sql_escape($config_name) . "'"); if (!$is_dynamic) { $cache->destroy('config'); } } /** * Generates an alphanumeric random string of given length * * #return string */ function gen_rand_string($num_chars = 8) { // [a, z] + [0, 9] = 36 return substr(strtoupper(base_convert(unique_id(), 16, 36)), 0, $num_chars); } /** * Generates a user-friendly alphanumeric random string of given length * We remove 0 and O so users cannot confuse those in passwords etc. * * #return string */ function gen_rand_string_friendly($num_chars = 8) { $rand_str = unique_id(); // Remove Z and Y from the base_convert(), replace 0 with Z and O with Y // [a, z] + [0, 9] - {z, y} = [a, z] + [0, 9] - {0, o} = 34 $rand_str = str_replace(array('0', 'O'), array('Z', 'Y'), strtoupper(base_convert($rand_str, 16, 34))); return substr($rand_str, 0, $num_chars); } /** * Return unique id * #param string $extra additional entropy */ function unique_id($extra = 'c') { static $dss_seeded = false; global $config; $val = $config['rand_seed'] . microtime(); $val = md5($val); $config['rand_seed'] = md5($config['rand_seed'] . $val . $extra); if ($dss_seeded !== true && ($config['rand_seed_last_update'] < time() - rand(1,10))) { set_config('rand_seed', $config['rand_seed'], true); set_config('rand_seed_last_update', time(), true); $dss_seeded = true; } return substr($val, 4, 16); } /** * Return formatted string for filesizes * * #param int $value filesize in bytes * #param bool $string_only true if language string should be returned * #param array $allowed_units only allow these units (data array indexes) * * #return mixed data array if $string_only is false * #author bantu */ function get_formatted_filesize($value, $string_only = true, $allowed_units = false) { global $user; $available_units = array( 'gb' => array( 'min' => 1073741824, // pow(2, 30) 'index' => 3, 'si_unit' => 'GB', 'iec_unit' => 'GIB', ), 'mb' => array( 'min' => 1048576, // pow(2, 20) 'index' => 2, 'si_unit' => 'MB', 'iec_unit' => 'MIB', ), 'kb' => array( 'min' => 1024, // pow(2, 10) 'index' => 1, 'si_unit' => 'KB', 'iec_unit' => 'KIB', ), 'b' => array( 'min' => 0, 'index' => 0, 'si_unit' => 'BYTES', // Language index 'iec_unit' => 'BYTES', // Language index ), ); foreach ($available_units as $si_identifier => $unit_info) { if (!empty($allowed_units) && $si_identifier != 'b' && !in_array($si_identifier, $allowed_units)) { continue; } if ($value >= $unit_info['min']) { $unit_info['si_identifier'] = $si_identifier; break; } } unset($available_units); for ($i = 0; $i < $unit_info['index']; $i++) { $value /= 1024; } $value = round($value, 2); // Lookup units in language dictionary $unit_info['si_unit'] = (isset($user->lang[$unit_info['si_unit']])) ? $user->lang[$unit_info['si_unit']] : $unit_info['si_unit']; $unit_info['iec_unit'] = (isset($user->lang[$unit_info['iec_unit']])) ? $user->lang[$unit_info['iec_unit']] : $unit_info['iec_unit']; // Default to IEC $unit_info['unit'] = $unit_info['iec_unit']; if (!$string_only) { $unit_info['value'] = $value; return $unit_info; } return $value . ' ' . $unit_info['unit']; } /** * Determine whether we are approaching the maximum execution time. Should be called once * at the beginning of the script in which it's used. * #return bool Either true if the maximum execution time is nearly reached, or false * if some time is still left. */ function still_on_time($extra_time = 15) { static $max_execution_time, $start_time; $time = explode(' ', microtime()); $current_time = $time[0] + $time[1]; if (empty($max_execution_time)) { $max_execution_time = (function_exists('ini_get')) ? (int) #ini_get('max_execution_time') : (int) #get_cfg_var('max_execution_time'); // If zero, then set to something higher to not let the user catch the ten seconds barrier. if ($max_execution_time === 0) { $max_execution_time = 50 + $extra_time; } $max_execution_time = min(max(10, ($max_execution_time - $extra_time)), 50); // For debugging purposes // $max_execution_time = 10; global $starttime; $start_time = (empty($starttime)) ? $current_time : $starttime; } return (ceil($current_time - $start_time) < $max_execution_time) ? true : false; } /** * * #version Version 0.1 / slightly modified for phpBB 3.0.x (using $H$ as hash type identifier) * * Portable PHP password hashing framework. * * Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in * the public domain. * * There's absolutely no warranty. * * The homepage URL for this framework is: * * http://www.openwall.com/phpass/ * * Please be sure to update the Version line if you edit this file in any way. * It is suggested that you leave the main version number intact, but indicate * your project name (after the slash) and add your own revision information. * * Please do not change the "private" password hashing method implemented in * here, thereby making your hashes incompatible. However, if you must, please * change the hash type identifier (the "$P$") to something different. * * Obviously, since this code is in the public domain, the above are not * requirements (there can be none), but merely suggestions. * * * Hash the password */ function phpbb_hash($password) { $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; $random_state = unique_id(); $random = ''; $count = 6; if (($fh = #fopen('/dev/urandom', 'rb'))) { $random = fread($fh, $count); fclose($fh); } if (strlen($random) < $count) { $random = ''; for ($i = 0; $i < $count; $i += 16) { $random_state = md5(unique_id() . $random_state); $random .= pack('H*', md5($random_state)); } $random = substr($random, 0, $count); } $hash = _hash_crypt_private($password, _hash_gensalt_private($random, $itoa64), $itoa64); if (strlen($hash) == 34) { return $hash; } return md5($password); } /** * Check for correct password * * #param string $password The password in plain text * #param string $hash The stored password hash * * #return bool Returns true if the password is correct, false if not. */ function phpbb_check_hash($password, $hash) { $itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; if (strlen($hash) == 34) { return (_hash_crypt_private($password, $hash, $itoa64) === $hash) ? true : false; } return (md5($password) === $hash) ? true : false; } /** * Generate salt for hash generation */ function _hash_gensalt_private($input, &$itoa64, $iteration_count_log2 = 6) { if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31) { $iteration_count_log2 = 8; } $output = '$H$'; $output .= $itoa64[min($iteration_count_log2 + ((PHP_VERSION >= 5) ? 5 : 3), 30)]; $output .= _hash_encode64($input, 6, $itoa64); return $output; } /** * Encode hash */ function _hash_encode64($input, $count, &$itoa64) { $output = ''; $i = 0; do { $value = ord($input[$i++]); $output .= $itoa64[$value & 0x3f]; if ($i < $count) { $value |= ord($input[$i]) << 8; } $output .= $itoa64[($value >> 6) & 0x3f]; if ($i++ >= $count) { break; } if ($i < $count) { $value |= ord($input[$i]) << 16; } $output .= $itoa64[($value >> 12) & 0x3f]; if ($i++ >= $count) { break; } $output .= $itoa64[($value >> 18) & 0x3f]; } while ($i < $count); return $output; } /** * The crypt function/replacement */ function _hash_crypt_private($password, $setting, &$itoa64) { $output = '*'; // Check for correct hash if (substr($setting, 0, 3) != '$H$') { return $output; } $count_log2 = strpos($itoa64, $setting[3]); if ($count_log2 < 7 || $count_log2 > 30) { return $output; } $count = 1 << $count_log2; $salt = substr($setting, 4, 8); if (strlen($salt) != 8) { return $output; } /** * We're kind of forced to use MD5 here since it's the only * cryptographic primitive available in all versions of PHP * currently in use. To implement our own low-level crypto * in PHP would result in much worse performance and * consequently in lower iteration counts and hashes that are * quicker to crack (by non-PHP code). */ if (PHP_VERSION >= 5) { $hash = md5($salt . $password, true); do { $hash = md5($hash . $password, true); } while (--$count); } else { $hash = pack('H*', md5($salt . $password)); do { $hash = pack('H*', md5($hash . $password)); } while (--$count); } $output = substr($setting, 0, 12); $output .= _hash_encode64($hash, 16, $itoa64); return $output; } /** * Hashes an email address to a big integer * * #param string $email Email address * * #return string Unsigned Big Integer */ function phpbb_email_hash($email) { return sprintf('%u', crc32(strtolower($email))) . strlen($email); } /** * Global function for chmodding directories and files for internal use * * This function determines owner and group whom the file belongs to and user and group of PHP and then set safest possible file permissions. * The function determines owner and group from common.php file and sets the same to the provided file. * The function uses bit fields to build the permissions. * The function sets the appropiate execute bit on directories. * * Supported constants representing bit fields are: * * CHMOD_ALL - all permissions (7) * CHMOD_READ - read permission (4) * CHMOD_WRITE - write permission (2) * CHMOD_EXECUTE - execute permission (1) * * NOTE: The function uses POSIX extension and fileowner()/filegroup() functions. If any of them is disabled, this function tries to build proper permissions, by calling is_readable() and is_writable() functions. * * #param string $filename The file/directory to be chmodded * #param int $perms Permissions to set * * #return bool true on success, otherwise false * #author faw, phpBB Group */ function phpbb_chmod($filename, $perms = CHMOD_READ) { static $_chmod_info; // Return if the file no longer exists. if (!file_exists($filename)) { return false; } // Determine some common vars if (empty($_chmod_info)) { if (!function_exists('fileowner') || !function_exists('filegroup')) { // No need to further determine owner/group - it is unknown $_chmod_info['process'] = false; } else { global $phpbb_root_path, $phpEx; // Determine owner/group of common.php file and the filename we want to change here $common_php_owner = #fileowner($phpbb_root_path . 'common.' . $phpEx); $common_php_group = #filegroup($phpbb_root_path . 'common.' . $phpEx); // And the owner and the groups PHP is running under. $php_uid = (function_exists('posix_getuid')) ? #posix_getuid() : false; $php_gids = (function_exists('posix_getgroups')) ? #posix_getgroups() : false; // If we are unable to get owner/group, then do not try to set them by guessing if (!$php_uid || empty($php_gids) || !$common_php_owner || !$common_php_group) { $_chmod_info['process'] = false; } else { $_chmod_info = array( 'process' => true, 'common_owner' => $common_php_owner, 'common_group' => $common_php_group, 'php_uid' => $php_uid, 'php_gids' => $php_gids, ); } } } if ($_chmod_info['process']) { $file_uid = #fileowner($filename); $file_gid = #filegroup($filename); // Change owner if (#chown($filename, $_chmod_info['common_owner'])) { clearstatcache(); $file_uid = #fileowner($filename); } // Change group if (#chgrp($filename, $_chmod_info['common_group'])) { clearstatcache(); $file_gid = #filegroup($filename); } // If the file_uid/gid now match the one from common.php we can process further, else we are not able to change something if ($file_uid != $_chmod_info['common_owner'] || $file_gid != $_chmod_info['common_group']) { $_chmod_info['process'] = false; } } // Still able to process? if ($_chmod_info['process']) { if ($file_uid == $_chmod_info['php_uid']) { $php = 'owner'; } else if (in_array($file_gid, $_chmod_info['php_gids'])) { $php = 'group'; } else { // Since we are setting the everyone bit anyway, no need to do expensive operations $_chmod_info['process'] = false; } } // We are not able to determine or change something if (!$_chmod_info['process']) { $php = 'other'; } // Owner always has read/write permission $owner = CHMOD_READ | CHMOD_WRITE; if (is_dir($filename)) { $owner |= CHMOD_EXECUTE; // Only add execute bit to the permission if the dir needs to be readable if ($perms & CHMOD_READ) { $perms |= CHMOD_EXECUTE; } } switch ($php) { case 'owner': $result = #chmod($filename, ($owner << 6) + (0 << 3) + (0 << 0)); clearstatcache(); if (is_readable($filename) && phpbb_is_writable($filename)) { break; } case 'group': $result = #chmod($filename, ($owner << 6) + ($perms << 3) + (0 << 0)); clearstatcache(); if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename))) { break; } case 'other': $result = #chmod($filename, ($owner << 6) + ($perms << 3) + ($perms << 0)); clearstatcache(); if ((!($perms & CHMOD_READ) || is_readable($filename)) && (!($perms & CHMOD_WRITE) || phpbb_is_writable($filename))) { break; } default: return false; break; } return $result; } /** * Test if a file/directory is writable * * This function calls the native is_writable() when not running under * Windows and it is not disabled. * * #param string $file Path to perform write test on * #return bool True when the path is writable, otherwise false. */ function phpbb_is_writable($file) { if (strtolower(substr(PHP_OS, 0, 3)) === 'win' || !function_exists('is_writable')) { if (file_exists($file)) { // Canonicalise path to absolute path $file = phpbb_realpath($file); if (is_dir($file)) { // Test directory by creating a file inside the directory $result = #tempnam($file, 'i_w'); if (is_string($result) && file_exists($result)) { unlink($result); // Ensure the file is actually in the directory (returned realpathed) return (strpos($result, $file) === 0) ? true : false; } } else { $handle = #fopen($file, 'r+'); if (is_resource($handle)) { fclose($handle); return true; } } } else { // file does not exist test if we can write to the directory $dir = dirname($file); if (file_exists($dir) && is_dir($dir) && phpbb_is_writable($dir)) { return true; } } return false; } else { return is_writable($file); } } // Compatibility functions if (!function_exists('array_combine')) { /** * A wrapper for the PHP5 function array_combine() * #param array $keys contains keys for the resulting array * #param array $values contains values for the resulting array * * #return Returns an array by using the values from the keys array as keys and the * values from the values array as the corresponding values. Returns false if the * number of elements for each array isn't equal or if the arrays are empty. */ function array_combine($keys, $values) { $keys = array_values($keys); $values = array_values($values); $n = sizeof($keys); $m = sizeof($values); if (!$n || !$m || ($n != $m)) { return false; } $combined = array(); for ($i = 0; $i < $n; $i++) { $combined[$keys[$i]] = $values[$i]; } return $combined; } } if (!function_exists('str_split')) { /** * A wrapper for the PHP5 function str_split() * #param array $string contains the string to be converted * #param array $split_length contains the length of each chunk * * #return Converts a string to an array. If the optional split_length parameter is specified, * the returned array will be broken down into
As you can see all the new lines are cut so its just a big mess. I did still add the new code and it messed everything up. What can I do? Is there some type of script or anything that I can run this php file through that will fix lines? Note that I have no experience with PHP so please be detailed in your reply!
Both WordPad and Notepad++ handle UNIX-style newlines fine. I'm guessing that you or someone else previously opened and saved it with another program such as Notepad, which doesn't understand such newlines and probably messed it up. If you haven't modified the file so far, the simplest solution might be to get a fresh copy of this file from the phpBB3 archive.
The file was probably created in *Nix, and uses the Unix newlines. Wordpad likely can't handle those.
Try opening it up with a program that can handle the different types of newline styles, like Notepad++.
http://beta.phpformatter.com/
This will make your code look better.
See the other solutions or try:
<?php
file_put_contents("source-fixed.php",
str_replace("\n", "\r\n", file_get_contents("source.php")));
?>
Adjust the file names accordingly, of course.

Categories