Hybridauth Library not compatible with installed PECL OAuth extension - php

I try to login in my websites using Google API, in local it's working good.
but on server it's given error. error is -
"Got An Error - Hybridauth Library not compatible with installed PECL
OAuth extension. Please disable it."

I had go for get right answer, do r&d and finally I solve my issue.
for it we need to update auth.php (lib. file)
<?php
/**
* HybridAuth
* http://hybridauth.sourceforge.net | http://github.com/hybridauth/hybridauth
* (c) 2009-2015, HybridAuth authors | http://hybridauth.sourceforge.net/licenses.html
*/
/**
* Hybrid_Auth class
*
* Hybrid_Auth class provide a simple way to authenticate users via OpenID and OAuth.
*
* Generally, Hybrid_Auth is the only class you should instanciate and use throughout your application.
*/
class Hybrid_Auth {
public static $version = "2.7.0-dev";
/**
* Configuration array
* #var array
*/
public static $config = array();
/**
* Auth cache
* #var Hybrid_Storage
*/
public static $store = null;
/**
* Error pool
* #var Hybrid_Error
*/
public static $error = null;
/**
* Logger
* #var Hybrid_Logger
*/
public static $logger = null;
/**
* Try to start a new session of none then initialize Hybrid_Auth
*
* Hybrid_Auth constructor will require either a valid config array or
* a path for a configuration file as parameter. To know more please
* refer to the Configuration section:
* http://hybridauth.sourceforge.net/userguide/Configuration.html
*
* #param array $config Configuration array or path to a configratuion file
*/
function __construct($config) {
Hybrid_Auth::initialize($config);
}
/**
* Try to initialize Hybrid_Auth with given $config hash or file
*
* #param array $config Configuration array or path to a configratuion file
* #return void
* #throws Exception
*/
public static function initialize($config) {
if (!is_array($config) && !file_exists($config)) {
throw new Exception("Hybriauth config does not exist on the given path.", 1);
}
if (!is_array($config)) {
$config = include $config;
}
// build some need'd paths
$config["path_base"] = realpath(dirname(__FILE__)) . "/";
$config["path_libraries"] = $config["path_base"] . "thirdparty/";
$config["path_resources"] = $config["path_base"] . "resources/";
$config["path_providers"] = $config["path_base"] . "Providers/";
// reset debug mode
if (!isset($config["debug_mode"])) {
$config["debug_mode"] = false;
$config["debug_file"] = null;
}
# load hybridauth required files, a autoload is on the way...
require_once $config["path_base"] . "Error.php";
//require_once $config["path_base"] . "Exception.php";
require_once $config["path_base"] . "Logger.php";
require_once $config["path_base"] . "Provider_Adapter.php";
require_once $config["path_base"] . "Provider_Model.php";
require_once $config["path_base"] . "Provider_Model_OpenID.php";
require_once $config["path_base"] . "Provider_Model_OAuth1.php";
require_once $config["path_base"] . "Provider_Model_OAuth2.php";
require_once $config["path_base"] . "User.php";
require_once $config["path_base"] . "User_Profile.php";
require_once $config["path_base"] . "User_Contact.php";
require_once $config["path_base"] . "User_Activity.php";
if (!class_exists("Hybrid_Storage", false)) {
require_once $config["path_base"] . "Storage.php";
}
// hash given config
Hybrid_Auth::$config = $config;
// instance of log mng
Hybrid_Auth::$logger = new Hybrid_Logger();
// instance of errors mng
Hybrid_Auth::$error = new Hybrid_Error();
// start session storage mng
Hybrid_Auth::$store = new Hybrid_Storage();
Hybrid_Logger::info("Enter Hybrid_Auth::initialize()");
Hybrid_Logger::info("Hybrid_Auth::initialize(). PHP version: " . PHP_VERSION);
Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth version: " . Hybrid_Auth::$version);
Hybrid_Logger::info("Hybrid_Auth::initialize(). Hybrid_Auth called from: " . Hybrid_Auth::getCurrentUrl());
// PHP Curl extension [http://www.php.net/manual/en/intro.curl.php]
if (!function_exists('curl_init')) {
Hybrid_Logger::error('Hybridauth Library needs the CURL PHP extension.');
throw new Exception('Hybridauth Library needs the CURL PHP extension.');
}
// PHP JSON extension [http://php.net/manual/en/book.json.php]
if (!function_exists('json_decode')) {
Hybrid_Logger::error('Hybridauth Library needs the JSON PHP extension.');
throw new Exception('Hybridauth Library needs the JSON PHP extension.');
}
// session.name
if (session_name() != "PHPSESSID") {
Hybrid_Logger::info('PHP session.name diff from default PHPSESSID. http://php.net/manual/en/session.configuration.php#ini.session.name.');
}
// safe_mode is on
if (ini_get('safe_mode')) {
Hybrid_Logger::info('PHP safe_mode is on. http://php.net/safe-mode.');
}
// open basedir is on
if (ini_get('open_basedir')) {
Hybrid_Logger::info('PHP open_basedir is on. http://php.net/open-basedir.');
}
Hybrid_Logger::debug("Hybrid_Auth initialize. dump used config: ", serialize($config));
Hybrid_Logger::debug("Hybrid_Auth initialize. dump current session: ", Hybrid_Auth::storage()->getSessionData());
Hybrid_Logger::info("Hybrid_Auth initialize: check if any error is stored on the endpoint...");
if (Hybrid_Error::hasError()) {
$m = Hybrid_Error::getErrorMessage();
$c = Hybrid_Error::getErrorCode();
$p = Hybrid_Error::getErrorPrevious();
Hybrid_Logger::error("Hybrid_Auth initialize: A stored Error found, Throw an new Exception and delete it from the store: Error#$c, '$m'");
Hybrid_Error::clearError();
// try to provide the previous if any
// Exception::getPrevious (PHP 5 >= 5.3.0) http://php.net/manual/en/exception.getprevious.php
if (version_compare(PHP_VERSION, '5.3.0', '>=') && ($p instanceof Exception)) {
throw new Exception($m, $c, $p);
} else {
throw new Exception($m, $c);
}
}
Hybrid_Logger::info("Hybrid_Auth initialize: no error found. initialization succeed.");
}
/**
* Hybrid storage system accessor
*
* Users sessions are stored using HybridAuth storage system ( HybridAuth 2.0 handle PHP Session only) and can be accessed directly by
* Hybrid_Auth::storage()->get($key) to retrieves the data for the given key, or calling
* Hybrid_Auth::storage()->set($key, $value) to store the key => $value set.
*
* #return Hybrid_Storage
*/
public static function storage() {
return Hybrid_Auth::$store;
}
/**
* Get hybridauth session data
* #return string|null
*/
function getSessionData() {
return Hybrid_Auth::storage()->getSessionData();
}
/**
* Restore hybridauth session data
*
* #param string $sessiondata Serialized session data
* #retun void
*/
function restoreSessionData($sessiondata = null) {
Hybrid_Auth::storage()->restoreSessionData($sessiondata);
}
/**
* Try to authenticate the user with a given provider.
*
* If the user is already connected we just return and instance of provider adapter,
* ELSE, try to authenticate and authorize the user with the provider.
*
* $params is generally an array with required info in order for this provider and HybridAuth to work,
* like :
* hauth_return_to: URL to call back after authentication is done
* openid_identifier: The OpenID identity provider identifier
* google_service: can be "Users" for Google user accounts service or "Apps" for Google hosted Apps
*
* #param string $providerId ID of the provider
* #param array $params Params
* #return
*/
public static function authenticate($providerId, $params = null) {
Hybrid_Logger::info("Enter Hybrid_Auth::authenticate( $providerId )");
if (!Hybrid_Auth::storage()->get("hauth_session.$providerId.is_logged_in")) {
// if user not connected to $providerId then try setup a new adapter and start the login process for this provider
Hybrid_Logger::info("Hybrid_Auth::authenticate( $providerId ), User not connected to the provider. Try to authenticate..");
$provider_adapter = Hybrid_Auth::setup($providerId, $params);
$provider_adapter->login();
} else {
// else, then return the adapter instance for the given provider
Hybrid_Logger::info("Hybrid_Auth::authenticate( $providerId ), User is already connected to this provider. Return the adapter instance.");
return Hybrid_Auth::getAdapter($providerId);
}
}
/**
* Return the adapter instance for an authenticated provider
*
* #param string $providerId ID of the provider
* #return Hybrid_Provider_Adapter
*/
public static function getAdapter($providerId = null) {
Hybrid_Logger::info("Enter Hybrid_Auth::getAdapter( $providerId )");
return Hybrid_Auth::setup($providerId);
}
/**
* Setup an adapter for a given provider
*
* #param string $providerId ID of the provider
* #param array $params Adapter params
* #return Hybrid_Provider_Adapter
*/
public static function setup($providerId, $params = null) {
Hybrid_Logger::debug("Enter Hybrid_Auth::setup( $providerId )", $params);
if (!$params) {
$params = Hybrid_Auth::storage()->get("hauth_session.$providerId.id_provider_params");
Hybrid_Logger::debug("Hybrid_Auth::setup( $providerId ), no params given. Trying to get the stored for this provider.", $params);
}
if (!$params) {
$params = array();
Hybrid_Logger::info("Hybrid_Auth::setup( $providerId ), no stored params found for this provider. Initialize a new one for new session");
}
if (is_array($params) && !isset($params["hauth_return_to"])) {
$params["hauth_return_to"] = Hybrid_Auth::getCurrentUrl();
Hybrid_Logger::debug("Hybrid_Auth::setup( $providerId ). HybridAuth Callback URL set to: ", $params["hauth_return_to"]);
}
# instantiate a new IDProvider Adapter
$provider = new Hybrid_Provider_Adapter();
$provider->factory($providerId, $params);
return $provider;
}
/**
* Check if the current user is connected to a given provider
*
* #param string $providerId ID of the provider
* #return bool
*/
public static function isConnectedWith($providerId) {
return (bool) Hybrid_Auth::storage()->get("hauth_session.{$providerId}.is_logged_in");
}
/**
* Return array listing all authenticated providers
* #return array
*/
public static function getConnectedProviders() {
$idps = array();
foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
if (Hybrid_Auth::isConnectedWith($idpid)) {
$idps[] = $idpid;
}
}
return $idps;
}
/**
* Return array listing all enabled providers as well as a flag if you are connected
*
* <code>
* array(
* 'Facebook' => array(
* 'connected' => true
* )
* )
* </code>
* #return array
*/
public static function getProviders() {
$idps = array();
foreach (Hybrid_Auth::$config["providers"] as $idpid => $params) {
if ($params['enabled']) {
$idps[$idpid] = array('connected' => false);
if (Hybrid_Auth::isConnectedWith($idpid)) {
$idps[$idpid]['connected'] = true;
}
}
}
return $idps;
}
/**
* A generic function to logout all connected provider at once
* #return void
*/
public static function logoutAllProviders() {
$idps = Hybrid_Auth::getConnectedProviders();
foreach ($idps as $idp) {
$adapter = Hybrid_Auth::getAdapter($idp);
$adapter->logout();
}
}
/**
* Utility function, redirect to a given URL with php header or using javascript location.href
*
* #param string $url URL to redirect to
* #param string $mode PHP|JS
*/
public static function redirect($url, $mode = "PHP") {
Hybrid_Logger::info("Enter Hybrid_Auth::redirect( $url, $mode )");
// Ensure session is saved before sending response, see https://github.com/symfony/symfony/pull/12341
if ((PHP_VERSION_ID >= 50400 && PHP_SESSION_ACTIVE === session_status()) || (PHP_VERSION_ID < 50400 && isset($_SESSION) && session_id())) {
session_write_close();
}
if ($mode == "PHP") {
header("Location: $url");
} elseif ($mode == "JS") {
echo '<html>';
echo '<head>';
echo '<script type="text/javascript">';
echo 'function redirect(){ window.top.location.href="' . $url . '"; }';
echo '</script>';
echo '</head>';
echo '<body onload="redirect()">';
echo 'Redirecting, please wait...';
echo '</body>';
echo '</html>';
}
die();
}
/**
* Utility function, return the current url
*
* #param bool $request_uri true to get $_SERVER['REQUEST_URI'], false for $_SERVER['PHP_SELF']
* #return string
*/
public static function getCurrentUrl($request_uri = true) {
if (php_sapi_name() == 'cli') {
return '';
}
$protocol = 'http://';
if ((isset($_SERVER['HTTPS']) && ( $_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1 ))
|| (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'))
{
$protocol = 'https://';
}
$url = $protocol . $_SERVER['HTTP_HOST'];
if ($request_uri) {
$url .= $_SERVER['REQUEST_URI'];
} else {
$url .= $_SERVER['PHP_SELF'];
}
// return current url
return $url;
}
}

Related

How do I resolve Cannot use 'Object' as class name as it is reserved in C:\projectfolder\ckphp-demo\cake\libs\object.php on line 33

In working on a new cakephp application I get the error message Cannot use 'Object' as class name as it is reserved in C:\projectfolder\ckphp-demo\cake\libs\object.php on line 33.
The project is a legacy web application using cakePHP 1.3.17 with php version PHP 7.4.28 on developement server. see below code for object.php
line 33 is where class Object { starts
<?php
/**
* Object class, allowing __construct and __destruct in PHP4.
*
* Also includes methods for logging and the special method RequestAction,
* to call other Controllers' Actions from anywhere.
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* #copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* #link http://cakephp.org CakePHP(tm) Project
* #package cake
* #subpackage cake.cake.libs
* #since CakePHP(tm) v 0.2.9
* #license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* Object class, allowing __construct and __destruct in PHP4.
*
* Also includes methods for logging and the special method RequestAction,
* to call other Controllers' Actions from anywhere.
*
* #package cake
* #subpackage cake.cake.libs
*/
class Object {
/**
* A hack to support __construct() on PHP 4
* Hint: descendant classes have no PHP4 class_name() constructors,
* so this constructor gets called first and calls the top-layer __construct()
* which (if present) should call parent::__construct()
*
* #return Object
*/
function Object() {
$args = func_get_args();
if (method_exists($this, '__destruct')) {
register_shutdown_function (array(&$this, '__destruct'));
}
call_user_func_array(array(&$this, '__construct'), $args);
}
/**
* Class constructor, overridden in descendant classes.
*/
function __construct() {
}
/**
* Object-to-string conversion.
* Each class can override this method as necessary.
*
* #return string The name of this class
* #access public
*/
function toString() {
$class = get_class($this);
return $class;
}
/**
* Calls a controller's method from any location. Can be used to connect controllers together
* or tie plugins into a main application. requestAction can be used to return rendered views
* or fetch the return value from controller actions.
*
* #param mixed $url String or array-based url.
* #param array $extra if array includes the key "return" it sets the AutoRender to true.
* #return mixed Boolean true or false on success/failure, or contents
* of rendered action if 'return' is set in $extra.
* #access public
*/
function requestAction($url, $extra = array()) {
if (empty($url)) {
return false;
}
if (!class_exists('dispatcher')) {
require CAKE . 'dispatcher.php';
}
if (in_array('return', $extra, true)) {
$extra = array_merge($extra, array('return' => 0, 'autoRender' => 1));
}
if (is_array($url) && !isset($extra['url'])) {
$extra['url'] = array();
}
$params = array_merge(array('autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1), $extra);
$dispatcher = new Dispatcher;
return $dispatcher->dispatch($url, $params);
}
/**
* Calls a method on this object with the given parameters. Provides an OO wrapper
* for `call_user_func_array`
*
* #param string $method Name of the method to call
* #param array $params Parameter list to use when calling $method
* #return mixed Returns the result of the method call
* #access public
*/
function dispatchMethod($method, $params = array()) {
switch (count($params)) {
case 0:
return $this->{$method}();
case 1:
return $this->{$method}($params[0]);
case 2:
return $this->{$method}($params[0], $params[1]);
case 3:
return $this->{$method}($params[0], $params[1], $params[2]);
case 4:
return $this->{$method}($params[0], $params[1], $params[2], $params[3]);
case 5:
return $this->{$method}($params[0], $params[1], $params[2], $params[3], $params[4]);
default:
return call_user_func_array(array(&$this, $method), $params);
break;
}
}
/**
* Stop execution of the current script. Wraps exit() making
* testing easier.
*
* #param $status see http://php.net/exit for values
* #return void
* #access public
*/
function _stop($status = 0) {
exit($status);
}
/**
* Convience method to write a message to CakeLog. See CakeLog::write()
* for more information on writing to logs.
*
* #param string $msg Log message
* #param integer $type Error type constant. Defined in app/config/core.php.
* #return boolean Success of log write
* #access public
*/
function log($msg, $type = LOG_ERROR) {
if (!class_exists('CakeLog')) {
require LIBS . 'cake_log.php';
}
if (!is_string($msg)) {
$msg = print_r($msg, true);
}
return CakeLog::write($type, $msg);
}
/**
* Allows setting of multiple properties of the object in a single line of code. Will only set
* properties that are part of a class declaration.
*
* #param array $properties An associative array containing properties and corresponding values.
* #return void
* #access protected
*/
function _set($properties = array()) {
if (is_array($properties) && !empty($properties)) {
$vars = get_object_vars($this);
foreach ($properties as $key => $val) {
if (array_key_exists($key, $vars)) {
$this->{$key} = $val;
}
}
}
}
/**
* Used to report user friendly errors.
* If there is a file app/error.php or app/app_error.php this file will be loaded
* error.php is the AppError class it should extend ErrorHandler class.
*
* #param string $method Method to be called in the error class (AppError or ErrorHandler classes)
* #param array $messages Message that is to be displayed by the error class
* #return error message
* #access public
*/
function cakeError($method, $messages = array()) {
if (!class_exists('ErrorHandler')) {
App::import('Core', 'Error');
if (file_exists(APP . 'error.php')) {
include_once (APP . 'error.php');
} elseif (file_exists(APP . 'app_error.php')) {
include_once (APP . 'app_error.php');
}
}
if (class_exists('AppError')) {
$error = new AppError($method, $messages);
} else {
$error = new ErrorHandler($method, $messages);
}
return $error;
}
/**
* Checks for a persistent class file, if found file is opened and true returned
* If file is not found a file is created and false returned
* If used in other locations of the model you should choose a unique name for the persistent file
* There are many uses for this method, see manual for examples
*
* #param string $name name of the class to persist
* #param string $object the object to persist
* #return boolean Success
* #access protected
* #todo add examples to manual
*/
function _persist($name, $return = null, &$object, $type = null) {
$file = CACHE . 'persistent' . DS . strtolower($name) . '.php';
if ($return === null) {
if (!file_exists($file)) {
return false;
} else {
return true;
}
}
if (!file_exists($file)) {
$this->_savePersistent($name, $object);
return false;
} else {
$this->__openPersistent($name, $type);
return true;
}
}
/**
* You should choose a unique name for the persistent file
*
* There are many uses for this method, see manual for examples
*
* #param string $name name used for object to cache
* #param object $object the object to persist
* #return boolean true on save, throws error if file can not be created
* #access protected
*/
function _savePersistent($name, &$object) {
$file = 'persistent' . DS . strtolower($name) . '.php';
$objectArray = array(&$object);
$data = str_replace('\\', '\\\\', serialize($objectArray));
$data = '<?php $' . $name . ' = \'' . str_replace('\'', '\\\'', $data) . '\' ?>';
$duration = '+999 days';
if (Configure::read() >= 1) {
$duration = '+10 seconds';
}
cache($file, $data, $duration);
}
/**
* Open the persistent class file for reading
* Used by Object::_persist()
*
* #param string $name Name of persisted class
* #param string $type Type of persistance (e.g: registry)
* #return void
* #access private
*/
function __openPersistent($name, $type = null) {
$file = CACHE . 'persistent' . DS . strtolower($name) . '.php';
include($file);
switch ($type) {
case 'registry':
$vars = unserialize(${$name});
foreach ($vars['0'] as $key => $value) {
if (strpos($key, '_behavior') !== false) {
App::import('Behavior', Inflector::classify(substr($key, 0, -9)));
} else {
App::import('Model', Inflector::camelize($key));
}
unset ($value);
}
unset($vars);
$vars = unserialize(${$name});
foreach ($vars['0'] as $key => $value) {
ClassRegistry::addObject($key, $value);
unset ($value);
}
unset($vars);
break;
default:
$vars = unserialize(${$name});
$this->{$name} = $vars['0'];
unset($vars);
break;
}
}
}

Adding Authentication to SOAP web services using Laminas-soap and php

Hello fellow travellers,
I am trying to learn how to create SOAP Web services end point in PHP. I have found Laminas-soap with its elegant solution. However when trying to add authentication to it although it works when adding creditials to SoapHeaders it goes through, the problem is even without SoapHeaders credentials it still goes through. Can anybody help me with this problem? Here is my Server Code:
Update: Should I just put authentication on every call to not put state on the server?
<?php
// api.php
require_once __DIR__ . '/vendor/autoload.php';
require_once '../classes/DBConnection.php';
class Server
{
private $conn;
/**
* authenticate
*
* #param string $username
* #param string $password
* #return boolean
*/
public static function authenticate($username, $password)
{
if($username == "Kaloy" && $password == 'password') return true;
else throw new SOAPFault("Wrong user/pass combination", 401);
}
public function __construct($conn)
{
$this->conn = $conn;
}
/**
* Say hello.
*
* #param string $firstName
* #return string $greetings
*/
public function sayHello($firstName)
{
return 'Hello ' . $firstName;
}
/**
* get products
*
* #param string $category
* #param string $category2
* #param string $category3
* #param string $category4
* #return Array $products
*/
public function getProd($category, $category2, $category3, $category4) {
if ($category == "books") {
// return join(",", array(
// "The WordPress Anthology",
// "PHP Master: Write Cutting Edge Code",
// "Build Your Own Website the Right Way"));
return array(
"The WordPress Anthology",
"PHP Master: Write Cutting Edge Code",
"Build Your Own Website the Right Way");
}
else {
return array("No products listed under that category");
}
}
/**
* getData
*
* #param string $id
* #return Object
*/
public function getData($id)
{
$result = [];
if (is_null($id)) return $result;
$qry = "SELECT * FROM test_table";
return $this->conn->query($qry)->fetchAll(PDO::FETCH_ASSOC);
}
}
$serverUrl = "http://localhost/laminas-soap/api.php";
$options = [
'uri' => $serverUrl,
];
$server = new \Laminas\Soap\Server(null, $options);
if (isset($_GET['wsdl'])) {
$soapAutoDiscover = new \Laminas\Soap\AutoDiscover(new \Laminas\Soap\Wsdl\ComplexTypeStrategy\ArrayOfTypeSequence());
$soapAutoDiscover->setBindingStyle(array('style' => 'document'));
$soapAutoDiscover->setOperationBodyStyle(array('use' => 'literal'));
$soapAutoDiscover->setClass('Server');
$soapAutoDiscover->setUri($serverUrl);
header("Content-Type: text/xml");
echo $soapAutoDiscover->generate()->toXml();
} else {
$soap = new \Laminas\Soap\Server($serverUrl . '?wsdl');
$soap->setObject(new \Laminas\Soap\Server\DocumentLiteralWrapper(new Server($conn)));
$soap->handle();
}

Kohana PHP framework Kohan_auth can't debug or use

I've inherited a project, which uses the Kohana MVC framework and it's Kohan_auth class to register someone. When submiting registration it submits a form post to the class below. I don't see where the ->register is used or what instance means or how to debug or solve this. Please help.
Auth::instance()->register($_POST, TRUE);
does not enter data and just redirects back to the registration page with no error messages. How can I debug this, unit tests also don't work as they require older phpunit versions.
Auth::instance() seems to go to this code
* #package Useradmin/Auth
* #author Gabriel R. Giannattasio
*/
abstract class Useradmin_Auth extends Kohana_Auth {
/**
* Singleton pattern
*
* #return Auth
*/
public static function instance()
{
if ( ! isset(Auth::$_instance))
{
// Load the configuration for this type
$config = Kohana::$config->load('auth');
if ( ! $type = $config->get('driver'))
{
$type = 'file';
}
// Set the session class name
$class = 'Auth_'.ucfirst($type);
$config->set("useradmin", Kohana::$config->load('useradmin.auth') );
// Create a new session instance
Auth::$_instance = new $class($config);
}
return Auth::$_instance;
}
}
which extends this
abstract class Kohana_Auth {
// Auth instances
protected static $_instance;
/**
* Singleton pattern
*
* #return Auth
*/
public static function instance()
{
if ( ! isset(Auth::$_instance))
{
// Load the configuration for this type
$config = Kohana::$config->load('auth');
if ( ! $type = $config->get('driver'))
{
$type = 'file';
}
// Set the session class name
$class = 'Auth_'.ucfirst($type);
// Create a new session instance
Auth::$_instance = new $class($config);
}
return Auth::$_instance;
}
protected $_session;
protected $_config;
/**
* Loads Session and configuration options.
*
* #return void
*/
public function __construct($config = array())
{
// Save the config in the object
$this->_config = $config;
$this->_session = Session::instance($this->_config['session_type']);
}
abstract protected function _login($username, $password, $remember);
abstract public function password($username);
abstract public function check_password($password);
/**
* Gets the currently logged in user from the session.
* Returns NULL if no user is currently logged in.
*
* #return mixed
*/
public function get_user($default = NULL)
{
return $this->_session->get($this->_config['session_key'], $default);
}
/**
* Attempt to log in a user by using an ORM object and plain-text password.
*
* #param string username to log in
* #param string password to check against
* #param boolean enable autologin
* #return boolean
*/
public function login($username, $password, $remember = FALSE)
{
if (empty($password))
return FALSE;
return $this->_login($username, $password, $remember);
}
/**
* Log out a user by removing the related session variables.
*
* #param boolean completely destroy the session
* #param boolean remove all tokens for user
* #return boolean
*/
public function logout($destroy = FALSE, $logout_all = FALSE)
{
if ($destroy === TRUE)
{
// Destroy the session completely
$this->_session->destroy();
}
else
{
// Remove the user from the session
$this->_session->delete($this->_config['session_key']);
// Regenerate session_id
$this->_session->regenerate();
}
// Double check
return ! $this->logged_in();
}
/**
* Check if there is an active session. Optionally allows checking for a
* specific role.
*
* #param string role name
* #return mixed
*/
public function logged_in($role = NULL)
{
return ($this->get_user() !== NULL);
}
/**
* Creates a hashed hmac password from a plaintext password. This
* method is deprecated, [Auth::hash] should be used instead.
*
* #deprecated
* #param string plaintext password
*/
public function hash_password($password)
{
return $this->hash($password);
}
/**
* Perform a hmac hash, using the configured method.
*
* #param string string to hash
* #return string
*/
public function hash($str)
{
if ( ! $this->_config['hash_key'])
throw new Kohana_Exception('A valid hash key must be set in your auth config.');
return hash_hmac($this->_config['hash_method'], $str, $this->_config['hash_key']);
}
protected function complete_login($user)
{
// Regenerate session_id
$this->_session->regenerate();
// Store username in session
$this->_session->set($this->_config['session_key'], $user);
return TRUE;
}
} // End Auth
Enable logging in application/bootstrap.php, php.ini and use:
Kohana::$log->add(Log::MESSAGE, $msg);
or
Kohana::$log->add(Log::MESSAGE, Kohana_Exception::text($e), Array(),Array('exception'=>$e));
see Log::MESSAGE
BTW: take my Log class:
<?php defined('SYSPATH') OR die('No direct script access.');
class Log extends Kohana_Log {
public function add($level, $message, array $values = NULL, array $additional = NULL){
if(strpos($message,'~') == FALSE) {
$message .= ' ~ ';
}
if(!isset($_SERVER['REQUEST_METHOD']))
$message .= " !!! TASK";
else
$message .= " !!! ($_SERVER[REQUEST_METHOD])//$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$message = strtr($message,"\r\n\t",' ');
if(count($_POST) > 0){
if(isset($_POST['csrf']))
unset($_POST['csrf']);
if(isset($_POST['f_pass']))
unset($_POST['f_pass']);
if(isset($_POST['password']))
$_POST['password'] = 'strlen() = '.strlen($_POST['password']);
if(isset($_POST['password2']))
$_POST['password2'] = 'strlen() = '.strlen($_POST['password2']).', pass==pass2: '.($_POST['password2'] == $_POST['password']?'tak':'nie');
$message .= '??'.http_build_query($_POST);
}
if (isset($additional['exception'])){
if($additional['exception'] instanceof HTTP_Exception_301)
return false;
if($additional['exception'] instanceof HTTP_Exception_302)
return false;
if($additional['exception'] instanceof ORM_Validation_Exception){
$message .= "\n".print_r($additional['exception']->errors('models'),TRUE)."\n";
}
if($additional['exception'] instanceof GuzzleHttp\Exception\RequestException) {
parent::add(self::DEBUG, 'HTTP request error [ 1 ]: :url'."\r\n".':body',[':url'=>$additional['exception']->getRequest()->getUrl(), ':body'=>$additional['exception']->getRequest()->getBody()]);
}
if($additional['exception'] instanceof GuzzleHttp\Exception\BadResponseException) {
$_body = $additional['exception']->getResponse()->getBody();
parent::add(self::DEBUG, 'HTTP reponse error [ 2 ]: :err', [':err'=> $_body]);
}
}
return parent::add($level, $message, $values, $additional);
}
public function add_exception($e, $error_level = Log::ERROR){
return $this->add($error_level, Kohana_Exception::text($e), Array(),Array('exception'=>$e));
}
public static function catch_ex($ex, $error_level = Log::ERROR){
return Kohana::$log->add_exception($ex, $error_level);
}
public static function msg($msg, $error_level = Log::ERROR) {
return Kohana::$log->add($error_level, $msg);
}
}

How to transfer files from another server, using FTP, in PHP

I am trying to find a way to transfer files from server-to-server. The source server can be any platform, and we may not even really know anything about it except that it supports FTP.
A number of posts I have found on SO recommend using scp, sftp, rsync, or wget for this purpose. Given that this PHP script needs to work every time, and the only thing we know for sure is that the source server supports FTP, how can this be achieved?
I found a couple FTP examples on SO, but they weren't explained very well.
We need to be able to download all files and folders, keeping the same directory structure as well.
I have found a PHP class that makes recursive FTP uploads and downloads easy. It can be found here
The code they used is below (The code at the top is example code for downloads, uploads, and error checking):
<?php // example
set_time_limit(0);
require 'ftp.php';
$ftp = new ftp();
$ftp->conn('host', 'username', 'password');
$ftp->get('download/demo', '/demo'); // download live "/demo" folder to local "download/demo"
$ftp->put('/demo/test', 'upload/vjtest'); // upload local "upload/vjtest" to live "/demo/test"
$arr = $ftp->getLogData();
if ($arr['error'] != "")
echo '<h2>Error:</h2>' . implode('<br />', $arr['error']);
if ($arr['ok'] != "")
echo '<h2>Success:</h2>' . implode('<br />', $arr['ok']);
class ftp {
private $conn, $login_result, $logData, $ftpUser, $ftpPass, $ftpHost, $retry, $ftpPasv, $ftpMode, $verbose, $logPath, $createMask;
// --------------------------------------------------------------------
/**
* Construct method
*
* #param array keys[passive_mode(true|false)|transfer_mode(FTP_ASCII|FTP_BINARY)|reattempts(int)|log_path|verbose(true|false)|create_mask(default:0777)]
* #return void
*/
function __construct()
{
$this->retry = (isset($o['reattempts'])) ? $o['reattempts'] : 3;
$this->ftpPasv = (isset($o['passive_mode'])) ? $o['passive_mode'] : true;
$this->ftpMode = (isset($o['transfer_mode'])) ? $o['transfer_mode'] : FTP_BINARY;
$this->verbose = (isset($o['verbose'])) ? $o['verbose'] : false;
$this->logPath = (isset($o['log_path'])) ? $o['log_path'] : dirname(__FILE__).'\log';
$this->createMask = (isset($o['create_mask'])) ? $o['create_mask'] : 0777;
}
// --------------------------------------------------------------------
/**
* Connection method
*
* #param string hostname
* #param string username
* #param string password
* #return void
*/
public function conn($hostname, $username, $password)
{
$this->ftpUser = $username;
$this->ftpPass = $password;
$this->ftpHost = $hostname;
$this->initConn();
}
// --------------------------------------------------------------------
/**
* Init connection method - connect to ftp server and set passive mode
*
* #return bool
*/
function initConn()
{
$this->conn = ftp_connect($this->ftpHost);
$this->login_result = ftp_login($this->conn, $this->ftpUser, $this->ftpPass);
if($this->conn && $this->login_result)
{
ftp_pasv($this->conn, $this->ftpPasv);
return true;
}
return false;
}
// --------------------------------------------------------------------
/**
* Put method - upload files(folders) to ftp server
*
* #param string path to destionation file/folder on ftp
* #param string path to source file/folder on local disk
* #param int only for identify reattempt, dont use this param
* #return bool
*/
public function put($destinationFile, $sourceFile, $retry = 0)
{
if(file_exists($sourceFile))
{
if(!$this->isDir($sourceFile, true))
{
$this->createSubDirs($destinationFile);
if(!ftp_put($this->conn, $destinationFile, $sourceFile, $this->ftpMode))
{
$retry++;
if($retry > $this->retry)
{
$this->logData('Error when uploading file: '.$sourceFile.' => '.$destinationFile, 'error');
return false;
}
if($this->verbose) echo 'Retry: '.$retry."\n";
$this->reconnect();
$this->put($destinationFile, $sourceFile, $retry);
}
else
{
$this->logData('Upload:'.$sourceFile.' => '.$destinationFile, 'ok');
return true;
}
}
else
{
$this->recursive($destinationFile, $sourceFile, 'put');
}
}
}
// --------------------------------------------------------------------
/**
* Get method - download files(folders) from ftp server
*
* #param string path to destionation file/folder on local disk
* #param string path to source file/folder on ftp server
* #param int only for identify reattempt, dont use this param
* #return bool
*/
public function get($destinationFile, $sourceFile, $retry = 0)
{
if(!$this->isDir($sourceFile, false))
{
if($this->verbose)echo $sourceFile.' => '.$destinationFile."\n";
$this->createSubDirs($destinationFile, false, true);
if(!ftp_get($this->conn, $destinationFile, $sourceFile, $this->ftpMode))
{
$retry++;
if($retry > $this->retry)
{
$this->logData('Error when downloading file: '.$sourceFile.' => '.$destinationFile, 'error');
return false;
}
if($this->verbose) echo 'Retry: '.$retry."\n";
$this->reconnect();
$this->get($destinationFile, $sourceFile, $retry);
}
else
{
$this->logData('Download:'.$sourceFile.' => '.$destinationFile, 'ok');
return true;
}
}
else
{
$this->recursive($destinationFile, $sourceFile, 'get');
}
}
// --------------------------------------------------------------------
/**
* Make dir method - make folder on ftp server or local disk
*
* #param string path to destionation folder on ftp or local disk
* #param bool true for local, false for ftp
* #return bool
*/
public function makeDir($dir, $local = false)
{
if($local)
{
if(!file_exists($dir) && !is_dir($dir))return mkdir($dir, $this->createMask); else return true;
}
else
{
ftp_mkdir($this->conn,$dir);
return ftp_chmod($this->conn, $this->createMask, $dir);
}
}
// --------------------------------------------------------------------
/**
* Cd up method - change working dir up
*
* #param bool true for local, false for ftp
* #return bool
*/
public function cdUp($local)
{
return $local ? chdir('..') : ftp_cdup($this->conn);
}
// --------------------------------------------------------------------
/**
* List contents of dir method - list all files in specified directory
*
* #param string path to destionation folder on ftp or local disk
* #param bool true for local, false for ftp
* #return bool
*/
public function listFiles($file, $local = false)
{
if(!$this->isDir($file, $local))return false;
if($local)
{
return scandir($file);
}
else
{
if(!preg_match('/\//', $file))
{
return ftp_nlist($this->conn, $file);
}else
{
$dirs = explode('/', $file);
foreach($dirs as $dir)
{
$this->changeDir($dir, $local);
}
$last = count($dirs)-1;
$this->cdUp($local);
$list = ftp_nlist($this->conn, $dirs[$last]);
$i = 0;
foreach($dirs as $dir)
{
if($i < $last) $this->cdUp($local);
$i++;
}
return $list;
}
}
}
// --------------------------------------------------------------------
/**
* Returns current working directory
*
* #param bool true for local, false for ftp
* #return bool
*/
public function pwd($local = false)
{
return $local ? getcwd() : ftp_pwd($this->conn);
}
// --------------------------------------------------------------------
/**
* Change current working directory
*
* #param string dir name
* #param bool true for local, false for ftp
* #return bool
*/
public function changeDir($dir, $local = false)
{
return $local ? chdir($dir) : #ftp_chdir($this->conn, $dir);
}
// --------------------------------------------------------------------
/**
* Create subdirectories
*
* #param string path
* #param bool
* #param bool true for local, false for ftp
* #param bool change current working directory back
* #return void
*/
function createSubDirs($file, $last = false, $local = false, $chDirBack = true)
{
if(preg_match('/\//',$file))
{
$origin = $this->pwd($local);
if(!$last) $file = substr($file, 0, strrpos($file,'/'));
$dirs = explode('/',$file);
foreach($dirs as $dir)
{
if(!$this->isDir($dir, $local))
{
$this->makeDir($dir, $local);
$this->changeDir($dir, $local);
}
else
{
$this->changeDir($dir, $local);
}
}
if($chDirBack) $this->changeDir($origin, $local);
}
}
// --------------------------------------------------------------------
/**
* Recursion
*
* #param string destionation file/folder
* #param string source file/folder
* #param string put or get
* #return void
*/
function recursive($destinationFile, $sourceFile, $mode)
{
$local = ($mode == 'put') ? true : false;
$list = $this->listFiles($sourceFile, $local);
if($this->verbose) echo "\n".'Folder: '.$sourceFile."\n";
$this->logData(($mode=='get')?('Download:'):('Upload:').$sourceFile.' => '.$destinationFile, 'ok');
if($this->verbose) print_r($list);
$x=0;
$z=0;
if(count($list)==2)// blank folder
{
if($mode == 'get')
$this->makeDir($destinationFile, true);
if($mode == 'put')
$this->makeDir($destinationFile);
}
foreach($list as $file)
{
if($file == '.' || $file == '..')continue;
$destFile = $destinationFile.'/'.$file;
$srcFile = $sourceFile.'/'.$file;
if($this->isDir($srcFile,$local))
{
$this->recursive($destFile, $srcFile, $mode);
}
else
{
if($local)
{
$this->put($destFile, $srcFile);
}
else
{
$this->get($destFile, $srcFile);
}
}
}
}
// --------------------------------------------------------------------
/**
* Check if is dir
*
* #param string path to folder
* #return bool
*/
public function isDir($dir, $local)
{
if($local) return is_dir($dir);
if($this->changeDir($dir))return $this->cdUp(0);
return false;
}
// --------------------------------------------------------------------
/**
* Save log data to array
*
* #param string data
* #param string type(error|ok)
* #return void
*/
function logData($data, $type)
{
$this->logData[$type][] = $data;
}
// --------------------------------------------------------------------
/**
* Get log data array
*
* #return array
*/
public function getLogData()
{
return $this->logData;
}
// --------------------------------------------------------------------
/**
* Save log data to file
*
* #return void
*/
public function logDataToFiles()
{
if(!$this->logPath) return false;
$this->makeDir($this->logPath, true);
$log = $this->getLogData();
$sep = "\n".date('y-m-d H:i:s').' ';
if($log['error'] != "")
{
$logc = date('y-m-d H:i:s').' '.join($sep,$log['error'])."\n";
$this->addToFile($this->logPath.'/'.$this->ftpUser.'-error.log',$logc);
}
if($log['ok'] != "")
{
$logc = date('y-m-d H:i:s').' '.join($sep,$log['ok'])."\n";
$this->addToFile($this->logPath.'/'.$this->ftpUser.'-ok.log',$logc);
}
}
// --------------------------------------------------------------------
/**
* Reconnect method
*
* #return void
*/
public function reconnect()
{
$this->closeConn();
$this->initConn();
}
// --------------------------------------------------------------------
/**
* Close connection method
*
* #return void
*/
public function closeConn()
{
return ftp_close($this->conn);
}
// --------------------------------------------------------------------
/**
* Write to file
*
* #param string path to file
* #param string text
* #param string fopen mode
* #return void
*/
function addToFile($file, $ins, $mode = 'a')
{
$fp = fopen($file, $mode);
fwrite($fp,$ins);
fclose($fp);
}
// --------------------------------------------------------------------
/**
* Destruct method - close connection and save log data to file
*
* #return void
*/
function __destruct()
{
$this->closeConn();
$this->logDataToFiles();
}
}
// END ftp class
/* End of file ftp.php */
/* Location: ftp.php */
This should be a comment, but its a bit long. Copying a file over FTP using PHP might be as simple as
file_put_contents($fname
, file_get_contents('FTP://ftp.example com/path/afile'));
But what do you know about where your PHP code is running? It may not have the capability to
resolve DNS names
make client connections to other/remote services
create a listening data channel (for non-passive data channel)
And we can't answer these questions for you. Hence your first step is to get a proof of concept up and running using similar code to that above before you start worrying about lots of files, directories and synchronisation.
Why the requirement to implement this in PHP?

How to use openinviter in zend framework

Hi
Can anyone tell me how to use openinviter script in zend framework
I have used Open Invitor in one of my projects by following a tutorials. Unfortunately, I couldn't find out the link. Here are the main steps:
(a) Create a custom library. To do this, create a folder inside library (library/openinvitor)
(b) Install the Open Invitor Package inside this library (ie library/openinvitor/install.php). I did this by commenting index & htaccess during the installation.
(c) Register new library in the Boot Strap. (Copy the line needed for the Open Invitor Loading)
protected function _initAutoload ()
{
// Add autoloader empty namespace
$autoLoader = Zend_Loader_Autoloader::getInstance();
$autoLoader->registerNamespace('openinviter_');
$resourceLoader = new Zend_Loader_Autoloader_Resource(array('basePath' => APPLICATION_PATH , 'namespace' => '' , 'resourceTypes' => array('form' => array('path' => 'forms/' , 'namespace' => 'Form_') , 'model' => array('path' => 'models/' , 'namespace' => 'Model_'))));
// Return it so that it can be stored by the bootstrap
return $autoLoader;
}
(d) The file name of the library file is: Service.php Also note the name of the class in the step (e)
(e) The content of the Service file is:
<?php
require_once 'openinviter.php';
/**
* This class is the connection between OpenInviter service and Zend Framework.
* The class is implemented only for extracting contacts.
*
* #tutorial
*
* $inviter = new OpenInviter_Service();
*
* p($inviter->getPlugins());// get all services
* p($inviter->getPlugins('email'));// get all services
* p($inviter->getPlugins('email', 'gmail'));// get gmail plugin properties
* p($inviter->getPlugins('email', 'gmail', 'version'));// get gmail plugin version
*
* // get contacts
* p($inviter->getContacts('me#example.com', 'mypass', 'example'));
*
*
* #author stoil
* #link http://openinviter.com/
* #uses OpenInviter 1.7.6
*
*/
class openinviter_Service
{
const PATH_PLUGINS = 'plugins/';
protected $_messages = array();
protected $_plugins;
protected $_openInviter;
/*~~~~~~~~~~ private methods ~~~~~~~~~~*/
private function _loadPlugins()
{
if($this->_plugins === null) {
$this->_plugins = $this->getOpenInviter()->getPlugins(false);
}
}
/*~~~~~~~~~~ protected methods ~~~~~~~~~~*/
protected function _addMessage($code, $message, $type = 'error')
{
$this->_messages[$type][$code] = $message;
}
protected function _initAutoload()
{
set_include_path(
dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . self::PATH_PLUGINS.
PATH_SEPARATOR.
get_include_path()
);
}
/*~~~~~~~~~~ constructor ~~~~~~~~~~*/
public function __construct()
{
$this->_initAutoload();
$this->_openInviter = new openinviter();
$this->_loadPlugins();
}
/*~~~~~~~~~~ public methods ~~~~~~~~~~*/
/**
* Update plugins
*/
public function updatePlugins()
{
$this->_plugins = $this->getOpenInviter()->getPlugins(true);
}
/**
* Get plugin(s), provider(s) or provider details
* #param $type
* #param $provider
* #param $detail
* #return unknown_type
*/
public function getPlugins($type = null, $provider = null, $detail = null)
{
if ($type !== null) {
if ($provider !== null) {
if ($detail !== null) {
return $this->_plugins[$type][$provider][$detail];
} else {
return $this->_plugins[$type][$provider];
}
} else {
return $this->_plugins[$type];
}
} else {
return $this->_plugins;
}
}
/**
* #return openinviter
*/
protected function getOpenInviter()
{
return $this->_openInviter;
}
/**
* Get system messages
* #param string $type
* #return array
*/
public function getMessages($type = null)
{
if($type !== null) {
return $this->_messages[$type];
} else {
return $this->_messages;
}
}
/**
* Get email clients
* #param string $email
* #param string $password
* #param string $provider
* #return array
*/
public function getContacts($email, $password, $provider)
{
$contacts = array();
$this->getOpenInviter()->startPlugin($provider);
$internalError = $this->getOpenInviter()->getInternalError();
if ($internalError) {
$this->_addMessage('inviter', $internalError);
} elseif (! $this->getOpenInviter()->login($email, $password)) {
$internalError = $this->getOpenInviter()->getInternalError();
$this->_addMessage(
'login',
($internalError
? $internalError
: 'Login failed. Please check the email and password you have provided and try again later !'
)
);
} elseif (false === $contacts = $this->getOpenInviter()->getMyContacts()) {
$this->_addMessage('contacts', 'Unable to get contacts');
}
return $contacts;
}
}
(f) Then in the desired controller/function, create an object of the Open Invitor librray and access any functions.
$inviter = new openinviter_Service(); // Create the Object of Opne Invitor
$plugins = $inviter->getPlugins('email'); // Read all Available Plugins.

Categories