I was wondering if it is at all possible to write a php file that will take a form submission from an external server and add the submission to wordpress as a blog post. The file should return a post->ID. Thanks
If you want to have the form processed on the remote server, you can remotely add the submission to WordPress via XMLRPC.
An example as follows:
<?php
class XMLRPClientWordPress
{
var $XMLRPCURL = "";
var $UserName = "";
var $PassWord = "";
// constructor
public function __construct($xmlrpcurl, $username, $password)
{
$this->XMLRPCURL = $xmlrpcurl;
$this->UserName = $username;
$this->PassWord = $password;
}
function send_request($requestname, $params)
{
$request = xmlrpc_encode_request($requestname, $params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, $this->XMLRPCURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$results = curl_exec($ch);
curl_close($ch);
return $results;
}
function create_post($title,$body,$category,$keywords='',$encoding='UTF-8')
{
$title = htmlentities($title,ENT_NOQUOTES,$encoding);
$keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);
$content = array(
'title'=>$title,
'description'=>$body,
'mt_allow_comments'=>0, // 1 to allow comments
'mt_allow_pings'=>0, // 1 to allow trackbacks
'post_type'=>'post',
'mt_keywords'=>$keywords,
'categories'=>array($category)
);
$params = array(0,$this->UserName,$this->PassWord,$content,true);
return $this->send_request('metaWeblog.newPost',$params);
}
function create_page($title,$body,$encoding='UTF-8')
{
$title = htmlentities($title,ENT_NOQUOTES,$encoding);
$content = array(
'title'=>$title,
'description'=>$body
);
$params = array(0,$this->UserName,$this->PassWord,$content,true);
return $this->send_request('wp.newPage',$params);
}
function display_authors()
{
$params = array(0,$this->UserName,$this->PassWord);
return $this->send_request('wp.getAuthors',$params);
}
function sayHello()
{
$params = array();
return $this->send_request('demo.sayHello',$params);
}
}
if(trim($_POST['subject'])=='' || trim($_POST['content'])==''){
die('All fields are required.');
}
$xmlrpc = new XMLRPClientWordPress("http://yoursite.com/xmlrpc.php" , "username" , "password");
$xmlrpc->create_post( mb_convert_encoding(stripslashes($_POST['subject']), 'HTML-ENTITIES', 'UTF-8'), mb_convert_encoding(htmlentities(stripslashes($_POST['content']), ENT_COMPAT, 'UTF-8'), 'HTML-ENTITIES', 'UTF-8'), 1);
echo 'Post successful!';
?>
Related
I'm working on password strength in my Yii 1.1 app. I'm using the haveibeenpwned API.
If the password is not accepted, what can I do to run the routine again?
If the password is accepted, what can I do to return to $user->save()?
This is my helper file (PasswordHelper.php):
public static function passwordCheck($password)
{
if ($password) {
// sha1 hash of new password
$hash = sha1($password, false);
// character 0-4 of new password
$prefix = strtoupper(substr($hash, 0, 5));
// character 5-39 of new password
$suffix = strtoupper(substr($hash, 5, 35));
// API url
$url = "https://api.pwnedpasswords.com/range/" . $prefix;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
curl_setopt($ch, CURLOPT_TIMEOUT, 500);
$result = curl_exec($ch);
// Change the result from string to array, split it by every line
$result = explode("\n", $result);
foreach ($result as $r) {
$r = explode(":", $r);
if ($r[0] == $suffix) {
return Yii::app()->systemMsg->raiseError(Yii::t('validators', 'NOT_APPROVED_PASSWORD'));
}
}
curl_close($ch);
}
}
}
And this is part of the controller file:
if ($user->newPassword) {
$password = $user->newPassword;
PasswordHelper::passwordCheck($password);
}
if ( $user->save() ) {
Yii::app()->systemMsg->raiseSuccess( Yii::t( 'validators', 'SAVE_SUCCESS' ) );
$redirectUrl = Yii::app()->input->get( 'return', $this->module->returnUrl );
$this->redirect( $redirectUrl );
}
else {
Yii::app()->systemMsg->raiseError( Yii::t( 'validators', 'SAVE_ERROR' ) );
$this->setModel( $user );
$this->actionEdit( $user->id );
}
instead of creating passwordCheck function on helper class. Please do create this function on Model and write accessrule So that validation can done when you perform $user->validate()
I'm not sure where I'm going wrong, but needing to post from my site to my Facebook Page.
~ fbautopost.php
require_once("Facebook/facebook.php");
class FacebookPost
{
var $consumer;
var $token;
var $method;
var $http_status;
var $last_api_call;
var $callback;
var $connection;
var $access_token;
function __construct($data)
{
$config = array();
$config['appId'] = $data['consumer_key'];
$config['secret'] = $data['consumer_secret'];
$pageID = $data['page_ID'];
$this->connection = new Facebook($config);
}
function share($title, $targetUrl, $imgUrl, $description, $access_token)
{
$this->connection->setAccessToken($access_token);
$params["access_token"] = $access_token;
if(!empty($title))
{
$params["message"] = $title;
$params["name"] = $title;
}
if(!empty($targetUrl))
{
$params["link"] = $targetUrl;
}
if(!empty($imgUrl))
{
$params["picture"] = $imgUrl;
}
if(!empty($description))
{
$params["description"] = $description;
}
// post to Facebook
try
{
$ret = $this->connection->api('/' .$pageID . '/feed/', 'post', $params);
}
catch(Exception $e)
{
$e->getMessage();
}
return true;
}
function getLoginUrl($params)
{
return $this->connection->getLoginUrl($params);
}
function getContent($url)
{
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_URL, $url);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ci, CURLOPT_HEADER, false);
curl_setopt( $ci, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ci);
curl_close ($ci);
return $response;
}
}
~ post.php
include('fbautopost.php');
$access_token = 'MY_ACCESS_TOKEN';
$facebookData = array();
$facebookData['consumer_key'] = 'MY_APP_ID';
$facebookData['consumer_secret'] = 'MY_SECRET_KEY';
$facebookData['page_ID'] = 'MY_PAGE_ID';
$title = 'Post Title';
$description = 'This is a test post';
$facebook = new FacebookPost($facebookData);
$facebook->share($title, $description, $access_token);
I haven't taken the app out of development, but as the admin I am not seeing any test posts posting on the page.
It's possible that I'm not getting the correct ACCESS TOKEN?? From the Graph Explorer, I am selecting my application, then getting a User Token with manage_page and publish_page permissions. I've also tried using a Page Token. Neither work. Is my code bad, or am I missing something else?
TIA
The issue was that I needed to require_once('Facebook/autoload.php'), not the Facebook.php that I had.
I have a class that login to a coffee machine. I have a laravel app that "scan" all the coffee machines given in a range of IP address.
The problem is that Curl stops after 39, 128 or even 90 requests. So, I don't know what is the problem or if is a memory leak because PHP and Curl doesn't show any error.
I need advice or tips how to achieve this type of problem. Below is my code.
CoffeeMachine class
<?php
namespace Starbucks\CoffeeMachine;
class CoffeeMachine
{
private $url = '';
private $username = '';
private $password = '';
private $session;
private $response;
private $responses;
private $lastMessage = '';
private $lastStatus = FALSE;
private $authenticated = FALSE;
private function setFailStatus($message = '')
{
$this->lastStatus = FALSE;
$this->lastMessage = $message;
return FALSE;
}
private function setSuccessStatus($message = '')
{
$this->lastStatus = TRUE;
$this->lastMessage = $message;
return TRUE;
}
public function __construct($url = '', $username = 'admin', $password = 'admin')
{
$this->boot();
$this->url = $url;
$this->username = $username;
$this->password = $password;
$this->session = curl_init();
curl_setopt($this->session, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($this->session, CURLOPT_FAILONERROR, 1);
curl_setopt($this->session, CURLOPT_FORBID_REUSE, 1);
curl_setopt($this->session, CURLOPT_FRESH_CONNECT, 1);
}
public function getResponse()
{
return $this->response;
}
public function login()
{
curl_setopt($this->session, CURLOPT_URL, $this->url . '/cgi-bin/dologin');
curl_setopt($this->session, CURLOPT_POST, 1);
curl_setopt($this->session, CURLOPT_POSTFIELDS, array(
'username' => $this->username,
'password' => $this->password
)
);
curl_setopt($this->session, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->session, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->session, CURLOPT_HEADER, 0);
$response = curl_exec($this->session);
$response = json_decode($response, 1);
if (!isset($response['response'])) return $this->setFailStatus('Auth with no data...');
if ($response['response'] != 'success') return $this->setFailStatus('Access denied...');
$this->response = $response;
$this->lastStatus = TRUE;
$this->lastMessage = 'OK';
$this->authenticated = TRUE;
return TRUE;
}
public function getDeviceInfo()
{
}
public function logout()
{
curl_close($this->session);
}
}
Discover method in a range of IP
<?php
public function discover(Request $request)
{
$from = ip2long($request->input('from', '0.0.0.0'));
$to = ip2long($request->input('to', '255.255.255.255'));
$ips = array();
// CHUNK IN GROUPS OF 10 FOR WAIT 60 SECONDS, BUT NOT WORK
for($i = $from; $i < $to; $i++) $ips[] = long2ip($i);
$group_of_ips = array_chunk($ips, 10);
// TESTED THIS AND NOT WORK
$default_max_execution_time = ini_get('max_execution_time');
ini_set('max_execution_time', ((abs($from - $to) * 5) + (count($group_of_ips) * 60)) );
$machine_ips = array();
foreach($group_of_ips as $index => $row) {
foreach($row as $ip) {
$gs = new CoffeeMachine($ip, 'admin', 'admin');
if ($gs->login()) {
$machine_ips[] = $ip;
}
$gs->logout();
}
sleep(60); // TESTED THIS AND NOT WORK
}
ini_set('max_execution_time', $default_max_execution_time);
/* RETURN THE COFFEE MACHINE IP ADDRESS */
return $machine_ips;
}
add more error checking. some snippets from my curl wrapper, hhb_curl:
$this->curlh = curl_init ( '' ); // why empty string? PHP Fatal error: Uncaught TypeError: curl_init() expects parameter 1 to be string, null given
if (! $this->curlh) {
throw new RuntimeException ( 'curl_init failed!' );
}
here i verify that curl_init managed to create a curl resource, if it didn't, i throw a RuntimeException. you should do the same.
$ret = curl_exec ( $this->curlh );
if ($this->errno ()) {
throw new RuntimeException ( 'curl_exec failed. errno: ' . var_export ( $this->errno (), true ) . ' error: ' . var_export ( $this->error (), true ) );
}
here, i verify that curl_exec didn't register any errors, else i throw a RuntimeException. you should do the same. (it uses curl_errno($ch) )
function setopt_array(array $options): bool {
foreach ( $options as $option => $value ) {
$this->setopt ( $option, $value );
}
return true;
}
here i make sure my setopt_array doesn't actually use curl_setopt_array, but my own curl_setopt wrapper, you should do the same, for reasons explained below.
private function _setopt(int $option, $value): bool {
$ret = curl_setopt ( $this->curlh, $option, $value );
if (! $ret) {
throw new InvalidArgumentException ( 'curl_setopt failed. errno: ' . $this->errno () . '. error: ' . $this->error () . '. option: ' . var_export ( $this->_curlopt_name ( $option ), true ) . ' (' . var_export ( $option, true ) . '). value: ' . var_export ( $value, true ) );
}
$this->curloptions [$option] = $value;
return $ret; // true...
}
here i verify that curl_setopt succeeded, if it didn't, i throw an InvalidArgumentException, you should do the same (or at least throw some kind of exception, rather than the silent ignore your current code does.), and unlike curl_setopt_array, you can actually easily determine which option couldn't be set.
and when debugging curl code, always set CURLOPT_VERBOSE. (hhb_curl always does this, and gives curl a CURLOPT_STDERR tempfile() to put the verbose/error logs in, and gives you the logs through $hc->getStdErr() ), you should at least add some form of CURLOPT_VERBOSE support for debugging. my curl wrapper, hhb_curl, is available here https://github.com/divinity76/hhb_.inc.php/blob/master/hhb_.inc.php
Adding a timeout to the curl execution solves the problem. You need to monitor the response time for each device you want to reach. for me, 10 seconds for CONNECTTIMEOUT and TIMEOUT works fine.
<?php
namespace Starbucks\CoffeeMachine;
class CoffeeMachine
{
private $url = '';
private $username = '';
private $password = '';
private $session;
private $response;
private $responses;
private $lastMessage = '';
private $lastStatus = FALSE;
private $authenticated = FALSE;
private function setFailStatus($message = '')
{
$this->lastStatus = FALSE;
$this->lastMessage = $message;
return FALSE;
}
private function setSuccessStatus($message = '')
{
$this->lastStatus = TRUE;
$this->lastMessage = $message;
return TRUE;
}
public function __construct($url = '', $username = 'admin', $password = 'admin')
{
$this->boot();
$this->url = $url;
$this->username = $username;
$this->password = $password;
$this->session = curl_init();
curl_setopt($this->session, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($this->session, CURLOPT_TIMEOUT, 10);
curl_setopt($this->session, CURLOPT_FAILONERROR, 1);
curl_setopt($this->session, CURLOPT_FORBID_REUSE, 1);
curl_setopt($this->session, CURLOPT_FRESH_CONNECT, 1);
}
public function getResponse()
{
return $this->response;
}
public function login()
{
curl_setopt($this->session, CURLOPT_URL, $this->url . '/cgi-bin/dologin');
curl_setopt($this->session, CURLOPT_POST, 1);
curl_setopt($this->session, CURLOPT_POSTFIELDS, array(
'username' => $this->username,
'password' => $this->password
)
);
curl_setopt($this->session, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($this->session, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($this->session, CURLOPT_HEADER, 0);
$response = curl_exec($this->session);
if (curl_errno($this->session)) {
$msg = $this->url . "\n" . curl_errno($this->session) . "\n" . curl_error($this->session);
return $this->setFailStatus($msg);
}
$response = json_decode($response, 1);
if (!isset($response['response'])) return $this->setFailStatus('Auth with no data...');
if ($response['response'] != 'success') return $this->setFailStatus('Access denied...');
$this->response = $response;
$this->lastStatus = TRUE;
$this->lastMessage = 'OK';
$this->authenticated = TRUE;
return TRUE;
}
public function getDeviceInfo()
{
}
public function logout()
{
curl_close($this->session);
}
}
Now I can loop and reach CoffeeMachines =)
My web app stops when it tries executing a function from another file. I am using a include_once to include the file where the function is. I am also pretty sure that the path is correct. (if there is anyway to check let me know). the functions which I am trying to use are written in the class.connections.php . Also as you can see I am echoing 2 test. Only the first one shows.
Invite.php
global $page_array ;
global $current_user ;
include_once(DITC_PATH."/class.friends.php");
include_once(DITC_PATH."/class.connections.php");
$process_status = $current_user->process_hotmail_contacts ;
global $page_array ;
if($page_array['url']['3'] == 'hotmail'){
$process_source = 'hotmail' ;
};
if($_GET['code']){
echo "Test 1 - ";
$access_token_json = get_hotmail_access_token();
echo "Test 2 - ";
if($access_token_json){
echo 'test';
update_user_meta($current_user->ID, 'hotmail_access_token', $access_token_json);
$taskurl = "/tasks";
$data = array();
$data['type'] = 'process_hotmail_contacts';
$data['lang'] = get_site_language();
$data['access_token'] = $access_token_json ;
$data['user_id'] = $current_user->ID ;
$options = array();
add_task($taskurl, $data, $options);
$process_status = 'busy' ;
$process_source = 'hotmail' ;
};
}
$ditc_title = _t("Invite connections") ;
get_header();
function in class.connections
function get_hotmail_access_token(){
global $hotmail_creds;
$fields=array(
'code'=> urlencode($hotmail_creds['auth_code']),
'client_id'=> urlencode($hotmail_creds['client_id']),
'client_secret'=> urlencode($hotmail_creds['client_secret']),
'redirect_uri'=> urlencode($hotmail_creds['redirect_uri']),
'grant_type'=> urlencode('authorization_code')
);
$post = '';
foreach($fields as $key=>$value) { $post .= $key.'='.$value.'&'; }
$post = rtrim($post,'&');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL,'https://login.live.com/oauth20_token.srf');
curl_setopt($curl, CURLOPT_POST,5);
curl_setopt($curl, CURLOPT_POSTFIELDS,$post);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
$result = curl_exec($curl);
curl_close($curl);
$response = json_decode($result);
$access_token_json = $response->access_token;
return $access_token_json;
};
I have successfully implemented geo-location into my website on localhost. however upon uploading the website to an online server, it doesn't work anymore. i get a bool(false) error.
Geo.php
<?php
class Geo{
protected $api = 'http://www.telize.com/geoip/%s';
protected $properties = [];
public function __get($key){
if (isset($this->properties[$key])){
return $this->properties[$key];
}
return null;
}
public function request($ip){
$url = sprintf($this->api, $ip);
$data = $this->sendRequest($url);
$this->properties = json_decode($data, true);
}
protected function sendRequest($url){
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
return curl_exec($curl);
}
}
?>
index.php
<?php
include ("functions/functions.php");
$ip = getIp();
require 'Geo.php';
$geo = new Geo;
$geo->request('$ip');
$location = $geo->city . ', ' .$geo->region;
?>
getIp() function is located in the function.php file which i included, that works fine so I've excluded it.
Code improvement.
Geo.php
<?php
class Geo {
protected $api = 'http://www.telize.com/geoip/%s';
protected $properties = [];
public function __get($key)
{
if (isset($this->properties[$key]))
return $this->properties[$key];
return null;
}
public function request($ip) {
$url = sprintf($this->api, $ip);
$data = $this->sendRequest($url);
if($data !== false) $this->properties = json_decode($data, true);
return ($data !== false);
}
protected function sendRequest($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
return curl_exec($curl);
}
}
?>
index.php
<?php
include ("functions/functions.php");
$ip = getIp();
require 'Geo.php';
$geo = new Geo;
if($geo->request($ip)) {
$location = $geo->city . ', ' .$geo->region;
}
else {
// Location not found
}
?>