closingtags </> – Page 6 – web development and then some
Categories
jQuery PHP Plugins WordPress

Restricting Dates of jQuery UI Datepicker with custom WordPress plugin

Recently, I was tasked with adding a custom field to a WooCommerce order details section. This itself is not a major task and is well documented online, but this particular field had some special requirements. It had to

Allow users to select a date for delivery/pickup
Restrict possible order dates to days when the facility is open

Sounds simple enough, right? Just toss a calendar widget in there and limit the days to weekdays since weekends and holidays are the only days when this particular facility is closed. Weekends are easy, but holidays? That’s where it got a little bit weird. Take Labor Day for instance. It always falls on the first Monday in September. President’s Day falls on the third Monday of February each year. These wouldn’t be difficult to code for the current year, but we don’t want our calendar widget to only work for this year. It should work for every year, so we don’t have to remember to go update our code every December 31st.
This company also has special rules regarding holidays. For example, if the 4th of July falls on a Saturday, then they are closed the Friday before. If the 4th is on a Sunday, then employees get the following Monday off. All in all, there are 11 different holidays we need to prevent orders from happening on.
I wasn’t sure how this could all be done with jQuery, so I ended up doing it in PHP and then serving up an array of dates to be blocked off in the widget with an AJAX call.
PHP
In our PHP code, I went through the normal suggested steps of enabling AJAX calls in a plugin and ended up with the function `company_holidays_callback`. This function gets our current year, and pushes each holiday onto an array. It does this for the current year, and the following year. Figuring out the date for each holiday wouldn’t have been so simple without the PHP strtotime function. That was a life saver! And the  function `fri_or_mon` was the logic used to mark the previous Friday or the following Monday off of the calendar as per special rule of this particular company.

jQuery
To break down the jQuery, we create the instance of our datepicker on the element `#order_fulfillment_date`. If that element exists on the page, we perform our AJAX call to get the list of dates that need to be restricted. The function `noWeekendsOrHolidays` checks to if the date is a weekend. If it is, it gets disabled. If it isn’t, it passes the day onto `nationalDays` where we check if the date is one of our holidays that needs to be disabled as well.

In all of this code there isn’t really anything special or groundbreaking, but I thought the logic that determined the holidays was useful and maybe someone else could save themselves a little bit of time and headaches. Thanks for reading!

Categories
Linux Python

Text to Speech in Python

I finally got around to looking at the Linux Voice 18 and I have to say, the Summer hacks section is really cool. I’ve always been curious about recompiling a kernel and playing around with the different settings, but the project that really caught my attention was the Python script that converted IRC chat into voice. That really just sounds like fun. So I tried going through with it, but ran into some issues with my Python versioning. And since I don’t really use IRC, I thought it might be fun to just whip up a quick script that converts whatever text is typed into the terminal into voice. It’s simple enough to do, so here it is!
from espeak import espeak
import time
while True:
response = input(“&gt;&gt; “)
espeak.synth(response)
time.sleep(1)
To install, make sure that the package espeak is installed. To install espeak, run:sudo apt-get install espeak espeak-dataThen, to run the script, runpython3 scriptname.pyHere’s a link to the Gist
At some point, I think it’d be pretty cool to turn this into a Telegram Bot via their API. Maybe use this to convert all text into a voice (like Gigolo Joe’s “say” function), but it would also be cool to allow Telegram to convert something a user says into text.

Categories
Plugins Themes WordPress

Deployments w/Git

FTP sucks. I mean, it’s fine. Whatever. But moving code with FTP sucks. You have to make sure you’ve downloaded the latest version, and you have to be careful not to overwrite or delete other files. One missed click, and you can have a long evening ahead of yourself. Because of the issues I’ve had with FTP in the past, I’ve been on the lookout for better ways of getting my code to my applications. You might remember that I previously posted about deploying a web app using Capistrano and while Capistrano is really cool, I still suck at Ruby. So when confronted with yet another deployment problem, I wanted to use Capistrano, but I didn’t want to have to butcher someone else’s deployment recipe again. And I really, really didn’t want to FTP my code up to the server again.
In comes Git; not just for version control. You’re already using it to keep your code safe. Why not use it to securely push your code to your server? In my case, I needed to push a plugin that contains custom features. So how do you use Git to deploy your code?
I’m going to operate off of the assumption that you’ve already got your code in a repository. If you haven’t done that, do it now. Once you have done that, then SSH into your server and create directory to store a remote repository.
ssh [email protected]
mkdir repo_title && cd repo_title
git –bare init
You’ve now got a bare repository to host your code. The next step deals with the hooks in the repo.nano hooks/post-receiveIn that file, drop this code:
#!/bin/sh
GIT_WORK_TREE=/var/www/public_html/wp-content/plugins/custom_plugin git checkout -f master
Obviously, change that path to whatever the path is to your plugin location on the server, save it, and then run:chmod +x hooks/post-receiveso that your code has execute rights.
Now exit your SSH connection, and go back to your local repository. You’ll now need to create a remote in your local repository for your server.
cd your-project
git remote add myserver ssh://[email protected]/~/repo_title
git push myserver +master:refs/heads/master
To deploy your code, just rungit push myserverAnd that’s it! Now, you can move code without ever having to write a Ruby script or open an FTP client.
Thanks to Matt Banks over at mattbanks.me for his excellent write-up. I recommend you go check that out seeing as how that’s where I found this.
Source: Managing WordPress Theme Deployments with Git – Matt Banks
Update: It’s become popular to rename the master branch to main. If that is the case for you, simply replace all instances of “master” in the code with the branch you would like to use.

