List Unique IPs that Accessed Linux Server

IPs from Apache access logs…

$ cat ./access_log | awk '{print $1}' | sort -n | uniq -c | sort -nr | head -20

IPs that logged into server (via SSH, etc)…

$ last

 

MAMP Pro Setup

Install

Download MAMP Pro and Install

Note: all MAMP Pro specific configuration files are in /Library/Application Support/appsolute/MAMP PRO/

Configure PHP Preferences

  1. Click the “PHP” section
  2. Set default PHP version as desired
  3. Enable “Make this version available on the command line”
  4. Set “mode” to “Individual PHP version…”
  5. Enable the “Xdebug” extension
  6. Enable “Log error ‘to screen'”

Setup Virtual Hosts

Click the “Hosts” section and add hosts as needed.

Create 2 host records for each site (http and https).  Hold down the ALT key when pressing the plus sign “+”  to bypass the popup when creating the second host.  They will show up in red and you will get a warning that you already have a host with that name, but that’s okay.

Update Command Line Services

These steps will allow you to run the MAMP services like apachectl and mysql from the command line using the MAMP versions (instead of the ones that come with your Mac) without having to put the full directory path to these commands.

  1. Edit your .bash_profile file… (you will need to do this for each user account on your Mac)
    vi ~/.bash_profile
  2. Add the following somewhere in that file…
    # MAMP
    export PATH=/Applications/MAMP/Library/bin:$PATH
    export PATH=/Applications/MAMP/bin/php/php5.6.30/bin:$PATH
  3. After making the change just close Terminal and reopen.

Additional information about this change…

Report SPAM to SpamCop Automatically (almost) on Mac OSX

If you’re email provider uses the SpamCop RLB to help block SPAM coming into your account then you can use the steps below to more easily report SPAM messages you receive and help reduce it.  Setup is a little cumbersome initially, but should be worth it in the end.

In my experience, SpamCop reporting really does work.  I went from getting 500-1,000 SPAM messages per day down to less than a dozen, if that.  It only took a couple days of serious reporting before I started to see a huge difference.

Prerequisites: This tutorial assumes you are using Apple Mail and have Firefox installed.

Setup Steps

1) Create SpamCop Account

Register for a SpamCop account.  Once you complete the registration process, you will be provided an email address that you can use to report your SPAM.  It will probably look something like submit._________@spam.spamcop.net with an alphanumeric string in place of the “_______”.

NOTE: We will need to put your SpamCop username and password in a file on your computer so it’s best to give it a unique password that you don’t use on any other account since this file will be saved in plaintext.

2) Save Python Script

Lucky you, I already did the hard work of writing a Selenium script in Python for you to run.  So just create the python script below called “spamcop-finalize-report.py” on your computer.  For this tutorial, we will assume you created a “python” subfolder in your main ~/Documents directory for this file.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep 

# Open SpamCop
driver = webdriver.Firefox()
driver.get("https://www.spamcop.net/mcgi?action=loginform;returnurl=%2F")

# Login
driver.find_element_by_name("username").send_keys("YOUR_USERNAME")
driver.find_element_by_name("password").send_keys("YOUR_PASSWORD")
driver.find_element_by_name("password").send_keys(Keys.RETURN)

# Report
for x in range(0, 50):
    try:
        print(x+1)
        driver.find_element_by_link_text("Report Now").click()
        subject_wrapper = driver.find_element_by_xpath('//font[@size="2" and @face="courier"]')
        subject = subject_wrapper.find_element_by_xpath('.//strong').text
        driver.find_element_by_xpath('//input[@type="submit" and @value="Send Spam Report(s) Now"]').click()
        print('SPAM Reported: {0}'.format(subject))
        x += 1
        sleep(randint(0,5))
    except:
        try:
            driver.find_element_by_link_text("Report Now")
            continue
        except: 
            print("No more spam to report")
            break        

driver.quit()

Change the text YOUR_USERNAME and YOUR_PASSWORD with the SpamCop username and password created during step #1.

3) Install Selenium WebDriver

Mac OSX already has python built in as well as a package manager called “easy_install” so to complete this step, all you need to do is open up Terminal and run the following command.

sudo easy_install selenium

FWIW… Selenium is what will allow our Python script to automatically open up the browser and finalize the SpamCop report without you having to log in and do it.

If you already have selenium installed or need to update it, just run the following command. You may need this if Firefox releases and update that breaks your selenium script (which they like to do every now and then).

sudo easy_install --upgrade selenium

