Session, PHP Incomplete Class - php

I am using cakePHP 2.x . Currently doing about the twitter OAuth, http://code.42dh.com/oauth/.
function twitter_authentication()
{
//assume above coding is all correct.
$this->Session->write('twitter_request_token', ($requestToken));
$this->redirect('http://api.twitter.com/oauth/authenticate?force_login=true&oauth_token='.$requestToken->key); //I able to get $requestToken.
}
function twitter_login()
{
$requestToken = $this->Session->read('twitter_request_token');
$accessToken = $this->OAuthConsumer->getAccessToken('Twitter','https://api.twitter.com/oauth/access_token', $requestToken);
At function_login(), I failed to read session and ended up with PhP Incomplete Class. If I do $this->Session->write('twitter_request_token', serialize($requestToken)); and $requestToken = $this->Session->read(unserialize('twitter_request_token'); it will work, but I will ended up error at other places which caused by using serialize and unserialize session.

"PHP Incomplete Class" means PHP doesn't have a class definition for the object you're loading.
Option A: figure out what class that object is when you write it into the session and ensure that class's definition is loaded before loading the object.
Option B: convert the object to an stdClass or array before writing it, and convert back after loading. This might be more complex than the first option.

OAuth.php's OauthToken class is quite simple with just two properties: key and secret. When you get the login url, you can store it to the session as an array:
CakeSession::write('Twitter.requestToken', array(
'key' => $requestToken->key,
'secret' => $requestToken->secret
));
Then, instantiate your own OAuthToken when calling OAuthClient->getAccessToken() like so:
$sessionRequestToken = CakeSession::read('Twitter.requestToken');
$accessToken = $twitterClient->getAccessToken('https://api.twitter.com/oauth/access_token',
new OAuthToken($sessionRequestToken['key'], $sessionRequestToken['secret']));
Should be ready to go:
if ($accessToken) {
$twitterClient->post($accessToken->key, $accessToken->secret,
'https://api.twitter.com/1/statuses/update.json', array('status' => 'My balls smells like A-1 sauce. #science'));
}

Related

Codeigniter how to set API keys and Resource urls for easy access in applications

I am trying to clean up my site by putting all of my configurations in one place for easy access.
I have many different configuration dependencies for example, PayPal and Stripe public/private and sandbox/live keys as well as a number of links e.g. google recaptcha links.
I don't want to be spreading these keys around my app and then need to go hunting for them if I want to go from sandbox to live for example.
I am trying to define my API keys and most used links in the CodeIgniter config.php file like this...
$config['stripe_live'] = [
'secret' => 'secret_key_xyz',
'private' => 'private_key_xyz',
]
$config['stripe_sandbox'] = [
'secret' => 'secret_key_xyz',
'private' => 'private_key_xyz',
]
$config['paypal'] = [
'secret' => 'secret_key_xyz',
'private' => 'private_key_xyz',
]
$config['recaptcha'] = [
'site_key' => 'xyz_one_two_three',
'secret_key' => 'xyz_one_two_three',
];
$config['jquery'] = [
['jquery_link'] => base_url() . 'Public/js/jquery.js',
]
$config['bootstrap'] = [
['bootstrap_link'] => base_url() . 'Public/js/jquery.js',
]
$config['fontawesome'] = [
]
$config['google_fonts'] = [
];
$config['groupworld'] = [
'groupworld_api' => 'api_key_xyz';
];
Question one:
If I wanted to access my Stripe live private key I would have to write...
$stripe_live = $this->config->item('stripe_live');
$stripe_live['public_key'];
This is almost as much work as just copying the key to where I need it (one or two places). So is there a simpler way?
Question two:
Is is okay to put my urls in the config file like in my example above? Or would it be better to define my URLs as constants (in the constants file) and then simply access them as constants instead of writing out $this->config->item('bootstrap_link')
Thanks.
After looking at the CodeIgniter Config documentation I have come up with the following solution at least for my API configuration settings, in the example below I am using the google recaptcha API.
1 - Make a new file inside of the application/config folder and call it whatever you want... e.g. api_config.php
Inside this file put your API keys like this:
// stripe api
$config["stripe_live_public_key"] = "public_key_xyz";
$config["stripe_live_private_key"] = "public_key_xyz";
$config["stripe_sandbox_public_key"] = "public_key_xyz";
$config["stripe_sandbox_private_key"] = "public_key_xyz";
// paypal api
$config["paypal_live_public_key"] = "public_key_xyz";
$config["paypal_live_private_key"] = "public_key_xyz";
$config["paypal_sandbox_public_key"] = "public_key_xyz";
$config["paypal_sandbox_private_key"] = "public_key_xyz";
// recaptcha api
$config["recaptcha_api_url"] = 'https://www.google.com/recaptcha/api.js';
$config["recaptcha_verification_url"] = "https://www.google.com/recaptcha/api/siteverify";
$config["recaptcha_public_key"] = "lfgksl;dfg;kkkkdsjfhskjfhkjsdhfjshjksjdh";
$config["recaptcha_private_key"] = "sfkljslfjsjfahjjjjjjhjhsdfjskhajkakkajdj";
// groupworld api
// phpmailer api
2 - In the controller file load your config file and mass the data to the view like this...
$this->config->load('api_config');
$data['recaptcha_api_url'] = $this->config->item('recaptcha_api_url');
$data['recaptcha_public_key'] = $this->config->item('recaptcha_public_key');
3 - In the view file simply display your data...
<script src="<?php echo $recaptcha_api_url; ?>"></script>
<div class="g-recaptcha" data-sitekey="<?php echo $recaptcha_public_key; ?>"></div>
Now to change your config data in multiple places simply go to the api_config.php file and paste in your new keys.
As I'm a newbie can't comment :/ .
I will start with question 2. Its ok to keep like this. But stripe,paypal are payment gateways it will be good to store it in db as Yogesh said and retrieve to use it.It will also comes in handy if you want to provide user to edit it.
For js,css links you can put them in a view like 'includefiles.php' and load it in all pages as we load views.
for easy retrieval of your data, you can use helper functions.
<?php
//paymentdetail_helper
function getpaymentdetailhelper(someid or gateway name as arg eg.$id){
$ins=& get_instance();
$ins->load->database();
//your queries $ins->db->query();
return $data;
}
?>
Save this in application/helpers as paymentdetail_helper.php and load it as usual. more info about helpers in questionInfo about helper
Its my idea. :) You're welcome with suggestions

WHMCS: How to get the current client in addon module clientarea page?

Given that I have a WHMCS addon that I call 'my_addon'. I created the main addon file 'my_addon.php' which does contain nothing than:
<?php
function my_addon_clientarea($vars) {
$client = null;
return array(
'pagetitle' => 'My Addon',
'breadcrumb' => array('index.php?m=my_addon'=>'My Addon'),
'templatefile' => 'views/myaddon_view',
'vars' => array(
'client' => $client
)
);
}
This does basically work. It does give me my template file, everything is passed through. My question is: How do I get the currently logged in client from within that function?
I didn't find any API method and I can't see any constant which does hold this information.
There must be a way to get the current client within the clientarea? Thanks for your help!
For those who do come after me and have the same problem: it's easy to solve. Turned out, that I just had to think it through... I found the client id to be available in the $_SESSION-variable.
So, if you are looking for the client's id:
<?php
function my_addon_clientarea($vars) {
$clientid = $_SESSION['uid'];
// And so on...
}
The official way to get current user information is:
$currentUser = new \WHMCS\Authentication\CurrentUser;
$user = $currentUser->user();
You can find more information here

MongoDB, how to insert object into new collection?

I have a return object coming from instagram.
I am trying to skate the entire build DB table structure process, I understand Mongo is the ideal DB to use for this task.
I am using the regular instagram libraries https://github.com/cosenary/Instagram-PHP-API
and my test code runs without error.
I don have the PhP PECL mongo libraries installed, I should be good to go.
session_start();
require 'vendor/autoload.php';
use MetzWeb\Instagram\Instagram;
$instagram = new Instagram(array(
'apiKey' => 'xxx',
'apiSecret' => 'xxx',
'apiCallback' => 'http://103.238.173.97/success.php'
));
$accessToken = $instagram->getAccessToken();
$_SESSION['InstagramAccessToken'] = $accessToken;
$instagram->setAccessToken($_SESSION['InstagramAccessToken']);
$popular = $instagram->getPopularMedia();
// After getting the response, let's iterate the payload
var_dump($popular);
added just now:
$conn = new MongoClient('mongodb://localhost/?w=1');
$db = $conn->instagram;
// access collection
$collection = $db->instagram1;
$collection->insert($popular);
How would I construct a PDO query to 'autobuild' the table structure just like the JSON object at reply from my request?
instagram JSON object
Repaste of object. Most got cut off due to size
Update:
I tried to insert straight into a collection, I get no error but the DB is still the same size
show dbs
Data 0.078GB
admin (empty)
instagram 0.078GB
local 0.078GB
test 0.078GB
week1 (empty)

Using Zend_Form_Element_Captcha - session has already been started

I am trying to add a Captcha as part of a big application form.
Getting the following error:
session has already been started by session.auto-start or session_start()
How can I get around this as behind the scenes it uses:
// Process metadata specific only to this namespace.
Zend_Session::start(true); // attempt auto-start (throws exception if strict option set)
I instantiate it in the Controller:
$this->view->captcha = new Zend_Form_Element_Captcha('captcha', array(
'captcha' => array(
'captcha' => 'Figlet',
'wordLen' => 6,
'width' => 300,
'height' => 100,
)
)
);
In the View:
<?php echo $this->captcha; ?>
I can't tamper with current session as it holds a lot of information. Is there a workaround?
Help would be appreciated.
You can do one thing in this case, try starting your Zend session in bootstrap file in below way and set that session object in registry:
protected function _initSession() {
$userSession = new Zend_Session_Namespace('user_session');
Zend_Registry::set('userSession', $userSession);
}
After this you will be able to get session object anywhere from registry.
$userSession = Zend_Registry::get('userSession');
Since you will start your Zend Session before session_start() so it might not produce any error.

Yii can't access session variables

My problem: I can't access session data in the view, which I tried to save in the controller before rendering the view.
In my opinion there's an error when storing the session data. (It's necessary for me to modify the session data after creating it, not only in the single action.)
ProcessController.php
public function actionNew() {
$formhash = md5(time());
$hashList = array();
$hashList[$formhash]['processingNumber'] = '';
//fill with empty model
$hashList[$formhash]['model'] = $this->loadModel();
//store hashList in session
Yii::app()->session['hashList'] = $hashList;
$this->render('/process', array('hashValue => $formHash));
}
Now in the view I need the data from the session to show them to the user. But when dumping the hashList it just dumps "null" (Maybe because the saving in the controller didn't went well).
process.php
<?php
$form = this->beginWidget('CActiveForm', array(
'id' => 'process_form',
//several other things...
));
//Output: null
CVarDumper::dump(Yii::app()->session['hashList'],10,true);
?>
I tried to use $_SESSION instead of Yii::app()->session, which gives me access to the data in the view. But when handling other actions in the Controller the $_SESSION variable is undefined.
Any suggestions?
Thank you.
Long answer is:
Regarding to this documents:
$session=new CHttpSession;
$session->open();
$value1=$session['name1']; // get session variable 'name1'
$value2=$session['name2']; // get session variable 'name2'
foreach($session as $name=>$value) // traverse all session variables
$session['name3']=$value3; // set session variable 'name3'
You can use as well:
Yii::app()->session->set('hashList', $hashList);
Yii::app()->session->get('hashList');
And set it again.
Beside this session thing, why do not you use this:
$this->render('/process', array('hashValue => $formHash, 'hashList' => $hashList));
So you do not need to save it in a session if you can reach it directly into the view.
According to the documentation your code should work. An alternative might be to use the following, but it does the same:
Yii::app()->session->add('hashList', $hashList); // set the value
$hashList = Yii::app()->session->get('hashList'); // get the value
I expect the problem either a debugging problem, meaning you have observed cached or otherwise outdated data or a problem in parts of your code that you have not shown.

Categories