How to integrate Akismet in wordpress/php programmatically - php

I would like to check a custom form against spam using Akismet.
I searched the web and the only simple way I found is this (see code excerpt below): http://www.binarymoon.co.uk/2010/03/akismet-plugin-theme-stop-spam-dead/. Unfortunately $isSpam returns true!
Does anyone know how to do the magic? I appreciate your help.
function akismet_isSpam ($content) {
// innocent until proven guilty
$isSpam = FALSE;
$content = (array) $content;
if (function_exists('akismet_init')) {
$wpcom_api_key = get_option('wordpress_api_key');
if (!empty($wpcom_api_key)) {
global $akismet_api_host, $akismet_api_port;
// set remaining required values for akismet api
$content['user_ip'] = preg_replace( '/[^0-9., ]/', '', $_SERVER['REMOTE_ADDR'] );
$content['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
$content['referrer'] = $_SERVER['HTTP_REFERER'];
$content['blog'] = get_option('home');
if (empty($content['referrer'])) {
$content['referrer'] = get_permalink();
}
$queryString = '';
foreach ($content as $key => $data) {
if (!empty($data)) {
$queryString .= $key . '=' . urlencode(stripslashes($data)) . '&';
}
}
$response = akismet_http_post($queryString, $akismet_api_host, '/1.1/comment-check', $akismet_api_port);
smart_dump($response, true);
if ($response[1] == 'true') {
update_option('akismet_spam_count', get_option('akismet_spam_count') + 1);
$isSpam = TRUE;
}
}
}
return $isSpam;
}

First , you can assume akismet is installed and API key verified, that will allow you to use the akismet_http_post function directly to post the data to servers ..
// Like above mentioned, We assume that :
// Akismet is installed with the corresponding API key
if( function_exists( 'akismet_http_post' ) )
{
global $akismet_api_host, $akismet_api_port;
// data to be delivered to Akismet (This is what you need Modify this to your needs)
$data = array(
'comment_author' => 'Spammer Spammy',
'comment_author_email' => 'spammy#spamserver.com',
'comment_author_url' => 'spamming.com',
'comment_content' => 'my Spam',
'user_ip' => '99.99.99.99',
'user_agent' => '',
'referrer' => '',
'blog' => 'http://example.com',
'blog_lang' => 'en_US',
'blog_charset' => 'UTF-8',
'permalink' => 'http://example.com/my-link',
'is_test' => TRUE,
);
// Now we need to construct the query string
$query_string = http_build_query( $data );
// and then post it to Akismet
$response = akismet_http_post( $query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port );
// ..and check the results
$result = ( is_array( $response ) && isset( $response[1] ) ) ? $response[1] : 'false';
// display the result ( 'true', 'false' or any error message you want )
printf( 'Spam check according to Akismet :%s', $result );
}
This was not thoroughly tested , but should work..
Note that the blog, user_ip and user_agent parameters are required for the akismet_http_post function.
Also, it would be nice to mention that Akismet has libraries and good API documents .

Related

Yourls: how to make plugin to accept url in other scheme than http or https

Default Yourls doesn't allow url to be shorten in other scheme than http or https. But I want it to accept them, too. I am going to implement by adding custom plugin.
there is a function evaluating url input by users as bellow.
includes\functions.php
function yourls_add_new_link( $url, $keyword = '', $title = '' ) {
// Allow plugins to short-circuit the whole function
$pre = yourls_apply_filter( 'shunt_add_new_link', false, $url, $keyword, $title );
if ( false !== $pre )
return $pre;
$url = yourls_encodeURI( $url );
$url = yourls_sanitize_url( $url );
if ( !$url || $url == 'http://' || $url == 'https://' ) {
$return['status'] = 'fail';
$return['code'] = 'error:nourl';
$return['message'] = yourls__( 'Missing or malformed URL' );
$return['errorCode'] = '400';
return yourls_apply_filter( 'add_new_link_fail_nourl', $return, $url, $keyword, $title );
}
I just don't know whether I can make it to allow other url scheme by adding plugin or not. Do you have any idea?

Why do my admin drop down menu doesn't show up when i try to create my own settings for a css customizable moodle theme?

I am creating a new moodle theme which the css needs to be customizable. By "customizable", i mean that from the admin page you can edit for exemple, the color of your background.
I followed the tutorial from https://docs.moodle.org/dev/Themes, which is great but should be, from my opinion, about the same parent theme for each parts of it.
My page is displaying well at the exception of my admin drop down menu (so i can't see my theme editing page). Everything was fine before i tried to setup my own settings just as the tutorial.
I assume that i probably made a mistake by adaptating my theme from the tutorial but i'm completly lost right now.
We are here in the 'theme/mytheme' directory.
File 'settings.php' :
<?php
defined('MOODLE_INTERNAL') || die();
$name = 'theme_mytheme/backcolor';
$title = get_string('backcolor', 'theme_mytheme');
$desc = get_string('backcolor_desc', 'theme_mytheme');
$setting = new admin_setting_configcolourpicker($name, $title, $desc, '#ffffff');
$setting->set_updatedcallback('theme_reset_all_caches');
$page->add($setting);
?>
File 'lib.php':
<?php
defined('MOODLE_INTERNAL') || die;
function theme_mytheme_process_css($css, $theme) {
// Set custom CSS.
if (!empty($theme->settings->customcss)) {
$customcss = $theme->settings->customcss;
} else {
$customcss = null;
}
$css = theme_mytheme_set_customcss($css, $customcss);
$defaults = array(
'[[setting:backcolor]]' => '#FFFFFF',
);
foreach ($theme->settings as $key => $val) {
if (array_key_exists('[[setting:'.$key.']]', $defaults) && !empty($val)) {
$defaults['[[setting:'.$key.']]'] = $val;
}
}
$homebkg = '';
if (!empty($theme->settings->homebk)) {
$homebkg = $theme->setting_file_url('homebk', 'homebk');
$homebkg = 'background-image: url("' . $homebkg . '");';
}
$defaults['[[setting:homebkg]]'] = $homebkg;
// Replace the CSS with values from the $defaults array.
$css = strtr($css, $defaults);
if (empty($theme->settings->tilesshowallcontacts) || $theme->settings->tilesshowallcontacts == false) {
$css = theme_mytheme_set_tilesshowallcontacts($css, false);
} else {
$css = theme_mytheme_set_tilesshowallcontacts($css, true);
}
return $css;
}
function theme_mytheme_set_customcss($css, $customcss) {
$tag = '[[setting:customcss]]';
$replacement = $customcss;
if (is_null($replacement)) {
$replacement = '';
}
$css = str_replace($tag, $replacement, $css);
return $css;
}
function theme_mytheme_set_tilesshowallcontacts($css, $display) {
$tag = '[[setting:tilesshowallcontacts]]';
if ($display) {
$replacement = 'block';
} else {
$replacement = 'none';
}
$css = str_replace($tag, $replacement, $css);
return $css;
}
function theme_mytheme_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options = array()) {
if ($context->contextlevel == CONTEXT_SYSTEM &&
($filearea === 'logo' || $filearea === 'smalllogo' || $filearea === 'backgroundimage')) {
$theme = theme_config::load('mytheme');
// By default, theme files must be cache-able by both browsers and proxies.
if (!array_key_exists('cacheability', $options)) {
$options['cacheability'] = 'public';
}
return $theme->setting_file_serve($filearea, $args, $forcedownload, $options);
} else {
send_file_not_found();
}
}
?>
File 'config.php' :
<?php
defined('MOODLE_INTERNAL') || die();
$THEME->name = 'mytheme';
$THEME->sheets = array('styles');
$THEME->editor_sheets = array();
$THEME->parents = array('base');
$THEME->yuicssmodules = array();
$THEME->scss = function($theme) {
return theme_mytheme_get_pre_scss($theme);
};
$THEME->layouts = array(
// Most backwards compatible layout without the blocks - this is the layout used by default
'base' => array(
'theme' => 'mytheme',
'file' => 'standard.php',
'regions' => array(),
),
'standard' => array(
'theme' => 'mytheme',
'file' => 'standard.php',
'regions' => array('side-pre', 'side-post'),
'defaultregion' => 'side-pre',
),
'frontpage' => array(
'theme' => 'mytheme',
'file' => 'standard.php',
'regions' => array('side-pre', 'side-post'),
'defaultregion' => 'side-post'
)
);
$THEME->csspostprocess = 'theme_mytheme_process_css';
?>
I feel sorry for passing my complete files but it can't be pertinent if i don't...

PHP $get_ empty when data is posted from website, but not manual url

I have an odd problem with this script. I can post directly to it using the URL: "http://example.com/script.php?payer_email=foo&txn_id=9229fjfua822". But trying to post the same data from lets say http://requestmaker.com nothing is showing in the variable(s). I'm using nginx with PHP5.
<?php
$panel_url = 'http://example.com:23462/';
$username = $_GET['payer_email'];
$invoice = $_GET['txn_id'];
$trimmedinvoice = substr($invoice, -6);
$password = $trimmedinvoice;
$max_connections = 1;
$reseller = 0;
$bouquet_ids = array(
1,
2,
3 );
$expirationdays = $_GET['custom'];
$expiration = "+$expirationdays day";
$expiredate = strtotime($expiration);
###############################################################################
$post_data = array( 'user_data' => array(
'username' => $username,
'password' => $password,
'max_connections' => $max_connections,
'is_restreamer' => $reseller,
'exp_date' => $expiredate,
'bouquet' => json_encode( $bouquet_ids ) ) );
$opts = array( 'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query( $post_data ) ) );
$context = stream_context_create( $opts );
$api_result = json_decode( file_get_contents( $panel_url . "api.php?action=user&sub=create", false, $context ) );
Echo "<b>Username:</b> <br>";
echo $username;
echo "<br></br>";
echo "<b>Password:<br></b>";
echo $password;
echo "<br></br>";
echo "<b>Expires (in unix time):<br></b>";
echo $expiredate;
?>
Been testing all night and found that adding this code will return the data being passed without problems. So the problem seems to be with the script, not the setup itself. Just can't figure where I'm going wrong.
print "CONTENT_TYPE: " . $_SERVER['CONTENT_TYPE'] . "<BR />";
$data = file_get_contents('php://input');
print "DATA: <pre>";
var_dump($data);
var_dump($_POST);
print "</pre>";
Output from the last block of code posting directly with the URL:
CONTENT_TYPE:
DATA:
string(0) ""
array(0) {
}
Output from the last block of code posting using an external poster like the requestmaker:
CONTENT_TYPE:
text/html<BR />
DATA: <pre>string(35) "payer_email=foo&txn_id=9229fjfua822"
array(0) {
}
POST variables are in $_POST not $_GET (the latter contains the arguments appended to the URI).
You could use $_REQUEST which contains both POST and GET variables.
See this document for more.

Drupal 7 PHP cURL not executing

I'm attempting to send results from a drupal webform through a cURL POST to a third party. My cURL function is not working, and I'm struggling to find my error. I have never used cURL before, so I'm not really sure how it works, or really even what it does.
From what I can tell, I'm piecing together the URL to be sent correctly, the send is just failing.
<?php
module_load_include('inc','webform','includes/webform.submissions');
$uri = $_SERVER[REQUEST_URI];
$sid = substr($uri, 20);
$submission = webform_get_submissions(array('sid' => $sid));
$nid = $submission[$sid]->nid;
$sql = db_select('webform_submitted_data', 'w');
$sql->fields('w', array('sid','cid','data'))
->condition('sid', $sid)
->condition('cid', array(1,2,3,4,5,6,7,8),'IN');
$results = $sql->execute();
$post = NULL;
$url = urlencode('http://ulm.datamark.com/services/lead_submission&client_code=DAV4516&source_code=DAVNCU');
foreach($results as $result)
{
if ($result->cid == 1) {
$post .= "first_name=" . urlencode($result->data);
} else if ($result->cid == 2) {
$post .= "&last_name=" . urlencode($result->data);
} else if ($result->cid == 3) {
$post .= "&email=" . urlencode($result->data);
} else if ($result->cid == 4) {
$post .= "&phone=" . urlencode($result->data);
} else if ($result->cid == 5) {
$who = $result->data;
} else if ($result->cid == 6) {
$post .= "&phone2=" . urlencode($result->data);
} else if ($result->cid == 8) {
$post .= "&comments=" . urlencode($result->data);
}
}
dsm($who);
dsm($url.$post);
if ($who == "fs")
{
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => $url,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 4,
CURLOPT_POSTFIELDS => http_build_query($post)
);
$ch = curl_init();
curl_setopt_array($ch, ($defaults));
if( ! $result = curl_exec($ch))
{
echo "Something went wrong";
trigger_error(curl_error($ch));
}
curl_close($ch);
?>
My eyes see a couple issues:
Do not urlencode the URL itself. That function is for data you are passing in the Query portion of the url (the part after ?)
It looks like you are missing the ? in your url.
I think you have some logical issues in your assembly of the Post data. First, you are encoding all of $result->data for every post field. You likely want to include only one field at a time. Second, you are passing a string into http_build_query(), which expects either an array or an object. Perhaps you can refactor to use $post as an array, which might make it easier to debug. Read the docs for cURL and http_build_query to see what everything expects and does. For example, the cURL extension can do a lot of work for you if you pass an array into curl_setopt for CURLOPT_POSTFIELDS.

File Writing using PHP

I am working on a project in my college which is about developing an online autograder website like that of hackerrank for my college. Now, for compiling codes, I am using the API provided by sphere engines. The API is returning the output as a string which then I store it into a file. Then, I use a previously defined output file to compare this file and check accordingly whether the code is right or wrong. Now the problem is for eg. if output is like below:
Hello World
Hello World
Hello World
The string is written in the file as Hello WorldHello WorldHwllo World. I am using PHP to write text to file.
Is there any way to write the string as it is to a file?
Any other alternative method will also be appreciated.
Thank You.
EDIT
for eg if the code:
#include<iotsream>
using namespace std;
int main()
{
int i;
for(i=0;i<3;i++)
{
cout<<"Hello World\n";
}
return 0;
}
The output of this code should be
Hello World
Hello World
Hello World
And when i am displaying the string which is stored in a PHP array $data['output'], it is getting displayed normally but when i am writing this string to a file, It is getting stored in a single line. I want to store the string as it is i.e. in different lines.
Due to this, this file if not equal to the template output file which contains the string Hello World in different lines.
EDIT
This is the PHP code for the file which will take the source code and input and send it to the compiler and receive it's output accordingly.
<?php
error_reporting(0);
include_once '../connection-script.php';
session_start();
$user = 'xxxxx';
$pass = 'xxxxx';
$code = '';
$input = '';
$run = true;
$private = false;
$subStatus = array(
0 => 'Success',
1 => 'Compiled',
3 => 'Running',
11 => 'Compilation Error',
12 => 'Runtime Error',
13 => 'Timelimit exceeded',
15 => 'Success',
17 => 'memory limit exceeded',
19 => 'illegal system call',
20 => 'internal error'
);
$error = array(
'status' => 'error',
'output' => 'Something went wrong :('
);
//echo json_encode( array( 'hi', 1 ) ); exit;
//print_r( $_POST ); exit;
if ( isset( $_POST['process'] ) && $_POST['process'] == 1 ) {
$lang = isset( $_POST['lang'] ) ? intval( $_POST['lang'] ) : 1;
$input = trim( $_POST['input'] );
$code = trim( $_POST['source'] );
$answerfile=$_POST['answerfile'];
$outputfile=$_POST['outputfile'];
$client = new SoapClient( "http://ideone.com/api/1/service.wsdl" );
//create new submission
$result = $client->createSubmission( $user, $pass, $code, $lang, $input, $run, $private );
//if submission is OK, get the status
if ( $result['error'] == 'OK' ) {
$status = $client->getSubmissionStatus( $user, $pass, $result['link'] );
if ( $status['error'] == 'OK' ) {
//check if the status is 0, otherwise getSubmissionStatus again
while ( $status['status'] != 0 ) {
sleep( 3 ); //sleep 3 seconds
$status = $client->getSubmissionStatus( $user, $pass, $result['link'] );
}
//finally get the submission results
$details = $client->getSubmissionDetails( $user, $pass, $result['link'], true, true, true, true, true );
if ( $details['error'] == 'OK' ) {
//print_r( $details );
if ( $details['status'] < 0 ) {
$status = 'waiting for compilation';
} else {
$status = $subStatus[$details['status']];
}
$data = array(
'status' => 'success',
'meta' => "Status: $status | Memory: {$details['memory']} | Returned value: {$details['status']} | Time: {$details['time']}s",
'output' => htmlspecialchars( $details['output'] ),
'raw' => $details
);
if( $details['cmpinfo'] ) {
$data['cmpinfo'] = $details['cmpinfo'];
}
$myfile=fopen("output.txt","w");
fwrite($myfile, $data['output']);
fclose($myfile);
$qid=$_POST['questionid'];
$did=$_POST['domainid'];
if(sha1_file("output.txt") == sha1_file($outputfile))
{
$file=fopen($answerfile,"w");
fwrite($file,$code);
fclose($file);
$mail=$_SESSION['email'];
$query="SELECT * from student where semail='$mail'";
$result1=mysql_query($query);
$row1=mysql_fetch_array($result1);
$sid=$row1['studentid'];
$sql="SELECT * from practiceques where did='$did' and quesid='$qid'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$marks=$row['marks'];
$curdate=date("Y-m-d H:i:s");
$answer=mysql_query("INSERT INTO points VALUES ('$sid','$qid','$curdate',1,'$marks','$did')");
echo json_encode( $data );
}
else
{
$mail=$_SESSION['email'];
$query="SELECT * from student where semail='$mail'";
$result1=mysql_query($query);
$row1=mysql_fetch_array($result1);
$sid=$row1['studentid'];
$sql="SELECT * from practiceques where did='$did' and quesid='$qid'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
$marks=$row['marks'];
$curdate=date("Y-m-d H:i:s");
$answer=mysql_query("INSERT INTO points VALUES ('$sid','$qid','$curdate',0,0,'$did')");
echo json_encode($data);
}
}
else {
//we got some error :(
//print_r( $details );
echo json_encode( $error );
}
}
else {
//we got some error :(
//print_r( $status );
echo json_encode( $error );
}
} else {
//we got some error :(
//print_r( $result );
echo json_encode( $error );
}
}
?>
You can't write with C in php document.
Anyway, This is the php code for write in file.
<?php
$fp = fopen('file.name', 'a+');
fwrite($fp, 'Hello World'.PHP_EOL);
fclose($fp);
?>

Categories