bainternet /
PHP-Hooks
The PHP Hooks Class is a fork of the WordPress filters hook system rolled in to a class to be ported into any php based system .
Loading repository data…
tappleby / repository
Hooks into the laravel auth module and provides an auth token upon success. This token is really only secure in https environment. This main purpose for this module was to provide an auth token to javascript web app which could be used to identify users on api calls.
Hooks into the laravel auth module and provides an auth token upon success. This token is really only secure in https environment. This main purpose for this module was to provide an auth token to javascript web app which could be used to identify users on api calls.
Upgrading to Laravel 4.1?, see the breaking changes
Use composer to install this package.
$ composer require tappleby/laravel-auth-token:0.3.*
Add the service provider to app/config/app.php
'Tappleby\AuthToken\AuthTokenServiceProvider',
Setup the optional aliases in app/config/app.php
'AuthToken' => 'Tappleby\Support\Facades\AuthToken',
'AuthTokenNotAuthorizedException' => 'Tappleby\AuthToken\Exceptions\NotAuthorizedException'
Currently the auth tokens are stored in the database, you will need to run the migrations:
php artisan migrate --package=tappleby/laravel-auth-token
This package defaults to using email as the username field to validate against, this can be changed via the package configuration.
php artisan config:publish tappleby/laravel-auth-tokenformat_credentials closure in app/config/packages/tappleby/laravel-auth-token/config.phpExample - Only validate active users and check the username column instead of email:
'format_credentials' => function ($username, $password) {
return array(
'username' => $username,
'password' => $password,
'active' => true
);
}
You can read more about the laravel Auth module here: Authenticating Users
A default controller is provided to grant, check and revoke tokens. Add the following to app/routes.php
Route::get('auth', 'Tappleby\AuthToken\AuthTokenController@index');
Route::post('auth', 'Tappleby\AuthToken\AuthTokenController@store');
Route::delete('auth', 'Tappleby\AuthToken\AuthTokenController@destroy');
CORS support is not built into this library by default, it can be enabled by using the following package: barryvdh/laravel-cors.
The configuration will be specific to how your routing is setup. If you are using the X-Auth-Token header, it is important to add this to the allowedHeaders configuration. See the package documentation for further configuration details.
Heres an example using the default auth route:
'paths' => array(
'auth' => array(
'allowedOrigins' => array('*'),
'allowedHeaders' => array('Content-Type', 'X-Auth-Token'),
'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
'maxAge' => 3600,
)
),
Note: If you know the list of
allowedOriginsit might be best to define them explicitly instead of using the wildcard*
All request must include one of:
X-Auth-Token header.auth_token field.GET Index actionReturns current user as json. Requires auth token parameter to be present. On Fail throws NotAuthorizedException.
POST Store actionRequired input username and password. On success returns json object containing token and user. On Fail throws NotAuthorizedException.
DELETE Destroy actionPurges the users tokens. Requires auth token parameter to be present. On Fail throws NotAuthorizedException.
NotAuthorizedException has a 401 error code by default.
An auth.token route filter gets registered by the service provider. To protect a resource just register a before filter. Filter will throw an NotAuthorizedException if a valid auth token is invalid or missing.
Route::group(array('prefix' => 'api', 'before' => 'auth.token'), function() {
Route::get('/', function() {
return "Protected resource";
});
});
The route filter will trigger auth.token.valid with the authorized user when a valid auth token is provided.
Event::listen('auth.token.valid', function($user)
{
//Token is valid, set the user on auth system.
Auth::setUser($user);
});
AuthTokenController::store will trigger auth.token.created before returning the response.
Event::listen('auth.token.created', function($user, $token)
{
$user->load('relation1', 'relation2');
});
AuthTokenController::destroy will trigger auth.token.deleted before returning the response.
Optionally register the NotAuthorizedException as alias eg. AuthTokenNotAuthorizedException
App::error(function(AuthTokenNotAuthorizedException $exception) {
if(Request::ajax()) {
return Response::json(array('error' => $exception->getMessage()), $exception->getCode());
}
…Handle non ajax response…
});
Some apps might already be using the traditional laravel based auth. The following can be used to manually generate a token.
if(Auth::check()) {
$authToken = AuthToken::create(Auth::user());
$publicToken = AuthToken::publicToken($authToken);
}
The AuthToken::publicToken method prepares the auth token to be sent to the browser.
0.3.0
auth.token.created event which gets triggered before response is returned in AuthTokenController::store0.2.0
Using the jQuery ajaxPrefilter method the X-Auth-Token can be set automatically on ajax request.
// Register ajax prefilter. If app config contains auth_token will automatically set header,
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (config.auth_token) {
jqXHR.setRequestHeader('X-Auth-Token', config.auth_token);
}
});
If a 401 response code is recieved it can also handled automatically. In the following example I opted to redirect to logout page to ensure user session was destroyed.
// If a 401 http error is recieved, automatically redirect to logout page.
$(document).ajaxError(function (event, jqxhr) {
if (jqxhr && jqxhr.status === 401) {
window.location = '/logout';
}
});
View composer can be used to automatically bind data to views. This keeps logic all in one spot. I use the following to setup config variables for javascript.
View::composer('layouts.default', function($view)
{
$rootUrl = rtrim(URL::route('home'), '/');
$jsConfig = isset($view->jsConfig) ? $view->jsConfig : array();
$jsConfig = array_merge(array(
'rootUrl' => $rootUrl
), $jsConfig);
if(Auth::check()) {
$authToken = AuthToken::create(Auth::user());
$publicToken = AuthToken::publicToken($authToken);
$userData = array_merge(
Auth::user()->toArray(),
array('auth_token' => $publicToken)
);
$jsConfig['userData'] = $userData;
}
$view->with('jsConfig', $jsConfig);
});
Selected from shared topics, language and repository description—not editorial ratings.
bainternet /
The PHP Hooks Class is a fork of the WordPress filters hook system rolled in to a class to be ported into any php based system .
BaluRaut /
Introduction This article, aimed at plugin developers, describes how to add Ajax to a plugin. Before reading this article, you should be familiar with the following: Ajax - Overview of the technology Writing a Plugin - How to write a plugin Plugin API - Filters and actions - what they are and how to use them How to add HTML to the appropriate WordPress page, post, or screen -- for instance, if you want to add Ajax to administration screens you create, you will need to understand how to add administration menus to WordPress; if you want to add Ajax to the display of a single post, you'll need to figure out the right filters and actions to add HTML to that spot on viewer-facing blog screens. This article does not cover these topics. Ajax on the Administration Side Since Ajax is already built into the core WordPress administration screens, adding more administration-side Ajax functionality to your plugin is fairly straightforward. This short example uses PHP to write our JavaScript in the footer of the page. This script then triggers the AJAX request when the page is fully loaded: <?php add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS below here function my_action_javascript() { ?> <script type="text/javascript" > jQuery(document).ready(function($) { var data = { 'action': 'my_action', 'whatever': 1234 }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php $.post(ajaxurl, data, function(response) { alert('Got this from the server: ' + response); }); }); </script> <?php } NOTE: Since Version 2.8, The JavaScript global variable ajaxurl can be used in case you want to separate your JavaScript code from php files into JavaScript only files. This is true on the administration side only. Then, set up a PHP function to handle the AJAX request. <?php add_action( 'wp_ajax_my_action', 'my_action_callback' ); function my_action_callback() { global $wpdb; // this is how you get access to the database $whatever = intval( $_POST['whatever'] ); $whatever += 10; echo $whatever; wp_die(); // this is required to terminate immediately and return a proper response } Notice how the 'action' key's value 'my_action', defined in our JavaScript above, matches the latter half of the action 'wp_ajax_my_action' in our AJAX handler below. This is because it is used to call the server side PHP function through admin-ajax.php. If an action is not specified, admin-ajax.php will exit, and return 0 in the process. You will need to add a few details, such as error checking and verifying that the request came from the right place ( using check_ajax_referer() ), but hopefully the example above will be enough to get you started on your own administration-side Ajax plugin. Notice the use of wp_die(), instead of die() or exit(). Most of the time you should be using wp_die() in your Ajax callback function. This provides better integration with WordPress and makes it easier to test your code. Separate Javascript File The same example as the previous one, except with the JavaScript on a separate external file we'll call js/my_query.js. The examples are relative to a plugin folder. jQuery(document).ready(function($) { var data = { 'action': 'my_action', 'whatever': ajax_object.we_value // We pass php values differently! }; // We can also pass the url value separately from ajaxurl for front end AJAX implementations jQuery.post(ajax_object.ajax_url, data, function(response) { alert('Got this from the server: ' + response); }); }); With external JavaScript files, we must first wp_enqueue_script() so they are included on the page. Additionally, we must use wp_localize_script() to pass values into JavaScript object properties, since PHP cannot directly echo values into our JavaScript file. The handler function is the same as the previous example. <?php add_action( 'admin_enqueue_scripts', 'my_enqueue' ); function my_enqueue($hook) { if( 'index.php' != $hook ) { // Only applies to dashboard panel return; } wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') ); // in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) ); } // Same handler function... add_action( 'wp_ajax_my_action', 'my_action_callback' ); function my_action_callback() { global $wpdb; $whatever = intval( $_POST['whatever'] ); $whatever += 10; echo $whatever; wp_die(); } Ajax on the Viewer-Facing Side Since WordPress 2.8, there is a hook similar to wp_ajax_(action): wp_ajax_nopriv_(action) executes for users that are not logged in. So, if you want it to fire on the front-end for both visitors and logged-in users, you can do this: add_action( 'wp_ajax_my_action', 'my_action_callback' ); add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' ); Note: Unlike on the admin side, the ajaxurl javascript global does not get automatically defined for you, unless you have BuddyPress or another Ajax-reliant plugin installed. So instead of relying on a global javascript variable, declare a javascript namespace object with its own property, ajaxurl. You might also use wp_localize_script() to make the URL available to your script, and generate it using this expression: admin_url( 'admin-ajax.php' ) Note 2: Both front-end and back-end Ajax requests use admin-ajax.php so is_admin() will always return true in your action handling code. When selectively loading your Ajax script handlers for the front-end and back-end, and using the is_admin() function, your wp_ajax_(action) and wp_ajax_nopriv_(action) hooks MUST be inside the is_admin() === true part. Ajax requests bound to either wp_ajax_ or wp_ajax_nopriv_ actions are executed in the WP Admin context. Carefully review the actions you are performing in your code since unprivileged users or visitors will be able to trigger requests with elevated permissions that they may not be authorized for. if ( is_admin() ) { add_action( 'wp_ajax_my_frontend_action', 'my_frontend_action_callback' ); add_action( 'wp_ajax_nopriv_my_frontend_action', 'my_frontend_action_callback' ); add_action( 'wp_ajax_my_backend_action', 'my_backend_action_callback' ); // Add other back-end action hooks here } else { // Add non-Ajax front-end action hooks here } Here the Ajax action my_frontend_action will trigger the PHP function my_frontend_action_callback() for all users. The Ajax action my_backend_action will trigger the PHP function my_backend_action_callback() for logged-in users only. Error Return Values If the Ajax request fails in wp-admin/admin-ajax.php, the response will be -1 or 0, depending on the reason for the failure. Additionally, if the request succeeds, but the Ajax action does not match a WordPress hook defined with add_action('wp_ajax_(action)', ...) or add_action('wp_ajax_nopriv_(action)', ...), then admin-ajax.php will respond 0. Debugging To parse AJAX, WordPress must be reloaded through the admin-ajax.php script, which means that any PHP errors encountered in the initial page load will also be present in the AJAX parsing. If error_reporting is enabled, these will be echoed to the output buffer, polluting your AJAX response with error messages. Because of this, care must be taken when debugging Ajax as any PHP notices or messages returned may confuse the parsing of the results or cause your Javascript to error. One option if you can't eliminate the messages and must run with debug turned on is to clear the buffer immediately before returning your data. ob_clean(); echo $whatever; wp_die(); It is also possible to use tools such as FirePHP to log debug messages to your browsers debug console. An alternative approach is to use a debugging proxy such as fiddler.
lad1337 /
a php powerd site that hooks into the xbmc sqlite db and creates a fancy web page. for movies and shows. you will need a lot of libarys incl image magic
thorpulse /
BLENC is an extension that permits you to protect PHP source scripts with Blowfish Encription. BLENC hooks into the Zend Engine, allowing for transparent execution of PHP scripts previously encoded with BLENC. It is not designed for complete security (it is still possible to disassemble the script into op codes using a package such as XDebug), however it does keep people out of your code(what I need it for) and make reverse engineering difficult.
corazzi /
Automatically create slugs for your Eloquent models by hooking into the creating event
PoPBackbone /
[READ ONLY] A fork of PHP-Hooks - A fork of the WordPress filters hook system rolled in to a class to be ported into any PHP-based system