Getting GitHub latest release URL

Do you need Download Latest Version button? Try follow PHP code:

function getLatestTagUrl($repository, $default = 'master') {
    $file = @json_decode(@file_get_contents("https://api.github.com/repos/$repository/tags", false,
        stream_context_create(['http' => ['header' => "User-Agent: Vestibulum\r\n"]])
    ));
    return sprintf("https://github.com/$repository/archive/%s.zip", $file ? reset($file)->name : $default);
}

echo getLatestTagUrl('sphido/sphido');
// will return https://github.com/sphido/sphido/archive/v0.2.1.zip

#github#PHP#2014

AngularJS $http not sending X-Requested-With header

Angular $http isn’t appending the header X-Requested-With = XMLHttpRequest since Angular 1.3.0.

X-Requested-With header is rarely used in practice and by using it all the time we are riggering preflight checks for crossdomain requests. See commit message

That can cause some problems on PHP side. If you need somehow differentiate XHR and common requests. For example Zend Framework and lot of others PHP frameworks use follow code:

function isXmlHttpRequest() {
 return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
  $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}

You can easily add on Angular side by following code:

myAppModule.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);

#angular#javascript#2014

How to add all custom post type to main Wordpress archive.php

Default archive shows only post type if you need show all post types just add follow code to function.php

add_filter(
'pre_get_posts', function ($query) {
        if (
            $query->is_main_query() &&
            !is_admin() &&
            (is_category() || is_tag())
            && empty($query->query_vars['suppress_filters'])
        ) {
            $posts = array_diff(
                get_post_types(['public' => true]), ['page', 'attachment', 'revision', 'forum', 'reply', 'topic'] /* array of ignored types*/
            );
            $query->set(
                'post_type', $posts
            );
            return $query;
        }
    }
);

#Wordpress#PHP#2014

How to protect your emails with PHP and Javascript

Working with or without javascript it's combine two technique for email protection ROT13 and CSS

function mail($email, $text = null) {
 return '<script type="text/javascript">document.write("' .
 addslashes(
  str_rot13(
   '<a href="mailto:' . $email . '" rel="nofollow">' . ($text ? : $email) . '</a>'
  )
 ) . '".replace(/[a-zA-Z]/g,function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);}));</script>' .
 '<noscript><span style="unicode-bidi: bidi-override; direction: rtl;">' . strrev($email) . '</span></noscript>';
}

#email#javascript#PHP#antispam#2014

Convert JSON data to valid PHP code

Do you need convert JSON data to valid PHP code without pain? I've got a short script for that! My simple solution used var_export() function. This function generates almost valid, well formatted PHP code from usual JSON data. Invalidity of code can be fix with one regular expression, which replace stdClass::__set_state/ with (object).

Take a closer look at example data. I have here currency.json - PHP code should look something like this:

<?php
 return array (
  'USD' =>
  (object)(array(
     'symbol' => '$',
     'name' => 'US Dollar',
     'symbol_native' => '$',
     'decimal_digits' => 2,
     'rounding' => 0,
     'code' => 'USD',
     'name' => 'US dollars',
  )),
  'CAD' =>
  //...
);

It's can be done in only four lines of PHP code:

$data = json_decode(file_get_contents(__DIR__ . '/currency.json'));
$code = var_export((array)$data, true);
$code = "<?php\n return " . preg_replace('/stdClass::__set_state/', '(object)', $code) . ';';
file_put_contents(__DIR__ . '/currencies.locale.php', $code);

If you need call some function (like gettext) above the variable, just add more regular expression:

$data = json_decode(file_get_contents(__DIR__ . '/currency.json'));
$code = var_export((array)$data, true);

// add gettext function call
$code = preg_replace("/'name' => '(.+)'/", "'name' => __('$1')", $code);
$code = preg_replace("/'name_plural' => '(.+)'/", "'name' => __('$1')", $code);

// save PHP code
$code = "<?php\n return " . preg_replace('/stdClass::__set_state/', '(object)', $code) . ';';
file_put_contents(__DIR__ . '/currencies.locale.php', $code);

#PHP#json#2014

How to clean flash drive before unmount on Mac

How to clean flash drive and delete all hidden (dot) files on mac before unmount? It's simple, save follow commands as flash:

#!/bin/bash

if [ -n "$1" ]; then
  read -r -p "Clean /Volumes/$1/ and unmount? [y/N] " response
  if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then      
    find /Volumes/$1/ -name '._*' -type f -delete
    rm -rf /Volumes/$1/.Spotlight-V100/
    rm -rf /Volumes/$1/.Trashes/
    diskutil unmount /Volumes/$1/
    echo "Done..."
  fi
else
  echo "Flash drive name missing"
fi

Then change the access mode of a file chmod +x flash. To unmount a clean flash drive just run ./flash Flashka (Flashka is name od drive).

#macOS#bash#2013

Run FTP server on Mac OS X

Setup everyhing: sudo subl /etc/ftpd.conf

# match umask from Mac OS×Server ftpd
umask all 022
chroot GUEST /Users/roman/ftp
modify guest off
umask  guest 0707
upload guest on

Start FTP server

sudo launchctl load /System/Library/LaunchDaemons/ftp.plist

And stop again:

sudo launchctl unload /System/Library/LaunchDaemons/ftp.plist

#ftp#macOS#2013