Pubnub PHP SDK subscribe function - php

I'm working on a chat application using PubNub and PHP. The publishing of messages is working but I'm not sure how to read from the subscriber.
I ran the subscriber file in the command line and it is showing the messages as they are published but I'm not sure how to read from it or how to return, as per the doc the subscriber is a separate process.
use PubNub\PNConfiguration;
class MySubscribeCallback extends SubscribeCallback {
function status($pubnub, $status) {
if ($status->getCategory() === PNStatusCategory::PNUnexpectedDisconnectCategory) {
// This event happens when radio / connectivity is lost
} else if ($status->getCategory() === PNStatusCategory::PNConnectedCategory) {
} else if ($status->getCategory() === PNStatusCategory::PNDecryptionErrorCategory) {
// Handle message decryption error. Probably client configured to
// encrypt messages and on live data feed it received plain text.
}
}
function message($pubnub, $message) {
print_r($pubnub);
print_r($message);
}
function presence($pubnub, $presence) {
// handle incoming presence data
}
}
$subscribeCallback = new MySubscribeCallback();
$pubnub->addListener($subscribeCallback);
$pubnub->subscribe()
->channels(["Channel-1","Channel-2","Channel-3"])
->execute();
this is the subscriber code present on the PubNub Doc.
I'm calling this file using javascript.

Related

AWS notification is failed after sending email to the user

I am using AWS to send emails in my project.. I created subscription and done all the steps. Its sending emails to the user but the notification is not receiving.. it says notification failed. I don't know the reason.. but I am getting notifications if I use http url instead https url.
The php code I am using is added below -
<?php
require 'path/to/vendor/autoload.php';
use AwsSnsMessageValidatorMessage;
use AwsSnsMessageValidatorMessageValidator;
use GuzzleHttpClient;
// Make sure the request is POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
die;
}
try {
// Create a message from the post data and validate its signature
$message = Message::fromRawPostData();
$validator = new MessageValidator();
$validator->validate($message);
} catch (Exception $e) {
// Pretend we're not here if the message is invalid
http_response_code(404);
die;
}
if ($message->get('Type') === 'SubscriptionConfirmation') {
// Send a request to the SubscribeURL to complete subscription
(new Client)->get($message->get('SubscribeURL'))->send();
} elseif ($message->get('Type') === 'Notification') {
// Do something with the notification
save_message_to_database($message);
}
I am following the AWS documentation. Do you know the reason.. is there any issue in this code?

Concrete5 Custom Ajax in Block View

On Concrete5-8.1.0 I have created a custom block with Ajax functionality based largely on the concrete5 docs - Implementing Ajax in Block View Templates. However, unlike the example I do not want to reload the block view, I want to pass specific messages based on the input. I tried a simple echo '{"msg":"ok"}'; and return '{"msg":"ok"}); as a test, but requests to the function yielded an empty response.
I found How To Send JSON Responses with Concrete5.7 and used Option 2 (for greater control of error codes) resulting in the following test code:
public function action_submit($token = false, $bID = false) {
if ($this->bID != $bID) {
return false;
}
if (Core::make('token')->validate('get_paper', $token)) {
//save to database
//removed for brevity
//send email
if ($this->emailto != '') {
//removed for brevity
}
if ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
return new Response(
json_encode(array('msg' => 'ok')),
200,
['Content-Type' => 'application/json']
);
} else {
Redirect::page($page)->send();
}
}
else {
return false;
}
exit;
}
The database save and email function as expected, but the response is still empty. In Chrome Dev Tools, I see the correct Content-Type (as a test, I tried text/html and saw that change in dev tools), but no content. Interestingly, if I change the status from 200 to 500 I not only see the status change reflected in dev tools, I also see the {"msg":"ok"} content that I'm expecting, but changing the status back to 200 and the content is again empty.
It seems I'm missing something simple... I have verified that all caching is turned off within C5 (site is still in development), I have also verified the jQuery request includes cache:false, but the solution escapes me.

How to validate authentication header in multiple functions in PHP

