PHP – closingtags </>
Categories
HTML5 Javascript Linux PHP Programming Python

Remote Debugging Web Apps on iOS from Linux

Debugging #WebApps on #iOS is a super easy if you have a Macbook. If you’re on #Linux, it’s not. This post documents how I got around that limitation by using #OpenSource utilties and tools.

Categories
Automation CSS HTML5 Javascript Linux Mobile PHP Programming Security Server Svelte WordPress

BUY! BUY! BUY!

I’ve been writing on this blog for nearly 9 years and I’ve learned so much since I started. The style and the content have come a long ways and I cringe every time I read old posts thoroughly enjoy seeing how I’ve grown as a developer. I’ve interacted with people that I never would have had the chance to otherwise. It’s been a wonderful learning experience.
While my intentions have always been for this site to exist as a sort of journal/wiki/knowledgebase/playground, I’ve always secretly wanted to become a billionaire tech influencer. And now you can help me achieve that goal by buying my merchandise!
BUY! BUY! BUY!
By purchasing merchandise from my shop, you can support this site financially, by giving me real money that you’ve earned for your “hard work.” While donations are always appreciated, I understand that you may want something in return; something tangible, something you can see and smell, something to keep you comfortable while you cry yourself to sleep. And since nobody actually donates to strangers on the internet, I opened a shop.

All of the designs are completely original and there are many, many more to come. The pricing is affordable for all budgets and will only expand with more options. Be sure to check posts here often by following the social media channels or the RSS feed. There may just be coupon codes hidden in future posts 😉.
So if you’re ready to showcase the fact that you know what HTML is and like the look of monospaced fonts, then you should go checkout the new closingtags merch shop. Once you’ve got the closingtags swag (closingswag 🤔), be prepared to have people you barely know ask if you “work with computers” or to tell you about their genius new app idea.
Don’t forget to buy, buy, buy!

Categories
PHP Programming

Generate thumbnails for PDFs

As I’ve noted a previous post, ImageMagick is an incredibly powerful tool for image manipulation. While it’s handy for image compression, it can also be used for so many more things, like processing uploaded files. Whether you want to crop all images to the same dimensions, or invert their orientation, Imagick can manage it. I’ve found it particularly useful for generating a thumbnail that can be used as a preview for PDFs uploaded to my application. Here’s some code that does just that:
// generates a jpg thumbnail for a PDF
// returns true on success
// returns false on failure
private function generateThumbnail($filePathNoExt = ”) {
try {
$img = new \Imagick($filePathNoExt . ‘.pdf[0]’);
$img->scaleImage(200, 0);
$img->setImageFormat(‘jpg’);
$img = $img->flattenImages();
$img->writeImage($filePathNoExt . ‘.jpg’);

$img->clear();
$img->destroy();
return true;
} catch (\ImagickException $e) {
// thumbnail generation failed
echo $e;
}
return false;
}

This code is pretty self-explanatory. After the PDF has been uploaded, this function is called with the path to the PDF provided as the parameter (minus the extension ‘.pdf’). A new Imagick object is instantiated and some settings are configured before writing the file. The flattenImages() method is used to merge all layers within the PDF for a consistent thumbnail. If you wished to have the thumbnail format as a PNG or with a different size, those parameters can be adjusted as need. At the end of it all, we return a true if the thumbnail was successfully written or a false if there was an error. The thumbnail can be found in the same directory as the PDF, with the same file name.
Then, show the thumbnail inside a link to your PDF like so:
<a href=”/path/to/file.pdf” title=”Open Attachment”>
<img src=”/path/to/file.jpg”>
</a>
For further reading, check out this article from BinaryTides that helped me along the way.

Categories
PHP Programming Security WordPress

I Gave a Talk

I recently had the opportunity to give a presentation in front of a live audience with real human beings at the WP Omaha meetup group. For my first technical talk, I thought things went pretty well. There were some minor hiccups with my connection to the live stream cutting out (and poor audio quality), but most of it was the talk was recorded and uploaded to the WP Omaha YouTube page.
https://www.youtube.com/watch?v=Scs_0gaVXoA&t=85
The talk itself was a security talk aimed at developers where we hacked a site installed on my computer in real time, analyzed the vulnerability within the code, and discussed how this could be prevented in the future. If you’re interested, the presentation can be downloaded here.

Categories
Linux PHP Server

Deployments w/Deployer