Categories
PHP Security WordPress Yii2

Deployments w/Capistrano

For so long, developers have been moving code with FTP/SFTP. It’s time consuming, and comes with its faults. One false click, and you could easily overwrite a file that you haven’t downloaded yet. And that’s not good. Especially if there’s no version control in place. I know; it’s 2015 and if that happens to you, you kind of deserve it. But the fact of the matter is that a lot of developers at smaller organizations are still doing things this way.
This is where Capistrano comes in. Capistrano is a Ruby gem that makes deployment a one command process. Seriously.
cap production deploy
That command is all you need to push code to your production server.
Capistrano lets you use a git repo to launch your application. Instead of opening up FileZilla, finding a directory, and uploading everything manually, Capistrano will go to your repository, and move that code via a secured connection (SSH) to your server. The Capistrano website has everything you need to get setup so I won’t go into that here, but I will drop in my configuration to show how I’m using it to deploy a Yii2 app.
config/deploy.rb
set :application, ‘PROJECT_NAME_HERE’
set :repo_url, ‘https://GIT_REPO_HERE.git’

# Default deploy_to directory is /var/www/my_app_name
set :deploy_to, ‘DIR_TO_DEPLOY_TO_ON_SERVER’

# Default value for linked_dirs is []
set :linked_dirs, fetch(:linked_dirs, []).push(‘web/uploads’, ‘vendor’, ‘runtime’)

# Default value for default_env is {}
# set :default_env, { path: “/opt/ruby/bin:$PATH” }

# Default value for keep_releases is 5
# set :keep_releases, 5

Rake::Task[”deploy:symlink:linked_dirs”].clear
Rake::Task[”deploy:symlink:linked_files”].clear
Rake::Task[”deploy:symlink:release”].clear

namespace :deploy do

after :restart, :clear_cache do
on roles(:app), in: :groups, limit: 3, wait: 10 do
# # Here we can do anything such as:
# within release_path do
# execute :rake, ‘cache:clear’
# end
end
end

namespace :symlink do
desc ‘Symlink release to current’
task :release do
on release_roles :all do
tmp_current_path = release_path.parent.join(current_path.basename)
execute :ln, ‘-s’, release_path.relative_path_from(current_path.dirname), tmp_current_path
execute :mv, tmp_current_path, current_path.parent
end
end

desc ‘Symlink files and directories from shared to release’
task :shared do
invoke ‘deploy:symlink:linked_files’
invoke ‘deploy:symlink:linked_dirs’
end

desc ‘Symlink linked directories’
task :linked_dirs do
next unless any? :linked_dirs
on release_roles :all do
execute :mkdir, ‘-p’, linked_dir_parents(release_path)

