Hide language WPML - php

I am using WPML language, and cant find solution for next thing:
On the Language switcher i want to hide language, lets say for example - "he", if current language is lets say for example "ar", so when we on arabic site we will not see on the selector the Hebrew, and same thing if we on Hebrew, the arabic will not display.
On shorten words: what i want is - if we on arabic site - the hebrew flag will be hidden.
What i tried:
function language_selector_flags(){
$languages = icl_get_languages('skip_missing=0');
if(!empty($languages)){
if(ICL_LANGUAGE_CODE=='en')
{
$order = array('ar'); //Specify your sort order here
}
elseif(ICL_LANGUAGE_CODE=='he')
{
$order = array('en', 'ar'); //Specify your sort order here
}
foreach ($order as $l) {
if (isset($languages[$l])) {
$l = $languages[$l]; //grab this language from the unsorted array that is returned by icl_get_languages()
//Display whatever way you want -- I'm just displaying flags in anchors (CSS: a {float:left; display:block;width:18px;height:12px;margin:0 2px;overflow:hidden;line-height:100px;})
if($l['active']) { $class = "active"; $url=""; } else { $class = ''; $url = 'href="'.$l['url'].'"'; }
echo '<a '.$url.' style="background:url('.$l['country_flag_url'].') no-repeat;" class="flag '.$class.'">';
echo $l['language_code'].'';
}
}
}
}
Its not affect at all the selector.

You can check out the plugin WPML Flag In Menu.
You could use the plugin_wpml_flag_in_menu() function from the plugin (see source code here) and replace:
// Exclude current viewing language
if( $l['language_code'] != ICL_LANGUAGE_CODE )
{
// ...
}
with
// Include only the current language
if( $l['language_code'] == ICL_LANGUAGE_CODE )
{
// ...
}
to show only the current language/flag, if I understand you correctly.
ps: If you need further assistance, you could for exampe show us the output of this debug function for the active language:
function debug_icl_active_language()
{
$languages = icl_get_languages( 'skip_missing=0' );
foreach( (array) $languages as $l )
{
if( $l['active'] )
{
printf( '<pre> Total languages: %d - Active: %s </pre>',
count( $languages ),
print_r( $l, TRUE ) );
}
}
}

i have some useful link for you, please go through it first:
http://wpml.org/forums/topic/hide-language-vs-display-hidden-languages-in-your-profile-not-working/
http://wpml.org/forums/topic/hide-one-language/
http://wpml.org/forums/topic/hiding-active-language-in-menu/
http://wpml.org/forums/topic/language-selector-how-to-hide-one-language/
thanks

function language_selector_flags(){
$languages = icl_get_languages('skip_missing=0');
if(!empty($languages)){
$filter = array();
$filter['ar'] = array( 'he' );
// set your other filters here
$active_language = null;
foreach ($languages as $l)
if($l['active']) {
$active_language = $l['language_code'];
break;
}
$filter = $active_language && isset( $filter[$active_language] ) ? $filter[$active_language] : array();
foreach ($languages as $l) {
//Display whatever way you want -- I'm just displaying flags in anchors (CSS: a {float:left; display:block;width:18px;height:12px;margin:0 2px;overflow:hidden;line-height:100px;})
if( in_array( $l['language_code'], $filter) )
continue;
if($l['active']) { $class = "active"; $url=""; } else { $class = ''; $url = 'href="'.$l['url'].'"'; }
echo '<a '.$url.' class="flag '.$class.'"><img src="', $l['country_flag_url'], '" alt="', esc_attr( $l['language_code'] ), '" /></a>';
}
}
}
EDIT: If I get this right, your client(I assume) doesn't want his customers (Israelis especiay) to know that he offer service also to the arabic speaking cusomers. If it so then you can parse the Accept-Language header and filter the language selector according the result.

