GithubHelp home page GithubHelp logo

brandonwamboldt / utilphp Goto Github PK

View Code? Open in Web Editor NEW
1.0K 73.0 129.0 1010 KB

util.php is a collection of useful functions and snippets that you need or could use every day, designed to avoid conflicts with existing projects

Home Page: http://brandonwamboldt.github.com/utilphp/

License: MIT License

PHP 100.00%

utilphp's Introduction

Util.php Build Status Coverage Status

UtilPHP (Aka util.php) is a collection of useful functions and snippets that you need or could use every day. It's implemented as a class with static methods, to avoid conflicts with your existing code-base. Just drop it in and start using it immediately.

Included are 55+ functions that provide you with the ability to do common tasks much easier and more efficiently, without having to find that one comment on php.net where you know it's been done already. Access superglobals without checking to see if certain indexes are set first and pass default values, use a nicely formatted var dump, validate emails, generate random strings, flatten an array, pull a single column out of a multidimensional array and much more.

Although it's implemented as one giant class, util.php has extensive documentation and a full suite of unit tests to avoid breaking backwards-compatibility unintentionally.

Release Information

This repo contains in development code for future releases as well as the current stable branch. Development code is contained in the develop branch.

Changelog and New Features

You can find a list of all changes for each release in the official documentation

Installation

Server Requirements

  • PHP version 5.3.3 or higher.

Standalone File

Simply drop util.php in any project and call include 'util.php'; in your project. You can then access the Util class.

Composer

Add the following dependency to your composer.json:

"brandonwamboldt/utilphp": "1.0.*"

When used with composer, the class is namespaced (\utilphp\util) instead of just util.

Contributing

UtilPHP is a community driven project and accepts contributions of code and documentation from the community. These contributions are made in the form of Issues or Pull Requests on the UtilityPHP repository on GitHub.

Issues are a quick way to point out a bug. If you find a bug or documentation error in UtilityPHP then please check a few things first:

  • There is not already an open Issue
  • The issue has already been fixed (check the develop branch, or look for closed Issues)
  • Is it something really obvious that you fix it yourself?

Reporting issues is helpful but an even better approach is to send a Pull Request, which is done by "Forking" the main repository and committing to your own copy. This will require you to use the version control system called Git.

Guidelines

Before we look into how, here are the guidelines. If your Pull Requests fail to pass these guidelines it will be declined and you will need to re-submit when you’ve made the changes. This might sound a bit tough, but it is required for me to maintain quality of the code-base.

PHP Style

Please ensure all new contributions match the PSR-2 coding style guide.

Documentation

If you change anything that requires a change to documentation then you will need to add it. New methods, parameters, changing default values, adding constants, etc are all things that will require a change to documentation. The change-log must also be updated for every change. Also PHPDoc blocks must be maintained.

PHP Version Compatibility

UtilityPHP is compatible with PHP 5.3.3 so all code supplied must stick to this requirement.

Of particular note is avoiding short array notation like this:

$var = [];

Please use the old notation instead:

$var = array();

I know it's uglier, but PHP 5.3 while EOL'd, still isn't that old.

Branching

One thing at a time: A pull request should only contain one change. That does not mean only one commit, but one change - however many commits it took. The reason for this is that if you change X and Y but send a pull request for both at the same time, we might really want X but disagree with Y, meaning we cannot merge the request. Using the Git-Flow branching model you can create new branches for both of these features and send two requests.

License

UtilPHP is licensed under the MIT license.

Resources

utilphp's People

Contributors

abhimanyu003 avatar alihamze avatar aracoool avatar bobdenotter avatar bradp avatar brandonwamboldt avatar cbulock avatar edito avatar gargaj avatar hopeseekr avatar jamesk322 avatar jremes-foss avatar lilobase avatar lyrixx avatar melt-snow avatar navarr avatar pborreli avatar psaunders88 avatar scottchiefbaker avatar smoqadam avatar softwarespot avatar userlond avatar wapmorgan avatar yoosefi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

utilphp's Issues

util::var_dump high memory consumption

hello,
I noticed that the function util :: var_dump () with large variable has a large RAM consumption.
We are talking about a relatively large object from a total of 75 properties (Smarty variables, as well as project-related variables).

Allowed memory size of 268435456 bytes exhausted (tried to allocate 551 bytes) in ../abnahme/core/classes/Util.class.php on line 230

We use an Apache web server with PHP 5.5.18 on a Ubuntu server.

There aren't 2592000 seconds in a month or 31536000 seconds in a year

