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

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' );

Related

How to: Refresh a page between certain times on a day of the week?

I'd like for a web page to automatically refresh between certain times on a specific day of the week (between 9am and 12pm on Wednesdays). New content will be made available on the page, and I want to ensure someone sees the content without having to remember to refresh the page themselves. Not sure how to finish getting this to work. Here's what I have so far:
<?php
$page = $_SERVER['REQUEST_URI'];
$sec = '600000'; // 10 minutes
date("Y-m-d");
date_default_timezone_set('America/Denver');
$time= date('w H:i'); // Day Hour:Minute
if($time >= '3 09:00' && $time <= '3 12:00') { //after 9am and before 12pm on Wednesday
echo '<style type="text/css">.element { display:block; }</style>';
} else {
echo '<style type="text/css">.element { display:none; }</style>';
}
?>
<script type="text/javascript">
setInterval(function() {
window.location.href = '<?php echo $page; ?>';
},<?php echo (int)$sec; ?>);
</script>
Even refreshing just once may be more ideal...
I think that it's better to put your javascript in a php variable ($js).
Better to use setTimeout instead of using setInterval if you want only refresh once.
<?php
$js = '';
$page = $_SERVER['REQUEST_URI'];
$sec = '600000'; // 10 minutes
date("Y-m-d");
date_default_timezone_set('America/Denver');
$time= date('w H:i'); // Day Hour:Minute
if($time >= '3 09:00' && $time <= '3 12:00') { //after 9am and before 12pm on Wednesday
echo '<style type="text/css">.element { display:block; }</style>';
$js = '<script type="text/javascript">setTimeout(function() { location.reload(); }, ".(int)$sec."); </script>';
} else {
echo '<style type="text/css">.element { display:none; }</style>';
}
echo $js;
?>
Tell me if it's what you need.

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

How to compare the time in from the nearest scheduled time