I have a similar problem/issue:
On this website: https://neu.member-diving.com/
I have languages I not need in the switcher. I tried the code above, but it nothing changed so far.
So, what I would like to do is, When a client is on the one "german" page, the other german languages in the switcher should not need to be there, only the english one and the actual german one.
Where do I need to put code like
function language_selector_flags(){
$languages = icl_get_languages('skip_missing=0');
if(!empty($languages)){
$filter = array();
$filter['ar'] = array( 'he' );
// set your other filters here
$active_language = null;
foreach ($languages as $l)
if($l['active']) {
$active_language = $l['language_code'];
break;
}
$filter = $active_language && isset( $filter[$active_language] ) ? $filter[$active_language] : array();
foreach ($languages as $l) {
//Display whatever way you want -- I'm just displaying flags in anchors (CSS: a {float:left; display:block;width:18px;height:12px;margin:0 2px;overflow:hidden;line-height:100px;})
if( in_array( $l['language_code'], $filter) )
continue;
if($l['active']) { $class = "active"; $url=""; } else { $class = ''; $url = 'href="'.$l['url'].'"'; }
echo '<a '.$url.' class="flag '.$class.'"><img src="', $l['country_flag_url'], '" alt="', esc_attr( $l['language_code'] ), '" /></a>';
}
}
}

Related

Send all of a dropdown in Contact Form 7

