Instagram Real Time Subscription Activity log - instagram

Working on instgram Real Time subscription. I am trying to save the image link based on Object id return from subscription. The activity log captures "N" only, not the image link. What I am doing wrong.
<?php
if (isset ($_GET['hub_challenge'])){
echo $_GET['hub_challenge'];
}
else{
$myString = file_get_contents('php://input');
$sub_update = json_decode($myString);
$access_token = 'xxxxx';
foreach($sub_update as $k => $v) // can be multiple updates per call
{ $objid = $v->object_id;
$recent_data = file_get_contents('https://api.instagram.com/v1/tags/'.$objid.'/media/recent?access_token='.$access_token);
$results=$results['data'];
$image_link = $results['images']['standard_resolution']['url'];
file_put_contents('activity.log', serialize($image_link), FILE_APPEND | LOCK_EX);
}
}
?>

Related

How to set output contexts while creating a intent in dialogflow PHP?

I am trying to set output context to a particular intent via v2 create intent API.
Please check my code.
use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\QueryInput;
use Google\Cloud\Dialogflow\V2\IntentsClient;
use Google\Cloud\Dialogflow\V2\Intent_TrainingPhrase_Part;
use Google\Cloud\Dialogflow\V2\Intent_TrainingPhrase;
use Google\Cloud\Dialogflow\V2\Intent_Message_Text;
use Google\Cloud\Dialogflow\V2\Intent_Message;
use Google\Cloud\Dialogflow\V2\Intent;
use Google\Cloud\Dialogflow\V2\Context;
use Google\Cloud\Dialogflow\V2\ContextsClient;
private function intent_create(){
putenv('GOOGLE_APPLICATION_CREDENTIALS='.getcwd() . '/strive_stage.json');
$intentsClient = new IntentsClient();
/** Create Intent **/
$disaplayName = "Where is Goa";
$utterances = ["Goa", "Where is Goa"];
// prepare training phrases for intent
$trainingPhrases = [];
foreach ($utterances as $trainingPhrasePart) {
$part = new Intent_TrainingPhrase_Part();
$part->setText($trainingPhrasePart);
// create new training phrase for each provided part
$trainingPhrase = new Intent_TrainingPhrase();
$trainingPhrase->setParts([$part]);
$trainingPhrases[] = $trainingPhrase;
}
$messageTexts = 'Goa is in India.';
// prepare messages for intent
$text = new Intent_Message_Text();
$text->setText([$messageTexts]);
$message = new Intent_Message();
$message->setText($text);
$createIntentObject = $intentsClient->projectAgentName(env("DIALOG_FLOW_PROJECT_ID"));
// prepare intent
$intent = new Intent();
$intent->setDisplayName($disaplayName);
$intent->setTrainingPhrases($trainingPhrases);
$intent->setMessages([$message]);
$contexts = ['test'];
foreach($contexts as $con){
$contextObj = new Context();
$contextObj->setName($con);
$contextData[] = $contextObj;
$intent->setOutputContexts($contextData);
}
// $intent->getOutputContexts('test');
//dd($intent);
$response = $intentsClient->createIntent($createIntentObject, $intent);
printf('Intent created: %s' . PHP_EOL, $response->getName());
}
I am getting error message
{
"message": "com.google.apps.framework.request.BadRequestException: Resource name does not match format 'projects/{project_id}/agent/sessions/{session_id}/contexts/{context_id}' or 'projects/{project_id}/locations/{location_id}/agent/sessions/{session_id}/contexts/{context_id}'.",
"code": 3,
"status": "INVALID_ARGUMENT",
"details": []
}
I believe the issue is with the format of storing the output context. Please help me on this.
I had the same issue. The answer is to not put in the bare name, but to have a string of a certain format made
see http://googleapis.github.io/google-cloud-php/#/docs/google-cloud/v0.131.0/dialogflow/v2/intent?method=setOutputContexts
// $projectId your project id
// $sessionId can be anything, I use $sessionId = uniqid();
$uri = "projects/$projectId/agent/sessions/$sessionId/contexts/$con";
$contextObj->setName($uri);
I can see that there are any response about this topic.
I leave here my solution for the next generations
To create a output context you need to create the correct format, for this objetive you can use Context class Google\Cloud\Dialogflow\V2\Context
private function parseoOutputContexts($contexts, $project_id, $lifespan = 5)
{
$newContexts = array();
foreach ($contexts as $context) {
$newContexts[] = new Context(
[
'name' => 'projects/' . $project_id . '/agent/sessions/-/contexts/' . $context,
'lifespan_count' => $lifespan
]
);
}
return $newContexts;
}
And you can use this function to finnaly add the output context to the object Intent.
$dialogflow_intent = new Intent();
$output_contexts = ['output_context_1'. 'output_context_2'];
$output_contexts = $this->parseOutputContexts($output_contexts, '[YOUR_PROJECT_ID]');
$dialogflow_intent->setOutputContexts($output_contexts);