can someone please help me how to fix this code. What I need is to let the current time compare it to the nearest saved schedule in the column "from"
because the current time is only comparing it to the first added schedule
code:
<?php
//Include the database configuration
include 'config.php';
//Get the data of the selected teacher
$teacher = $dbconnect->prepare("SELECT * FROM time WHERE IMEI = ? AND NFC = ?");
$teacher->bindValue(1,$_GET['IMEI']);
$teacher->bindValue(2,$_GET['NFC']);
$teacher->execute();
//Get the data
$time = $teacher->fetch();
//Store the current time
$current_time = new DateTime();
//Placeholder variables
$time_difference = 0;
$remark = "";
//If there is such a teacher let the teacher enter
if(!empty($time))
{
//Get the time difference
$time_difference = round( (strtotime($current_time->format('H:i:s')) - strtotime($time['From'])) / 60 );
//Check if the professor is late or not
//If the time difference is negative he/she is early
if($time_difference < 0)
{
$remark = 'Sir why are you so early?';
}
//If the prof is on time which is 0 time difference or less than 15 minutes
else if($time_difference == 0 || $time_difference < 15)
{
$remark = "Sir it's a miracle you are on time";
}
//Oh come on why are you so late Sir?Porn marathon at night?
else if($time_difference == 15 || $time_difference > 15)
{
$remark = 'Sir why are you late?';
}
$time_in = $dbconnect->prepare("INSERT INTO time_in (teacher_id,name,NFC,IMEI,time_in,remarks) VALUES (?,?,?,?,?,?)");
$time_in->bindValue(1,$time['teacher_id']);
$time_in->bindValue(2,$time['name']);
$time_in->bindValue(3,$time['NFC']);
$time_in->bindValue(4,$time['IMEI']);
$time_in->bindValue(5,$current_time->format('H:i:s'));
$time_in->bindValue(6,$remark);
$time_in->execute();
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome!</title>
</head>
<body>
<h1>
<?php
//If there is such a teacher,welcome him/her
if(!empty($time))
{
echo 'Welcome '.$time['name'].'! Your NFC is '.$time['NFC'];
echo '</br>';
echo 'Time in at: '.$current_time->format('H:i:s');
//This is just a temporary display to show the time difference for testing.Kindly delete it later
echo '</br>';
echo 'Time difference: '.$time_difference;
//Display remark
echo '</br>';
echo 'Remark:'.$remark;
}
else
{
echo 'You are not registered.';
}
?>
</h1>
</body>
</html>

PHP Performing a persistent DB check

I'm actually trying to create a ( more or less ) instant chat.
There's just one thing left to go, until it's finished. And that's a DB check for new entries every second by PHP itself.
A while loop works great for it, because i can exit it perfectly.
The Problem is, that the "every second" thing isn't working.
I tried a sleep(1), but that causes a 1 minute server freeze, until the script has been completed.
Hope someone can help me, i'm actually frustrated about this problem.
elseif($latestID != 'undefined' && $_POST['returnafter'] == '60')
{
$timeout = '60';
$i = '0';
while ($i != $timeout)
{
$chat_content = "";
$i++;
$getLastID = mysql_query("SELECT id, userid, content, time_posted FROM (SELECT * FROM chat_system ORDER BY id DESC LIMIT 150) chat_system WHERE id > '" . $latestID . "' $extraQuery ORDER BY id ASC");
while ($lastID = mysql_fetch_object($getLastID))
{
$rowID = $lastID->id;
$user_posted_id = $lastID->userid;
$chat_content = $lastID->content;
$chat_posted = $lastID->time_posted;
$getUserData = mysql_query("SELECT username, avatar, loggedIn FROM account_data WHERE account_id=('" . $user_posted_id . "')");
while ($userData = mysql_fetch_object($getUserData))
{
$username = $userData->username;
$useravatar = $userData->avatar;
$loginStatus = $userData->loggedIn;
}
if ($loginStatus == '1')
{
$onlineStatus = '<img src="./images/3DArt/newOnline.png" class="chat_onlineStatus">';
}
else
{
$onlineStatus = '<img src="./images/3DArt/newOffline.png" class="chat_onlineStatus">';
}
if (date('Y-m-d', $chat_posted) == date('Y-m-d'))
{
$time_posted = strftime('Heute, %H:%M', $chat_posted);
}
elseif (date('Y-m-d', $chat_posted) == date('Y-m-d', strtotime("Yesterday")))
{
$time_posted = strftime('Gestern, %H:%M', $chat_posted);
}
elseif (date('Y-m-d', $chat_posted) < date('Y-m-d', strtotime("Yesterday")))
{
$time_posted = strftime("%A, %d %B %Y %H:%M", $chat_posted);
}
if (isset($_POST['parseEmoticons']) && $_POST['parseEmoticons'] == 'true')
{
$chat_content = emoticons($chat_content);
}
$newChatRow.= '<div class="chatRow" id="' . $rowID . '">
<div class="chatRow_container">
<div><img src="' . $useravatar . '" class="chatAvatar">' . $onlineStatus . '<b>' . $username . '</b>
</div>
</div>' . $modActions . '
<div class="chat_mainMsg">
' . $chat_content . '
</div>
<div class="chatTime">' . $time_posted . '</div>
</div>';
}
$content = str_replace(array(
'\r\n',
'\r',
'\n'
) , "<br />", $newChatRow);
if(!empty($chat_content)) { echo $newChatRow; $i = $timeout; return false; }
if(empty($chat_content)) { sleep(1); return true; }
}
}
I think, this informations should be enough. If not, just ask.
EDIT: The request is initialized by Ajax and on success the request repeats.
That's why PHP have to check for 60 seconds.
you should let the clientside decide what messages it "like" to receive.
eg you call your messages.php class - per ajax on the client side and pass a timestamp when the last time was the script requested new messages
example:
ajax interval with 1 second loop call the messages.php?last=123456 and receive all messages that were created after or equal this timestamp. now you update in javascript the last timestamp and so on.
or you use a perfect framework (if possible) that is designed perfectly for your task to solve this.
http://socket.io/ (or js keyword websockets)

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

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

Categories