fetch(:linked_dirs).each do |dir|
target = release_path.join(dir)
source = shared_path.join(dir)
unless test “[ -L #{target} ]”
if test “[ -d #{target} ]”
execute :rm, ‘-rf’, target
end
execute :ln, ‘-s’, source.relative_path_from(target.dirname), target
end
end
end
end

desc ‘Symlink linked files’
task :linked_files do
next unless any? :linked_files
on release_roles :all do
execute :mkdir, ‘-p’, linked_file_dirs(release_path)

fetch(:linked_files).each do |file|
target = release_path.join(file)
source = shared_path.join(file)
unless test “[ -L #{target} ]”
if test “[ -f #{target} ]”
execute :rm, target
end
execute :ln, ‘-s’, source.relative_path_from(target.dirname), target
end
end
end
end
end

task :composer do
on roles(:app) do
within release_path do
execute “cd #{release_path} &amp;&amp; php-latest ~/composer.phar install”
end
end
end

task :setup do
on roles(:app) do
within release_path do
execute “cd #{release_path} &amp;&amp; php-latest yii.php setup”
# execute :php, “yii setup”
end
end
end

after :updated, “deploy:composer”
after :updated, “deploy:setup”

end
config/deploy/production.rb
server ‘closingtags.com’,
roles: %w{app},
branch: ‘master’,
ssh_options: {
user: ‘SSH_USER_NAME_HERE’,
keys: %w(~/.ssh/id_rsa),
# forward_agent: false,
auth_methods: %w(publickey)
# password: ‘please use keys’
}
Now, I’m no Ruby developer, so if my code could be cleaned up, which I know it can be, let me know. But let’s take a quick walk through with what we have here. Firstly, anything starting with # shows a commented line. I’ve removed most of mine, but left a few I thought might be helpful. You’ll notice the first three uncommented lines of the deployment file are just setting some variables for the configuration.
The fourth line, set :linked_dirs, is doing something really interesting. When Capistrano deploys my app, it creates a git repo on the server and will keep the last 5 versions. The linked_dirs variable is basically creating a symlink on my server, so that it doesn’t recreate those files every time. This was necessary for my uploads directory, which needs to be have the same location each time I deploy. If I created a new directory each time I deployed, users would get 404’d every time I deployed.
The next few segments actually contain a description so there isn’t much to say about those, other than they were necessary to deploy to MediaTemple’s GridServer. Most of the time, this stuff isn’t necessary, but I had a special case with our server.
task :composer installs all of my dependencies and task :setup runs a custom yii2 command that upgrades the database, if necessary.
Now like I said earlier, I’m using this to deploy a Yii2 app, but really, it could be used for anything. It’s mostly used to deploy Ruby applications, but there really isn’t anything stopping you from deploying something built WordPress or Laravel. If you have some suggestions on how I could streamline my process, let me know!

Categories
PHP Yii2

Yii2 Feedback Widget

I needed to get feedback directly from my users to me on a Yii2 web application. Most of the options were fairly expensive. After a lot of looking, I found a JavaScript plugin (https://github.com/ivoviz/feedback) that did some of what I needed but not all. So I developed a Yii2 widget with the intent of bundling it all into one package and maintaining it as just a side project. Well, I’ve basically built the Yii2 wrapper for the ivoviz/feedback JS plugin. It uses all of the same parameters as the original plugin, and currently only has one JS error (yay).
My plugin and all the documentation needed to use it can be found on GitHub! I’ve even included some sample controller code for getting the AJAX response handled.

Categories
PHP Security WordPress

Status Update + wp-class.php backdoor

It’s been a very long time since I’ve written anything, and I’m really sorry about that. This summer has been crazy, but I know that’s not an excuse. That being said, I have a new job now, so I’m not putting in as much time with WordPress as I’d like to. I’m working with a different framework (Yii2, still PHP) now and WordPress development may become something more like a hobby for me. I still have plans to develop some more plugins, but being realistic, those things might not happen until the cold winter falls and I’m stuck indoors for 9+ months. Such is life in the tundra of ND. Also, security and penetration testing have fallen on my radar so there may be more blog posts about things like that. Actually, this is a great post to lead into that, so let’s talk about security.
A long while back, I found another compromised site, and it being my job to clean it up, I had to do some dirty work by getting into a few files. While I was doing that, I found this little guy. It was so obfuscated that I almost just deleted it and left it at that, but I’m glad I didn’t. I cleaned it up, and made it legible so take a look at it.
This file, is pretty cool actually. It’s basically a backdoor to read, write, and delete anything on the file system. It has a file system browser built in, plus a few tools to execute code, and some others to analyze the system it’s on. Basically, once somebody gets this onto your system, they’re making their life easier to make your life harder. All of the things this file does, could be done with other tools, but how great is it to have one file do it all on the target system? Plus, if you’ve got a bot crawling known exploits on systems anyways, it’d be even easier to just have it drop this little devil on the target for you so you can come back later. It also helps that it was called wp-class.php (not a real WordPress file), because nobody would think to delete something that sounds that important.
Jesse, over at blackdoorsec.blogspot.com, did a nice write up on this file, and posted some comments on it line by line. I definitely recommend taking a look at his post. He’s much more thorough than I was here.

Categories
Plugins Themes WordPress

VVV

As far as development goes, it feels like if you aren’t using Vagrant, you aren’t doing it right. And if you’re doing WordPress development (themes, plugins, or even Core), you’re behind the curve if you haven’t started using VVV (Varying-Vagrant-Vagrants). VVV let’s you spin up another development instance relatively easily, but apparently, it can be even easier with vv (Variable VVV).
Damn, that’s a lot of V’s.
But seriously, this tool makes it even easier to create another development instance. If you haven’t checked it out already, I definitely recommend it. Use the command create to spin up another instance, and get a few questions about the kind of instance you want to create. This stuff is magical.

Categories
WordPress

You (and I) should be contributing to WordPress

I haven’t contributed to WordPress.
There. I said it. I’m already starting to feel a little better, knowing that my secret is out. I’m admitting it and getting it off my chest. Now, when I say I haven’t contributed to WordPress, I mean that I haven’t really worked on core because that’s what first comes to my mind. But there’s a twist.
You don’t have to contribute code.
There are so many different ways to contribute to WordPress and I learned just that at WordCamp Minneapolis 2015 from Nikhil Vimal (@TechVoltz), whose presentation can be found here.
Code
Obviously, you can still contribute to WordPress by writing code. If that’s something you’re interested in, you should check out https://make.wordpress.org/core/. There, you’ll find all of the information you would need to get started on creating bug reports, fixing bugs, adding documentation, creating patches, testing, etc. All of the good things that happen when developers come together, you can be apart of. They used to have an IRC channel, but now the core team has moved over to Slack for real-time conversations. Join in on that, and find out where you might be needed.
Mobile
WordPress also had a mobile app, so if you’re an iOS or Android developer, there is still a place for you to make some open-source contributions.
Accessibility
Everyone that has ever been involved with WordPress knows it has a bit of a reputation for not being as accessible as it could be. Making it more accessible, means that WordPress would be much easier to use for vision impaired individuals. Special tools exist to make using the internet easier for vision impaired individuals, but those tools need help. By developing for accessibility, WordPress can reach a wider audience, and give more people access to this powerful platform we all love so dearly.
Languages
English speaking people aren’t the only ones that use WordPress. It’s used all over the globe, and as such, it needs to be translated. If you can speak more than one language, you can help translate WordPress and spread the good word about it even farther.
Community
I’m writing this blog post because I attended a WordCamp. It was awesome, and I definitely recommend going to one if you get a chance. If there are none in your area, maybe you should try organizing one. It’s possible to get help with this undertaking as well. Or you could always just plan a meetup.
Support
In my personal opinion, this is probably one of the most important, and easiest ways to contribute to WordPress. By answering someone else’s questions, you can solve real problems and see real results, almost immediately. Without the support forums, WordPress wouldn’t be what it is today. So go make an account at wordpress.org and start helping people.
Etc.
I could probably make one blog post a day for the next two months about different ways that you could contribute to WordPress, but you probably don’t want to read that. Really, what you need to do, is just participate. In any and every way you can think of. Build themes, make plugins, answer questions, document code, blog about WordPress, chat in the Slack channel, go to WordCamps and volunteer, etc, etc. There are just so many ways that @TechVoltz and I can’t cover them all. Just get out there, and do something.

Categories
PHP Plugins WordPress

Writing (More) Secure Plugins

Over the past weekend, I had the pleasure of attending WordCamp Minneapolis 2015 and it was a blast. You can check out my twitter feed (@awebdevguy) for some pictures of all the swag I scored. I basically got a new wardrobe from it, so tickets are definitely worth it.
But anyways, back to what this post is actually about.
Plugins are great. WordPress is great. Sometimes though, developers make mistakes. If you’ve followed my blog at all, you’d know that I just created a plugin recently, and the entire time, all I could think about was security. Recently, some big security issues have come up in WordPress and some big name plugins (Yoast SEO, Gravity Forms, etc). The thing that’s scary about this, is that these guys are the pros. Even the pros make mistakes, so how likely is it for an amateur developer like me to slip up? Probably much more. So while at WordCamp, the very first talk that caught my eye was from John Havlik titled Writing (More) Secure Plugins. Obviously, I would like to know how to do that. Every WordPress developer should, and John does an excellent job of explaining not only why you should care, but how you can remedy the most common issues of security. His presentation can be found here so definitely give that a glance.

WordPress Is A Big Fat Target
That’s one of the problems of being king. It’s not that WordPress is inherently insecure. It’s just that it has such a large market share. Think of it like the conversation that inevitably comes up when discussing PCs vs Macs. Someone always says “Macs don’t get viruses.” which is blatantly false. They are just as prone to viruses as PCs but PCs just make for a bigger target. WordPress is the same way. It is estimated to make up ~23.8% of all sites on the web! Why wouldn’t you target that as a hacker?
And since there are so many WordPress sites, it’s not uncommon to find poorly developed plugins and themes. That’s why we, as developers, have a responsibility to make our plugins more secure. It isn’t entirely the developers fault though. PHP has to take some of the blame. PHP is very dynamic and weakly typed. Variables can be created on the fly, and you can’t really prevent a variable from suddenly becoming a string. Strings open us up to vulnerabilities with our HTML output, form input, and database queries.
XSS
XSS (cross-site scripting) is probably one of the most common and easy ways to get into a site. It looks like this:
<a href=”<?php echo $_SERVER[‘REQUEST_URI’];?>”><?php echo $title;?></a>
The issue here is the $_SERVER[] request being echo’d out immediately. If someone were to discover this loophole, they could drop whatever code the wanted in the URL like so:
http://my-wp-site.com/?”><script>alert(‘Porkchop Sandwiches!’);</script>
Now if someone really knows their way around WordPress or your site, they could inject any number of things there, and execute their own code on your server. So how do you prevent this? You almost have to stop anytime you’re accepting input from the client, and make sure it’s validated. Check that it lands between an expected range, that it is a certain type, and only allow specific characters. This will all help protect your plugin. John suggests that you sanitize and validate your inputs as early as possible. Using functions like intval(), absint(), and isset() will help against invalid types and values. Functions like  sanitize_email(), sanitize_text_field(), and sanitize_file_name() will clean your inputs, but be warned, they might change values that your users have submitted. Be sure to check out John’s presentation for more examples.
SQLi
SQLi (SQL injection) is nasty. We’re talking, all of your posts, comments, data, tables, etc. gone in one fell swoop. If you’re developing a WordPress plugin, use the WordPress API. The functionality is there, and most of the leg work is already done for you. Plus, it’s more secure. If you do have to access the database directly, WordPress has you covered there too. By using the $wpdb object, you get access to $wpdb::insert(), $wpdb::update(), $wpdb::delete(), and $wpdb::replace(). Those should be able to handle just about everything database related. If you are writing SQL, then use $wpdb::prepare() to make sure your query is safe to run.
When it comes to getting data back from your database, you can’t trust it. Data needs to be escaped as late as possible, cause who knows what our users entered in there. By using esc_html(), esc_attr(), esc_url(), and esc_js() we can prevent more problems.
Unsafe:
<a href=”<?php echo add_query_arg( ‘foo’, ‘bar’ ); ?>”><?php echo $title;?></a>
Safe:
<a href=”<?php echo esc_url( add_query_arg( ‘foo’, ‘bar’ ) ); ?>”>
<?php echo esc_html( $title ); ?>
</a>
CSRF
Cross-Site Request Forgery is a combination of hacking and social engineering. Basically, by tricking someone who is already logged into your site to click on a malicious link, an attacker can gain that user’s access. That link could be embedded in a comment or an email. To prevent this from happening to your users, use a nonce. Nonces are one time use tokens that are used for protecting links that execute an action. For instance, if I want to create a link that deletes a user, I don’t want that link to be available to anyone. We want it protected so that it can’t be emailed off and clicked by another user. Nonce’s look like this:
wp_nonce_url( $actionurl, $action, $name )
$actionurl is the URL we want to protect, $action is our action name, and $name is our nonce name. At this point, I’d recommend checking out John’s presentation again, just because he does such a good job of explaining nonces. Also, read up on the WordPress Codex.
So to sum this up, don’t trust external inputs (including the database), validate early, and escape late. Those are some of the big things to keep in mind when developing a plugin. It’s also a good idea to never trust the contents of $_SERVER, as it could be manipulated by the client. And did you know is_admin() doesn’t check if the user is an admin? It checks to see if the dashboard or administration panel is attempting to display. So don’t try locking your admin specific features down with that. Aside from that, stay away from the PHP functions eval() and assert(). You’re just asking for trouble by using those.

Categories
WordPress

WordCamp Minneapolis

I know that it’s been a while since I’ve written anything, and I really don’t have a good excuse, but I promise that I’ll have some good content coming soon because tomorrow, I’ll be attending WordCamp Minneapolis. WordCamp is a great place to meet other WordPress developers, and learn about a ton of different WordPress related stuff. To be honest, I don’t really know how else to describe it. I’ll try and take notes, and relay back all sorts of useful developer related information here. Stay tuned!