I have these two variables
$page_title = '[[+pagetitle]]';
$title_match = 'Marketing Campaign Calendar';
The first is pulling the name of an asset or page and the second are three words I want to search for within those titles. I currently have this if statement which works perfectly as is but I need to add another condition.
if(in_array($content_name, $open_modal_types)) {
// Return view / download buttons
return '<div class="button-group">
<a href="[[~[[+id]]]]"
class="button secondary open-modal"
data-mfp-src="#document-modal"
data-title="[[+pagetitle]]"
data-type="' . $content_name . '"
>View</a>
<a href="[[~[[+id]]]]" class="button secondary" download>Download</a>
</div>';
}
else if($is_binary == '1') {
// Return download button
return '<a href="[[~[[+id]]]]" class="button secondary" download>Download</a>';
}
So I'm trying to accomplish something like this:
if(in_array($content_name, $open_modal_types)) {
// Return view / download buttons
if($page_title contains all of the words in $title_match) {
return "something";
}else{
return '<div class="button-group">
<a href="[[~[[+id]]]]"
class="button secondary open-modal"
data-mfp-src="#document-modal"
data-title="[[+pagetitle]]"
data-type="' . $content_name . '"
>View</a>
<a href="[[~[[+id]]]]" class="button secondary" download>Download</a>
</div>';
}
}
else if($is_binary == '1') {
// Return download button
return '<a href="[[~[[+id]]]]" class="button secondary" download>Download</a>';
}
I've tried using strpos and preg_match but couldn't get it to work. I don't know if I have too many if statements or what. Any suggestions will be helpful.
Thanks
You can use a function like this
<?php
$words = "test1 test2 test3";
function containsAllWords($title, $words) {
$arrWords = explode(" ", $words);
foreach ($arrWords as $word) {
if (strpos($title, $word) === false) {
return false; // one word is not found, so it doesn't contain ALL
}
}
return true; // if we got here, it contains all the words
}
var_dump(containsAllWords("test1 test2 test4", $words)); // false
var_dump(containsAllWords("test1 test2 test3 test4", $words)); // true
may be instead of this
if($page_title contains all of the words in $title_match)
use preg_match:
$title_match = '('.str_replace(' ',')&(', $title_match).')';
if(preg_match('/'.$title_match.'/i', $title_match))
But you should be sure that $title_match not contains special symbols, or filter it by \
So the site I am working on is built in Modx which is fairly new to me. Instead of my original solution I was trying to attempt, I created a new content type within the CMS and wrote my modifications for that content type only. This makes much better sense than what I was trying to do before.
Any other Modx users out there, feel free to reach out to me if you want more details on my solution and what I was trying accomplish.
Thanks to those for trying to help.
Related
I am making a tool to convert steam profile urls to the different steam ids, whatever.
I have the different functions, triggered when submitting the URL of the profile with a form.
One of the function are, that it gets the avatar of the regarding steam profile.
Actually it gets the link of the image. What I can do is, echo an img element with the link, this wont give me any flexibility since I wont be really able to style etc that afterwards.
Now, the function of getting the avatar, is in the function of the submit form.
I tried just inserting the image URL into an img element.
<img src"<?php echo $avatar ?>">
Well, then I get a error message, saying "$avatar" is undefined, even though I defined it in my main php tags. I think that is due to the fact that it is done inside the form function, could be wrong though.
My main question now is, what could be a different approach to this? I need that in the form function because it should only be called then.
Maybe I just have to use the inconvenient way of echoing an img element every time.
Here is the actual code.
<form method="post">
<input type="text" name="profile_url">
<input type="submit" value="click" name="submit">
</form>
<div id="avatar-div" style="height:100px; width:100px;">
<img src="<?php echo $avatar; ?>">
</div>
the main php part
if(isset($_POST['submit']))
{
display();
}
function display() {
require_once 'steamid.class.php';
$input = $_POST["profile_url"];
$api_key = "xxxxxxxxxxxxxxx";
$id = new SteamID($input,$api_key);
if(substr_count($input, ' ') === strlen($input)) {
echo "Enter URL";
} else {
if ($id->resolveVanity()) {
$avatar = $id->toAvatar();
$communityid = $id->toCommunityID();
echo $communityid . ", " . " ";
$steamid = $id->toSteamID();
echo $steamid . ", " . " ";
$userid = '[U:1:'.$id->toUserID().']';
echo $userid . ", " . " ";
} else {
echo "Profile wasnt found!";
}
}
}
I'm refactoring my answer based on the conversation we had. Here is the recommended PHP code.
function urlCheck() {
$input = $_POST["profile_url"];
if(empty($input)) {
echo "Enter URL";
return false;
} else {
return true;
}
}
function display() {
require_once 'steamid.class.php';
$api_key = "xxxxxxxxxxxxxxx";
$id = new SteamID($input,$api_key);
if (urlCheck()) {
if ($id->resolveVanity()) {
$communityid = $id->toCommunityID();
echo $communityid . ", " . " ";
$steamid = $id->toSteamID();
echo $steamid . ", " . " ";
$userid = '[U:1:'.$id->toUserID().']';
echo $userid . ", " . " ";
return $id->toAvatar();
} else {
echo "Profile wasn't found!";
}
}
}
You haven't mentioned where you're running display(), or where you're expecting the output (echo) to display. I can only assume you want it at the top of the page. Let me explain how to use this.
<head>
$avatar = display();
</head>
<body>
<div id="avatar-div" style="height:100px; width:100px;">
<img src="<?= $avatar ?>">
</div>
</body>
Basically the way this works, is that wherever you run display(), is where the echoes will output (in this case, before the body). Wherever you echo $avatar is where the id will be displayed. I hope this works for you.
Take a look at PHP's Variable Scope
Any variable used inside a function is by default limited to the local function scope.
To fix this problem, use the global keyword. This way you will explicitly set $avatar; as a global variable so it can be used outside of your display() function.
Here is how it would work for your example:
function display() {
global $avatar;
// Rest of your display() function
// Set $avatar somewhere in here
}
display(); // Actually call display so $avatar is set
<div id="avatar-div" style="height:100px; width:100px;">
<img src="<?=$avatar;?>">
</div>
I am developing an API call with PHP for FreshDesk and would love some insight. I am trying to page the results of the JSON call, and have been successful so far. The problem is that my direct links are working but the dynamic ones aren't.
I have tried all kinds of order, casting, type changes, and other tweaks but to no avail. Plus the company's programmer is not even around to help... Here is an excerpt of the code.. more on github.
class MyPaginator {
public $tickets;
public $wantedStr;
public $pageNum;
function __construct($number) {
$this->$pageNum = $number;
$this->$wantedStr = $addr . $this->$pageNum;
}
}
function getPageDecision() {
$selected = parse_url(curPageURL())['query'];
if (empty($selected)) {
$selected = '1';
} else {
$selected = str_replace('page=', '', $selected);
}
return $selected;
}
$paginator = new MyPaginator(getPageDecision());
$previousPage = ((int)$paginator->$pageNum) - 1;
$nextPage = ((int)$paginator->$pageNum) + 1;
function showPageMenu(){
echo '<br /><div class="pagination">
«
<a href="http://tickets.cloudlink.biz/?page=1"'.activeClass('1').'>1</a>
<a href="http://tickets.cloudlink.biz/?page=2"'.activeClass('2').'>2</a>
<a href="http://tickets.cloudlink.biz/?page=3"'.activeClass('3').'>3</a>
<a href="http://tickets.cloudlink.biz/?page=4"'.activeClass('4').'>4</a>
<a href="http://tickets.cloudlink.biz/?page=5"'.activeClass('5').'>5</a>
<a href="http://tickets.cloudlink.biz/?page=6"'.activeClass('6').'>6</a>
<a href="http://tickets.cloudlink.biz/?page='.strval($nextPage).'">»
</a>
</div>';
}
I expect the result of clicking the forward or backward buttons to lead me to /?page= dynamically because the number ones are working..... Thanks in advance!
Problem was not using the global keyword for referencing the correct scope for the function. Problem is solved.
I am having an issue with attempting to show different confirm text from an array when using a hyperlink. The text always ends up being from the last confirmation text in the array. I have seen 2 examples on this forum using a function() in a function but I was not able to get this working from viewing the examples.
Here is my code:
echo '
<script type="text/javascript">
function getDetails(message)
{
if (confirm(message))
return true;
else
{
var links = document.getElementsByTagName("a");
for(i=0;i<links.length;i++)
links[i].href = item_NoLink;
}
}
</script>';
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php;report='. $item['id'];
echo '
<script type="text/javascript">
var item_detail = ', json_encode($item['reported_spam']['detail']),'
var item_NoLink = ', json_encode('http://test_url/mytest.php;'),'
</script>
<a id="mylink[]" onclick="getDetails(item_detail);" href="'.$link.'" style="text-decoration:none;">
<img id="myImage" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}
Thanks.
Edit: I figured it out.
#Grant Zhu: Arrays are not written like that in php and one can progress to the next key just using the empty square brackets. You were correct as I did make an err for the image id array and the js variables. Also for php when using single quotes inside echo with single quotes one must use the backslash (unless using php again).
I got it working as such:
echo '
<script type="text/javascript">
var item_NoLink = ', json_encode('http://test_url/mytest.php;'),'
function getDetails(message)
{
if (confirm(message))
return true;
else
{
var links = document.getElementsByTagName("a");
for(i=0;i<links.length;i++)
links[i].href = item_NoLink;
}
}
</script>';
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php?report='. $item['id'];
echo '
<a id="mylink[]" onclick="getDetails(\'',$item['reported_spam']['detail'],'\');" href="'.$link.'" style="text-decoration:none;">
<img id="myImage[]" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}
Thank you.
$link = 'http://test_url/mytest.php;report='. $item['id'];
this code is weird , I think your code might be
$link = 'http://test_url/mytest.php?report='. $item['id'];
You should check the javascript generated and you will find there're multiple declarations of item_detail and item_NoLink. That means you assign the values to the same variables again and again. Of course, the last assignment takes effect in the end.
You can put the detail text directly in the getDetails function. Make sure the text is quoted by '. And you'd better make the id of <a> and <img> unique because that's what id means. I'm not familiar with PHP, check the syntax below if it's correct.
foreach ($items as $item)
{
$link = 'http://test_url/mytest.php;report='. $item['id'];
echo '
<a id="mylink$item['id']" onclick="getDetails(', json_encode($item['reported_spam']['detail']),');" href="'.$link.'" style="text-decoration:none;">
<img id="myImage$item['id']" alt="" src="http://test_url/images/reported.gif" title="'.$item['reported_spam']['title'].'" style="position:relative;border=0px;vertical-align:middle;right:5px;" />
</a>';
}
I have a problem when using jQuery Post, the PHP returns all the HTML of the page up to the newly created HTML, rather then just the HTML that is output by the PHP.
As an example say the php outputs: '<div>Some Content</div>'
Then the jQuery Post returns: '<html><head>...all the head content...</head><body>...other content...<div>Some Content</div>'
Here's the jQuery (link to full code: http://pastebin.com/U7R8PqX1):
jQuery("form[ID^=product_form]").submit(function() {
var current_url = js_data.current_url;
form_values = jQuery(this).serialize();
jQuery.post(current_url+"?ajax=true", form_values, function(returned_data) {
jQuery('div.shopping-cart').html(returned_data);
}
});
return false;
});
And here's the PHP (version 5.3.6 - link to full code: http://pastebin.com/zjSUUbmL):
function output_cart()
{
ob_start();
echo $this->output_cart_html();
$output = ob_get_contents();
ob_end_clean();
echo $output;
exit();
}
function output_cart_html() {
if (!isset($_SESSION['cart_items']))
{
$output = '<div class="cart_content faded">BASKET - Empty</div>';
return $output;
} else {
$total_items = 0;
$total_items = 0;
$items_in_cart = $_SESSION['cart_items'];
// work out total price and total items
foreach ($items_in_cart as $item_in_cart) {
$total_items += $item_in_cart['quantity'];
$total_price += floatval($item_in_cart['updated_price']*$item_in_cart['quantity']);
}
$template_url = get_bloginfo('template_directory');
$output = '';
$output_price = $dp_shopping_cart_settings['dp_currency_symbol'].number_format($total_price,2);
if($total_items == 1){ $item_text = ' Item'; } else { $item_text = ' Items'; }
$output .= $total_items . $item_text;
$output .= ' <span class="bullet"></span> Total '.$output_price;
// empty cart btn
$output .= '<form action="" method="post" class="empty_cart">
<input type="hidden" name="ajax_action" value="empty_cart" />
<span class="emptycart"> <img src="'.$template_url.'/images/empty.png" width="9" height="9" title="Empty Your Items" alt="Empty Your Items" />Empty Your Cart</span>
</form>';
// check out btn
$output .= ' <span class="bullet"></span> <span class="gocheckout">'.$this->output_checkout_link().' </span>';
return $output;
}
}
You need to check if the form has been posted yet with the PHP. To do this, just check if the 'ajax' parameter is there, or send another $_GET variable if you wish (by adding &anotherparementer=1 to the end of the jQuery post URL). Example:
<?php
if(isset($_GET['ajax'])) {
//your PHP code here that submits the form, i.e. the functions that you have, etc.
}
else {
?>
<html>
<head>
head content here...
</head>
<body>
body content here...
</body>
</html>
<?php
}
?>
I hope this helps.
Ok it turns out my problem was with the way Wordpress processes AJAX requests. The plugin I was building on top of was using AJAX but didn't have these issues (I'm not sure why maybe because they were using eval), so I hadn't realised there was a correct way of using AJAX with Wordpress. Here's a bunch of information if anyone else has similar problems:
http://codex.wordpress.org/AJAX_in_Plugins
http://byronyasgur.wordpress.com/2011/06/27/frontend-forward-facing-ajax-in-wordpress/
(this one really helped me out, a very simple example that I was able to adapt)
-- sorry I couldn't post more links because I'm too new on this site, but check out the links at the bottom of the first link above, especially the '5 Tips'.
As I'm using classes I instantiated the class from the index file of my plugin with this:
if ($_POST['action'] === 'action_name') {
$class_obj = new \namespace_name\class();
add_action('wp_ajax_action_name', array($class_obj, 'method_name'));
add_action('wp_ajax_nopriv_action_name', array($class_obj, 'method_name'));
}
<?php
function check($user_id, $topic_id){
$query = mysql_query("SELECT user_id, topic_id FROM sa where topic_id='$topic_id' and user_id='$user_id'");
if (mysql_num_rows($query)==1){
return 'you have already voted';
}
else {
$against = ' <li>
<button type="submit" value="Actions" class="against" title="against">
<i></i><span>Against</span></button>
</li>';
$support ='<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i>
<span>Support</span>
</button>
</li>';
return compact('support', 'against');
}
extract(check($_SESSION['user_id'], $topicId));
echo $against;
echo $support;
?>
i keep getting this error:
Warning: extract() [function.extract]: First argument should be an array
The extract function expects an array. You're passing it the results of your check function, which is sometimes an array
return compact('support', 'against');
but sometimes a string.
return 'you have already voted';
So, I imagine you're seeing the error when the first return statements is executed.
Maybe something like this is better:
function check($user_id, $topic_id){
$query = mysql_query("SELECT user_id, topic_id FROM sa where topic_id='$topic_id' and user_id='$user_id'");
if (mysql_num_rows($query)==1){
return array('error'=>'you have already voted');
}
else {
$against = ' <li>
<button type="submit" value="Actions" class="against" title="against">
<i></i><span>Against</span></button>
</li>';
$support ='<li>
<button type="submit" value="Actions" class="support" title="support">
<i></i>
<span>Support</span>
</button>
</li>';
return compact('support', 'against');
}
}
$result = check($_SESSION['user_id'], $topicId);
if(isset($result['error'])) {
echo $result['error'];
}
else {
echo $result['against'];
echo $result['support'];
}
You could also consider to use exceptions.
First, function definition is not closed in your code (no closing "}")
Second, your function returns string if user has already voted - in this case PHP would obviously say "First argument should be an array" on extract() function call.
Generally, I'd recommend not to use compact-extract construction, but use structures or associative arrays as return value instead. In this case behavior would be much clearer.
So as it suggests: Warning: extract() [function.extract]: First argument should be an array
Try following:
$arr = check($_SESSION['user_id'], $topicId);
if(is_array($arr)) {
extract($arr);
echo $against;
echo $support;
} else {
echo $arr;
}