In keeping with my previous posts discussing deployments with Git and Capistrano, I thought it appropriate to mention the latest tool I’ve been using to automate shipping code; Deployer. Since discovering Deployer, I’ve dropped Capistrano and git deployments. Those tools were fine, and if you’re developing with Ruby, I’d encourage you to stick with Capistrano but since I’m doing most of my development with PHP, it only makes sense to use something that was made for PHP and can be easily installed alongside all of my other dependencies with Composer.
So what do you have to do to get started deploying your PHP code quickly, easily, and securely? Let’s dig in.
Installation
There are a few ways to handle this: 1) install Deployer globally with a curl/wget request, 2) install using composer on a per project basis, or 3) install globally with composer. If you install globally, Deployer will function in the same way a global composer install works. That is, you’ll download a .phar archive, move that .phar archive into a directory where it can be run that works with your environment’s PATH, and make that it executable.
curl -LO https://deployer.org/deployer.pharmv deployer.phar /usr/local/bin/dep
chmod +x /usr/local/bin/dep
That’s all you have to do for a global install of Deployer. Otherwise, you can install with one simple line using composer.
composer require deployer/deployer for per project basis or composer global require deployer/deployer for the global composer install.
If you did the curl request, Deployer should work using the command “dep.” If using composer, it’ll probably be “php vendor/bin/dep” but this can be corrected for by creating a quick alias in your system’s .bashrc file that looks like so:
alias dep=’php vendor/bin/dep’
Usage
Once we have Deployer installed, we can use it by navigating to our project’s root directory. In there, type dep init to create a deploy.php file. We’re going to modify ours so that it looks similar to the one below. Feel free to use as needed.
<?php
namespace Deployer;

require ‘recipe/common.php’;

// Project name
set(‘application’, ‘PROJECT_NAME_HERE’);

// Project repository
set(‘repository’, ‘YOUR_GIT_REPO_HERE’);

// [Optional] Allocate tty for git clone. Default value is false.
set(‘git_tty’, true);

// Shared files/dirs between deployments
set(‘shared_files’, []);
set(‘shared_dirs’, [’vendor’]);
set(‘keep_releases’, 5);

// Writable dirs by web server
set(‘writable_dirs’, []);

// Hosts
// live is the alias of the server, this would come in handy
// when specifying which server to deploy if I had another to include

host(‘live’)
-&gt;hostname(‘DEPLOY_TO_THIS_SERVER’)
-&gt;user(‘USER_TO_DEPLOY_AS’)
-&gt;identityFile(‘~/.ssh/id_rsa’)
-&gt;set(‘deploy_path’, ‘PATH_TO_DEPLOY_TO’)
-&gt;set(‘composer_options’, ‘install –no-dev’)
-&gt;set(‘branch’, ‘master’);

// Tasks

// This is sample task that I’ve included to show how simple
// it is to customize your deployer configuration. For now,
// it just needs to be declared and we’ll call it later.

// Runs database migrations using a package called Phinx (post to come later)
desc(‘Phinx DB migrations’);
task(‘deploy:migrate’, function () {
run(‘cd {{release_path}} &amp;&amp; php vendor/bin/phinx migrate -e live’);
});

desc(‘Deploy your project’);
task(‘deploy’, [
‘deploy:info’,
‘deploy:prepare’,
‘deploy:lock’,
‘deploy:release’,
‘deploy:update_code’,
‘deploy:shared’,
‘deploy:writable’,
‘deploy:vendors’,
‘deploy:migrate’,
‘deploy:clear_paths’,
‘deploy:symlink’,
‘deploy:unlock’,
‘cleanup’,
‘success’
]);

// [Optional] If deploy fails automatically unlock.
after(‘deploy:failed’, ‘deploy:unlock’);
This file should be pretty self explanatory so I won’t go through it line by line but notice there are a couple of things that should be pointed out. Firstly, the shared directories are useful so that on my production server, I don’t have 5 different vendor folders that need to be installed every time I deploy. Next, I’ve specified an alias for my server and called it live. That makes running the deployment command very simple and gives me the option to specify which host to deploy to, should I need to add another host. Thirdly, I’ve specified that for this host live, I should run composer with the –no-dev flag so that dependencies like Deployer aren’t installed. And finally, my custom task deploy:migrate is called after the deploy:vendors. This doesn’t necessarily need to be called here, but it does need to be called after deploy:update_code as that is the task that will pull my code from the git repo, and I don’t want to be running and older version of the migrations.
Launch!
Now what? Deploy! Just kidding, there is actually one other thing you should check before you deploy. Some services like Bitbucket, require that your production server can pull down your git repo. You may need to create an SSH key on your server and add the public key to your git repo’s access keys. Check your repo’s settings to make sure your server can pull code from there.
Now, you can launch and it’s as easy as dep deploy live. Assuming you’ve pushed all of your code to your repo, you should see the latest version running on your server!

Categories
PHP Security

I’m back!

After deciding not to renew hosting with my previous provider and that hosting expiring in the middle of a very turbulent time for me, closingtags.com is back online!

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
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.