Monday 8 December 2014

Fedora: how to restart nginx and php-fpm

sudo service nginx restart
sudo service php-fpm restart

Monday 1 December 2014

PHP file browser

http://sourceforge.net/projects/autoindex/

Monday 24 November 2014

Check if an array is multi-dimensional

if (count($array) == count($array, COUNT_RECURSIVE)) 
{
  echo 'array is not multidimensional';
}
else
{
  echo 'array is multidimensional';
}


http://stackoverflow.com/questions/145337/checking-if-array-is-multidimensional-or-not

Filtering data with PHP (Sanitizing data) and Validation

http://www.phpro.org/tutorials/Filtering-Data-with-PHP.html

http://code.tutsplus.com/tutorials/sanitize-and-validate-data-with-php-filters--net-259

http://www.sitepoint.com/input-validation-using-filter-functions/

To filter arrays:

http://stackoverflow.com/questions/19637210/post-variable-array-and-filter-input




http://php.net/manual/en/function.filter-input.php

http://php.net/manual/en/filter.constants.php

http://php.net/manual/en/function.filter-input-array.php

http://php.net/manual/en/filter.filters.php

http://php.net/manual/en/filter.filters.validate.php

Get url query string parameters using Javascript only

http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript

Difference between array merge and array + array

http://stackoverflow.com/questions/5394157/whats-the-difference-between-array-merge-and-array-array

Responsive Design: Screen resolution reference

http://spirelightmedia.com/resources/responsive-design-device-resolution-reference

Using rems

https://bugsnag.com/blog/responsive-typography-with-rems

http://snook.ca/archives/html_and_css/font-size-with-rem

CSS Clear Fix

http://perishablepress.com/lessons-learned-concerning-the-clearfix-css-hack/

Parallax websites

http://moz.com/blog/parallax-scrolling-websites-and-seo-a-collection-of-solutions-and-examples

Single Page Website

http://searchengineland.com/single-page-websites-seo-182506

Install both OpenJDK and Oracle Java on Fedora

Use the "alternatives" app to switch between the two.

http://www.if-not-true-then-false.com/2010/install-sun-oracle-java-jdk-jre-7-on-fedora-centos-red-hat-rhel/

Assign event to Escape keypress


$(document).keyup(function(e) {
  if (e.keyCode == 27) { some_code_here }   // esc
});

CSS 3 resize property

https://developer.mozilla.org/en-US/docs/Web/CSS/resize

https://developer.mozilla.org/samples/cssref/resize.html

Doesn't work on iframes in Firefox  33

Prevent link from doing default action

$( "a" ).click(function( event ) {
event.preventDefault();});
http://api.jquery.com/event.preventdefault/

Make link open in parent of iframe

window.parent.location.href= "http://www.google.com";

Saturday 8 November 2014

Restrict web site access to specific IP addresses in Apache

order deny,allow
deny from all
allow from 111.222.333.444

Put the above code in the .htaccess in the root. You can add more "allow from" lines for more ip addresses.

http://stackoverflow.com/questions/4400154/htaccess-deny-all-allow-only-one-ip

Friday 7 November 2014

Word wraping by word breaking

.break-word {
  word-wrap: break-word;
}

 http://webdesignerwall.com/tutorials/word-wrap-force-text-to-wrap

Friday 31 October 2014

Linux: Change permissions recursively of only directories or only files

For directories:

find /path/to/folder -type d -exec chmod 755 {} \;

For files:

find /path/to/folder -type f -exec chmod 644 {} \;

Another way:

find /path/to/base/dir -type d -exec chmod 755 {} +
find /path/to/base/dir -type f -exec chmod 644 {} + 

http://superuser.com/questions/91935/how-to-chmod-755-all-directories-but-no-file-recursively

However, this seems to be the best solution, when you do not need to unset execute permissions on files:


chmod -R u+rwX,go+rX,go-w /path
The important thing to note here is that X acts differently to x - the man page says The execute/search bits if the file is a directory or any of the execute/search bits are set in the original (unmodified) mode. In other words, chmod u+X on a file won't set the execute bit; and g+X will only set it if it's already set for the user.

Tuesday 28 October 2014

Apache Keep Alive Setting

This setting determines if a connection is kept alive after a single file is transferred between the server and the browser.

Default is off

Can be turned on depending on available RAM and traffic patterns:

https://ausweb.com.au/technobabble/2012/07/27/apache-optimization/

Content Negotiation for Languages

http://www.w3.org/blog/2006/02/content-negotiation/

How to configure etags


"remove the iNode portion of Etags. To do this in Apache add the following lines to your configuration file.
<Directory /usr/local/httpd/htdocs>
    FileETag MTime Size