I'm trying to use JWT to create a authentication system using AngularJs and PHP. I understood the concept of JWT, I can modify the headers and send my access token, etc... My doubt is on the logic to elaborate this since I have a lot of different functions.
For example, I have a file called client.php where I have client related functions, such as getClient, updateClient, insertClient, etc.. The same applies for other files, product.php, category.php, filter.php and so on.
So, how am i supposed to do this token validation before actually running any of these functions?
I tought of creating a common function and use it inside each function, for example:
function.php
function checkToken($token) {
$serverToken = //getting server token;
if($token !== $serverToken) {
return false;
}
}
client.php
require_once 'function.php';
$tokenError = array('status' => 'Unauthorized');
function insertClient() {
global $tokenError;
$accessToken = $_SERVER['HTTP_TOKEN'];
if(!checkToken($accessToken)) {
return $tokenError;
} else {
//Proceed with the function
}
}
function getClient() {
//Repeat samething as insertClient
//...
}
But it doesn't feel like the proper way to do this. So, is there a better, or a correct way, to do headers validation/authorization on each http request the user make?

How to call destructor after response in php?

I have a chat bot which save some data into db which user is sending. I want to save it to db (a slow network call) after sending response to the user.
I could do that in Python Tornado but I havent been able to do it PHP Apache.
user sends input as request -> we process it -> we send output to user as response -> then we wish to store data
class A
{
function __construct()
{
echo "Hello World";
}
function __destruct()
{
sleep(15); //I want this to happen after response is being send
}
function calc()
{
echo "Progress World";
}
}
__destruct is called upon object deletion, the object being out of scope, or normal script ending. If the script isn't terminating normally but killed, the destructor may not be called at all.
If you just want to do cleanup task at specific points and ensure them being processed use the PHP 5.5-introduced finally clause
A __destruct example from the PHP site:
<?php
class my_class {
public $error_reporting = false;
function __construct($error_reporting = false) {
$this->error_reporting = $error_reporting;
}
function __destruct() {
if($this->error_reporting === true) $this->show_report();
unset($this->error_reporting);
}
?>
See the PHP Documentation on destructors. I hope this helps.

Codeigniter Email error handling

The CI Email send() function only returns true or false. Is there a way to get a more detailed reason as to why a sending failed? I'm using SMTP.
You can further inspect what happened by using the email debugger:
$r = $this->send(FALSE);
if (!$r)
$this->email->print_debugger()
;
From the Codeigniter Email Class Reference.
If you need the debugger output as a string, you can just catch the output with an output buffer:
$errors = array();
... # Loop
$r = $this->send(FALSE);
if (!$r) {
ob_start();
$this->email->print_debugger();
$error = ob_end_clean();
$errors[] = $error;
}
... # Loop end
Codeigniter in more recent versions requires an explicit FALSE for the $auto_clear parameter of the email->send() function in order to not clear the message and the debugging, effectively killing the debugger function if you fail to pass the FALSE.
The print_debugger() function will work but it appends the e-mail header and message at the bottom. If all you want is an array of the debug message (which include both success and error messages), you could consider extending the functionality of the Email class as follows:
<?php
class MY_Email extends CI_Email
{
public function clear_debugger_messages()
{
$this->_debug_msg = array();
}
public function get_debugger_messages()
{
return $this->_debug_msg;
}
}
You'd want to place this in a file named MY_Email.php in your ./application/libraries folder. CodeIgniter will automatically recognize the existence of this class and use it instead of it's default one.
When you want to get a list (array) of debug messages, you can then do this:
$this->email->get_debugger_messages();
If you're looping through messages and don't want to include debugger messages from previous attempts, you can do this:
foreach ($email_addresses as $email_address)
{
$this->email->to($email_address);
if (! $this->email->send())
{
echo 'Failed';
// Loop through the debugger messages.
foreach ($this->email->get_debugger_messages() as $debugger_message)
echo $debugger_message;
// Remove the debugger messages as they're not necessary for the next attempt.
$this->email->clear_debugger_messages();
}
else
echo 'Sent';
}
Reference: "Extending Native Libraries" section of https://www.codeigniter.com/user_guide/general/creating_libraries.html.
Codeigniter 3:
if ( $this->email->send() ) {
echo 'Your Email has successfully been sent.';
} else {
$errors = $this->email->print_debugger();
print_r($errors);
}
You could check your mail logs. If the mail errors out then you should have a record saying why in there.
I'm not sure where they will be located though it depends on your system.

Categories