PHP Parse loops through # days but want to limit number the outputs - php

So I'm using the following long bit of code to list upcoming events. It asks for the number of days you want to display events for, let's say 10 days, and it groups as many events in those 10 days. I changed the code so there isn't just one header for a given date with multiple events under it, rather than each event date is shown. However it still gives me all the events of the next 10 days. I would like to limit the code so that of the numerous events of the next 10 days it only returns/displays/outputs 6 events.
I'm pretty sure what I need to change is here:
for ($i=0; $i<$days_to_display; $i++)
but the $days_to_display bit makes it tricky.
Any help would be greatly appreciated!
<?php
// List View of Coming Events v .9
// Plug-in for PHPiCalendar 2.0 / 2.1
// developed by Johnathon Wright (my initials # mustmodify.com)
// Original Publication Date: 2005 10 28
// Originally Developed for St. Barnabas Episcopal Church website
// Include this file from your PHP-enabled front page.
// Do something like this:
// <?PHP include 'd:/inetpub/.../phpical/event_list.php';
// DEFINE the base PHPiCalendar directory below.
define('BASE', 'c:/inetpub/ouhsd.k12.ca.us/phpicalendar/');
// create an actual PHPiCalendar instance
require_once(BASE.'functions/ical_parser.php');
require_once(BASE.'functions/list_functions.php');
require_once(BASE.'functions/template.php');
header("Content-Type: text/html; charset=$charset");
// at this point, the calendar has been generated and its data
// is stored in $master_array. Test to ensure that this is working by
// un-commenting the lines below.
/*
echo "<pre>";
print_r($master_array);
echo "</pre>";
*/
// A few settings...
// days_to_display_default should be a positive integer.
$days_to_display_default = 14;
// SHOW PRIVATE EVENTS {TRUE, FALSE}
// In Mozilla Sunbird, events can be set to PRIVATE.
// PHPiCalendar does not display the title or description for
// these events, but does display the time, if applicable.
// If you want to hide these events, set $show_private_events to FALSE.
// Otherwise, it should be TRUE
$show_private_events = TRUE;
// day_to_begin should be a text string. See http://www.php.net/strtotime
// for full documentation. Some values I tested:
// -------------------------------------------------------
// last monday - the most recent Monday.
// thursday - this gave me the date of the next Wednesday.
// yesterday - yesterday
// today - today
// next week - +2 weeks (How can this be? Don't ask me, it's PHP...)
// 1 week - a week from today
$day_to_begin = "today";
// Replace with the commented code if you would NOT like
// users to be able to set this value on their own.
$days_to_display = $days_to_display_default;
/*
// this code replaces the above code if you want to prevent
// users from setting the number of days to display
$days_to_display = $days_to_display_default;
*/
// This next section seems terribly inefficient. We calculate the unix
// timestamp of first-thing-this-morning by finding out the date
// and then looking up the timestamp for that date...
// Again, the commented code prevents users from setting their own start date.
$date_start = date('Ymd', strtotime("now"));
$timestamp_start = strtotime(dateOfWeek($getdate, $date_start));
/*
$date_start = date('Ymd', strtotime("now"));
$timestamp_start = strtotime(dateOfWeek($getdate, $date_start));
*/
// Display the date range for this list
$timestamp_end = $timestamp_start + ($days_to_display * 24 * 60 * 60);
// seed the iterator $thisdate with todays timestamp.
// It will loop through $days_to_display...
$thisdate = $timestamp_start;
// Loop through the days, finding events in each day
for ($i=0; $i<$days_to_display; $i++)
{
$thisday = date("Ymd", $thisdate);
if (isset($master_array[$thisday]))
{
echo "<br/>";
foreach($master_array[($thisday)] as $event_start_time => $event_set)
{
foreach ($event_set as $event_id => $event_info)
{
// Where are we?
// date is $thisdate
// time is $event_start_time
// event is $event_id;
if (! (($event_info['event_text'] == '**PRIVATE**') && ($show_private_events == FALSE)))
{
// event title
echo "<li>";
echo "<span class='bold_text'>" . stripslashes(urldecode($event_info['event_text'])) . "</span><br/>";
// event time range, if not an all-day event
echo " <span style='display: block;'>". date("D. F jS", $thisdate) . "";
if (! (($event_info['event_start'] == '0000') && ($event_info['event_end'] == '0000')))
{
echo ":
" . date("g:ia", $event_info['start_unixtime']) . " - " . date("g:ia", $event_info['end_unixtime'])."</span>";
}
// event location
if (strlen($event_info['location']) > 0)
{
echo " <span class='italic_text'>" . stripslashes(urldecode($event_info['location'])) . "</span>";
}
/*
if ( (($event_info['event_start'] == '0000') && ($event_info['event_end'] == '0000')))
{
echo "all day";
}*/
// event description.
echo "</li>";
} // IF private event AND we don't want to see those
}// END enter this event
} // END foreach event
} // END if there are any events today in the array
// iterator should be the next day.
// Why is this 25? Shouldn't it be 24?
$thisdate = ($thisdate + (25 * 60 * 60));
}
?>