All the time constants are inaccurate, at least under certain circumstances. Time math is more complex than that (leap years and seconds, DST changes etc.) and requires a proper time library to be accurate. PHP already comes with a pretty competent implementation in the form of the DateTime class.

1.2 BC break to refactor loose data

OK,

I propose you change the scope level of all of util's public properties to private. There is very little good reason for the end-dev to ever use them, and if there becomes a need, a getter method can be provided.

This is a minor BC break, so I don't think it'd require an upping of the major version to 2.

Add xss function

Hi,

It's a very cool lib, could you add a function against xss attack please ?

Cheers,
Arrowbaz.

array_first and array_last alias standard library functions

PHP is already an extremely high-level "framework" and it has functions for practically everything. Are you sure you want to obfuscate the standard library with aliases like array_first and array_last?

public static function array_first( array $array )
{
    return reset( $array );
}

public static function array_last( array $array )
{
    return end( $array );
}

If someone doesn't know how to use the reset and end functions it's not doing them any favors to wrap them in another name.

Added function to delete a dir recursive

/**
     * Deletes a dir recursive
     * @param string $path
     * @return boolean
     */

    public static function deleteDirRecursive($path) {
        if (is_dir($path) === true) {
            $files = array_diff(scandir($path), array('.', '..'));

            // Get all Files in Dir
            foreach ($files as $file) {
                self::deleteDirRecursive(realpath($path) . '/' . $file);
            }
            return rmdir($path);
        }

        // Delete File
        else if (is_file($path) === true) {
            return unlink($path);
        }
        return false;
    }

slugify() contains unnecessary replaces

The slugify function contains this code for replacement:

$slug = preg_replace( '/([^A-Za-z0-9\-]+)/', '-', strtolower( self::remove_accents( $string ) ) );
$slug = preg_replace( '/(\-+)/', '-', $slug );

However, it can be optimized in the following ways:

  • Remove A-Z from the match regex - this is not needed since strtolower is used
  • Remove \- from the 1st match regex and remove the second preg_replace. This causes 1 or more sequences of - (and other characters) to be replaced in the first preg_replace call.

The final replace call would then be:

$slug = preg_replace( '/([^a-z0-9]+)/', '-', strtolower( self::remove_accents( $string ) ) );

Also it might help to wrap that output in trim(..., '-') since characters outside the [a-z0-9] range might occur at the beginning or end of a string -- and you probably wouldn't want a title like -a-simple-title.

performance and licensing issues with `remove_accents`