</Directory>" 


Or choose "MTime  Size" for the Etags setting in WHM's Apache configuration

http://www.websiteoptimization.com/speed/tweak/etags-revisited/

Monday 13 October 2014

Jquery multiple selectors

jQuery( "selector1, selector2, selectorN" )

Note that the commas are within the selector.

Jquery iterating over arrays, objects, and array-like objects

http://learn.jquery.com/using-jquery-core/iterating/

var sum = 0;
var arr = [ 1, 2, 3, 4, 5 ];

$.each( arr, function( index, value ){
sum += value;
});

Javascript associative array

Javascript does not feature associative arrays. However, you can create something similar using object arrays.

Example:

arr={'key1': 'value1','key2':'value2'};

This array can be accessed with:

the_value = array['key2']

Values can be added or changes:

arr['key3']='value3';

More info here: http://www.i-programmer.info/programming/javascript/1441-javascript-data-structures-the-associative-array.html

You can iterate over the object array using Jquery:

$.each( arr, function( index, value ){
sum += value;
});

Monday 18 August 2014

How To Set Up HTTP Authentication With Nginx

https://www.digitalocean.com/community/tutorials/how-to-set-up-http-authentication-with-nginx-on-ubuntu-12-10

Nginx configuration file error

When restarting nginx after a configuration file change, if you get an error message that the configuration file has an error, you can get more info about the error with:

sudo nginx -t

Tuesday 5 August 2014

To get a mysql formatted datetime using javascript:

**
 * You first need to create a formatting function to pad numbers to two digits…
 **/
function twoDigits(d) {
    if(0 <= d && d < 10) return "0" + d.toString();
    if(-10 < d && d < 0) return "-0" + (-1*d).toString();
    return d.toString();
}

/**
 * …and then create the method to output the date string as desired.
 * Some people hate using prototypes this way, but if you are going
 * to apply this to more than one Date object, having it as a prototype
 * makes sense.
 **/
Date.prototype.toMysqlFormat = function() {
    return this.getUTCFullYear() + "-" + twoDigits(1 + this.getUTCMonth()) + "-" + twoDigits(this.getUTCDate()) + " " + twoDigits(this.getUTCHours()) + ":" + twoDigits(this.getUTCMinutes()) + ":" + twoDigits(this.getUTCSeconds());
};

I couldn't find a simpler jQuery solution to this.
If you want the time according to the user's time zone, remove the "UTC" in the second last line of the code.

Monday 28 July 2014

Set Timezone

This will set the timezone for all the php functions in a page. Put this at the top of a page:

date_default_timezone_set('Asia/Calcutta');

Solve 5 annoying moodle problems

http://www.iteachwithmoodle.com/2012/11/16/solve-5-annoying-moodle-problems-quickly/

XMPP chat

Prosody is a good XMPP chat server. It can be installed from the distro repository.

A guide: http://www.techytalk.info/install-configure-prosody-xmpp-jabber-server-on-debian-ubuntu-linux/

There are many desktop clients for XMPP. There are a few web clients too: https://conversejs.org/ and http://candy-chat.github.io/candy/

https://conversejs.org/docs/html/

However, for these web clients to connect to the XMPP server, they need to use HTTP, so the XMPP server needs a plugin to communicate using xmpp over http, called BOSH: http://xmpp.org/extensions/xep-0124.html

The BOSH plugin for Prosody is: http://prosody.im/doc/modules/mod_bosh

Once the bosh-bind plugin is installed, a redirect should be setup in the web server (Apache or Nginx). This is because, converse.js must connect to the XMPP server (through bosh) at port 5280. However, browsers prevent authentication to this port because of same-origin policies (to prevent XSS). Therefore, the javascript can be made to authenticate to a particular directory which redirects the request to the correct url and port.

http://prosody.im/doc/setting_up_bosh

For integrating prosody with Wordpress, there is a plugin:
https://github.com/llun/wordpress-authenticator

However, this plugin requires wordpress to store passwords as md5 hashes (using a plugin) instead of phpass. Md5 hashes are very insecure so wordpress-authenticator cannot be used.

There is another prosody plugin for wordpress authentication: https://code.google.com/p/prosody-modules/wiki/mod_auth_wordpress
However, the code is alpha and development seems to have halted.

To integrate converse.js with a site that already uses authentication, one needs to use PHP prebinding: http://www.techytalk.info/other-projects/xmpp-bosh-toolkit/
http://stackoverflow.com/questions/3696165/get-xmpp-sid-and-rid-from-bosh-in-php
http://stackoverflow.com/questions/23264662/java-trying-to-prebind-converse-js-using-bosh-but-not-able-to-get-the-sid-and