Put a counter in there somewhere to keep track of how many events have been output, and terminate the loop once you reach the limit:
$limit = 6;
$displayed = 0;
foreach(...) {
if (show_event()) {
... show event ...
$displayed++;
if ($displayed >= $limit) {
break;
}
}
}

This may not be the best way! But you could add another for loop above the foreach eg:
for ($i=0; $i<$days_to_display; $i++)
{
$thisday = date("Ymd", $thisdate);
if (isset($master_array[$thisday]))
{
echo "<br/>";
for($k=0;$k<=$noofevents;$k++) //Where $noofevents is the number of events!
{
foreach($master_array[($thisday)] as $event_start_time => $event_set)
{
foreach ($event_set as $event_id => $event_info)
{
// Where are we?
// date is $thisdate
// time is $event_start_time
// event is $event_id;
if (! (($event_info['event_text'] == '**PRIVATE**') && ($show_private_events == FALSE)))
{
// event title
echo "<li>";
echo "<span class='bold_text'>" . stripslashes(urldecode($event_info['event_text'])) . "</span><br/>";
// event time range, if not an all-day event
echo " <span style='display: block;'>". date("D. F jS", $thisdate) . "";
if (! (($event_info['event_start'] == '0000') && ($event_info['event_end'] == '0000')))
{
echo ":
" . date("g:ia", $event_info['start_unixtime']) . " - " . date("g:ia", $event_info['end_unixtime'])."</span>";
}
// event location
if (strlen($event_info['location']) > 0)
{
echo " <span class='italic_text'>" . stripslashes(urldecode($event_info['location'])) . "</span>";
}
/*
if ( (($event_info['event_start'] == '0000') && ($event_info['event_end'] == '0000')))
{
echo "all day";
}*/
// event description.
echo "</li>";
} // IF private event AND we don't want to see those
}// END enter this event
} // END foreach event
} // END for x events
} //END if isset
}//END for days

Related

Creating Store Clock Function - Open/Close & Events depending on time

So I have a code that is functioning properly. I received some help putting this together because despite feeling reasonably confident in my coding skills (fairly new) - time avoids me, I find it confusing to determine how it works in PHP.
I am looking to create a function that acts as my stores clock and returns "open" - "closed" - "1 hour to close" results that I can use in other functions.
For example:
if ( store_clock() == 'open' ) {
echo 'Open';
}
elseif ( store_clock() == '1_hr_left' ) {
echo 'You have 27 mins and 12 secs to place an order' );
else {
echo 'Sorry, we are closed.';
}
I currently have the following code which works correctly in regard to closing times, properly displaying the time left countdown etc. The issue being I don't have my open times, and I would prefer to split the code up - allowing me to use the store_clock() function to trigger other events throughout the site... not just the closing counter.
To do this I am assuming I would need 2 to 3 different functions, rather than just the 1... however I am feeling very confused. Any help appreciated. (PS. get_field() is calling ACF values)
function sat_clock() {
$the_time = current_time('timestamp');
$exact_time = gmdate('g:ia', $the_time);
$weekday_close = get_field('weekday_close', 'options');
$sat_close = get_field('sat_close', 'options');
$sun_close = get_field('sun_close', 'options');
// Set your closing times here from sun-sat
$closing_times = array( $sun_close, $weekday_close, $weekday_close, $weekday_close, $weekday_close, '7:31 pm', $sat_close );
if ( $closing_times[date( 'w', current_time('timestamp') )] !== false ) {
$closing_time = strtotime( sprintf( '%s %s', date( 'd F Y', current_time('timestamp') ), $closing_times[date( 'w', current_time('timestamp') )] ) );
if ( $closing_time - current_time('timestamp') > 0 && $closing_time - current_time('timestamp') < 1800 ) {
echo '<strong>LAST CALL</strong><p class="m-0" id="closing-soon-timer"></p>';
?>
<script>
var timeLeft = <?php echo $closing_time - current_time('timestamp'); ?>;
// Update the count down every 1 second
var x = setInterval(function() {
// Time calculations for minutes and seconds
var minutes = Math.floor(timeLeft / 60);
var seconds = Math.floor(timeLeft % 60);
// Display the result in the element with id="demo"
document.getElementById("closing-soon-timer").innerHTML = "You have <strong>" + minutes + "</strong> minutes " + "<strong>" + seconds + "</strong> seconds to place an order.";
// If the count down is finished, write some text
if (timeLeft < 0) {
clearInterval(x);
document.getElementById("closing-soon-timer").innerHTML = "Closed for today";
}
timeLeft--;
}, 1000);
</script>
<?php
} elseif ( $closing_time - current_time('timestamp') < 0 ) {
echo "<p>Closed for today</p>";
} else {
echo "<p>Opened</p>" . gmdate('g:ia', $closing_time);
var_dump($exact_time);
}
} else {
echo "<p>Closed for today</p>";
}
}
add_action( 'woocommerce_archive_description', 'sat_clock' );

