Enable a mediawiki function to render wikitext - mediawiki

My mediawiki version is 1.16.5. I have a function that selects a random quote from the database and displays it on a wiki page. Italics and bold are rendered when I use html, however, I want to be able to use wikitext, specifically external links format, i.e.
[http://mediawiki.org MediaWiki]
Currently, if using something like the above, it is not rendered and displays literally. There is some reference on what is needed here: http://www.mediawiki.org/wiki/Manual:Tag_extensions#How_do_I_render_wikitext_in_my_extension.3F but I do not know how to implement this.
Here is the code:
function wfGetQuote() {
$randstr = wfRandom();
$row = selectRandomQuoteFromDB( $randstr );
if( !$row )
$row = selectRandomQuoteFromDB( "0" );
if( $row ) {
list( $quote, $attribution ) = explode( "\n", $row->quote_text );
return '<div id="trrandomquote"><div id="trquote">'. $quote .'</div> <span>'. $attribution .'</span></div>';
}
else
return 'Error: No quote found';
}
function selectRandomQuoteFromDB( $randstr ) {
global $wgUser, $site;
$lang = $wgUser->getOption( 'language' );
if( $site == 'wiki' )
$lang = 'en';
$dbr = wfGetDB( DB_SLAVE );
$use_index = $dbr->useIndexClause( 'quote_random' );
$quote = $dbr->tableName( 'quote' );
$sql = "SELECT quote_text
FROM $quote $use_index
WHERE quote_random >= $randstr
AND quote_lang = '$lang'";
$sql = $dbr->limitResult( $sql, 1, 0 );
$fname = 'RandomQuote::selectRandomQuoteFromDB';
$res = $dbr->query( $sql, $fname );
return $dbr->fetchObject( $res );
}

Normally I use the $wgOut->addWikiText( $msg ); function.
I would modify your code to:
function wfGetQuote() {
global $wgOut; // Added line
$randstr = wfRandom();
$row = selectRandomQuoteFromDB( $randstr );
if( !$row )
$row = selectRandomQuoteFromDB( "0" );
if( $row ) {
list( $quote, $attribution ) = explode( "\n", $row->quote_text );
$wgOut->addWikiText( '<div id="trrandomquote"><div id="trquote">'. $quote .'</div> <span>'. $attribution .'</span></div>' );
}
else
return 'Error: No quote found';
}
I haven't tested it, but it may do the job you're looking for.

Related

Custom WordPress New User E-Mail from Template

From a custom function to register users, I inserted this function to generate and overwrite the WordPress system email for new user notification.
function custom_wp_new_user_notification_email( $wp_new_user_notification_email, $user, $blogname ) {
global $wpcargo;
$user_url = stripslashes( $user->user_url );
$user_login = stripslashes( $user->user_login );
$user_email = stripslashes( $user->user_email );
$user_firstname = stripslashes( $user->user_firstname );
$user_last_name = stripslashes( $user->user_last_name );
$user_pass = stripslashes( $user->user_pass );
$message = file_get_contents('../email/mail-template.php');
$wp_new_user_notification_email['subject'] = sprintf( '[%s] Welcome.', $blogname );
$wp_new_user_notification_email['headers'] = array('Content-Type: text/html; charset=UTF-8');
$wp_new_user_notification_email['message'] = $message;
return $wp_new_user_notification_email;
}
add_filter( 'wp_new_user_notification_email', 'custom_wp_new_user_notification_email', 10, 3 );
Emails are being sent but I cannot get user data printed in the PHP / HTML file.
<p style="margin-top:0;margin-bottom:12px;"><b>Name</b>: <?php $user_firstname; ?></p>
I'm wrong with the code, any suggestions?
I would use locate_template for the email contents and output buffering rather than file_get_contents - also as #Zak pointed out, you have to echo your output otherwise it won't show up.
function custom_wp_new_user_notification_email( $wp_new_user_notification_email, $user, $blogname ) {
global $wpcargo;
$user_url = stripslashes( $user->user_url );
$user_login = stripslashes( $user->user_login );
$user_email = stripslashes( $user->user_email );
$user_firstname = stripslashes( $user->user_firstname );
$user_last_name = stripslashes( $user->user_last_name );
$user_pass = stripslashes( $user->user_pass );
ob_start();
include( locate_template( '/email/mail-template.php' ); // This path may vary depending on your setup.
$wp_new_user_notification_email['message'] = ob_get_clean();
$wp_new_user_notification_email['subject'] = sprintf( '[%s] Welcome.', $blogname );
$wp_new_user_notification_email['headers'] = array('Content-Type: text/html; charset=UTF-8');
return $wp_new_user_notification_email;
}
add_filter( 'wp_new_user_notification_email', 'custom_wp_new_user_notification_email', 10, 3 );
Within your template you want to make sure you echo and esc_html() for anything that is being outputted.
<?php echo esc_html( $user_firstname ); ?>

gravity forms validate field entry values against mysql table value

Basically, I have a table with 8 million codes for promotion. The contestant will enter the code on a gravity form, which will then query the database for code, once it is there the code will be marked as used, and the contestant should be redirected to the entry form. If not the form should tell the user code is invalid. This is my code below which I pulled from other sources because I am not a coder. However, when I submit, the correct code, it says incorrect. Any help will be appreciated just bear in mind I am not a programmer
add_filter( 'gform_field_validation_4', 'validate_code' );
function validate_code($validation_result){
$form = $validation_result['form'];
foreach( $form['fields'] as &$field ) {
if ( strpos( $field->cssClass, 'validate-code' ) === false ) {
continue;
}
}
$field_value = rgpost( "input_1" );
$is_valid = is_code( $field_value );
$validation_result['is_valid'] = false;
$field->failed_validation = true;
$field->validation_message = 'The code you have entered is not valid. Please enter another.';
$validation_result['form'] = $form;
return $validation_result;
}
function is_code($code){
$info = 'mysql response';
require_once(ABSPATH . '/wp-config.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
echo 'Unable to connect to server, please use the back button in your browser and resubmit the form';
exit();
}
$code = mysqli_real_escape_string($conn, $_POST['codes']);
$sql_check = mysqli_query($conn, "SELECT * FROM entrycode WHERE codes = '$code' AND valid = 0");
$sql_checkrows = mysqli_num_rows($sql_check);
if ($sql_checkrows > 0) {
$sql_update = "UPDATE entrycode SET used = 1 WHERE codes ='$code'";
if (mysqli_query($conn, $sql_update)) {
$info = mysqli_affected_rows($conn) . " Row updated.\n";
$info = 'success';
return true;
} else {
return false;
}
mysql_close($conn);
}
}
add_filter('gform_confirmation_4', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$success_url = 'https://sample.com/enter' . '/?code=' . $lead[1];
$confirmation = array('redirect' => $success_url);
return $confirmation;
}
so I modified the code from Phill, I am no longer getting the error, but the code is not being validated, as a matter of fact, any code I type in is valid., I am at a lost. My table is structured like this
entry codes table
ID
Codes
Used
34
98j65XF16
O
add_filter('gform_validation_4_1', 'validate_code');
function validate_code($validation_result){
// this assumes the code is entered in field one on your form
// change this input_ number if it's a different field
if($is_code_valid($_POST['input_1'])){
$validation_result['is_valid'] = false;
foreach($validation_result['form']['fields'] as &$field){
// field 1 is the field where we want to show the validation message
if($field['id'] == 1){
$field['failed_validation'] = true;
$field['validation_message'] = 'The code you entered is invalid: please try again.';
break;
}
}
}
return $validation_result;
}
// use this function to validate codes
function is_code_valid($thiscode){
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( $matched_codes > 0) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
// doing this here because the redirect URL does not support variables or shortcodes
// change the 70 here to your form ID
add_filter('gform_confirmation_4', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$success_url = 'https://demo.com/enter' . '/?code=' . $lead[1];
$confirmation = array('redirect' => $success_url);
return $confirmation;
}
Updated function to validate codes:
function is_code_valid($thiscode){
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( !empty ( $matched_codes ) ) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
this code i have still is not checking the database with codes for validation ,, all codes returning invalid code message
add_filter('gform_validation_2', 'validate_code');
GFCommon::log_debug( __METHOD__ . '(): The POST => ' . print_r( $_POST, true ) );
function validate_code($validation_result){
// this assumes the code is entered in field one on your form
// change this input_ number if it's a different field
if(!is_code_valid($_POST['input_1'])){
$validation_result['is_valid'] = false;
foreach($validation_result['form']['fields'] as &$field){
// field 1 is the field where we want to show the validation message
if($field['id'] == 1){
$field['failed_validation'] = true;
$field['validation_message'] = 'The code you entered is invalid: please try again.';
break;
}
}
}
return $validation_result;
}
function is_code_valid($thiscode){
GFCommon::log_debug( __METHOD__ . '(): The POST => ' . print_r( $_POST, true ) );
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( !empty ( $matched_codes ) ) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
// doing this here because the redirect URL does not support variables or shortcodes
// change the 70 here to your form ID
add_filter('gform_confirmation_2', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$country = ($_POST['input_3']);
$success_url = 'https://sample.com/enter' . '/?code=' .$lead[1] .'&country=' .$country;
$confirmation = array('redirect' => $success_url);
return $confirmation;
}

How to make a json from youtube api v3 with a wp_cron

I'm doing a cron job in wordpress and it only worked once, it sent me an email but it never created the json file.
I want to save in a json file data from youtube api v3 in order not make petitions each time because youtube limit the petitions so I thought it will be convenient make a cache job with wp cron but this code is not working. I not sure where is the problem.
function isa_add_every_three_minutes( $schedules ) {
$schedules['every_three_minutes'] = array(
'interval' => 180,
'display' => __( 'Every 3 Minutes', 'textdomain' )
);
return $schedules;
}
add_filter( 'cron_schedules', 'isa_add_every_three_minutes' );
if ( !wp_next_scheduled('hook_saveVideos') ) {
wp_schedule_event( time(), 'every_three_minutes', 'hook_saveVideos' );
}
function saveVideos() {
$channel_id = "channelExample";
$user_id = "example";
$url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=30&playlistId=".$cv_id."&key=".$user_id;
$data = file_get_contents($url);
$videos = json_decode($data, true);
$videos = $videos['items'];
$dVideos = array();
for ($i=0; $i < count($videos) ; $i++) {
$title = $videos[$i]['snippet']['title'];
$description = $videos[$i]['snippet']['description'];
$videoId = $videos[$i]['snippet']['resourceId']['videoId'];
$id = "v".$i;
$dVideos[$id] = array("title"=>$title, "description"=>$description, "videoId"=>$videoId);
}
$ruta = "http://localhost/example/cache";
$fp = fopen($ruta, 'w');
fwrite($fp, json_encode($dVideos ));
fclose($fp);
wp_mail('user#example.com', 'Mail mandado por el cron', 'Hola, esto es un correo enviado automáticamente');
}

How to fetch single row/data from Mysql_fetch_array?

I am reading .csv file through PHP using fgetcsv(). Now I am able to fetch I mean read data from .csv file.
Then I need to check SKU column with my fetch result & accordingly have to perform either Insertion Or Updation.
Suppose SKU is already present there, then I have to update my row in table else I need to insert new record.
I have write following code...Plz check n tell me where I am doing mistake-:
<?php
$row = 1;
if (($handle = fopen("localhost/data/htdocs/magento/var/import/Price.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 8000, ",")) !== FALSE)
{
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
for ($c=0; $c < $num; $c++)
{
$temp = $data;
$string = implode(";", $temp);
}
$pieces = explode(";", $string);
$col1 = $pieces[0];
$col2 = $pieces[1];
$col3 = $pieces[2];
$col4 = $pieces[3];
$db_name = "magento";
$con = mysql_connect("localhost", "magento", "password");
If (!$con)
{
die('Could not connect: ' . mysql_error());
mysql_close($con);
}
$seldb = mysql_select_db($db_name, $con);
$query_fetch = "SELECT `sku` from `imoprt_prices`";
$result_fetch = mysql_query($query_fetch);
$num_rows = mysql_num_rows($result_fetch);
for($i = 0; $i < $num_rows; $i++)
{
$value = mysql_result($result_fetch, i, 'sku');
if(strcmp('".$value."', '".$col2."') == 0)
{
$flag = 1;
break;
}
else
{
$flag = 0;
break;
}
}
if($flag == 1)
{
$query_upadte = "(UPDATE imoprt_prices SET customer_id= '".$col1."', sku ='".$col2."', price= '".$col3."', website= '".$col4."'
)";
mysql_query($query_upadte);
$row++;
}
if($flag == 0)
{
mysql_query("INSERT INTO `imoprt_prices`(`customer_id`,`sku`,`price`,`website`) VALUES('".$col1."','".$col2."','".$col3."','".$col4."')");
$row++;
}
}
}
?>
If you have an actual UNIQUE index on your imoprt_prices table, you can use the ON DUPLICATE KEY UPDATE syntax and simplify your code a bit to something similar to; (note, can't test, so see as pseudo code)
$db_name = "magento";
$con = mysql_connect("localhost", "magento", "password") or die(mysql_error());
$seldb = mysql_select_db($db_name, $con);
if (($handle = fopen("localhost/data/htdocs/magento/var/import/Price.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 8000, ",")) !== FALSE)
{
$col1 = $pieces[0];
$col2 = $pieces[1];
$col3 = $pieces[2];
$col4 = $pieces[3];
$query_upadte = "INSERT INTO imoprt_prices (customer_id, sku, price, website) ".
"VALUES('".$col1."','".$col2."','".$col3."','".$col4."') ".
"ON DUPLICATE KEY UPDATE customer_id='".$col1."', price='".$col3.
"',website='".$col4."'";
mysql_query($query_upadte);
}
}
You may also want to either mysql_real_escape_string() or use parameterized queries to make sure there's no ' in your inserted values though. That is always a danger with building sql strings like this.
Simple demo here.
In the following snippet:
$query_upadte = "UPDATE imoprt_prices SET customer_id= '".$col1."', sku ='".$col2."', price= '".$col3."', website= '".$col4."'";
You're trying to update all the rows repeatedly, instead of just updating a single row. This is normally not allowed in MySQL. You need to specify a particular unique ID to be updated.

Truncate a HTML formatted text with SMARTY

I've got a variable which is formatted with random HTML code. I call it to {$text} and i truncate it.
The value is for example:
<div>Lorem <i>ipsum <b>dolor <span>sit </span>amet</b>, con</i> elit.</div>
If i truncate the text's first ~30 letters, I'll get this:
<div>Lorem <i>ipsum <b>dolor <span>sit
The problem is, I can't close the elements. So, I need a script, which check the <*> elements in the code (where * could be anything), and if it dont have a close tag, close 'em.
Please help me in this. Thanks.
Solution after hours, and 4 vote-up # stackoverflow:
PHP:
...
function closetags($content) {
preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $content, $result);
$openedtags = $result[1];
preg_match_all('#</([a-z]+)>#iU', $content, $result);
$closedtags = $result[1];
$len_opened = count($openedtags);
if (count($closedtags) == $len_opened) {
return $content;
}
$openedtags = array_reverse($openedtags);
for ($i=0; $i < $len_opened; $i++) {
if (!in_array($openedtags[$i], $closedtags)) {
$content .= '</'.$openedtags[$i].'>';
} else {
unset($closedtags[array_search($openedtags[$i], $closedtags)]);
}
}
return $content;
}
...
the TPL:
{$pages[j].text|truncate:300|#closetags}
Pull out all the open tags, push them into an array (array_1) one-by-one.
Pull out all of the closed tags, push them into an array (array_2) one-by-on (this includes self closing tags).
For the tags in the first array (array_1) that are not found in the second array (array_2), add them to the html.
[edit]
Of course, this method fails miserably if you do not write proper html... but whatchagonnado?
Another way would be to look ahead in the string to see which tags are closed and close them as needed.
To simplify, if the code is valid XML before truncating and you don't cut off tags in half, the algorithm would be something like this:
Push opening tags onto a stack
Pop them off when you find the closing tag (which will match if the code is valid)
When you get to the end, start popping to create closing. The remaining tags should be appended to the original (truncated) text.
Example:
<div>Lorem <i>ipsum <b>dolor <span>sit </span>amet</b><div>
Push "div","i","b","span"
Found closing tag "span"
Pop "span"
Found closing tag "b"
Pop "b"
Push "div"
End of truncated text
Pop "div" --> add </div> to text
Pop "b" --> add </b> to text
Pop "i" --> add </i> to text
Pop "div" --> add </div> to text
End
for other people like me and you I found this code ,I think is a better solution
add this file named "modifier.html_substr.php"
<?php
/*
* Smarty plugin
*
-------------------------------------------------------------
* File: modifier.html_substr.php
* Type: modifier
* Name: html_substr
* Version: 1.0
* Date: June 19th, 2003
* Purpose: Cut a string preserving any tag nesting and matching.
* Install: Drop into the plugin directory.
* Author: Original Javascript Code: Benjamin Lupu <hide#address.com>
* Translation to PHP & Smarty: Edward Dale <hide#address.com>
* Modification to add a string: Sebastian Kuhlmann <hide#address.com>
* Modification to put the added string before closing <p> or <li> tags by Peter Carter http://www.podhawk.com
-------------------------------------------------------------
*/
function smarty_modifier_html_substr($string, $length, $addstring="")
{
//some nice italics for the add-string
if (!empty($addstring)) $addstring = "<i> " . $addstring . "</i>";
if (strlen($string) > $length) {
if( !empty( $string ) && $length>0 ) {
$isText = true;
$ret = "";
$i = 0;
$currentChar = "";
$lastSpacePosition = -1;
$lastChar = "";
$tagsArray = array();
$currentTag = "";
$tagLevel = 0;
$addstringAdded = false;
$noTagLength = strlen( strip_tags( $string ) );
// Parser loop
for( $j=0; $j<strlen( $string ); $j++ ) {
$currentChar = substr( $string, $j, 1 );
$ret .= $currentChar;
// Lesser than event
if( $currentChar == "<") $isText = false;
// Character handler
if( $isText ) {
// Memorize last space position
if( $currentChar == " " ) { $lastSpacePosition = $j; }
else { $lastChar = $currentChar; }
$i++;
} else {
$currentTag .= $currentChar;
}
// Greater than event
if( $currentChar == ">" ) {
$isText = true;
// Opening tag handler
if( ( strpos( $currentTag, "<" ) !== FALSE ) &&
( strpos( $currentTag, "/>" ) === FALSE ) &&
( strpos( $currentTag, "</") === FALSE ) ) {
// Tag has attribute(s)
if( strpos( $currentTag, " " ) !== FALSE ) {
$currentTag = substr( $currentTag, 1, strpos( $currentTag, " " ) - 1 );
} else {
// Tag doesn't have attribute(s)
$currentTag = substr( $currentTag, 1, -1 );
}
array_push( $tagsArray, $currentTag );
} else if( strpos( $currentTag, "</" ) !== FALSE ) {
array_pop( $tagsArray );
}
$currentTag = "";
}
if( $i >= $length) {
break;
}
}
// Cut HTML string at last space position
if( $length < $noTagLength ) {
if( $lastSpacePosition != -1 ) {
$ret = substr( $string, 0, $lastSpacePosition );
} else {
$ret = substr( $string, $j );
}
}
// Close broken XHTML elements
while( sizeof( $tagsArray ) != 0 ) {
$aTag = array_pop( $tagsArray );
// if a <p> or <li> tag needs to be closed, put the add-string in first
if (($aTag == "p" || $aTag == "li") && strlen($string) > $length) {
$ret .= $addstring;
$addstringAdded = true;
}
$ret .= "</" . $aTag . ">\n";
}
} else {
$ret = "";
}
// if we have not added the add-string already
if ( strlen($string) > $length && $addstringAdded == false) {
return( $ret.$addstring );
}
else {
return ( $ret );
}
}
else {
return ( $string );
}
}
?>
usage
{$yourdata|html_substr:300:' ...'}