login to modx from external/other server revolution 2.2.5

I am pissed off with this problem from 2 days.
I am using MODx Revolution 2.2.5 (traditional) and want to login to modx from external server just to fetch some user details.
1) I know that runprocessor method works only if i am logged in to manager (unfortunately, that's the only way i know to login user in) So i tried IFRAME method to avoid (cross scripting) it worked perfectly but i am not able to read the data from IFRAME using javascript because of same issue, cross domain access policy.
When i try to post data using some other method like CURL, Ajax using
header("Access-Control-Allow-Origin: *");
I am able to login (I see $response->response['success'] == 1) but cant access any data and it says
Fatal error: Call to a member function get() on a non-object
Below is the snippet code i am using
if(isset($_POST) && count($_POST)){
$c = array(
'username' => $_POST['username'],
'password' => $_POST['password']
);
$response = $modx->runProcessor('security/login',$c);
if($response->response['success'] == 1){
$user['id'] = $modx->user->get('id');
$profile = $modx->user->getOne('Profile');
$user['fullname'] = $profile->get('fullname');
$user['email'] = $profile->get('email');
echo json_encode($user);
}else{
echo json_encode($response->response);
}
}
2) I can use login snippet but it doesnt return output what i expect. We have ready site and we are already using login plugin so i cant even modify login plugin to respond with expected data
How can i login to modx using api or any other method ??
You are really attacking this problem completely wrong in my opinion. If you want to access a server/webpage from another, you don't iFrame and do it the way you are. That is hacking, and this hole will most likely be fixed in a future version.
What you SHOULD do is connecting to the database and just gather the information from the user-table.
No hacking, no "tricks", won't stop working and much safer.
Well, I sorted out this today, Below is the complete come that worked perfectly.
Pay attention to
header("Access-Control-Allow-Origin: http://www.xyz.com");
Using above CORS specification you can allow 2 servers to communication.
header("Access-Control-Allow-Origin: http://www.xyz.com");
if(isset($_POST['username']) && isset($_POST['password'])){
// get username and password from POST array
$username = $modx->sanitizeString($_POST['username']);
$password = $modx->sanitizeString($_POST['password']);
if(trim($username) != "" and trim($password) != ""){
// Load lexicons to show proper error messages
if (!isset($modx->lexicon) || !is_object($modx->lexicon)) {
$modx->getService('lexicon','modLexicon');
}
$modx->lexicon->load('login');
$loginContext= isset ($scriptProperties['login_context']) ? $scriptProperties['login_context'] :
$modx->context->get('key');
$addContexts= isset ($scriptProperties['add_contexts']) && !empty($scriptProperties['add_contexts']) ? explode(',', $scriptProperties['add_contexts']) : array();
$mgrEvents = ($loginContext == 'mgr');
$givenPassword = $password;
/** #var $user modUser */
$user= $modx->getObjectGraph('modUser', '{"Profile":{},"UserSettings":{}}', array ('modUser.username' => $username));
if (!$user) {
$ru = $modx->invokeEvent("OnUserNotFound", array(
'user' => &$user,
'username' => $username,
'password' => $password,
'attributes' => array(
'loginContext' => $loginContext,
)
));
if (!empty($ru)) {
foreach ($ru as $obj) {
if (is_object($obj) && $obj instanceof modUser) {
$user = $obj;
break;
}
}
}
if (!is_object($user) || !($user instanceof modUser)) {
//echo "cant locate account";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_cannot_locate_account')));
exit;
}
}
if (!$user->get('active')) {
//echo "inactivated accout";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_user_inactive')));
exit;
}
if (!$user->passwordMatches($givenPassword)) {
if (!array_key_exists('login_failed', $_SESSION)) {
$_SESSION['login_failed'] = 0;
}
if ($_SESSION['login_failed'] == 0) {
$flc = ((integer) $user->Profile->get('failedlogincount')) + 1;
$user->Profile->set('failedlogincount', $flc);
$user->Profile->save();
$_SESSION['login_failed']++;
} else {
$_SESSION['login_failed'] = 0;
}
//echo "wrong username pass";
echo $modx->toJSON($modx->error->failure($modx->lexicon('login_username_password_incorrect')));
exit;
}
$fullname = $user->Profile->get('fullname');
echo '{"success":true,"message":"Welcome '.$fullname.'!"}';
}else{
echo '{"success":false,"message":"Please enter username and password"}';
}
}

