I am trying to get a log in with facebook working on Yii site using Crugeconnector. http://yiiframeworkenespanol.org/wiki/index.php?title=CrugeConnector . It is in Spanish but Google Translate works well with it.
Anyway my problem at the moment is that the successfunction is not being called and I have no idea why. The following code is in my main.php under components array.
'crugeconnector'=>array(
'class'=>'ext.crugeconnector.CrugeConnector',
'hostcontrollername'=>'site',
'onSuccess'=>array('site/loginsuccess'),
'onError'=>array('site/loginerror'),
'clients'=>array(
'facebook'=>array(
// required by crugeconnector:
'enabled'=>true,
'class'=>'ext.crugeconnector.clients.Facebook',
'callback'=>'http://smecontracts.ie/6/facebook-callback.php',
// required by remote interface:
'client_id'=>"290200194448698",
'client_secret'=>"0608f1e94db5a3a8b6612af1c61fb25d",
'scope'=>'email, read_stream',
),
The next batch of code is under my site controller.
public function actionLoginSuccess($key){
error_log("In Sitecontroller successful login page", 0);
$loginData = Yii::app()->crugeconnector->getStoredData();
// loginData: remote user information in JSON format.
$info = $loginData;
error_log($info, 0);
$this->renderText('<h1>Welcome!</h1><p>'.$info.'</p> key='.$key);
$this->redirect(Yii::app()->params["GREETINGS_PAGE_LINK"]);
}
The actionLoginSuccess function is never being called. I have calls to the log files that are never being called as can be seen above. Finally the facebook-callback.php looks as follows.
<?php
error_log("In facebook-callback page", 0);
$yii=dirname(__FILE__).'/../yii/framework/yii.php';
$config=dirname(__FILE__).'/protected/config/main.php';
defined('YII_DEBUG') or define('YII_DEBUG',false);
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
$_GET['r'] = '/site/crugeconnector'; // <--using 'site' ?
$_GET['crugekey'] = 'facebook'; // <--facebook key
$_GET['crugemode'] = 'callback';
require_once($yii);
Yii::createWebApplication($config)->run();
?>
This page is being called. The error_log above does get called however the only thing happening is that the user is being brought back to the main welcome page on my website which was set the in facebook app creation. I have no idea where to go from here, I need to retrieve the information from facebook and create an account using Yii, which would be done fairly easily if the login success function worked but there lies my problem.
Thanks for any help.
im the author on this yii extension.
the problem is not the callback itself. the problem is your own access rules. try making that actions required by the extension to be user-free, in other words, those actions should be out of any access rule. In your yii applicacion tell the system that this action are enabled to be executed by a anonymouse user (the * (asterisc) in the access rules).
hope it helps you.
I think you put this function in site controller and if function exist than put only one line.
public function actions() {
return array(
'crugeconnector' => array('class' => 'CrugeConnectorAction'),
);
}
And for Facebook button use this:
<?php if(Yii::app()->crugeconnector->hasEnabledClients){ ?>
<div class='crugeconnector'>
<span>Use your Facebook or Google account:</span>
<ul>
<?php
$cc = Yii::app()->crugeconnector;
foreach($cc->enabledClients as $key=>$config){
$image = CHtml::image($cc->getClientDefaultImage($key));
echo "<li>".CHtml::link($image,
$cc->getClientLoginUrl($key))."</li>";
}
?>
</ul>
</div>
<?php } ?>
Related
I'm trying to move the QR code block to the main login page, i don't want to use the QR code to login, just the download app QR code generated on the profile page, i seems that the only way is via code insert but i'm not very sure how to do it because i can't find either the code or the function related to the img generation, i looked at the profile.php page on my moodle and it seems that it is created by the function:
echo $OUTPUT->custom_block_region('content');
but this function looks like is related to all the profile fields instead of just the QR code block, i'm trying to find some code or function related to it but no success until so i'm asking if someone knows if it is possible to put the "download app QR code" block on the login and how to do it.
Mobile QR code section renderer from the component tool_mobile.
you can find the QR code image generation method on the function tool_mobile_myprofile_navigation in "YourMoodle\admin\tool\mobile\lib.PHP"
You can generate the QR code to access the mobile app using the below code.
$mobilesettings = get_config('tool_mobile');
$qrcodeimg = tool_mobile\api::generate_login_qrcode($mobilesettings);
$qrcodeforappstr = get_string('qrcodeformobileappaccess', 'tool_mobile');
echo html_writer::div(html_writer::img($qrcodeimg, $qrcodeforappstr));
If you want to add this QR code to the login page. You can do it by rendering the login page using the theme (recommended). Or you can do it by modifying the core.
Render by theme.
In your boost theme core_renderer.php file. Please add the below function in the core_renderer class to render the login page.
you can find the core_renderer file in "Moodle\theme\boost\classes\output\core_renderer.php"
public function render_login(\core_auth\output\login $form) {
global $CFG, $SITE;
$context = $form->export_for_template($this);
// Override because rendering is not supported in template yet.
if ($CFG->rememberusername == 0) {
$context->cookieshelpiconformatted = $this->help_icon('cookiesenabledonlysession');
} else {
$context->cookieshelpiconformatted = $this->help_icon('cookiesenabled');
}
$context->errorformatted = $this->error_text($context->error);
$url = $this->get_logo_url();
if ($url) {
$url = $url->out(false);
}
$context->logourl = $url;
$context->sitename = format_string($SITE->fullname, true,
['context' => \context_course::instance(SITEID), "escape" => false]);
// QR Code to access the site URL in mobile app.
$mobilesettings = get_config('tool_mobile');
$qrcodeimg = \tool_mobile\api::generate_login_qrcode($mobilesettings);
$qrcodeforappstr = get_string('qrcodeformobileappaccess', 'tool_mobile');
$context->qrcodeimage = \html_writer::div(\html_writer::img($qrcodeimg, $qrcodeforappstr));
return $this->render_from_template('core/loginform', $context);
}
Then create the folder "core" in your boost theme templates folder.
Then copy the loginform.mustache file from Moodle\lib\templates\loginform.mustache to the folder "core" which is created in your boost theme templates folder.
And add the code {{{qrcodeimage}}} in the copied loginform.mustache file.
I am basically android developer, I also work on PHP to create REST APIs for mobile apps. I am working on an android app, I want to create a WordPress-REST-API for my android app to add users into WordPress wp_user's table through the android app.
For this, i created a REST API in PHP and used wp_create_user() method to add a user into WordPress database. I placed API into 'wp-content/themes/mytheme' directory but it's always showing me this error 'Call to undefined function wp_create_user()', i think wp_create_user() function is unavailable in my API.
I asked from my WordPress friend and he said, you have to create a custom page template and have to call that page from android app but this is illogical fro me. How can I resolve this issue?
<?php
if (!isset($_POST['ins_name'])) {
die("ins_name is not set");
}
$ins_name = $_POST['ins_name'];
if (!isset($_POST['ins_email'])) {
die("ins_email is not set");
}
$ins_email = $_POST['ins_email'];
if (!isset($_POST['ins_password'])) {
die("ins_password is not set");
}
$ins_password = $_POST['ins_password'];
function addUserIntoWordpressTable($email, $password) {
$user_id = wp_create_user( $username, $password, $email );
echo $user_id;
}
addUserIntoWordpressTable($ins_name, $ins_password, $ins_email);
?>
I want to add users's data into WordPress database through REST API.
Wordpress has it's own built in REST API framework where you can use all the existing functions, and extend it in a clean way without having to worry about REST boilerplate or doing ugly things like making a REST page template.
You can read more about it here: https://developer.wordpress.org/rest-api/
For any WordPress functions to work in your custom folder or api folder you have to include the file wp-load.php in your file.
Like:
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
You need to include this file at the top of your php file.
Hope it works for you.
I have adopted a CakePhp 2 project. We get to the project from another project, linking to the CakePhp project with a "token" and a conference ID as a parameter in the URL. Using that token, we authorize the user, and using the conference ID get the information from the database. The session value "auth" is set to true.
We have it running on 2 "platforms" locally on my system using a vagrant machine, and on a production server. Locally the session value dies really quick and at random times. On the production server not as often, but the issues we have where Ajax calls don't seem to do what are expected, we believe are being caused by a similar issue. We have many different projects, all Laravel, with zero issues where the session values clear. This issue is strictly with the CakePhp project.
All the authentication magic happens in the beforeFilter method. The code:
public function beforeFilter() {
$session = new CakeSession();
/**
*
* We will check if the current user is authorized here!
*
*/
// If the visitor is coming for the first time, there should be a parameter in
// the URL that is the auth code to check against the database.
if ( ( isset($_GET['conf']) && is_numeric($_GET['conf']) ) && isset($_GET['token']) ) {
$getConference = ClassRegistry::init('Conference')->find('first', ["conditions" => ["conference_id"=>$_GET['conf'] ]]);
$checkToken = ClassRegistry::init('User')->find('first', ["conditions" => ["remember_token"=>$_GET['token'] ]]);
if ($getConference && $checkToken) {
$checkToken['User']['remember_token'] = $this->generateToken();
if ( ClassRegistry::init('User')->save( $checkToken ) ) {
$session->write('auth', true);
$session->write('conferenceId', $_GET['conf']);
$this->redirect('/');
}
}
else {
$session->write('auth', false);
$session->write('conferenceId', null);
}
}
if (! $session->read('auth') || $session->read('conferenceId') == null ) {
echo "No permission!";
exit;
}
}
At the top of the controller:
App::uses('CakeSession', 'Model/Datasource');
When the URL parameters are present, it traps them, does the work, and redirects to the home route without the parameters.
$this->generateToken();
Creates a new token, and overwrites the old one in the database.
There are 2 main controllers. The controller with this code is the main projects controller. The only time it is really hit is the first time you go to the project, and we hit the index method. From there everything else is AJAX calls to the other controller. There is one link, a "home" type link that will hit that index method.
Sometimes these Ajax calls stop working, and clicking that home link will output "No Permission" instead of the expected html in the container the Ajax call outputs too.
Steps to troubleshoot led me to putting this beforeFilter method on the top of the second controller. Now, randomly I'll get no permission. Sometimes, when I'm on the main project that links to this CakePhp project, I click that link, I get no permission right off the bat.
I found this page: cakephp takes me to login page on multiple request and have tried to set the session details like this:
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => '300' // <- added this element
));
And I have tried:
Configure::write('Session.timeout', '300');
Additionally, I have tried cookieTimeout in both of those cases.
I've also tried
Configure::write('Security.level', 'low');
and included
Configure::write('Session.autoRegenerate', true);
In any order, any of these cause the session to bomb out immediately. I get "No permission on page load, and never get anywhere.
The code for this project is honestly crap. The developer who wrote it had mistakes and errors all over the place. On top of that, we are a Laravel shop. We are just trying to keep the project limping along until sometime in the future when we can nuke it from orbit. So we just need to get this working. Any thoughts on what could be causing this? Any other details I am forgetting to include that would help troubleshoot this issue?
Thanks
Reading & writing session data
You can read values from the session using Set::classicExtract() compatible syntax:
CakeSession::read('Config.language');
$key should be the dot separated path you wish to write $value to:
CakeSession::write('Config.language', 'eng');
When you need to delete data from the session, you can use delete:
CakeSession::delete('Config.language');
You should also see the documentation on Sessions and SessionHelper for how to access Session data in the controller and view.
I have problem with posting offer to page (which I am admin) via facebook api. It'is work, when I post feed to this page, but not for offers. This always return me FacebookSDKException with message : Invalid parameter. I use PHP (Laravel framework), but I think it does not matter on the language I use. I use this code:
try {
$response = $fb->post('/' . $page_id . '/offers' , $offerData, (string) $request->access_token
);
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
return response()->json(['error'=>$e->getMessage(),
], 200);
}
where my "$request->access_token" is page access token. And in my "$offerData" I have this fields:
$offerData =[
'claim_limit'=>8,
'expiration_time'=>\Carbon\Carbon::now()->addDays(10)->toDateTimeString(),
'message'=>"bbb",
'title'=>"ascvc",
'coupon_required'=>false,
'image_url'=>'...',
'published'=>true,
'reminder_time'=>\Carbon\Carbon::now()->addDays(5)->toDateTimeString(),
// 'scheduled_publish_time'=>5
];
I also try do this by curl (not by first code) and by curl it returns similar error message.
"{"error":{"message":"Invalid parameter","type":"OAuthException","code":100,"error_subcode":1528104,"is_transient":false,"error_user_title":"Check Your Admin Permission Level","error_user_msg":"Only some admins of your Page are able to create and edit offers. Talk to the person responsible for your Page about your admin permission level.","fbtrace_id":"..."}}"
It looks that there is problem with permissions but at login to facebook I set this permissions:
['manage_pages', 'pages_show_list', 'email',
'user_hometown', 'publish_actions', 'user_photos', 'publish_pages']
I have no idea where is problem. I must to tell you that feeds on same page works fine, but not offers. Can you help me, please?
Take a look at the newer /nativeoffers endpoint; that should be a cleaner path through this one.
https://developers.facebook.com/ads/blog/post/2016/08/30/offer-ads-apis/
I'm wondering if there is any proper way to include HTML in the setFlash() function of the Session component.
Basically I have this admin interface on an e-commerce website which allows administrators to create and edit "shops" found on the website. Upon saving the "shop", I would like CakePHP to display something like "Your shop has been successfully saved. Return to Shop Index". "Return to Shop Index" would be a link. I'm currently using plain old HTML like:
$this->Session->setFlash("Shop has been successfully published. Return to Shop Index");
Works, but it's HTML in the Controller, which I think is a "bad thing".
Thanks!
EDIT:
Thanks #YonoRan for solution. Missed that out in the CakePHP documentation. Here's what I did:
1) Created new element session_flash_link.ctp in app/views/elements.
2) Added the following code in session_flash_link.ctp:
<div id="flashMessage" class="message">
<?php
echo $message;
echo $this->Html->link($link_text, $link_url, array("escape" => false));
?>
</div>
3) Code in controller:
$this->Session->setFlash("Shop has been successfully saved. ", "session_flash_link", array(
"link_text" => "Return to Shop Management ยป",
"link_url" => array(
"controller" => "shops",
"action" => "manage",
"admin" => true
)
));
This might be a solution for what you are trying to do, it loads a "Layout" with all the HTML in it as a setFlash message.
Custom CakePHP flash message
Update:
I just checked the Manual for setFlash
SetFlash Manual
And it shows that you can specify and element that holds the HTML for the setFlash message + a bunch of other properties.
setFlash($message, $element = 'default', $params = array(), $key = 'flash')
So it seems like a better way of doing whats suggested in the first link I posted, because it doesn't require a new layout but just uses Elements.
Good luck.
I've just found another way to do this that doesn't need new specific templates:
You can use the HtmlHelper - which you can access since it's probably loaded in the view, and we have access to that:
// access the html helper
$Html = (new View($this))->loadHelper('Html');
// use it to generate a link
$resend = $Html->link(__('resend'), array(
'controller' => 'users',
'action' => 'resend',
));
// sprintf to insert the link to your standard message text!
$this->Session->setFlash(sprintf(_("Do you want to %s the email?"), $resend));
Should work in any case where you need Helper functionality in a View. Works in 2.3.5.