https://github.com/candy-chat/xmpp-prebind-php/

Prosody: creating accounts:  http://prosody.im/doc/creating_accounts





Wednesday 23 July 2014

Enable error display in PHP

error_reporting(E_ALL);
ini_set('display_errors','1');

Wednesday 9 July 2014

Improving email delivery (preventing spam flagging)

http://www.emailvendorselection.com/email-deliverability-checklist-improve-email-deliverability-now/

Friday 27 June 2014

Windows 7 Panning Desktop Applications

http://superuser.com/questions/85362/looking-for-an-application-that-scrolls-or-pans-netbook-screens-running-windows

http://ynea.futureware.at/cgi-bin/infinite_screen.pl


http://kjh.ca/contour_mods/doku.php?id=solution_for_storyteller_on_1024x600%3asolution_for_storyteller_on_1024x600


http://www.addictivetips.com/windows-tips/get-infinite-scroll-on-windows-desktop-with-windowslider/

http://ficusdev.com/WindowSlider/Description

Friday 20 June 2014

Page caching for Buddypress? Transients, memcached, vs others

Since Buddypress works on having users login, page caches software such W3 Total Cache, BP Super Cache, Nginx microcache, APC, Memcached, etc. won't work.

What would work is a partial page caching software. But there doesn't seem to be any such software now.

http://chrislema.com/high-performance-wordpress-membership-site/

However, by using the wordpress transients API, one can manually code fragment or partial page caching.

http://premium.wpmudev.org/blog/wordpress-transients/

Problems with transients:

http://wpengine.com/2013/02/21/wordpress-transient-api/

Starting with Wordpress 3.7, transients are garbage collected, so the issues mentioned above may be fixed.

Enabling Opcache in PHP

Here are the commands that can be entered in php.ini for configuration of the opcache. There is also an explanation ofthe features.

http://www.php.net//manual/en/opcache.configuration.php


Here are some Opcache GUI reporting tools:

https://rtcamp.com/tutorials/php/zend-opcache/

Some configuration tips:

https://www.activecollab.com/blog/3-zend-opcache-memcached.html

More detailed configuration tips:

https://www.scalingphpbook.com/best-zend-opcache-settings-tuning-config/



Tuesday 17 June 2014

Wordpress: Disable heartbeat

If wordpress is taking too much server resources, you can disable wordpress heartbeat. If you are using buddypress, disable "Activity auto-refresh" in Buddypress settings.

http://www.inmotionhosting.com/support/website/wordpress/heartbeat-heavy-admin-ajax-php-usage

In the above page, you will find the code to disable heartbeat on all pages except post.php and post-new.php (here it is required for autosave while creating new posts and commenting).

To be added in functions.php

add_action( 'init', 'stop_heartbeat', 1 );

function stop_heartbeat() {
        global $pagenow;

        if ( $pagenow != 'post.php' && $pagenow != 'post-new.php' )
        wp_deregister_script('heartbeat');
}

Nginx with CPanel

http://cpxstack.sysally.net/

Cpxstack is a plugin to cPanel that completely replaces Apache with nginx (other plugins keeps apache and configure nginx as a reverse proxy).

To install cpxstack, you need Incron. For this you need to enable the EPEL repository (see previous article for this).

You also need to install php-devel. Cpanel prevents installing any php related packages through an "exclude" entry in yum.conf. Open yum.conf and remove "php*".

After upgrading to the latest stable PHP version, you should enable the Remi repository and the php55 remi repository. You can now install php-devel.

You can run the cpxstack.sh script as per instructions here: http://cpxstack.sysally.net/documentation.htm

For incron and php-devel you can alternatively directly run the cpxstack.sh script to see if it installs these packages automatically.

After the script has run, you should go to WHM, when you click on the cpxstack icon in the sidebar, it will ask you to change a setting in the Tweak Settings area.
You also need to go to cPanel and manually enable nginx for your site. Also in WHM change the default number of worker processes to a lower number (default is 15).

http://www.nginxtips.com/cpxstack-nginx-php-fpm-cpanel/

Nginx: Allow selected IP addresses only

  server {
    listen 80;
    server_name www.foo.bar;

    location / {

      allow   my.public.ip.here;
      deny    all;
    }
  } 
 
You can have multiple "allow" lines.

http://stackoverflow.com/questions/8438867/how-can-i-allow-access-to-a-single-ip-address-via-nginx-conf

301 permanently moved redirect with PHP