PHP variables not showing up. GETid not working properly

I have all the login scripts and profiles set up. I have a data table where all the profile information is stored called plus_signup but I can't seem to get this GET[id] thing to work. Am I missing something? Here's what I have.
When I view the page with the code I have now, there are blank areas where PHP is supposed to fill in the variables.
session_start();
include "include/z_db.php";
if ($_GET['id']){
$id = $_GET['id'];
} else if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
}
else {
print "important data to render this page is missing";
exit();
$sql = mysql_query("SELECT * FROM plus_signup WHERE id='$userid'");
while($row = mysql_fetch_array($sql)){
$userid = $row["userid"];
$name = $row["name"];
$location = $row["location"];
$sex = $row["sex"];
$aboutme = $row["aboutme"];
}
$check_pic = "users/$id/image01.jpg";
$default_pic = "users/0/image01.jpg";
if (file_exists($check_pic)){
$user_pic = "<img src=\"$check_pic\" width=\"175px\"/>";
} else {
$user_pic = "<img src=\"$default_pic\"/>";
}}
I know it's a little late and that you may have already figured out the answer to this question, but I was having the same issue and just figured it out.
Your SQL query is calling on a variable that has not been defined.
session_start();
include "include/z_db.php";
if ($_GET['id']){
$id = $_GET['id'];
} else if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
}
else {
print "important data to render this page is missing";
exit();
$sql = mysql_query("SELECT * FROM plus_signup WHERE id='$userid'");
while($row = mysql_fetch_array($sql)){
$userid = $row["userid"];
$name = $row["name"];
$location = $row["location"];
$sex = $row["sex"];
$aboutme = $row["aboutme"];
}
$check_pic = "users/$id/image01.jpg";
$default_pic = "users/0/image01.jpg";
if (file_exists($check_pic)){
$user_pic = "<img src=\"$check_pic\" width=\"175px\"/>";
} else {
$user_pic = "<img src=\"$default_pic\"/>";
}}
You are getting the 'id' from the url and storing it as $id. When you call your query, you are having it search for where ID = $userid when you really should be having it search for ID = $id.
Make sure that your variables are the same throughout!
^Hope that helps some people avoid an hour or two of frustration when trying to figure out why their function isn't working!

Search Facebook using PHP SDK

