Add substr max length to my function - php

Below is a code snippet from the file I am working with. I will start by saying I have attempted to find out on my own many times with failure, I am not a coder but I wish I knew more. I need some help figuring out how to add a substr length to the string $forum
This function outputs the latest 5 forum topics. The problem I'm having is the topic titles are to long for where the widget is being placed, so I wanted to truncate it to max 35 characters displayed. Can you help me? I know I'm a newb!
function sf_recent_posts_tag($limit=5, $forum=false, $user=true, $postdate=false, $listtags=true, $forumids=0, $posttime=false, $avatar=false, $size=25)
{
global $wpdb, $current_user, $sfvars;
$limit = sf_esc_int($limit);
if (empty($limit)) return;
sf_initialise_globals($sfvars['forumid']);
$out = '';
$forum_ids = '';
# are we passing forum ID's?
if ($forumids != 0)
{
$flist = explode(",", $forumids);
foreach($flist as $thisforum)
{
if (sf_can_view_forum($thisforum))
{
$forum_ids[] = $thisforum;
}
}
} else {
# limit to viewable forums based on permissions
if($current_user->forumadmin == false)
{
$allforums = sf_get_forum_memberships($current_user->ID);
if ($allforums)
{
foreach ($allforums as $thisforum)
{
if (sf_can_view_forum($thisforum->forum_id))
{
$forum_ids[] = $thisforum->forum_id;
}
}
} else {
return '';
}
}
}
# get out if nothing to see
if($current_user->forumadmin == false && empty($forum_ids)) return '';
# create where clause based on forums that current user can view
if ($forum_ids != '')
{
$where = ' AND '.SFPOSTS.".forum_id IN (" . implode(",", $forum_ids) . ") = 1 ";
} else {
$where = '';
}
$sfposts = $wpdb->get_results("SELECT DISTINCT topic_id
FROM ".SFPOSTS."
WHERE post_status = 0 ".$where."
ORDER BY post_id DESC
LIMIT ".$limit);
if($sfposts)
{
foreach($sfposts as $sfpost)
{
$postdetails = sf_get_last_post_in_topic($sfpost->topic_id);
$thisforum = sf_get_forum_record($postdetails->forum_id);
$p=false;
# Start contruction
if($listtags) $out.="<li class='sftagli'>\n";
if ($avatar)
{
if ($postdetails->user_id)
{
$icon = 'user';
if (sf_is_forum_admin($postdetails->user_id)) $icon='admin';
} else {
$icon = 'guest';
}
$out.= sf_render_avatar($icon, $postdetails->user_id, sf_filter_email_display($postdetails->user_email), sf_filter_email_display($postdetails->guestemail), false, $size);
}
$out.= sf_get_topic_url_newpost($thisforum->forum_slug, $sfpost->topic_id, $postdetails->post_id, $postdetails->post_index);
if($forum)
{
if ($p == false) $out.="<p class='sftagp'>";
$out.= __("posted in forum", "sforum").' '.sf_filter_title_display($thisforum->forum_name)." "."\n";
$p=true;
}
if($user)
{
if($p == false) $out.="<p class='sftagp'>";
$poster = sf_build_name_display($postdetails->user_id, sf_filter_name_display($postdetails->display_name));
if(empty($poster)) $poster = sf_filter_name_display($postdetails->guest_name);
$out.=__("by", "sforum").' '.$poster.' '."\n";
$p=true;
}
if($postdate)
{
if($p == false) $out.="<p class='sftagp'>";
$out.=__("on", "sforum").' '.sf_date('d', $postdetails->post_date)."\n";
if ($posttime)
{
$out.=' '.__("at", "sforum").' '.sf_date('t', $postdetails->post_date)."\n";
}
$p=true;
}
if($p) $out.="</p>\n";
if($listtags) $out.="</li>\n";
}
} else {
if($listtags) $out.="<li class='sftagli'>\n";
$out.='<p>'.__("No Topics to Display", "sforum").'</p>'."\n";
if($listtags) $out.="</li>\n";
}
echo($out);
return;
}

I can't find where you get the post titles in your code, but to truncate a string to 35 chars you simply need something like $truncated = substr($title, 0, 35)
You may find it helpful to append '...' to the truncated titles:
$truncated = substr($title, 0, 35).'...';
EDIT:
without seeing a lot of code that you have omitted it's hard to say, but I suspect it's a matter of changing
$out.= sf_get_topic_url_newpost($thisforum->forum_slug, $sfpost->topic_id, $postdetails->post_id, $postdetails->post_index);
to
$out.= substr(sf_get_topic_url_newpost($thisforum->forum_slug, $sfpost->topic_id, $postdetails->post_id, $postdetails->post_index), 0, 35).'...';

Related

Wordpress - Customizing Breadcrumbs NavXT

Right now my breadcrumbs are showing up like Home > Services > X-Ray, but I would like them to just show up like Home > Services, is there a way to customize Breadcrumbs NavXT to do this this?
go in /wp-content/plugins/breadcrumb-navxt/class.bcn_breadcrumb_trail.php
find function display and replace it with:
public function display($return = false, $linked = true, $reverse = false)
{
//Set trail order based on reverse flag
$this->order($reverse);
//Initilize the string which will hold the assembled trail
$trail_str = '';
$position = 1;
//The main compiling loop
foreach($this->breadcrumbs as $key => $breadcrumb)
{
//We do different things for the separator based on the breadcrumb order
if($reverse)
{
//Add in the separator only if we are the 2nd or greater element
if($key > 0)
{
$trail_str .= $this->opt['hseparator'];
}
}
else
{
if($key == 0 ) continue;
//Only show the separator when necessary
if($key < count($this->breadcrumbs) - 1)
{
$trail_str .= $this->opt['hseparator'];
}
}
//Trim titles, if needed
if($this->opt['blimit_title'] && $this->opt['amax_title_length'] > 0)
{
//Trim the breadcrumb's title
$breadcrumb->title_trim($this->opt['amax_title_length']);
}
//Place in the breadcrumb's assembled elements
$trail_str .= $breadcrumb->assemble($linked, $position);
$position++;
}
//Should we return or echo the assembled trail?
if($return)
{
return $trail_str;
}
else
{
//Helps track issues, please don't remove it
$credits = "<!-- Breadcrumb NavXT " . $this::version . " -->\n";
echo $credits . $trail_str;
}
}
if you use a different version i have add this row:
if($key == 0 ) continue;

Joomla, php GET and redirecting

I have joomla 2.5 site, and I have
http://www.something.com/places?x=target
I would like to have URL like this:
http://www.something.com/places/target
How can I do this?
EDIT:
on .htaccess following works:
RewriteRule ^places/(.*)$ http://www.something.com/places?x=$1 [L,P,nc]
However it does not work with spaces ('/places/tar get' will only go to '/places?x=tar'). How can I fix that?
EDIT 2:
RewriteRule ^places/([^\ ])\ (.)$ http://www.something.com/places?x=$1\%20$2 [L,P,nc]
RewriteRule ^places/(.*)$ http://www.something.com/places?x=$1 [L,P,nc]
doest the trick. Thank you all!
If the places page belongs to a custom component (not a Joomla! built-in component), you will need to write or adjust the router.php file, in the component's directory.
It will need to contain something like:
function yourcomponentnameBuildRoute(&$query) {
$segments = array();
if (isset($query["x"])) {
$segments[] = $query["x"];
unset($query["x"]);
}
return $segments;
}
function yourcomponentnameParseRoute($segments) {
$vars = array();
$count = count($segments);
switch($segments[0]) {
case "target":
$vars["x"] = "target";
break;
}
return $vars;
}
UPDATE for your specific case:
Unfortunately there is no way to do this without a core hack.
So backup your *components/com_content/router.php* file, and then edit it as follows:
Replace the following code (around line 132):
if ($view == 'article') {
if ($advanced) {
list($tmp, $id) = explode(':', $query['id'], 2);
}
else {
$id = $query['id'];
}
$segments[] = $id;
}
unset($query['id']);
unset($query['catid']);
with this:
if ($view == 'article') {
if ($advanced) {
list($tmp, $id) = explode(':', $query['id'], 2);
}
else {
$id = $query['id'];
}
if(isset($query['x']) && $query['x']) {
$segments[] = $query['x'];
}
$segments[] = $id;
}
unset($query['x']);
unset($query['id']);
unset($query['catid']);
and this code (around line 212):
if (!isset($item)) {
$vars['view'] = $segments[0];
$vars['id'] = $segments[$count - 1];
return $vars;
}
// if there is only one segment, then it points to either an article or a category
// we test it first to see if it is a category. If the id and alias match a category
// then we assume it is a category. If they don't we assume it is an article
if ($count == 1) {
// we check to see if an alias is given. If not, we assume it is an article
if (strpos($segments[0], ':') === false) {
$vars['view'] = 'article';
$vars['id'] = (int)$segments[0];
return $vars;
}
with this:
if (!isset($item)) {
$vars['view'] = $segments[0];
$vars['id'] = $segments[$count - 1];
$vars['x'] = $count >= 2 ? $segments[$count - 2] : NULL;
return $vars;
}
// if there is only one segment, then it points to either an article or a category
// we test it first to see if it is a category. If the id and alias match a category
// then we assume it is a category. If they don't we assume it is an article
if ($count == 1 || ($count == 2 && (int) $segments[0] === 0)) {
// we check to see if an alias is given. If not, we assume it is an article
if (strpos($segments[0], ':') === false) {
$vars['view'] = 'article';
$vars['x'] = $count == 2 ? $segments[$count - 2] : NULL;
$vars['id'] = (int)$segments[$count - 1];
return $vars;
}
Then in your article's PHP code, you would use:
$target = JRequest::getVar("x");
I haven't tested it, so I'm not sure if it works. Let me know.

Making code more efficient and less a copy and paste

I've been working on a piece of code that that pulls the name of a guild and with it the information of boss/monsters said guild has killed in an online game. There are many many monsters in this game and every one has three difficulty settings. I have managed to get the code to do what i want however it has an enormous amount of copy and paste and ive only done about 1/5 of the total amount of enteries. I really cant think how to make this code less of a giant bloat. This is the code for just one monster for the 3 difficulty settings as you can see it's alot just for one. there are probably another 60 of these!. Can anybody help me understand better ways to do this. Thanks!
$sql = 'SELECT * FROM `phpbb_profile_fields_data`';
$result = $db->sql_query($sql);
while ($row = $db->sql_fetchrow($result))
{
/////////////////////////////////// START - 8 MAN BONETHRASHER
$normal = '';
$hard = '';
$nightmare = '';
/////// START - CHECK NORMAL
if ($row['pf_kp_em_no_bonethr'] == '1')
{
$normal = ' <img src="/styles/subsilver2/theme/images/soap/no.png" />';
}
else if ($row['pf_kp_em_no_bonethr'] == '2')
{
$normal = '';
}
else if (is_null($row['pf_kp_em_no_bonethr']))
{
echo "Boss was set as NULL This should not happen!";
}
else
{
echo "Sosia messed up go hit him in the face.";
}
/////// END - CHECK NORMAL
/////// START - CHECK HARD
if ($row['pf_kp_em_ha_bonethr'] == '1')
{
$hard = ' <img src="/styles/subsilver2/theme/images/soap/ha.png" />';
}
else if ($row['pf_kp_em_ha_bonethr'] == '2')
{
$hard = '';
}
else if (is_null($row['pf_kp_em_ha_bonethr']))
{
echo "Boss was set as NULL This should not happen!";
}
else
{
echo "Sosia messed up go hit him in the face.";
}
/////// END - CHECK HARD
/////// START - CHECK NIGHTMARE
if ($row['pf_kp_em_kn_bonethr'] == '1')
{
$nightmare =' <img src="/styles/subsilver2/theme/images/soap/kn.png" />';
}
else if ($row['pf_kp_em_kn_bonethr'] == '2')
{
$nightmare = '';
}
else if (is_null($row['pf_kp_em_kn_bonethr']))
{
echo "Boss was set as NULL This should not happen!";
}
else
{
echo "Sosia messed up go hit him in the face.";
}
/////// END - CHECK NIGHTMARE
if ($normal == '' && $hard == '' && $nightmare == '')
{
}
else
{
$template->assign_block_vars('8m_bonethrasher', array(
'VAR1' => $row['pf_guild_name'],
'VAR2' => $normal,
'VAR3' => $hard,
'VAR4' => $nightmare,
));
}
}
$db->sql_freeresult($result);
I'm still slightly fuzzy at what you are trying to do, but I'll give helping you out a shot.
You could probably get away will creating a class that does all of this.
For example:
class checks {
public function checkBosses($normalBoss, $hardBoss, $nightmareBoss) {
$difficulties = array();
$difficulties['normal'] = array('boss' => $normalBoss);
$difficulties['hard'] = array('boss' => $hardBoss);
$difficulties['nightmare'] = array('boss' => $nightmareBoss);
foreach ($this->difficulties as $difficulty -> $boss) {
$this->difficulties[$difficulty]['result'] = checkDifficulty($boss['boss'], $difficulty);
}
$normal = $this->difficulties['normal']['result'];
$hard = $this->difficulties['hard']['result'];
$nightmare = $this->difficulties['nightmare']['result'];
if ($normal == '' && $hard == '' && $nightmare == '') {
return null;
} else {
return array(
'normal' => $normal,
'hard' => $hard,
'nightmare' => $nightmare,
);
}
}
protected function checkDifficulty($boss, $difficulty) {
if ($difficulty == 'normal') {
$image = ' <img src="/styles/subsilver2/theme/images/soap/no.png" />';
} else if ($difficulty == 'hard') {
$image = ' <img src="/styles/subsilver2/theme/images/soap/ha.png" />';
} else if ($difficulty == 'nightmare') {
$image = ' <img src="/styles/subsilver2/theme/images/soap/kn.png" />';
}
if ($boss == '1') {
return $image;
} else if ($boss == '2') {
return '';
} else if (is_null($boss)) {
echo "Boss was set as NULL This should not happen!";
} else {
echo "Sosia messed up go hit him in the face.";
}
}
}
Then all you would need to do is call:
$checkResult = checks::checkBosses($row['pf_kp_em_no_bonethr'], $row['pf_kp_em_ha_bonethr'], $row['pf_kp_em_kn_bonethr']);
if ($checkResult != null) {
$template->assign_block_vars('8m_bonethrasher', array(
'VAR1' => $row['pf_guild_name'],
'VAR2' => $normal,
'VAR3' => $hard,
'VAR4' => $nightmare,
));
}
If you can retrieve an array of bosses, you can do a foreach loop on them to run that same bit of code for each boss like this:
foreach ($bosses as $boss) {
//Full code to be repeated for each boss here
}

if else simple beginner issue

Good day guys,
I've made a sweet favorites function with php mysql and ajax, and its working great. Now I want to show 'favorite' when favorite = 0 and show 'unfavorite' when favorite = 1
if ($favorites == 0) {
$favorite = 'Favorite';
}
if ($favorites == 1) {
$unfavorite = 'unFavorite';
}
and echo it in the row as :
<div id="favorites">' .($favorite). ' ' .($unfavorite). '</div>
The problem is: when favorite = 0, both $favorite and $unfavorite are being shown. When favorite = 1 only $unfavorite is being shown correctly. Of course it should be $favorite OR $unfavorite. I assume the problem is clear and simple to you, please assist :)
Thanks in advance
It's easier to use just one variable:
$text = ''
if ($favorites == 0) {
$text = 'Favorite';
} else {
$text = 'unFavorite';
}
...
echo $text;
If you want to check $favorite, you are using the wrong variable in your control statement. Also, it is better coding practice to use elseif rather than if for that second if. One more thing: it's easier to manage one resulting variable.
$output = "";
if ($favorite == 0) {
$output = 'Favorite';
}
elseif ($favorite == 1) {
$output = 'unFavorite';
}
...
echo $output; // Or whatever you want to do with your output
Is $favorites an integer?
Anyway try using three equal signs (===) or else instead of the second if:
if ( $favorites === 0 )
{
// ...
}
else // or if ($favorites === 1)
{
// ...
}
You're making a toggle, so you only need one variable:
if(empty($favourites)){
$fav_toggle = 'Favorite';
} else {
$fav_toggle = 'unFavorite';
}
echo $fav_toggle;
Same code is working on me if I assigned $favorites = 0; or $favorites = 1;
You can also use if else
$favorites = 1;
if ($favorites == 0) {
$favorite = 'Favorite';
}
else if ($favorites == 1) {
$unfavorite = 'unFavorite';
}

php foreach results

foreach ($flr_array as $flr) {
if (!($flr = trim($flr)))
continue;
//list($flr, $keyword) = explode('|', $flr, 2);
$ip = '';
$err_msg = isValidFLR($flr, $ip);
if (!$err_msg) {
list($randlink, $lastid, $scr) = addLink($flr, $ip);
$flr = stripslashes($flr);
$url_array[$i]['number'] = $i + 1;
$url_array[$i]['flr'] = $flr;
$url_array[$i]['flr_substr'] = (strlen($flr) > 33) ? substr($flr, 0, 33) . '...' : $flr;
$url_array[$i]['randlink'] = $randlink;
$url_array[$i]['fullrand'] = $config['indexurl'] . $config['mod_rewrite_char'] . $randlink;
$url_array[$i]['scr'] = $scr;
$url_array[$i]['id'] = $lastid;
$url_array[$i]['flr_length'] = strlen($flr);
$url_array[$i++]['randlink_length'] = strlen($config['indexurl'] . $config['mod_rewrite_char'] . $randlink);
////
//$smarty->assign("flr_length", strlen($_REQUEST['flr']));
//$smarty->assign("randlink_length", strlen($config['indexurl'] . $config['mod_rewrite_char'] . $randlink));
////
} else {
js_alert($err_msg);
}
}
In function isValidFLR these is part of captcha check:
if ($config['captcha_check']) {
if (verifyCaptcha() == false) {
return 'Wrong code!';
}
}
Let's say in textarea i enter:
google.com
google.de
google.net
and enter wrong captcha code, so it gives me 3 messages of Wrong code!
It's happen i think because of foreach. Any ideas how to make in foreach display only one error message ?
Your question is hard to understand but I think you are right (in the foreach)....
if err_msg <> '' then you should put a break in your code to get out of the foreach (if that is what you want).
else {
js_alert($err_msg);
break; //this will break out of for loop
//or return false if it a function
}

Categories