The following php commands will do a 301 redirect when using PHP FPM 
 
 
header('Status: 301 Moved Permanently', true);
header('Location: ' . $url); // or header('Location: ' . $url, true, 301);
 
http://stackoverflow.com/questions/5268454/php-301-redirect-impossible 

Nginx configuration for Wordpress

For wordpress pretty permalinks to work, you need to add this to your nginx.conf file where the wordpress directory is /wordpress:

location /wordpress {
    index index.php index.html index.htm;
    try_files $uri $uri/ /index.php?$args;
}

Nginx configuration for Moodle

If the moodle directory is /moodle then put this in the configuration file nginx.conf or the appropriate file under the nginx.include.d folder:

server {
     server_name  example.com www.example.com;
     rewrite ^/moodle/(.*\.php)(/)(.*)$ /moodle/$1?file=/$3 last;
 
In the same file, in the php section:
 
  location ~ \.php$ {
     fastcgi_split_path_info ^(.+\.php)(/.+)$;
 
 
Putting the same rewrite rule in the location /moodle section does not work.
 
If you are using the cpXstack plugin for cPanel, make sure you follow this:
 
For any domain that has nginX+PHP-FPM enabled, additional nginX configuration can be added by the root user at
/opt/pifpm/nginx.include.d/<DOMAINNAME>.autoinclude where DOMAINNAME is the domain .
 
Changes made any where else may not be preserved during server shut down. 

Monday 16 June 2014

cPanel: Install php-devel

CPanel disables installation of php related packages using yum. To enable it:

nano /etc/yum.conf

Remove php* from the "exclude" line.

EPEL repositories for Fedora and Cent OS

Certain applications such as incron can't be found in the default repositories of Cent OS. To get this software, you need to enable the EPEL (Extra Packages for Enterprise Linux) repository:

https://fedoraproject.org/wiki/EPEL#How_can_I_use_these_extra_packages.3F

http://www.rackspace.com/knowledge_center/article/installing-rhel-epel-repo-on-centos-5x-or-6x

Wednesday 7 May 2014

Tuesday 6 May 2014

Manually activating a user in Buddypress

To completely activate an imported user in Buddypress, you need to update two different tables:

In wp_usermeta add a date to the last_activity field.
In wp_bp_activity add a record for each user like so
INSERT INTO `wp_new`.`wp_bp_activity` (`id`, `user_id`, `component`, `type`, `action`, `content`, `primary_link`, `item_id`, `secondary_item_id`, `date_recorded`, `hide_sitewide`, `mptt_left`, `mptt_right`, `is_spam`) VALUES (NULL, '4', 'members', 'last_activity', '', '', '', '0', NULL, '2014-05-06 12:41:51', '0', '0', '0', '0');

Only after this will the person's name be available for private messaging.

Friday 4 April 2014

Fuzzy matching in MySql (Levenshtien Distance)

http://stackoverflow.com/questions/4671378/levenshtein-mysql-php

Friday 31 January 2014

How to make Wordpress root-relative

Add the following lines to your wp-config file (found in the root).


define('WP_HOME',"http://" . $_SERVER['HTTP_HOST']);
define('WP_SITEURL',"http://" . $_SERVER['HTTP_HOST']);

define( 'WP_CONTENT_DIR',  dirname( __FILE__ ) . '/wp-content' );
define( 'WP_CONTENT_URL',  'http://' . $_SERVER['HTTP_HOST'] . '/wp-content' );
//  added by chetan Custom plugin directory
define( 'WP_PLUGIN_DIR',   dirname( __FILE__ ) . '/wp-content/plugins' );
define( 'WP_PLUGIN_URL',   'http://' . $_SERVER['HTTP_HOST'] . '/wp-content/plugins' );

Then prevent the functions get_site_url() and  get_home_url from accessing the wp_options database table to get the server domain or ip.

For this edit the link-template.php file:

Find the function get_home_url and comment every occurrence of this line like so:
//        $url = get_option( 'home' );

and add this:

    $url = "http://" . $_SERVER['HTTP_HOST'];

Do the same for get_site_url():

//        $url = get_option( 'siteurl' );

and add this:

    $url = "http://" . $_SERVER['HTTP_HOST'];


Now, to make sure any media files that are uploaded use root relative urls, install the following plugin:

http://wordpress.org/plugins/root-relative-urls/


Monday 27 January 2014

VirtualBox Disable Time Sync

vboxmanage setextradata [VMname] "VBoxInternal/Devices/VMMDev/0/Config/GetHostTimeDisabled" "1"

Turn it back on:
vboxmanage setextradata [VMname] "VBoxInternal/Devices/VMMDev/0/Config/GetHostTimeDisabled" "0"