How to use openinviter in zend framework - php

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.

Related

can't set dynamic classname in php

I have this function:
public function __construct()
{
$config = include APPPATH."email_config.php";
$driver = "Email_".ucfirst(strtolower($config['driver'])); echo $driver.RT; //gives Email_Smtp
// return new $driver($config); //do not work
return new Email_Smtp($config); //works
}
new $driver($config) gives the error message:
Fatal error: Uncaught Error: Class 'Email_Smtp' not found
$driver is the string "Email_Smtp".
return new Email_Smtp($config) works like a charm.
Whats wrong here?
the config file:
return array(
/**
* Mail useragent string wird in Header als X-Mailer: gesetzt
*/
'useragent' => 'my agent',
/**
* Mail driver (mail, smtp, sendmail, noop, php)
*/
'driver' => 'smtp',
...
here is my autoload:
class Autoloader {
/**
* #type string
*/
protected $namespacePrefix = '';
/**
* #type string
*/
protected $baseDir = '';
/**
* Sets the namespace's prefix.
* Only classes with this namespace will be autoloaded.
*
* #param string $prefix
* #return \Autoloader
*/
public function setNamespacePrefix($prefix) {
$this->namespacePrefix = $prefix;
return $this;
}
/**
* Sets the base directory, where we can find our php files.
*
* #param string $dir
* #return \Autoloader
*/
public function setBaseDir($dir) {
$this->baseDir = $dir;
return $this;
}
/**
* Register our autoloader.
*
* #return void
*/
public function register() {
spl_autoload_register(function($class) {
if (!preg_match('/^' . preg_quote($this->namespacePrefix) . '/', $class)) {
// Don't register a class without our namespace's prefix
return;
}
$relativeClass = substr($class, strlen($this->namespacePrefix));
$file = $this->baseDir . str_replace('\\', DIRECTORY_SEPARATOR, $relativeClass) . '.php';
if (file_exists($file)) {
require_once($file);
// if the loaded file contains a class...
if (class_exists($class, false))
{
if (method_exists($class, '_init') and is_callable($class.'::_init'))
{
call_user_func($class.'::_init');
}
}
}
});
}
}

Cannot declare class \Content, because the name is already in use

I've setup my server with Yii2 and Humhub ext,
What i'm trying to do is set a rest api to it , but I get 500 Internal server error :
"message": "Cannot declare class humhub\modules\content\models\Content, because the name is already in use",
"file": "***\content\models\Content.php",
The first class is :
<?php
namespace app\models;
use Yii;
include '../humhub/modules/content/models/content.php';
class Content extends \humhub\modules\content\models\Content
{
public function getPosts()
{
return $this->hasMany(Post::className(), ['id' => 'object_id']);
}
}
The second class is (pretty big):
<?php
/**
* #link https://www.humhub.org/
* #copyright Copyright (c) 2017 HumHub GmbH & Co. KG
* #license https://www.humhub.com/licences
*/
namespace humhub\modules\content\models;
include __DIR__ .'/../../../modules\content\models\ContentDeprecated.php';
use Yii;
use humhub\modules\user\components\PermissionManager;
use yii\base\Exception;
use yii\helpers\Url;
use humhub\modules\user\models\User;
use humhub\modules\space\models\Space;
use humhub\modules\content\components\ContentActiveRecord;
use humhub\modules\content\components\ContentContainerActiveRecord;
use humhub\modules\content\permissions\ManageContent;
use yii\rbac\Permission;
/**
* This is the model class for table "content".
*
*
* The followings are the available columns in table 'content':
* #property integer $id
* #property string $guid
* #property string $object_model
* #property integer $object_id
* #property integer $visibility
* #property integer $pinned
* #property string $archived
* #property string $created_at
* #property integer $created_by
* #property string $updated_at
* #property integer $updated_by
* #property ContentContainer $contentContainer
*
* #since 0.5
*/
class Content extends ContentDeprecated
{
/**
* A array of user objects which should informed about this new content.
*
* #var array User
*/
public $notifyUsersOfNewContent = [];
/**
* #var int The private visibility mode (e.g. for space member content or user profile posts for friends)
*/
const VISIBILITY_PRIVATE = 0;
/**
* #var int Public visibility mode, e.g. content which are visibile for followers
*/
const VISIBILITY_PUBLIC = 1;
/**
* #var int Owner visibility mode, only visible for contentContainer + content owner
*/
const VISIBILITY_OWNER = 2;
/**
* #var ContentContainerActiveRecord the Container (e.g. Space or User) where this content belongs to.
*/
protected $_container = null;
/**
* #inheritdoc
*/
public function behaviors()
{
return [
[
'class' => \humhub\components\behaviors\PolymorphicRelation::className(),
'mustBeInstanceOf' => array(ContentActiveRecord::className()),
],
[
'class' => \humhub\components\behaviors\GUID::className(),
],
];
}
/**
* #inheritdoc
*/
public static function tableName()
{
return 'content';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['object_id', 'visibility', 'pinned'], 'integer'],
[['archived'], 'safe'],
[['guid'], 'string', 'max' => 45],
[['object_model'], 'string', 'max' => 100],
[['object_model', 'object_id'], 'unique', 'targetAttribute' => ['object_model', 'object_id'], 'message' => 'The combination of Object Model and Object ID has already been taken.'],
[['guid'], 'unique']
];
}
/**
* Returns a Content Object by given Class and ID
*
* #param string $className Class Name of the Content
* #param int $id Primary Key
*/
public static function Get($className, $id)
{
$content = self::findOne(['object_model' => $className, 'object_id' => $id]);
if ($content != null) {
return $className::findOne(['id' => $id]);
}
return null;
}
/**
* #inheritdoc
*/
public function beforeSave($insert)
{
if ($this->object_model == "" || $this->object_id == "") {
throw new Exception("Could not save content with object_model or object_id!");
}
// Set some default values
if (!$this->archived) {
$this->archived = 0;
}
if (!$this->visibility) {
$this->visibility = self::VISIBILITY_PRIVATE;
}
if (!$this->pinned) {
$this->pinned = 0;
}
if ($insert) {
if ($this->created_by == "") {
$this->created_by = Yii::$app->user->id;
}
}
$this->stream_sort_date = new \yii\db\Expression('NOW()');
if ($this->created_by == "") {
throw new Exception("Could not save content without created_by!");
}
return parent::beforeSave($insert);
}
/**
* #inheritdoc
*/
public function afterSave($insert, $changedAttributes)
{
$contentSource = $this->getPolymorphicRelation();
foreach ($this->notifyUsersOfNewContent as $user) {
$contentSource->follow($user->id);
}
if ($insert && !$contentSource instanceof \humhub\modules\activity\models\Activity) {
if ($this->container !== null) {
$notifyUsers = array_merge($this->notifyUsersOfNewContent, Yii::$app->notification->getFollowers($this));
\humhub\modules\content\notifications\ContentCreated::instance()
->from($this->user)
->about($contentSource)
->sendBulk($notifyUsers);
\humhub\modules\content\activities\ContentCreated::instance()
->about($contentSource)->save();
Yii::$app->live->send(new \humhub\modules\content\live\NewContent([
'sguid' => ($this->container instanceof Space) ? $this->container->guid : null,
'uguid' => ($this->container instanceof User) ? $this->container->guid : null,
'originator' => $this->user->guid,
'contentContainerId' => $this->container->contentContainerRecord->id,
'visibility' => $this->visibility,
'contentId' => $this->id
]));
}
}
return parent::afterSave($insert, $changedAttributes);
}
/**
* #inheritdoc
*/
public function afterDelete()
{
// Try delete the underlying object (Post, Question, Task, ...)
$this->resetPolymorphicRelation();
if ($this->getPolymorphicRelation() !== null) {
$this->getPolymorphicRelation()->delete();
}
parent::afterDelete();
}
/**
* Returns the visibility of the content object
*
* #return Integer
*/
public function getVisibility()
{
return $this->visibility;
}
/**
* Checks if the content visiblity is set to public.
*
* #return boolean
*/
public function isPublic()
{
return $this->visibility == self::VISIBILITY_PUBLIC;
}
/**
* Checks if the content visiblity is set to private.
*
* #return boolean
*/
public function isPrivate()
{
return $this->visibility == self::VISIBILITY_PRIVATE;
}
/**
* Checks if the content object is pinned
*
* #return Boolean
*/
public function isPinned()
{
return ($this->pinned);
}
/**
* Pins the content object
*/
public function pin()
{
$this->pinned = 1;
//This prevents the call of beforesave, and the setting of update_at
$this->updateAttributes(['pinned']);
}
/**
* Unpins the content object
*/
public function unpin()
{
$this->pinned = 0;
$this->updateAttributes(['pinned']);
}
/**
* Checks if the user can pin this content.
* This is only allowed for workspace owner.
*
* #return boolean
*/
public function canPin()
{
if ($this->isArchived()) {
return false;
}
return $this->getContainer()->permissionManager->can(new ManageContent());
}
/**
* Creates a list of pinned content objects of the wall
*
* #return Int
*/
public function countPinnedItems()
{
return Content::find()->where(['content.contentcontainer_id' => $this->contentcontainer_id, 'content.pinned' => 1])->count();
}
/**
* Checks if current content object is archived
*
* #return boolean
*/
public function isArchived()
{
return $this->archived || ($this->getContainer() !== null && $this->getContainer()->isArchived());
}
/**
* Checks if the current user can archive this content.
* The content owner and the workspace admin can archive contents.
*
* #return boolean
*/
public function canArchive()
{
// Disabled on user profiles, there is no stream filter available yet.
if ($this->getContainer() instanceof User) {
return false;
}
return $this->getContainer()->permissionManager->can(new ManageContent());
}
/**
* Archives the content object
*/
public function archive()
{
if ($this->canArchive()) {
if ($this->isPinned()) {
$this->unpin();
}
$this->archived = 1;
if (!$this->save()) {
throw new Exception("Could not archive content!" . print_r($this->getErrors(), 1));
}
}
}
/**
* Unarchives the content object
*/
public function unarchive()
{
if ($this->canArchive()) {
$this->archived = 0;
$this->save();
}
}
/**
* Returns the url of this content.
*
* By default is returns the url of the wall entry.
*
* Optionally it's possible to create an own getUrl method in the underlying
* HActiveRecordContent (e.g. Post) to overwrite this behavior.
* e.g. in case there is no wall entry available for this content.
*
* #since 0.11.1
*/
public function getUrl()
{
if (method_exists($this->getPolymorphicRelation(), 'getUrl')) {
return $this->getPolymorphicRelation()->getUrl();
}
return Url::toRoute(['/content/perma', 'id' => $this->id]);
}
/**
* Sets container (e.g. space or user record) for this content.
*
* #param ContentContainerActiveRecord $container
* #throws Exception
*/
public function setContainer(ContentContainerActiveRecord $container)
{
$this->contentcontainer_id = $container->contentContainerRecord->id;
$this->_container = $container;
}
/**
* Returns the content container (e.g. space or user record) of this content
*
* #return ContentContainerActiveRecord
* #throws Exception
*/
public function getContainer()
{
if ($this->_container != null) {
return $this->_container;
}
if ($this->contentContainer !== null) {
$this->_container = $this->contentContainer->getPolymorphicRelation();
}
return $this->_container;
}
/**
* Relation to ContentContainer model
* Note: this is not a Space or User instance!
*
* #since 1.1
* #return \yii\db\ActiveQuery
*/
public function getContentContainer()
{
return $this->hasOne(ContentContainer::className(), ['id' => 'contentcontainer_id']);
}
/**
* Checks if the given user can edit this content.
*
* A user can edit a content if one of the following conditions are met:
*
* - User is the owner of the content
* - User is system administrator and the content module setting `adminCanEditAllContent` is set to true (default)
* - The user is granted the managePermission set by the model record class
* - The user meets the additional condition implemented by the model records class own `canEdit()` function.
*
* #since 1.1
* #param User $user
* #return bool can edit this content
*/
public function canEdit($user = null)
{
if (Yii::$app->user->isGuest) {
return false;
}
if ($user === null) {
$user = Yii::$app->user->getIdentity();
}
// Only owner can edit his content
if ($user !== null && $this->created_by == $user->id) {
return true;
}
// Global Admin can edit/delete arbitrarily content
if (Yii::$app->getModule('content')->adminCanEditAllContent && $user->isSystemAdmin()) {
return true;
}
/* #var $model ContentActiveRecord */
$model = $this->getPolymorphicRelation();
// Check additional manage permission for the given container
if ($model->hasManagePermission() && $this->getContainer() && $this->getContainer()->getPermissionManager($user)->can($model->getManagePermission())) {
return true;
}
// Check if underlying models canEdit implementation
// ToDo: Implement this as interface
if (method_exists($model, 'canEdit') && $model->canEdit($user)) {
return true;
}
return false;
}
/**
* Checks the given $permission of the current user in the contents content container.
* This is short for `$this->getContainer()->getPermissionManager()->can()`.
*
* #param $permission
* #param array $params
* #param bool $allowCaching
* #see PermissionManager::can()
* #since 1.2.1
* #return bool
*/
public function can($permission, $params = [], $allowCaching = true)
{
return $this->getContainer()->getPermissionManager()->can($permission, $params, $allowCaching);
}
/**
* Checks if user can view this content.
*
* #since 1.1
* #param User $user
* #return boolean can view this content
*/
public function canView($user = null)
{
if (!$user && !Yii::$app->user->isGuest) {
$user = Yii::$app->user->getIdentity();
}
// Check Guest Visibility
if (!$user) {
return $this->checkGuestAccess();
}
// Public visible content
if ($this->isPublic()) {
return true;
}
// Check system admin can see all content module configuration
if ($user->isSystemAdmin() && Yii::$app->getModule('content')->adminCanViewAllContent) {
return true;
}
if ($this->isPrivate() && $this->getContainer()->canAccessPrivateContent($user)) {
return true;
}
return false;
}
/**
* Determines if a guest user is able to read this content.
* This is the case if all of the following conditions are met:
*
* - The content is public
* - The `auth.allowGuestAccess` module setting is enabled
* - The space or profile visibility is set to VISIBILITY_ALL
*
* #return bool
*/
public function checkGuestAccess()
{
if(!$this->isPublic() || !Yii::$app->getModule('user')->settings->get('auth.allowGuestAccess')) {
return false;
}
// Check container visibility for guests
return ($this->container instanceof Space && $this->container->visibility == Space::VISIBILITY_ALL)
|| ($this->container instanceof User && $this->container->visibility == User::VISIBILITY_ALL);
}
/**
* Updates the wall/stream sorting time of this content for "updated at" sorting
*/
public function updateStreamSortTime()
{
$this->updateAttributes(['stream_sort_date' => new \yii\db\Expression('NOW()')]);
}
}
As you can see the first class extends the second one , I'm rather new to php but i'm guessing that's the issue
UPDATE : I tried using the "use class as " and still the same error , I also tried changing the name of the first class to Content1 just to check and still the same .
The problem occours in the second class from the error report
This is a recurring error in a few places in the server I figure I will solve it here and the rest will be the same ,
Many Thanks!
You included file with exacly same class name, so you have 2 class declarations with name Content in this file. Easiest ways to fix it:
Change one of class name
Start using Yii2 autloader, if you need to include something - there's something wrong in your code. You should be able to access
class only by using namespace. There's small conditions you have to
met:
Each class must be under a namespace (e.g. foo\bar\MyClass)
Each class must be saved in an individual file whose path is determined by the following algorithm:
// $className is a fully qualified class name without the leading backslash
$classFile = Yii::getAlias('#' . str_replace('\\', '/', $className) . '.php');
More about Yii2 autloading: Class Autoloading

