closingtags </> – Page 6 – web development and then some
Categories
Linux Security Server

Storj-CLI Update + Shortcuts

I hate typing the same commands over and over into the terminal. I hate it so much that every time I have CLI deja-vu, the first thing I say to myself is “How can I automate this?” Usually, it’s as simple as adding a quick alias to my `~/.bash_aliases` file but this time I did that along with throwing together a quick bash script. If you ever install the storjshare client on an Ubuntu or Debian based machine, putting these aliases and script on your system might help you with a few of the commands I found myself typing frequently.
Storjshare Aliases

https://gist.github.com/Dilden/ec379a64532ec5e1d36586fd35ed0101

If these helped you out at all, let me know by starring the repo or leaving a comment here.
UPDATE!Something that bothered me about the storjshare daemon was that it didn’t startup when the system did. Depending on how you look at this, it can be a good thing. Fewer system resources consumed during startup is nice, but if it’s the only thing you’re hosting on your machine and you’re striving for up-time, then it’s a necessity. To get around this quickly and easily, you can update the cron jobs to fire on startup.
@reboot su – YOUR_STORJ_USER_HERE -c “storjshare daemon && storjshare start -c /home/YOUR_STORJ_USER_HERE/.config/storjshare/configs/YOUR_STORJ_NODE_ID.json”
This will likely need to be put in your root user’s cron which you can gain access to with the command `crontab -e` (while logged in as root).

Categories
Linux Security Server WordPress

WordPress Backup Bash Script

I threw together a simple bash script to be run via cron jobs that will backup an entire WordPress site. Technically, it will work for a lot more than that assuming the site you’re backing up has a single directory to be backed up and a MySQL/MariaDB database. It’s a fairly simple script and it is easy to expand to work with multiple directories. Just take a look at the source for yourself!
To use, fill in the information at the top of the script (site name, database name, database user + password, path to site, and backup path), upload the script to `/etc/cron.daily/` on your server and you’ll be good to go!
Take note of the `SITE_PATH` variable at the top of the script. For whatever reason, there needs to be a space between the first “/” and the rest of the path.

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
Linux Server

Custom LXC Container Templates in Proxmox 5.0

If you’re at all into homelabbing, are a server administrator, or have an interest virtualization, you’ve probably heard of Proxmox. In my case, I just love to tinker with my homelab. One of the things I love about Proxmox, is how quickly I can get a containerized server up and running. All I need to do is open the web interface, click ‘Create CT’, fill out a couple of fields, and it’s done. It takes less than a minute to get an entirely new server on my network. The downside? I have to reinstall various services like Apache/nginx, PHP, and MySQL/MariaDB every time I spin up a new container. Now, I know what you’re thinking:
Couldn’t you just use a turnkey template provided by Proxmox with everything pre-installed?
And you’re right, I could do that but I want to have complete control over these containers. I want to know everything that’s installed them. So what’s next best option?
Create one container with everything that I regularly need, and use that as a template. It sounds intimidating, but it’s so ridiculously simple that I’m concerned with how short this blog post will be. Here’s what you do:

Create a new container using the whichever distro you prefer. I went with Ubuntu 16.04
Start that container
SSH into that container (or you can SSH into Proxmox and use the command pct enter <container ID> to access your new container)
Install all of the services that you need. Things like nginx, PHP 7, MariaDB, Git, and the Let’s Encrypt Certbot could be useful for web dev projects.
Verify everything you need is working with this container.
Exit your container and shut it down.
In the Proxmox web GUI under Server View, select your container and navigate to Backup
Create a new backup but be sure to select GZIP compression
After your backup finishes, open a terminal to your Proxmox environment (not the container)
Find the backup you just made under /var/lib/vz/dump/<backup-name>.tar.gz and copy it to /var/lib/vz/template/cache/<new-backup-name>.tar.gz

You’ve just created a new LXC template for use with your Proxmox 5.0 environment. Now anytime you want to spin up another container, you can just select that as your template! Also, the container that you previously created is still valid so feel free to use that as well.

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