4) Setup AppleScripts

We will need two AppleScripts to automate reporting.  Download each file, extract, and save the .scpt files in the root “/Library/Scripts/Mail Scripts/” directory (if you don’t already have a “Mail Scripts” directory, just create one).

5) Setup Keyboard Shortcuts for the AppleScripts

To more easy run these scripts we can setup keyboard shortcuts by downloading a little program call “Fast Scripts”.

  • Download Fast Scripts and Install
  • Open up the Fast Scripts “Preferences”
  • Click the “Script Shortcuts” tab
    Screenshot of Fast Scripts Preferences for Keyboard Shortcuts
  • Expand “/Library/Scripts” and then “Mail Scripts” and you should now see your two Apple Script files
  • Double click on each of your scripts and then press the keyboard shortcut you want to use.  In my case I used…
    • Report_to_SpamCop: Ctrl + Cmd + R
    • Finalize_Report_to_SpamCop: Ctrl + Opt + Cmd + R

Actually Reporting SPAM

Now that you have everything setup, to actually report your SPAM, here are the steps…

  • When in your Mail program, highlight the messages you want to report as SPAM
  • Press Ctrl+Cmd+R (the shortcut you set up for your Report_to_SpamCop script)
  • Wait for SpamCop to email you back with a message like “[SpamCop] has accepted X emails for processing”
  • Press Ctrl+Opt+Cmd+R (the shortcut you set up for your Finalize_Report_to_SpamCop script)

Personally I like to mark all my SPAM as Junk first in Mail then go through my Junk folder to report it.  Once done you can just use the keyboard shortcut Opt+Cmd+J to erase all the mail in your Junk folder.

Important Notes

  • Emailed reports to SpamCop have a maximum size and attachment count.  The most common one you will hit is the max size of 50 KB.  So when you are reporting multiple emails, just tally up the total of each email and try and keep it under 50 KB for each report).  Per SpamCop…

    You may attach multiple spams to a single submission. You should not exceed 20 spams attached to a submission. The maximum size for the overall submission must not exceed 50 KB.

  • Be careful to only report actual SPAM messages.  SpamCop is a great tool for helping cut down your SPAM, but if you report messages that are not SPAM you could lose your SpamCop account as well as blocking actual messages from getting to recipients for anyone in the world using SpamCop.  This is also why I don’t recommend fully automating your reporting because you do not want to accidentally report the wrong messages.  Use with caution.

Prevent Duplicate Form Submission with jQuery Validate

To prevent users from accidentally submitting your form multiple times you can add a bit of javascript to track if the form has been submitted and prevent further submits. If you are using the jQuery Validate plugin you can do this via submitHandler.

$('form.your-form').validate({
	rules: {
		name: 'required',
		email: {
			required: true,
			email: true
		}
	},
	submitHandler: function (form) {
		// Prevent double submission
		if (!this.beenSubmitted) {
			this.beenSubmitted = true;
			form.submit();
		}
	}
});

Transfer Domain from eNom to ResellerClub

These are the steps you can follow to transfer your client’s domains from your eNom account to ResellerClub.

eNom

  • Go to Domains > My Domains
  • Click on the domain you want to transfer.
  • Edit “Contact Information” to use an email that you can access (this is temporary for verification purposes so you won’t have to rely on your client to verify the transfer) (optional)
  • Go to “General Settings” on the domain
  • Disable “Registrar Lock” and save
  • Request the EPP Code by clicking the “Email Auth Info to Registrant” link

ResellerClub

  • Go to Products > Domain Registration > Transfer
  • Login with the customer account to which you want to assign the domain
  • Enter the domain name and the EPP Code you got from the email previously
  • Select to activate the order but don’t create the invoice (optional) and click “Process Order(s)”
    Reseller Club - Process Transfer
  • Once order is successful, click “continue managing order” to be taken to the control panel page to manage your order.
  • Wait for email to authorize as the domain administrator.  Until then you will see this screen.
    ResellerClub - Transfer Pending Domain Administrator Approval
  • Once approved you will need to wait for the current registrar to approve the transfer.  You should have received an email after approving the last step that reads…

    “This Request has been sent to the Registry. This Request will be processed within the next 5 days. The current Domain holder may receive an email from the Current Registrar to approve this Renewal Request. Please follow the steps highlighted in that email immediately in order to process this Renewal Request.”

    If you use a host like HostGator you may need to wait up to 5 days.  Some companies may allow you requesting that they approve the transfer more quickly in which case you can contact them and request that they approve it.  If not you just need to sit back and wait and follow any instructions if you receive any from your current registrar.  Until then your control panel for the domain at Reseller Club will look like this…
    ResellerClub - Transfer Pending Registrar Approval

 