How do I pass the controller by other means than the url in PHP MVC

I realize this may be a dumb question, but I am struggling with a custom MVC project I started in order to learn PHP and I was not able to find what I was looking for anywhere else.
My question is, how do I pass the controller to my router, in a way that does not use the url. How would I make it so that the href in my link tags only provide the category and id and yet make it work. At the moment my urls look like this:
website/controller/method/args
ex: website/articles/post/13
I want the url to be like:
website/category/id-or-slug-from-title
I would really appreciate the help, since it's been bugging me for a week now.
Thanks in advance.
Well, it would be hard to describe possible steps in comment section, so I will add an answer.
The following steps will be exemplary and they do not describe the whole process. I will omit some details
Assuming that you're trying to implement MVC, you should have some kind of bootstrap.php (or something like that)
So, let's create our router class
/**
* Current method
* #var string
*/
protected $method;
/**
* Current args
* #var unknown
*/
protected $args = array();
private static $instance;
/**
* That's how we retrieve class instance
* #return app_router_http
*/
public static function getInstance()
{
if (!isset(static::$instance))
{
static::$instance = new self;
}
return static::$instance;
}
private function __clone() {}
/**
* #throws app_exception
*/
private function __construct()
{
/* парсим текущий урл */
$url = parse_url (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : "/", PHP_URL_PATH);
$url = preg_replace("/\\/{2,}/i", "/", $url);
/* Let's retrieve static route (for example - /category/id-or-slug-from-title) */
if ($_route = $this->getStaticRoute($url))
{
if ($_route->hasErrors())
{
throw new app_exception($_route->getErrors(";"));
}
$this
->setController($_route->getController())
->setMethod($_route->getMethod())
->setArgs($_route->getArgs() ? $_route->getArgs() : null)
;
return;
}
/* Let's retrive dynamic route, because we didn't fing static */
if ($_route = $this->getDynamicRoute($url))
{
if ($_route->hasErrors())
{
throw new app_exception($_route->getErrors(";"));
}
$this
->setController($_route->getController())
->setMethod($_route->getMethod())
->setArgs($_route->getArgs() ? $_route->getArgs() : null);
return;
}
throw new app_exception("Can't found any route objects", 503);
}
/**
* #param string $controller
* #return Router
*/
public function setController($controller)
{
$this->controller = $controller;
return $this;
}
/**
* #return string
*/
public function getController()
{
return $this->controller;
}
/**
* #param string $method
* #return Router
*/
public function setMethod($method)
{
$this->method = $method;
return $this;
}
/**
* #return string
*/
public function getMethod()
{
return $this->method;
}
/**
* #param array $args
* #return Router
*/
public function setArgs(array $args = null)
{
if (isset($args))
{
$this->args = $args;
}
return $this;
}
/**
* #return mixed
*/
public function getArgs()
{
return $this->args;
}
/**
* #param string $route
* #param string $controller
* #param string $method
* #param string $objectId
* #return Route|NULL
*/
public function getStaticRoute($route = null, $controller = null, $method = null, $objectId = null)
{
$db = new DB(); //Some class for db connections
if (isset($route) && !isset($controller) && !isset($method) && !isset($objectId))
{
$selector = "SELECT * FROM `routes` WHERE `route` = '".$db->escape($route)."'";
}
if (!isset($route) && isset($controller) && isset($method) && isset($objectId))
{
$selector = "SELECT * FROM `routes` WHERE `controller` = '".$db->escape($controller)."' && `method` = '".$db->escape($method)."' && `objectId` = '".$db->escape($objectId)."'";
}
if (!isset($selector))
{
throw new app_exception(get_class($this)."::getStaticRoute incorrect params", 503);
}
if ($db->query($selector)->rows())
{
$row = $db->fetch();
$object = new Router();
$object->setAttributes($row);
if (!$object->hasErrors())
{
$object->setController("{$object->getController()}");//Here we are setting our awesome controller
if (!$this->isControllerExist($object->getController()))
{
return $object->addError("Controller {$object->getController()} missing (static route: #{$object->getId()})");
}
if (!$this->isMethodExist($object->getController(), $object->getMethod()))
{
return $object->addError("Method {$object->getMethod()} missing (controller: {$object->getController()}) (static route: #{$object->getId()})");
}
}
return $object;
}
return null;
}
/**
* #param string $path
* #return Router
*/
public function getDynamicRoute($path)
{
$object = new Router;
//Here we will assume that our url looks like this /controller/method/args
/* Url fragments */
$fragments = explode("/", substr($path, 1));
//Removing trailing slash
if (!$fragments[sizeof($fragments)-1])
{
unset($fragments[sizeof($fragments)-1]);
}
if (!isset($fragments[0]))
{
$fragments[0] = APP_ROUTE_DEFAULT_CONTROLLER; //Some kind of magic constant
}
$controller = $fragments[0];
if(!class_exists($controller)
{
throw new Exception("Ooops, controller not found", 404);
}
array_shift($fragments); //We don't need controller element anymore
for ($i = 0; $i <= 1; $i++)
{
if ($i == 0)
{
$method = APP_ROUTE_DEFAULT_METHOD;//We also need to handle urls like /news. For example, each controllers has default method index()
}
else
{
$method = $fragments[0];
}
if ($this->isControllerExist($controller) && $this->isMethodExist($controller, $method))
{
return
$object
->setController($controller)
->setMethod($method);
}
}
return $object->addError("Can't route to <strong>".implode("/", $fragments)."</strong> (dynamic route for module <strong>{$module}</strong>)");
}
/**
* #param string $controller
* #return boolean
*/
public function isControllerExist($controller = null)
{
if (!isset($controller))
{
$controller = $this->getController();
}
return class_exists($controller);
}
/**
* #param string $controller
* #param string $method
* #return boolean
*/
public function isMethodExist($controller = null, $method = null)
{
if (!isset($controller))
{
$controller = $this->getController();
}
if (!isset($method))
{
$method = $this->getMethod();
}
return method_exists($controller, $method);
}
public function run()
{
$_str = $this->getController();
$controller = new $_str;
$return = call_user_func_array(array($controller, $this->getMethod()), $this->getArgs());
return $return;
}
}
So, in bootstrap.php you just need to need to make a call Router::getInstance()->run()
Static route will try to pass your params
For dynamic routes, you always can read args from $_REQUEST
P.S. To be true, this is a cutted examaple made from my old project

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);
}
}

Hybridauth Library not compatible with installed PECL OAuth extension

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;
}
}

Categories