Posts Tagged ‘php’

Using Custom Profile Field Data in Buddypress Templates

November 18th, 2009

I ran into what I thought would be fairly common need for Buddypress theme development, the ability to pull data from a custom user profile field and display it. After searching a bit, I could only find way to pull either random fields, or all of the fields together. So after digging around in the core files, I found the pieces to put together my own function for the task.

1. Create the file “bp-custom.php” and place it directly in the plugins folder. Note, do not place it in the “buddypress” folder, otherwise it will be overwritten when upgrading. If the file exists, simply append to it rather than creating a new one.

2. Paste the following function in:

function bp_the_site_member_profile_data($field_name = '', $echo = 1) {
  if( !$field_name ) {
    return false;
  }
  global $site_members_template;
  if( function_exists( 'xprofile_get_field_data' ) ) {
    $data = xprofile_get_field_data( $field_name,
                                     $site_members_template->member->id);
    if( $echo ) {
      echo "$data";
      return true;
    } else {
      return $data;
    }
  }
}

3. You can now use the function ‘bp_the_site_member_profile_data(‘MyField’) in your templates (of course, substituting ‘MyField’ with the one you’d like to use). Note, this must be place inside a ‘Members Loop’ so that the $site_members_template variable is populated.  Odds are, you’re inserting this near other profile data already in the loop, so there should be no problems.

UPDATE:
As of BuddyPress 1.2, this functionality has been included. While in the members loop, you can use the included function: ‘bp_member_profile_data( ‘field=the field name’ )’ to much the same effect.

Ubuntu Server Setup Checklist

June 20th, 2009

I’ve now set up half a dozen or so Ubuntu Server installations over the past year or two.  For the last few, I created a checklist to make sure I don’t leave any of the smaller, less obvious things out.  I present it here, completely unmodified.  Note, this is more of a preliminary checklist, as it doesn’t include installation of Apache, MySql, PHP or any other programs such as Postfix.  Basically, I’ll perform these steps regardless of whether It’ll be a web or mail server.  These also assume you like the vi text editor, if not, you can substitute emacs, nano, or whatever your preference when neccesary.  Also, some of these are already done depending on your server host.

Time/Date/Language
Fix Locale Warnings:
# apt-get install language-pack-en

Set Timezone:
# dpkg-reconfigure tzdata

Install Time Daemon:
# apt-get install ntp

General
Install Manual Pages:
# apt-get install man

Add Domain name
# vi /etc/hosts
127.0.0.1 localhost
123.456.789.012 computername.domain.com computername (replace external ip)

Security
Add Administrative User (with home directory):
# useradd myusername -m

Give Admin user Sudo Powers
# visudo
myusername ALL=(ALL) ALL

Set Admin Password
# passwd myusername

Set Admin Shell Preference (optional)
# vi /etc/passwd
myusername: […] :bash

Disable Root SSH Login:
# vi /etc/ssh/sshd_config
PermitRootLogin no <–MAKE SURE YOU CREATED ADMIN & PASSWORD

Tighten default permissions for file & directory creation:
# vi /etc/profile
umask 027 (no default access for others)

Install and Set Up Firewall
# apt-get install ufw
# ufw allow ssh <–DO NOT FORGET THIS
# ufw enable

Dynamic Display of the Alphabet with PHP

December 23rd, 2008

Here’s a neat trick I recently used: Say you want to the display the alphabet on your web page.  The most likely scenario being for paging links to organize a directory of people or businesses. PHP has a chr() function, which displays the ASCII character for any given integer.

Rather than looping through an array with 26 values, or worse yet, typing out 26 lines of code, just loop through the display code 26 times.

<?php
for ($i=65; $i<=90; $i++) {
 echo chr($i);
}
?>

For those not familiar with ASCII mappings, values 65-90 represent the uppercase letters A-Z. Alternately, you could use the values 97-122 for lowercase a-z.  If you wanted to mix the two (say to display uppercase, but use lowercase in the link) just use the strtoupper() or strtolower() functions inside the loop.  Here’s a more applicable sample:

<?php
for ($i=97; $i<=122; $i++) {
 $x = chr($i);
 echo '<a href="memberlist.php?alpha=' . $x . '>' . strtoupper($x) . '</a>';
}
?>

You can see an example of both applied here.

PHP Month View Calendar

December 3rd, 2008