I need to send a full array of custom field to a mail (dynamicaly populate) with contact Form 7 to work it here before sending :
// define the wpcf7_posted_data callback
function action_wpcf7_posted_data($array)
{
$a = get_field('date')
//WORK HERE
$array['Nom & Prénom'] = $array['name'];
unset($array['name']);
$array['E-mail'] = $array['email'];
unset($array['email']);
$array['Téléphone'] = $array['tel'];
unset($array['tel']);
$array['Profession'] = $array['job'];
unset($array['job']);
$array['Session'] = $array['upcoming-gigs'];
unset($array['upcoming-gigs']);
unset($array['privacy']);
return $array;
}
add_filter('wpcf7_posted_data', 'action_wpcf7_posted_data', 10, 1);
Because it's before sending a mail I can't call anything to compare before sending.
So I want to send all the data in a hidden input next to compare it.
This the two input in contact Form 7 :
[select upcoming-gigs data:gigs id:date] [hidden select upcoming-gigs2 data:gigs2]
My goal here is to send all the data of the hidden select.
I don't find a way to send all input in the mail.
Is it possible ? There is a better way ?
Thx
EDIT :
My question mark2 :
The goal is to send a mail with the date of the session and the id of it.
I use ACF and I have :
And after a dynamic dropdown, it's look like this for the user :
The problem is I don't have the id of the session, only the date.
To know the id I need to compar to the array of all the custom field, I can't import it during wpcf7_posted_data.
I think if I send all the data of the array in a hidden field, I could remake the array and find the id of the session my user choose.
I hope I'm clearer.
(I can't make a request in php during wpcf7_posted_data. Can I make an ajax request ?)
EDIT2 :
This my hidden select with session and text
This is the html of contact form 7 the rest is div for CSS
[select upcoming-date data:date id:date] [hidden select upcoming-date2 data:date2]
EDIT3 :
Okay get it.
The custom fields I use to make the dropdown are in two part id and text. I have the text part I need the id.
If I send every text and id in the mail I can compare to the answer of the user et add to the mail the right id.
Here the generated html : http://www.sharemycode.fr/5ax
EDIT 4 :
That where I write the id and text of the dropdown :
That where I create the select :
add_filter('wpcf7_form_tag_data_option', function ($n, $options, $args) {
$ses = (array)get_field('date_new');
$sesCount = count($ses);
$gigs = [];
$gigs2 = [];
if (in_array('gigs', $options)) {
for ($i = 0; $i < $sesCount; $i++) {
if ($ses[$i]['date_start'] > date('d-m-Y', time())) {
$a = "A réaliser entre le " . $ses[$i]['date_start'] . " et le " . $ses[$i]['date_end'] ." | bla";
array_push($gigs, $a);
}
}
return $gigs;
}
}
It looks like this is supported by Contact Form 7 natively, it's just not very obvious on how to make it happen.
Here's a documentation page explaining the functionality: http://contactform7.com/selectable-recipient-with-pipes/
Basically all you have to do is put the values like so:
Visible Value|actual-form-value
What comes before the pipe "|" character will be shown in the form, and what comes after will be the actual value filled in for the form.
EDIT kanarpp :
I add my code here to separate the answer of HowardE.
This is how I dynamicaly create my select :
add_filter('wpcf7_form_tag_data_option', function ($n, $options, $args) {
$ses = (array)get_field('date');
$sesCount = count($ses);
$date= [];
if (in_array('date', $options)) {
for ($i = 0; $i < $sesCount; $i++) {
if ($ses[$i]['date_start'] > date('d-m-Y', time())) {
$a = "A réaliser entre le " . $ses[$i]['date_start'] . " et le " . $ses[$i]['date_end'] ." | bla";
array_push($date, $a);
}
}
return $date;
}
It's not working, I use Smart Grid-Layout Design for Contact Form 7 to create dynmicaly my select
I would create a custom form tag for the select. The following code will create a custom form tag called [gigs] which would be used like this:
[gigs upcoming-gigs]
I've also included ability to add the * and make it required.
My assumptions are how you're actually getting the ACF fields, which I can't actually do, since I don't have them, and you haven't completely shared how it's stored. You would add this to your functions.php.
add_action('wpcf7_init', function (){
wpcf7_add_form_tag( array('gigs', 'gigs*'), 'dd_cf7_upcoming_gigs' , array('name-attr' => true) );
});
function dd_cf7_upcoming_gigs($tag) {
if ( empty( $tag->name ) ) {
return '';
}
$validation_error = wpcf7_get_validation_error( $tag->name );
$class = wpcf7_form_controls_class( $tag->type );
if ( $validation_error ) {
$class .= ' wpcf7-not-valid';
}
$atts = array();
$atts['class'] = $tag->get_class_option( $class );
$atts['id'] = $tag->get_id_option();
$atts['tabindex'] = $tag->get_option( 'tabindex', 'signed_int', true );
if ( $tag->is_required() ) {
$atts['aria-required'] = 'true';
}
if ( $validation_error ) {
$atts['aria-invalid'] = 'true';
$atts['aria-describedby'] = wpcf7_get_validation_error_reference(
$tag->name
);
} else {
$atts['aria-invalid'] = 'false';
}
// Make first option unselected and please choose
$html = '<option value="">- - '. __('Please Choose', 'text-domain'). ' - -</option>';
// This part you may have to update with your custom fields
$ses = (array)get_field('date_new');
$sesCount = count($ses);
for ($i = 0; $i < $sesCount; $i++) {
if ($ses[$i]['date_start'] > date('d-m-Y', time())) {
$a = "A réaliser entre le " . $ses[$i]['date_start'] . " et le " . $ses[$i]['date_end'];
// if session ID is in fact $ses[$i]['session']
$html .= sprintf( '<option %1$s>%2$s</option>',
$ses[$i]['session'], $a );
}
}
foreach ($gigs as $key => $value){
$html .= sprintf( '<option %1$s>%2$s</option>',
$key, $value );
}
$atts['name'] = $tag->name;
$atts = wpcf7_format_atts( $atts );
$html = sprintf(
'<span class="wpcf7-form-control-wrap %1$s"><select %2$s>%3$s</select>%4$s</span>',
sanitize_html_class( $tag->name ), $atts, $html, $validation_error
);
return $html;
}
add_filter( 'wpcf7_validate_gigs', 'dd_validate_gigs_filter', 10, 2 );
add_filter( 'wpcf7_validate_gigs*', 'dd_validate_gigs_filter', 10, 2 );
function dd_validate_gigs_filter( $result, $tag ) {
$name = $tag->name;
$has_value = isset( $_POST[$name] ) && '' !== $_POST[$name];
if ( $has_value and $tag->has_option( 'multiple' ) ) {
$vals = array_filter( (array) $_POST[$name], function( $val ) {
return '' !== $val;
} );
$has_value = ! empty( $vals );
}
if ( $tag->is_required() and ! $has_value ) {
$result->invalidate( $tag, wpcf7_get_message( 'invalid_required' ) );
}
return $result;
}

Set selected value on dynamic dropdown list

I have the below code, so the user can select the language he desire:
<label style="float: left; width: 50%;" for="system_language">Select Language:</label>
<select id="system_language" class="selectbox float-right" onChange="switchLanguageLogin(); ">
<? echo getLanguageList(); ?>
</select>
This is the function of the languages!
function loadLanguage($lng, $units = '')
{
global $ms, $la, $gsValues;
// always load main english language to prevet error if something is not translated in another language
include ($gsValues['PATH_ROOT'].'lng/english/lng_main.php');
// load another language
if ($lng != 'english')
{
$lng = $gsValues['PATH_ROOT'].'lng/'.$lng.'/lng_main.php';
if (file_exists($lng))
{
include($lng);
}
}
Added the Language Function
function getLanguageList()
{
global $ms, $gsValues;
$result = '';
$languages = array();
$q = "SELECT * FROM `gs_system` WHERE `key`='LANGUAGES'";
$r = mysqli_query($ms, $q);
$row = mysqli_fetch_array($r);
$languages = explode(",", $row['value']);
array_unshift($languages , 'english');
foreach ($languages as $value)
{
if ($value != '')
{
$result .= '<option value="'.$value.'">'.ucfirst($value).'</option>';
}
}
return $result;
}
The first (and default) option on the dropdown menu is English. The problem is that if I choose Spanish, it translates to Spanish, but on the dropdowm menu it leaves the default value which is English. This concludes that the page is in Spanish, but the value from the dropdown shows "English".
How can i solve this?
You do not use your $lng variable in the global scope, so it is not visible for your function. A solution would therefore be to provide the selected language as parameter to the getLanguageList function and set the equal value as selected:
function getLanguageList($selected = 'english') {
//...
foreach ($languages as $value) {
if ($value !== '') {
$result .= '<option value="'.$value.'" ' . ($selected === $value ? ' selected="selected"' : ''). '>' . ucfirst($value) . '</option>';
}
}
//...
}
Like this the selection is kept for the dropdown and therefore for the HTML.
In your view you would then need to provide $lng and call <? echo getLanguageList($lng); ?>.
Check in your init.php file should have a comment
// gets language from cookies
If there is not such comment, write it just before MySQL connection and add the following code after it
if (isset($_COOKIE['gs_language']))
{
$gsValues['LANGUAGE'] = $_COOKIE['gs_language'];
}
else
{
$expire = time() + 2592000;
setcookie('gs_language', $gsValues['LANGUAGE'], $expire, '/');
}
// puts selected language into cookies
if (isset($_GET['lng']))
{
$gsValues['LANGUAGE'] = $_GET['lng'];
$expire = time() + 2592000;
setcookie('gs_language', $gsValues['LANGUAGE'], $expire, '/');
}
Then go to fn_common.php file and change the getLanguageList function to
function getLanguageList()
{
global $ms, $gsValues;
$result = '';
$languages = array();
$q = "SELECT * FROM `gs_system` WHERE `key`='LANGUAGES'";
$r = mysqli_query($ms, $q);
$row = mysqli_fetch_array($r);
$languages = explode(",", $row['value']);
array_unshift($languages , 'english');
$currentLang = $gsValues['LANGUAGE'];
foreach ($languages as $value)
{
if ($value != '')
{
$result .= '<option value="'.$value.'" ' . ($currentLang === $value ? ' selected="selected"' : ''). '>' . ucfirst($value) . '</option>';
}
}
return $result;
}

joomla plugin replace tag by mysql query

I want write a plugin with replace //tag syntax need {loaddata mysite.com}
how to write a php plugin i think, this no hard but but im understaned php.
i found other sample plugin to helps maid it, but need modify it.
jimport( 'joomla.plugin.plugin' );
class plgSystemNiceUserInfoLite extends JPlugin {
var $u; var $guestname; var $rgx;
function plgSystemNiceUserInfoLite( &$subject, $params ){
parent::__construct( $subject, $params );
$this->guestname = $this->params->get( 'guestname', 'Guest' );
$this->rgx = '/{niceuserinfo}/'; // {loaddata mysite.com}
}
function onAfterRender(){ $app = JFactory::getApplication();
if( $app->isAdmin() || strpos($_SERVER["PHP_SELF"], "index.php") === false || JRequest::getCmd('task') == 'edit' || JRequest::getCmd('layout') == 'edit' ){return;}
$u = JFactory::getUser(); $c = JResponse::getBody(); $r = array();
preg_match_all($this->rgx, $c, $r, PREG_PATTERN_ORDER);
if(count($r[0]) > 0){
for ($i=0; $i < count($r[0]); $i++){$c = preg_replace($this->rgx, $this->bldUserInfo($u), $c, 1);}
JResponse::setBody($c);
}
return true;
}
function bldUserInfo($u){
if (isset($u->id)) {$ui = $u->id == 0 ? $this->guestname : $u->username;}else {$ui = $this->guestname;}
return $ui;
}
}
when plugin found tag {loaddata mysite.com} a will build sql query to load data for this site...

PHP: How to use the Twitter API's data to convert URLs, mentions, and hastags in tweets to links?

I'm really stumped on how Twitter expects users of its API to convert the plaintext tweets it sends to properly linked HTML.
Here's the deal: Twitter's JSON API sends this set of information back when you request the detailed data for a tweet:
{
"created_at":"Wed Jul 18 01:03:31 +0000 2012",
"id":225395341250412544,
"id_str":"225395341250412544",
"text":"This is a test tweet. #boring #nbc http://t.co/LUfDreY6 #skronk #crux http://t.co/VpuMlaDs #twitter",
"source":"web",
"truncated":false,
"in_reply_to_status_id":null,
"in_reply_to_status_id_str":null,
"in_reply_to_user_id":null,
"in_reply_to_user_id_str":null,
"in_reply_to_screen_name":null,
"user": <REDACTED>,
"geo":null,
"coordinates":null,
"place":null,
"contributors":null,
"retweet_count":0,
"entities":{
"hashtags":[
{
"text":"boring",
"indices":[22,29]
},
{
"text":"skronk",
"indices":[56,63]
}
],
"urls":[
{
"url":"http://t.co/LUfDreY6",
"expanded_url":"http://www.twitter.com",
"display_url":"twitter.com",
"indices":[35,55]
},
{
"url":"http://t.co/VpuMlaDs",
"expanded_url":"http://www.example.com",
"display_url":"example.com",
"indices":[70,90]
}
],
"user_mentions":[
{
"screen_name":"nbc",
"name":"NBC",
"id":26585095,
"id_str":"26585095",
"indices":[30,34]
},
{
"screen_name":"crux",
"name":"Z. D. Smith",
"id":407213,
"id_str":"407213",
"indices":[64,69]
},
{
"screen_name":"twitter",
"name":"Twitter",
"id":783214,
"id_str":"783214",
"indices":[91,99]
}
]
},
"favorited":false,
"retweeted":false,
"possibly_sensitive":false
}
The interesting parts, for this question, are the text element and the entries in the hashtags, user_mentions, and urls arrays. Twitter is telling us where in the text element the hastags, mentions, and urls appear with the indices arrays... so here's the crux of the question:
How do you use those indices arrays?
You can't just use them straight up by looping over each link element with something like substr_replace, since replacing the first link element in the text will invalidate all the index values for subsequent link elements. You also can't use substr_replace's array functionality, since it only works when you give it an array of strings for the first arg, rather than a single string (I've tested this. The results are... strange).
Is there some function that can simultaneously replace multiple index-delimited substrings in a single string with different replacement strings?
All you have to do to use the indices twitter provides straight up with a simple replace is collect the replacements you want to make and then sort them backwards. You can probably find a more clever way to build $entities, I wanted them optional anyway, so I KISS as far as that went.
Either way, my point here was just to show that you don't need to explode the string and character count and whatnot. Regardless of how you do it, all you need to to is start at the end and work to the beginning of the string, and the index twitter has is still valid.
<?php
function json_tweet_text_to_HTML($tweet, $links=true, $users=true, $hashtags=true)
{
$return = $tweet->text;
$entities = array();
if($links && is_array($tweet->entities->urls))
{
foreach($tweet->entities->urls as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='".$e->expanded_url."' target='_blank'>".$e->display_url."</a>";
$entities[] = $temp;
}
}
if($users && is_array($tweet->entities->user_mentions))
{
foreach($tweet->entities->user_mentions as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='https://twitter.com/".$e->screen_name."' target='_blank'>#".$e->screen_name."</a>";
$entities[] = $temp;
}
}
if($hashtags && is_array($tweet->entities->hashtags))
{
foreach($tweet->entities->hashtags as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='https://twitter.com/hashtag/".$e->text."?src=hash' target='_blank'>#".$e->text."</a>";
$entities[] = $temp;
}
}
usort($entities, function($a,$b){return($b["start"]-$a["start"]);});
foreach($entities as $item)
{
$return = substr_replace($return, $item["replacement"], $item["start"], $item["end"] - $item["start"]);
}
return($return);
}
?>
Ok so I needed to do exactly this and I solved it. Here is the function I wrote. https://gist.github.com/3337428
function parse_message( &$tweet ) {
if ( !empty($tweet['entities']) ) {
$replace_index = array();
$append = array();
$text = $tweet['text'];
foreach ($tweet['entities'] as $area => $items) {
$prefix = false;
$display = false;
switch ( $area ) {
case 'hashtags':
$find = 'text';
$prefix = '#';
$url = 'https://twitter.com/search/?src=hash&q=%23';
break;
case 'user_mentions':
$find = 'screen_name';
$prefix = '#';
$url = 'https://twitter.com/';
break;
case 'media':
$display = 'media_url_https';
$href = 'media_url_https';
$size = 'small';
break;
case 'urls':
$find = 'url';
$display = 'display_url';
$url = "expanded_url";
break;
default: break;
}
foreach ($items as $item) {
if ( $area == 'media' ) {
// We can display images at the end of the tweet but sizing needs to added all the way to the top.
// $append[$item->$display] = "<img src=\"{$item->$href}:$size\" />";
}else{
$msg = $display ? $prefix.$item->$display : $prefix.$item->$find;
$replace = $prefix.$item->$find;
$href = isset($item->$url) ? $item->$url : $url;
if (!(strpos($href, 'http') === 0)) $href = "http://".$href;
if ( $prefix ) $href .= $item->$find;
$with = "$msg";
$replace_index[$replace] = $with;
}
}
}
foreach ($replace_index as $replace => $with) $tweet['text'] = str_replace($replace,$with,$tweet['text']);
foreach ($append as $add) $tweet['text'] .= $add;
}
}
It's an edge case but the use of str_replace() in Styledev's answer could cause issues if one entity is contained within another. For example, "I'm a genius! #me #mensa" could become "I'm a genius! #me #mensa" if the shorter entity is substituted first.
This solution avoids that problem:
<?php
/**
* Hyperlinks hashtags, twitter names, and urls within the text of a tweet
*
* #param object $apiResponseTweetObject A json_decoded() one of these: https://dev.twitter.com/docs/platform-objects/tweets
* #return string The tweet's text with hyperlinks added
*/
function linkEntitiesWithinText($apiResponseTweetObject) {
// Convert tweet text to array of one-character strings
// $characters = str_split($apiResponseTweetObject->text);
$characters = preg_split('//u', $apiResponseTweetObject->text, null, PREG_SPLIT_NO_EMPTY);
// Insert starting and closing link tags at indices...
// ... for #user_mentions
foreach ($apiResponseTweetObject->entities->user_mentions as $entity) {
$link = "https://twitter.com/" . $entity->screen_name;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// ... for #hashtags
foreach ($apiResponseTweetObject->entities->hashtags as $entity) {
$link = "https://twitter.com/search?q=%23" . $entity->text;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// ... for http://urls
foreach ($apiResponseTweetObject->entities->urls as $entity) {
$link = $entity->expanded_url;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// ... for media
foreach ($apiResponseTweetObject->entities->media as $entity) {
$link = $entity->expanded_url;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// Convert array back to string
return implode('', $characters);
}
?>
Jeff's solution worked well with English text but it got broken when the tweet contained non-ASCII characters. This solution avoids that problem:
mb_internal_encoding("UTF-8");
// Return hyperlinked tweet text from json_decoded status object:
function MakeStatusLinks($status)
{$TextLength=mb_strlen($status['text']); // Number of UTF-8 characters in plain tweet.
for ($i=0;$i<$TextLength;$i++)
{$ch=mb_substr($status['text'],$i,1); if ($ch<>"\n") $ChAr[]=$ch; else $ChAr[]="\n<br/>"; // Keep new lines in HTML tweet.
}
if (isset($status['entities']['user_mentions']))
foreach ($status['entities']['user_mentions'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='https://twitter.com/".$entity['screen_name']."'>".$ChAr[$entity['indices'][0]];
$ChAr[$entity['indices'][1]-1].="</a>";
}
if (isset($status['entities']['hashtags']))
foreach ($status['entities']['hashtags'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='https://twitter.com/search?q=%23".$entity['text']."'>".$ChAr[$entity['indices'][0]];
$ChAr[$entity['indices'][1]-1] .= "</a>";
}
if (isset($status['entities']['urls']))
foreach ($status['entities']['urls'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='".$entity['expanded_url']."'>".$entity['display_url']."</a>";
for ($i=$entity['indices'][0]+1;$i<$entity['indices'][1];$i++) $ChAr[$i]='';
}
if (isset($status['entities']['media']))
foreach ($status['entities']['media'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='".$entity['expanded_url']."'>".$entity['display_url']."</a>";
for ($i=$entity['indices'][0]+1;$i<$entity['indices'][1];$i++) $ChAr[$i]='';
}
return implode('', $ChAr); // HTML tweet.
}
Here is an updated answer that works with Twitter's new Extended Mode. It combines the answer by #vita10gy and the comment by #Hugo (to make it utf8 compatible), with a few minor tweaks to work with the new api values.
function utf8_substr_replace($original, $replacement, $position, $length) {
$startString = mb_substr($original, 0, $position, "UTF-8");
$endString = mb_substr($original, $position + $length, mb_strlen($original), "UTF-8");
$out = $startString . $replacement . $endString;
return $out;
}
function json_tweet_text_to_HTML($tweet, $links=true, $users=true, $hashtags=true) {
// Media urls can show up on the end of the full_text tweet, but twitter doesn't index that url.
// The display_text_range indexes show the actual tweet text length.
// Cut the string off at the end to get rid of this unindexed url.
$return = mb_substr($tweet->full_text, $tweet->display_text_range[0],$tweet->display_text_range[1]);
$entities = array();
if($links && is_array($tweet->entities->urls))
{
foreach($tweet->entities->urls as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = " <a href='".$e->expanded_url."' target='_blank'>".$e->display_url."</a>";
$entities[] = $temp;
}
}
if($users && is_array($tweet->entities->user_mentions))
{
foreach($tweet->entities->user_mentions as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = " <a href='https://twitter.com/".$e->screen_name."' target='_blank'>#".$e->screen_name."</a>";
$entities[] = $temp;
}
}
if($hashtags && is_array($tweet->entities->hashtags))
{
foreach($tweet->entities->hashtags as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = " <a href='https://twitter.com/hashtag/".$e->text."?src=hash' target='_blank'>#".$e->text."</a>";
$entities[] = $temp;
}
}
usort($entities, function($a,$b){return($b["start"]-$a["start"]);});
foreach($entities as $item)
{
$return = utf8_substr_replace($return, $item["replacement"], $item["start"], $item["end"] - $item["start"]);
}
return($return);
}
Here is a JavaScript version (using jQuery) of vita10gy's solution
function tweetTextToHtml(tweet, links, users, hashtags) {
if (typeof(links)==='undefined') { links = true; }
if (typeof(users)==='undefined') { users = true; }
if (typeof(hashtags)==='undefined') { hashtags = true; }
var returnStr = tweet.text;
var entitiesArray = [];
if(links && tweet.entities.urls.length > 0) {
jQuery.each(tweet.entities.urls, function() {
var temp1 = {};
temp1.start = this.indices[0];
temp1.end = this.indices[1];
temp1.replacement = '' + this.display_url + '';
entitiesArray.push(temp1);
});
}
if(users && tweet.entities.user_mentions.length > 0) {
jQuery.each(tweet.entities.user_mentions, function() {
var temp2 = {};
temp2.start = this.indices[0];
temp2.end = this.indices[1];
temp2.replacement = '#' + this.screen_name + '';
entitiesArray.push(temp2);
});
}
if(hashtags && tweet.entities.hashtags.length > 0) {
jQuery.each(tweet.entities.hashtags, function() {
var temp3 = {};
temp3.start = this.indices[0];
temp3.end = this.indices[1];
temp3.replacement = '#' + this.text + '';
entitiesArray.push(temp3);
});
}
entitiesArray.sort(function(a, b) {return b.start - a.start;});
jQuery.each(entitiesArray, function() {
returnStr = substrReplace(returnStr, this.replacement, this.start, this.end - this.start);
});
return returnStr;
}
You can then use this function like so ...
for(var i in tweetsJsonObj) {
var tweet = tweetsJsonObj[i];
var htmlTweetText = tweetTextToHtml(tweet);
// Do something with the formatted tweet here ...
}
Regarding vita10gy's helpful json_tweet_text_to_HTML(), I found a tweet that it could not format correctly: 626125868247552000.
This tweet has a nonbreaking space in it. My solution was to replace the first line of the function with the following:
$return = str_replace("\xC2\xA0", ' ', $tweet->text);
Performing a str_replace() on is covered here.

How do I find out how many edits a user has for my MediaWiki extension?

I'm writing an extension that will allow me to add the magic words: CURRENTUSER, CURRENTUSERREALNAME, CURRENTUSERLANGABBR, CURRENTUSERGROUPS, and now I want to add CURRENTUSEREDITCOUNT and CURRENTUSEREDITCOUNTALL.
That section of my code is currently:
function wfGetCustomVariable(&$parser,&$cache,&$index,&$ret) {
switch ($index) {
case MAG_CURRENTUSER:
$parser->disableCache(); # Mark this content as uncacheable
$ret = $GLOBALS['wgUser']->getName();
break;
case MAG_CURRENTUSERREALNAME:
$parser->disableCache(); # Mark this content as uncacheable
$ret = $GLOBALS['wgUser']->getRealName();
break;
case MAG_CURRENTUSERLANGABBR
$parser->disableCache(); # Mark this content as uncacheable
$ret = $GLOBALS['wgLang']->getCode();
break;
case MAG_CURRENTUSERGROUPS
$parser->disableCache(); # Mark this content as uncacheable
$array = $GLOBALS['wgUser']->getEffectiveGroups();
$ret = implode(",", $array);
break;
}
return true;
}
However, I can't seem to find the $GLOBAL for the edit counts. I've done some research based on other extensions that use different edit counts for different reasons and have found:
For CURRENTUSEREDITCOUNT:
function wfContributionseditcount( $uid ) {
if ( $uid != 0 ) {
global $wgOut, $wgLang;
$wgOut->addWikiText( wfMsgExt( 'contributionseditcount', array( 'parsemag' ),
$wgLang->formatNum( User::edits( $uid ) ),
User::whoIs( $uid ) ) );
}
return true;
}
and for CURRENTUSEREDITCOUNTALL:
public function execute( $params ) {
global $wgOut, $wgUser;
$skin = $wgUser->getSkin();
$this->setHeaders();
$this->loadRequest( $params );
$wgOut->addHTML( $this->makeForm() );
if( $this->target ) {
if( User::isIP( $this->target ) ) {
$this->showResults( $this->countEditsReal( 0, $this->target ) );
} else {
$id = User::idFromName( $this->target );
if( $id ) {
$this->showResults( $this->countEditsReal( $id, false ), $id );
} else {
$wgOut->addHTML( '<p>' . wfMsgHtml( 'countedits-nosuchuser', htmlspecialchars( $this->target ) ) . '</p>' );
}
}
}
$this->showTopTen( $wgOut );
return true;
}
I have tried to learn PHP on my own in the past, and have struggled with it. I'm signed up for a PHP class at my local community college, but I do not start until Fall `12. Am I looking in the right place, or is there a simpler place to find the user's edit counts? Maybe as part of /trunk/phase3/includes/User.php someplace? I should mention this needs to run on a wiki running MW 1.17.1, so classUser would not work where-as it is MW 1.18+.
If what you want is to change the definition of edit count, perhaps you should directly change the code where it reduces the user's editcount after a page is deleted.

Categories