Your implementation of remove_accents has been lifted off WordPress (https://github.com/WordPress/WordPress/blob/master/wp-includes/formatting.php#L822) which is licensed under the GPL. This means that as long as you're using their code, you have to release your library under the GPL too.

Also, the function is really inefficient as it builds that huge replacement table every time it's called. If you have to generate many slugs, you start to spend more and more time calling chr() instead of really doing something useful.

These replacement tables are static and you really don't need to generate them every time the function is called.

Use mb_* functions

I am wandering whether it would be good to use multi-byte string functions by default or have a wrapper for both e.g. strlen and mb_strlen?

You should not name the base class "util"

The name of the class is that "handy" that you will likely clash existing util classes. Name it "ptil" maybe. Or "until" in the sense until that PHP provides that missing functionality. Okay not that a good suggestion, so I better keep it simple:

As this is still PHP 5.2 based code, choose some name-spacing that will not crush that easily here. Also it might be useful to divide packages later on, so even if your concept is already monolithic, it can become modular at least.

Just my 2 cents. And thanks for sharing.

Severe License breach of UtilPHP

A verbatim copy of utilphp exists in the $58 PixelGrade Wordpress theme, bucket (http://themeforest.net/item/bucket-a-digital-magazine-style-wordpress-theme/6107209), but they seem to have both

  1. removed all references to UtilPHP,
  2. removed your copyright claim,
  3. claimed direct authorship of all of the code, and
  4. labeled your code as proprietary property of their company, expressly forbidding permissions to copy or redistribute it.

Evidence: https://github.com/madison-plus/madison-plus/blob/master/wp-content/themes/bucket/theme-utilities/bucket.php

Because it only postdates the release of utilphp by 33 days, this is a more serious matter and all efforts to reach out to the project maintainer should be taken, including a cease and desist letter to them if no response after 60 days, followed by a DMCA takedown (for just that file) to Github and various sites that include PixelGrade's bucket theme.

Besides, it's ethically and legally wrong to commandeer MIT-licensed work as one's own while simultaneously forbidding others the right to even reproduce it. It also violates clause 2 of your of license.

seems_utf8 is superfluous

The seems_utf8 function is superfluous and simply reimplements a subset of the already existing mb_check_encoding functionality in a complicated regex. Both appear to be working exactly the same, as can be demonstrated with this simple script:

require 'util.php';

while (true) {

    $str = null;

    for ($i = 0, $end = mt_rand(1, 100); $i <= $end; $i++) {
        $str .= chr(mt_rand(0, 255));
    }

    $mb = mb_check_encoding($str, 'UTF-8');
    $util = util::seems_utf8($str);

    if ($mb != $util) {
        echo bin2hex($str), PHP_EOL, 'Not in agreement!', PHP_EOL;
        exit;
    } else if ($mb) {
        echo PHP_EOL, bin2hex($str), PHP_EOL;
    } else {
        echo '.';
    }

}

I am not aware of any case that seems_utf8 would catch that mb_check_encoding doesn't.

`get_client_ip` is a security risk

HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP (and any other HTTP_* header) are arbitrary values sent by the client. Only REMOTE_ADDR is a trustable value as confirmed by the TCP/IP handshake. You should never use any other value for the client's IP, or anybody can spoof their own IP address trivially.

Need safeguards against GPL infection

I like UtilPHP. I also like how the project maintainer actively addresses pull requests and even includes a lot of them.

The main reason I can personally and corporately use UtilPHP is because it is permissively licensed under a non-copyleft license (currently the MIT License). But this could change, may have changed already, if just one function is committed from a GPL, LGPL, or APL licensed project.

Ideally, you would add language stating that only code which is specifically created for this project will be accepted, unless the submitter puts an appropriate source-of-origin comment in both the source code and the pull request.

Also, it would be helpful to add a requirement that forbids code from viral (so-called "copyleft") licenses, like all of the Free Software Foundation licenses and even the Creative Commons ShareAlike licenses.

This is doubly important as UtilPHP is a library.

Thanks.

is_https does not work with SSL proxies like Pound or Varnish Hitch

https://github.com/brandonwamboldt/utilphp/blob/master/src/utilphp/util.php#L775

Most of the mentioned systems can add an extra header to the request which is usually:

X_FORWARDED_PROTO = "https"

I agree that there is no standard (known to me) for this header-value solution, but common setups suggest the above example.

Extending the checks, to look for this header, and the right value would enable is_https to detect SSL Proxy setups.

I found a possible solution here: http://amal.net/?p=3991

function is_ssl() {
    if ( isset($_SERVER['HTTPS']) ) {
        if ( 'on' == strtolower($_SERVER['HTTPS']) ) return true;
        if ( '1' == $_SERVER['HTTPS'] ) return true;
    } elseif ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && ( 'https' == strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) ) ) {
        return true;
    } elseif ( isset($_SERVER['X_FORWARDED_PROTO']) && ( 'https' == strtolower($_SERVER['X_FORWARDED_PROTO']) ) ) {
        return true;
    }
    return false;
}

Supporting 5.5 and above

Maybe this library should support versions of PHP that are still receiving security updates? The reason I say this, is because the web is about moving forward and not living in the past! If you support 5.3+, then you're encouraging developers not to upgrade to supported versions of PHP. Thanks for listening.

seconds to human -function

function which would convert seconds to human time would actually be very useful

echo util::sec_to_human(3600); // 1h

or bit more verbose like

echo util::sec_to_human(12345); // 3 hours, 25 minutes, 45 seconds

seems_utf8 uses an incomplete regex and will match invalid characters

seems_utf8 - That will match invalid characters. The real regex to check for proper UTF8 is much more complicated:

'/(
    | [\xF8-\xFF] # Invalid UTF-8 Bytes
    | [\xC0-\xDF](?![\x80-\xBF]) # Invalid UTF-8 Sequence Start
    | [\xE0-\xEF](?![\x80-\xBF]{2}) # Invalid UTF-8 Sequence Start
    | [\xF0-\xF7](?![\x80-\xBF]{3}) # Invalid UTF-8 Sequence Start
    | (?<=[\x0-\x7F\xF8-\xFF])[\x80-\xBF] # Invalid UTF-8 Sequence Middle
    | (?<![\xC0-\xDF]|[\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF]|[\xF0-\xF7]|[\xF0-\xF7][\x80-\xBF]|[\xF0-\xF7][\x80-\xBF]{2})[\x80-\xBF] # Overlong Sequence
    | (?<=[\xE0-\xEF])[\x80-\xBF](?![\x80-\xBF]) # Short 3 byte sequence
    | (?<=[\xF0-\xF7])[\x80-\xBF](?![\x80-\xBF]{2}) # Short 4 byte sequence
    | (?<=[\xF0-\xF7][\x80-\xBF])[\x80-\xBF](?![\x80-\xBF]) # Short 4 byte sequence (2)
)/x',