In the last days, I'm working on the application which needs to search for users on Facebook. Since the FQL query for "username" was deprecated/canceled, I have decided to use common search API.
I use PHP so FB PHP SDK is the way I'd prefer. I have used it earlier for FQL queries, just like this:
// $api is already initialized, with access_key, app secret and so on
$users = $api(array(
'method' => 'fql.query',
'query' => "SELECT first_name,last_name FROM user WHERE uid='12345'",
));
I'd like to build the search query in the similar way. Especially, I don't want to urlencode the parameters, specify access key, app secret and all the stuff the SDK is supposed to do for me. However, I haven't been able to build this query using SDK yet. Is there any possibility to do it? If yes, how? I have found long list of sdk-supported "api calls" but I need to build the query for graph.facebook.com/search?arguments.
Thanks in advance.
EDIT: To make it clear, I don't want to build the string by myself. I know this solution works. But imho it's ugly when I have SDK:
$name = urlencode(trim($first_name . " " . $last_name_));
$users = $this->facebook->api("/search?q=$name&type=user&access_token=$key");
Searching User via Graph API using php-sdk 3.1.1
User will need to authorize your app before making a search for
users.
{
"error": {
"message": "A user access token is required to request this resource.",
"type": "OAuthException"
}
}
Php-skd 3.1.1 init.
<?php
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'your-app-id',
'secret' => 'your-app-secret',
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
/* */
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
?>
Search includes, encoding search term, setting results limit, and
offset for paging.
<?php
/* Get Search parameter from url or post and urlencode it. */
$q = urlencode($_GET['qs']);
if(!$_GET['qs']){
$q = urlencode($_POST['qs']);
if(!$_POST['qs']){
/* Default Search Term */
$q = "Shawn+E+Carter";
}
}
/* Get Results Limit from url or set default. */
$limit = $_GET['limit'];
if (!$_GET['limit']){
$limit = 60;
}
/* Get Offset from url or set default for paging. */
$offset = $_GET['offset'];
if (!$_GET['offset']){
$offset = 0;
}
/* Make Graph API call to user */
$usersearch = 'search%3Fq='.$q.'%26type=user%26limit='.$limit.'%26offset='.$offset.'';
echo '<pre style="text-align: left;">';
print_r($usersearch);
echo '</pre>';
?>

Webforms in excel instead of e-mail

A client of mine asked me if i can find a solution for this problem.
His website (still a WIP) http://welkommagazine.nl/luuk/ has a form. The form obviously uses a sendmail script to send the form to e-mail. From thereon he manually copy/pastes all the submissions to excel.
What he wants is that the forms online automaticcaly are added to an excel document to save him a lot of work.
Now i am not a programmer, but a designer.. I think this can be done, but i have absolutely no clue how. I googled alot for it and the only thing i found was a dreamweaverplugin.
Is there a way to do this, if so, how?
Not a programmer's response, but...
I think an easy solution is to use Google docs. You can set-up a Google Spreadsheet and associate a form to it. Whenever a user fills the form , his data is added to the spreadsheet.
Your client may download that anytime.
There are some other providers on the market, some free, some not. E.g: wufoo.com
Found the answer myself. I wrote a PHP code snippet which actually stores the fields comma seperated in a CSV file and sends an email to a desired adress with the filled in fields.
if(isset($_POST['Submit'])){
$pakket = $_POST['pakket'];
$extragidsen = $_POST['extragidsen'];
$naambedrijf = $_POST['naambedrijf'];
$err = '';
if(trim($pakket)==''){
$err .= '-Please enter a name';
}
if(empty($extragidsen)){
$err .= '-Please enter an email address';
}
if(strlen($naambedrijf)==0){
$err .= '-Please enter a comment';
}
if($err!=''){
echo $err;
}
else{
$filename = 'file.csv';
$somecontent = $pakket . ',' . $extragidsen . ',' . $naambedrijf . "\n";
// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (!$handle = fopen($filename, 'a')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
//--------------------------Set these paramaters--------------------------
// Subject of email sent to you.
$subject = 'Inschrijving welkom';
// Your email address. This is where the form information will be sent.
$emailadd = 'luuk#luukratief.com';
// Where to redirect after form is processed.
$url = 'http://www.google.com';
// Makes all fields required. If set to '1' no field can not be empty. If set to '0' any or all fields can be empty.
$req = '0';
// --------------------------Do not edit below this line--------------------------
$text = "Results from form:\n\n";
$space = ' ';
$line = '
';
foreach ($_POST as $key => $value)
{
if ($req == '1')
{
if ($value == '')
{echo "$key is empty";die;}
}
$j = strlen($key);
if ($j >= 20)
{echo "Name of form element $key cannot be longer than 20 characters";die;}
$j = 20 - $j;
for ($i = 1; $i ';
fclose($handle);
} else {
echo "The file $filename is not writable";
}
}
}
Maybe the code aint that clean as it can be, but eh it works.
Feel free to clean up the code if you want to :)
I guessed I would answer this myself for the community...
BTW u need to set "write" rights to "file.csv"
cheers

Resources