Submit form with multiple conditions not working

Situation
I have a submit form. With this form, users are able to reserve a table in a restaurant. With each submit there is some data send to the database with the wp_insert_post function. For example the user_ip and the datum_nieuwe_reservering(explained later). I want to use this to check if the user is allowed to submit a new reservation(prevent spamming). I have tried a couple of thing, but it's not working. See code below.
Question
How can I get this to work? What am I doing wrong?
CODE
reserving.php
<!-- CODE WHEN POST = SUBMIT, MAKE A NEW RESERVATION.
=========================================== -->
<?php
global $wpdb;
$user_ip_db = getUserIP();
$date = date("d-m-Y H:i:s");
//echo $date;
$check_user_ip = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'user_ip_reservering' AND meta_value = '$user_ip_db'");
$check_time_new = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = 'datum_nieuwe_reservering'");
print_r($check_time_new);
if ( isset($_POST['submit_reservering']) ) {
if ( (empty($check_user_ip)) && $date > $check_time_new ) {
create_reservering();
echo "Your reservation has been send";
} else {
echo 'You have already reserved';
}
}
?><!-- end CODE FOR MAKING RESERVATION-->
Plugin file
//Using this function to send the current day + 1 day to the database
//with a hidden text field named `datum_nieuwe_reservering`(show below)
//and in the end check if current date >= `datum_nieuwe_reservering`
<?php
function getDateTime(){
date_default_timezone_set('Europe/Amsterdam');
$next_day = time() + (1 * 24 * 60 * 60);
$date_now = date('d-m-Y H:i:s');
$date_tomorrow = date('d-m-Y H:i:s', $next_day);
echo $date_tomorrow;
}
?>
Hidden field for datum_nieuwe_reservering
<input type='hidden' value='<?php echo getDateTime(); ?>' name='datum_nieuwe_reservering'>
NOTE: The submit form is working correctly with the if (empty($check_user_ip)) { }; code only. So I'm struggle to add the date in the if statement too.
I hope someone can help me in the right direction!
Thanks in advance.
Have you tried to use brackets in condition?
if ( isset($_POST['submit_reservering']) ) {
if ( (empty($check_user_ip)) && ($date > $check_time_new) ) {
create_reservering();
echo "Your reservation has been send";
} else {
echo 'You have already reserved';
}
}
if (isset($_POST['submit_reservering']) === true) {
$reserved = false;
if (empty($check_user_ip) === true) {
$test = end($check_time_new);
if(date > $test->meta_value) {
create_reservering();
echo "Your reservation has been send";
} else {
echo 'You have already reserved';
}
}
}

How to check past date should not be past from current date in PHP? in this second condition not working