If that regex matches, there are invalid UTF8 bytes...

Thanks to ircmaxell on reddit

array_get unnecessary complicated

Why not just implement it as the following?

function array_get(& $var, $default)
{
    if (isset($var))
        return $var;
    else
        return $default;
}

Then you can use it as

$action = array_get($_GET['action']['do'], 'index');

`validate_email` should use existing filter extension

Instead of a hard-to-maintain and hard to understand regex, util::validate_email should be:

return filter_var($email, FILTER_VALIDATE_EMAIL);

On the other hand, that means util::validate_email is not really needed.

var_dump may cause 500 Internal Server Error - requires mbstring

Unless I'm doing something wrong, it seems var_dump can't always handle some classes. I tried the following from $ php -a (interactive):

php > include "util.php";
php > $mysqli = new mysqli("host", "user", "pword", "dbname"); // change these values to an actual mysql db
php > util::var_dump($mysqli);
PHP Fatal error: Call to undefined function mb_internal_encoding() in /opt/kaltura/app/alpha/web/jorge/util.php on line 759
$

and yes php quits. so when this happens on apache of course there's a 500 HTTP error (and no error message is printed).

I am using PHP 5.3.3 in an environment where I can't re-compile it to include the mb_ functions (which are not part of a default php extension). This might actually be an issue of compatibility which will break util randomly as I continue to try and use it.

I feel the requirement for the mbstring extension should be expressed clearly in the README. Alternatively, if the 6 calls to mb_ functions can be substituted in util.php this would make the project more compatible.

Implement all desired Illuminate/Support functions?

Apparently, overdependence on Illuminate/Support from Laravel is a pressing problem for the PHP community, since it is depended on by over 6,000 packages, mostly for superfluous needs primarily around its utility functions related to arrays.

I nominate that we implement the functions in their Collection class that we currently do not implement. And then we market this project as The Solution to the over-reliance of the heavy-requirements Illuminate/Support.

http://mattallan.org/2016/dont-use-illuminate-support/

The utf8 conversion functions should not exist

It is fundamentally impossible to 100% accurately guess the encoding of a string and convert it based on that guess. You need to know what encoding a string is in and convert it according to that knowledge. If you do not know what encoding a string is in, you should solve that problem first.

When you know the encoding, iconv or mb_convert_encoding are perfectly adequate to convert from anything to anything else.

PHPUnit won't run after last patch

Hi all, just to let you know: PHPUnit does not run any longer.

Error message:

➜ utilphp git:(master) ✗ phpunit
PHPUnit 4.5.0 by Sebastian Bergmann and contributors.

Cannot open file "/var/www/html/utilphp/vendor/autoload.php".

This started happening when I checked out the latest repository.

Is it just my PHPUnit or is there something wrong with the repo unit testing?

Thanks.

Should var_dump_plain() be a protected method?

var_dump_plain() is not listed in the documentation, and it seems to just be a worker for var_dump(). Should it be a protected method?

Also, I cannot easily use PHP's internal var_dump() with Postman for debugging REST responses, because when xdebug is installed, var_dump() returns HTML output. I could actually really use a HTML-stripped var_dump(), which var_dump_plain() sounds like it should provide.

Invalid version string

I've tried to install via composer but return "Could not parse version constraint utilphp: Invalid version string "utilphp"

Any suggestion?

util::number_to_word(50)

All the tests pass, but when I try to render "50" with util::number_to_word it renders blank. I have a list of numbers 25, 50, 75, & 100 that all render correctly other than 50. Why would this be?

error example

already, thank you for this excellent library that saves time!
by cons there is a small bug in the example of the doc for xxlinkifyxx function

util :: Linkify ('this string: has a link to www.google.com');
=> Returns 'this string: has a link to www.google.com'

this returns the text without the link

I must specify the http:// for than the link is converted

> util :: Linkify ('this string: has a link to http://www.google.com');
> => Returns 'this string: has a link to <a href="http://wwww.google.com/" > http://www.google.com </a>'

Method `absint` is superfluous

There is no use case where util::absint($var) has any advantage over a simple abs($var).
The method should be removed.

util.php contains class Util

Hi,

I can't use the newest version, because some time ago the class was renamed to Util from util, without renaming the file. That leads to problems on systems without case-insensitive filesystems.

Error in util::array_search_deep

If i use the function like in the example:

util::array_search_deep('rogue_coder', $users, 'username');

I get a PHP error.

The correct usage is:

util::array_search_deep($users, 'rogue_coder', 'username');

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.