Share Mac Mail Accounts Between 2 Users

You can set up your Mac so users can share the same main Mail directory by following the steps below.

Copy Mail to Shared Directory

Select which user’s Mail setup you want to use as the basis for all other accounts then copy their Mail directory to the Shared users folder.

Note: This tutorial uses the username “userone” for the primary user (whose email you are using as the basis of your shared directory) and “usertwo” for a secondary user who will also be accessing the shared mail directory.

Open Terminal and enter…

sudo cp -vR /Users/userone/Library/Mail/ /Users/Shared/Mail/

Set Permissions

Set the file permissions so all users can access them along with all new files that may be added.

sudo chown -R userone:wheel /Users/Shared/Mail/
sudo chmod -R +a "wheel allow list,add_file,search,add_subdirectory,delete_child,readattr,writeattr,readextattr,writeextattr,readsecurity,file_inherit,directory_inherit" /Users/Shared/Mail/

Backup and Create Symbolic Link

Backup each users current mail folder and then set up symbolic links to the new shared mail folder. (Note: there is no trailing slash after the symbolic link declaration)

sudo mv /Users/usertwo/Library/Mail/ /Users/usertwo/Library/Mail-BAK/
sudo ln -s /Users/Shared/Mail/ /Users/usertwo/Library/Mail

Test and Cleanup

Test by opening up Mail.app for usertwo and verify it’s working as you expect. If so repeat the two commands above for all other users that will share that Mail folder (including userone).

After you have set it all up and used it a bit you can go back in and clean up all the backed up mail folders (repeat for all users). I recommend waiting a couple days just in case you run into any bugs and need to revert. Leaving the backed up folders there won’t hurt anything aside from taking up unnecessary harddrive space.

sudo rm -rf /Users/usertwo/Library/Mail-BAK/

Rebuild Search Indexes

You will likely also want to rebuild your indexes. The most efficient way to do so is to go in and remove your index files.

rm -rf /Users/Shared/Mail/V2/MailData/Envelope\ Index*

Next time you open Mail it will tell you it needs to import your messages. Press “continue” and wait for it to complete. Once done you should be back up and running.

Use Mandrill to Send Mail on Mac Localhost via Postfix

If sending mail via your localhost is unreliable or not working, try setting up postfix to use an SMTP account through Mandrill.  You can essentially use any SMTP account, but Mandrill has nice features that allow better monitoring of messages and if they are being delivered.

Edit the postfix config file.

sudo vi /etc/postfix/main.cf

Add the following settings to the very bottom of the main.cf file.

# Mandrill SMTP
relayhost = [smtp.mandrillapp.com]:587
# Enable SASL Authentication
smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options = noanonymous
smtp_sasl_mechanism_filter = plain
# Enable TLS (SSL)
smtp_use_tls = yes

Verify the following three variables are set correctly in the main.cf file (these may appear anywhere in your file).

mydomain_fallback = localhost
mail_owner = _postfix
setgid_group = _postdrop

Set SASL login credentials by editing the password file.

sudo vi /etc/postfix/sasl_passwd

Enter your host, username, and password in the following format.

[smtp.mandrillapp.com]:587 your_mandrill_username@example.com:y0Ur_passw0rD

Create the postfix lookup table from the sasl_passwd file. This will generate the file sasl_passwd.db. Note that anytime you edit the sasl_passwd file you will need to run this command.

$ sudo postmap hash:/etc/postfix/sasl_passwd

Restart postfix.

sudo postfix reload

Send a Test Message

$ date | mail -s testing you@example.com

Additional Commands

You may need to run these to check on the status of postfix.

$ sudo postfix status         # check if postfix is running
$ sudo postfix start          # start postfix
$ mailq                       # check mail queue
$ sudo postfix flush          # force mail in queue to send
$ tail -f /var/log/mail.log   # monitor mail logs

Filter by Multiple Taxonomies with SEO-Friendly URLs in WordPress

/**
 * Add rewrite for new query vars
 *
 * @return array
 */