I recently had to develop a month view Calendar for a website I’m building.  While such a thing is very common, it presents a number of twists:

  • You can’t start it on the first of the month – The first will likely fall mid-week
  • To find the acutual first day of the week, you need to know how many days are in the previous month and count backwards
  • You cannot assume 4 weeks per month -most have 5 or 6
  • you will need to use the correct number of days in the month, and then add on the correct number of days of the next month to finish the week

After playing with a few algorithms, I decided to represent the month with a 2-dimensional array, one index for each week, and another for each day.  Then, you can put the actual string date in each value, or perhaps an array with that day’s events.  Without further ado:

<?php
//CreateMonthView -
//Takes one parameter: a unix timestamp anywhere in the month
function CreateMonthView( $now ) {

    //get numberic day of month (01-31)
    $dayOfMonth = strftime('%d', $now);
    //subtract as approptriate to get to start of month
    $monthStart = $now - (86400 * ($dayOfMonth -1));

    //get numeric day of week (0-6)
    $dayOfWeek = strftime('%w', $monthStart);

    //subtract appropriate number of days to get to the start of the week
    //this will usually be the last part of the previous month
    $calMonthStart = $monthStart - (86400 * $dayOfWeek );

    //initialize variables for while loop
    $thisWeekStart = $calMonthStart;
    $week = 1;
    $monthArray = array();

    //last day of month - text condition for while loop
    $lastDayOfMonth = mktime(23, 59, 59,
                             date("m", $now),
                             date("t", $now),
                             date("Y", $now));

    //foreach week, create a new array to hold the days
    while( $thisWeekStart <= $lastDayOfMonth ) {
        $monthArray[$week] = array();

        //iterate through week - adding each day as a value
        for( $i=0; $i<7; $i++) {
            //get timestamp for each day
            $dayOfWeek = $thisWeekStart + 86400 * $i;
            //convert to a and ISO date - seconds are too precise
            $date = date('Y-m-d',$dayOfWeek);

            //each day will be the value in the array
            $monthArray[$week][] = $date;
        }

        //increment sentinal variable and week counter
        $thisWeekStart = $dayOfWeek + 86400;
        $week++;
    }

    return $monthArray;
}
?>

Now you may be saying to yourself “okay, that’s all fine and good, but it doesn’t do anything on it’s own”, and you’d be right, it’s just a function.  To make something happen, you simply need to call it, and display the result.  Here is another snippet that does just that:

<?php
$month = CreateMonthView( mktime() ); //create the current month

echo '<table>';
foreach( $month as $week ) {
    echo '<tr>';

    foreach ($week as $day ) {
        if( $day == date('Y-m-d') ){
            //apply selector to distinguish today's date
            echo '<td class="today">';
        } else {
            echo '<td>';
        }
        //reduce the complete ISO date down to the day and display it
        echo substr($day, 8, 2);
        echo '</td>';
    }
    echo "</tr>\n";
}
echo '</table>';
?>

Viola! You can certainly copy and paste this code as is, but it’s not very visually exciting. Here’s an example. It could definitely use some styling – but I’ll leave that up to you.

Quick Hash Generator

December 2nd, 2008

I often find myself quickly needing the 1-way encrypted value (hash) of a string. Most often, it’s to securely store an individual password into a database or script. Rather than temporarily hard-coding the plain text to see what PHP will generate, I wrote a little reusable script to generate hash values. Anyone who might find it useful can find it here. If you’re paranoid about security, you can find a secure version here, although you may get a warning about my self-signed certificate.

Get a Random Row from Database

November 29th, 2008

I had an app the other day that required a single random row to be displayed from the database. It’s an easy task, but I tripped on it for a second. Here was my impulse:

//Get the total number of rows from the MySQL database
$query = "SELECT COUNT(*) as total FROM table";
$result = mysql_query( $query);
$rows = mysql_fetch_assoc( $result );

//Let PHP choose a random row
//pick a number between 1 & the total
$row = rand(1, $rows['total'])

//Now get that row
$query = "SELECT * FROM table LIMIT($row, 1)";
$result = mysql_query( $query);

After typing that out, I realized that I had take the long way round the problem. Very similar to taking the Misty Mountain Path rather than the Mines of Moria. Here’s a better way:

//Get a random row from the database
$query = "SELECT * FROM table ORDER BY RAND() LIMIT 1";
$result = mysql_query( $query );

Much better. Gimley the dwarf would be proud