My code is here,I am not able to perfect. when press submit button it check old date correct.. and shows "date must be in future" it correct. and whenever i put future date.. that time not show second alert instead it showing first.
if(isset($_POST['update']))
{
$pdata["card"] = $_POST['smcard'];
$pdata["expiry_date"] = date("Y-m-d" strtotime($_POST['smexdate']));
$dateone = $pdata["expiry_date"];
$nowdate = new DateTime();
if ($dateone < $nowdate)
{
echo "<script>";
echo "alert('date must be in future');";
echo "</script>";
}
elseif ($dateone > $nowdate)
{
echo "<script>";
echo "alert('Okay Good, Your date is in future');";
echo "</script>";
}
update_data('smartcard_data', $pdata, 'promotion_id='.$_REQUEST['promotion_id']);
exit;
}
Try below example to fine date passed or not
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');
if ( $dtA > $dtB ) {
echo 'dtA > dtB';
}
else {
echo 'dtA <= dtB';
}

Facebook API PHP - Posts 'created_time' data not displaying properly

I am making a Facebook application using PHP. Through the Facebook API the application displays the recent posts from the logged in user. When it came to working on retrieving the created_time of each post, I found that it either did not display anything or only displayed 1970-01-01T00:00:00+0000. (This can be seen in the picture below.) This held even when I used DateTime.
It should return something like 2016-01-31T16:31:26+0000, as seen by using Facebook's Graph API Explorer.
Not sure how to correct this, I was able to get it to display in the correct format like so:
$ts = strtotime($key['created_time']);
$myTime = gmdate(DATE_ISO8601, $ts);
All of the information is pulled from Facebook, and is within a foreach loop. It goes through each post and knows what to put where, and each created_time value is sated as $key['created_time']
Front End Example
Graph API Explorer
This is my code:
<?php
// Getting all posts published by user
try {
$posts_request = $fb->get('/me/posts?fields=id,created_time,message,link,picture,name&limit=7');
$posts_response = $posts_request->getGraphEdge();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if ($fb->next($posts_response)) {
$total_posts = $posts_response->asArray();
$totalPosts = count($total_posts);
// Form - Post
echo "<p><strong>* With this text box below, you can post to your Facebook Profile about your experience using this application if you wish. Once submitted, this post will then also appear in the list of your other posts below.</strong></p>";
echo "<form action='posttouserstimeline.php' method='post'>";
echo "<textarea name='description' class='posts'></textarea>";
echo "<br><br>";
echo "<input type='submit' class='webbutton' value='Post to Facebook'>";
echo "</form>";
echo "<br>";
echo "<p><strong>* Below are your '5' most resent posts, from your Facebook Profile</strong></p>";
//$date = new DateTime($key['created_time']);
foreach($total_posts as $key) {
$ts = strtotime($key['created_time']);
$myTime = gmdate(DATE_ISO8601, $ts);
echo "Time and Date of Post: ".$myTime."<br>";
echo "<img class='postsprofile' alt='profilepic' src='".$picture['url']."'/> <a href='https://facebook.com/".$profile['id']."' target='_blank'>".$profile['name']."</a><br>";
echo $key['message'].'<br><br>';
echo "<a href='".$key['link']."' target='_blank'><img class='postsprofile' alt='".$key['name']."' src='".$key['picture']."'/></a><br><hr><br>";
//echo "<img class='postsprofile' alt='".$key['name']."' src='".$key['picture']."'/><br>";
//echo "<a href='".$key['link']."' target='_blank'>".$key['link']."</a><br><hr><br>";
}
}
The problem is the facebook time function does not give the time in the standard numeric form needed for the call from strtotime to work. Here is a function I found online that converts facebook time to the time in the standard numeric form we are used to.
var fuzzyFacebookTime = (function(){
fuzzyTime.defaultOptions={
// time display options
relativeTime : 48,
// language options
monthNames : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
amPm : ['AM', 'PM'],
ordinalSuffix : function(n) {return ['th','st','nd','rd'][n<4 || (n>20 && n % 10<4) ? n % 10 : 0]}
}
function fuzzyTime (timeValue, options) {
var options=options||fuzzyTime.defaultOptions,
date=parseDate(timeValue),
delta=parseInt(((new Date()).getTime()-date.getTime())/1000),
relative=options.relativeTime,
cutoff=+relative===relative ? relative*60*60 : Infinity;
if (relative===false || delta>cutoff)
return formatTime(date, options)+' '+formatDate(date, options);
if (delta<60) return 'less than a minute ago';
var minutes=parseInt(delta/60 +0.5);
if (minutes <= 1) return 'about a minute ago';
var hours=parseInt(minutes/60 +0.5);
if (hours<1) return minutes+' minutes ago';
if (hours==1) return 'about an hour ago';
var days=parseInt(hours/24 +0.5);
if (days<1) return hours+' hours ago';
if (days==1) return formatTime(date, options)+' yesterday';
var weeks=parseInt(days/7 +0.5);
if (weeks<2) return formatTime(date, options)+' '+days+' days ago';
var months=parseInt(weeks/4.34812141 +0.5);
if (months<2) return weeks+' weeks ago';
var years=parseInt(months/12 +0.5);
if (years<2) return months+' months ago';
return years+' years ago';
}
function parseDate (str) {
var v=str.replace(/[T\+]/g,' ').split(' ');
return new Date(Date.parse(v[0] + " " + v[1] + " UTC"));
}
function formatTime (date, options) {
var h=date.getHours(), m=''+date.getMinutes(), am=options.amPm;
return (h>12 ? h-12 : h)+':'+(m.length==1 ? '0' : '' )+m+' '+(h<12 ? am[0] : am[1]);
}
function formatDate (date, options) {
var mon=options.monthNames[date.getMonth()],
day=date.getDate(),
year=date.getFullYear(),
thisyear=(new Date()).getFullYear(),
suf=options.ordinalSuffix(day);
return mon+' '+day+suf+(thisyear!=year ? ', '+year : '');
}
return fuzzyTime;
}());
Source:
http://tipsandtricks.nogoodatcoding.com/2011/02/facebook-createdtime-format-in-json.html

PHP Twitter search api with tweet back button

I'm using working on building a WordPress plugin, that uses the Twitter api - but I'm very new to working with Twitter.
I currently have a keyword search form and results working
<?php
// get the keyword from url
$srchterm = $_GET['search_box'];
// encode it for the safe search
$srchterm = urlencode($srchterm);
// search the keyword using Twitter API
$srch_twitts = "http://search.twitter.com/search.atom?q=".$srchterm."";
// use curl to execute the Twitter URL
$twits = curl_init();
curl_setopt($twits, CURLOPT_URL, $srch_twitts);
curl_setopt($twits, CURLOPT_RETURNTRANSFER, TRUE);
$twi = curl_exec($twits);
// here we have the searched result in an array
$search_res = new SimpleXMLElement($twi);
//print_r($search_res);
?>
<?php
/* display the data */
$i = 0;
// displays the search keyword
echo "<p style='padding-left:10px; color:brown'>Your search term is: " . stripslashes($_GET['q']) . "</p>";
// tweets in an array. split it by foreach
// we need only 10 result so, use if condition
foreach ($search_res->entry as $result) if ($i++ < 10)
{
echo "<div id='tweets'>";
echo "<p>$i</p> ";
echo "<div class='avatar'><img src='". $result->link[1]->attributes()->href. "' /> </div>";
echo "<div class='twitcont'>";
echo "<div class='name'>". $result->author->name . "</div>";
echo "<div class='content'>" . $result->content ;
// convert the updated date of tweet to seconds
$twittedSeconds = time() - strtotime($result->updated);
$names = array('second', 'minute', 'hour', 'day', 'week', 'month', 'year');
$seconds = array( 1, 60, 3600, 86400, 604800, 2630880, 31570560);
// find the time difference between present time and tweet time
if($twittedSeconds > 0)
{
for($j = count($seconds) - 1; $j >= 0 ; $j--)
{
$interval = $seconds[$j];
if($twittedSeconds >= $interval)
{
$getTime = round($twittedSeconds / $interval);
if ($getTime > 1)
{
$names[$j] .= s;
}
$time = $getTime. ' ' . $names[$j] . ' ago';
break;
}
}
//echo the time difference
echo "<div class='time'> " . $time . "</div>";
}
echo "</div>";
echo "</div></div>";
}
?>
My question:
How can I integrate a tweet button for each result - this would allow the admin to (after searching twitter for keyword matches) tweet back on conversations.
Please see this example: http://screencast.com/t/2xBkTyUHT
Find the tweet id then attach a hyper link of this format
https://twitter.com/intent/tweet?in_reply_to={tweet id}
So the link might look like this.
$tweet_id = substr($entry->id, strrpos($entry->id, ':')+1);
echo "Reply";
More information can be found here. Twitter Web Intents
Note: You put echo "<div id='tweets'>"; in a loop. Means DOM will have multiple elements with same id. Correct it either using class or put it outside the loop.

Categories