function fd_add_rewrite_rules( $aRules ) {
	$new1 = array( 'plant-group/(.+?)/genus/(.+?)/page/?([0-9]{1,})/?$' => 'index.php?fdplt_plant_group=$matches[1]&fdplt_genus=$matches[2]&paged=$matches[3]' );
	$new2 = array( 'plant-group/(.+?)/genus/(.+?)/?$' => 'index.php?fdplt_plant_group=$matches[1]&fdplt_genus=$matches[2]' );
	$aRules = $new1 + $new2 + $aRules;

	return $aRules;
}
add_filter( 'rewrite_rules_array', 'fd_add_rewrite_rules' );

Note: The rule with pagination needs to come first otherwise it will use the non-page rewrite rule.

Extensions for Testing

These extensions are helpful for testing during development of your rewrites.  Once you have completed development and everything is rewriting as desired these extensions can be removed.

Monkeyman Rewrite Analyzer

Monkeyman Rewrite Analyzer allows you to enter your proposed URL and it will highlight the related rewrite rule that will be used. Note: As of this writing, the plugin hasn’t been updated in a while, but it still works like a charm.

Rewrite Rules Inspector

Rewrite Rules Inspector shows you all of your current rewrite rules and lets your easily “Flush Rules” to pick up any of your new changes as you edit them in your code. Note: Rewrite rules are cached and only updated when a flush rules command is run.

Filtering on a Custom Variable

If you are using a new custom variable that is not already tracked by the build in WordPress query_vars you will need to add it.

/**
 * Tell WordPress to track a new query variables
 *
 * @return array
 */
public function fd_add_query_vars( $aVars ) {
    $aVars[] = "my_custom_var";
    return $aVars;
}
add_filter( 'query_vars', 'fd_add_query_vars' );

Create WordPress Admin User with MySQL

These commands let you quickly add a new administrator user account in WordPress using MySQL. Just replace the variables at the beginning with the values you want to use and run it.

-- Set user variables
SET @USERNAME = '<USERNAME>';
SET @PASSWORD = '<PASSWORD>';
SET @DISPLAY_NAME = '<NAME>';
SET @EMAIL = '<EMAIL>';
SET @URL = '<URL>';

-- Add new user
INSERT INTO `wp_users`
	(`user_login`, `user_pass`, `user_nicename`, `user_email`, `user_url`, `user_registered`, `display_name`)
VALUES
	(@USERNAME, MD5(@PASSWORD), @DISPLAY_NAME, @EMAIL, @URL, NOW(), @DISPLAY_NAME);

-- Get new user ID
SELECT @NEW_ID:=ID FROM `wp_users` WHERE `user_email` = @EMAIL;

-- Add Capabilities and User Level
INSERT INTO `wp_usermeta`
	(`user_id`, `meta_key`, `meta_value`)
VALUES
	(@NEW_ID, 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}'),
	(@NEW_ID, 'wp_user_level', '10');

NOTE: You will need to replace the “wp_” in the table names with your prefix if yours is different.

Dump & Import a MySQL Database

The below statements assume some options are being used such as –add-drop-table, –add-locks and gzip compression.  These are optional.

Dump Database

mysqldump --single-transaction --quick --add-drop-table --add-locks -u <USERNAME> -p -h <HOST> <DB_NAME> | gzip -9 > <BACKUP_FILENAME>-$(date +"%Y%m%d").sql.gz

NOTES:

  • –single-transaction and –quick are added to prevent taking down a site when dumping a large DB (thanks to this post)

Import Database

gunzip < <BACKUP_FILE.sql.gz> | mysql -u <USERNAME> -p -h <HOST> <DB_NAME> < <BACKUP_FILE.sql>

View Your Progress

You can run the commands below to use pv (Pipe Viewer) to watch your progress like this…

15.1MiB 0:01:01 [   0 B/s] [========>                          ] 18% ETA 0:12:26

Dump

mysqldump --single-transaction --quick --add-drop-table --add-locks -u <USERNAME> -p <DB_NAME> | pv | gzip -9 > <BACKUP_FILENAME>-$(date +"%Y%m%d").sql.gz

Import

pv <BACKUP_FILE.sql.gz> | gunzip | mysql -u <USERNAME> -p <DB_NAME> < <BACKUP_FILE.sql>

Don’t have pv?  You can install with

yum install pv

or with MacPorts

sudo port install pv

Create Secure Dump-only MySQL User

This is optional, but will add an extra layer of security when dump-only privileges are needed.  To dump a MySQL database the user will need the following minimum privileges…

  • SELECT
  • SHOW VIEW
  • TRIGGER
  • LOCK TABLES

Additional may be required depending on the options you select.  More details on the mysqldump Reference Page.