Archive for the ‘PHP’ Category

Randomly writing CSV data in PHP

Today’s project: add or replace values in a comma-separated-value file. The application is for tag-counting by week, so the first column is effectively an ID column & the rest (for me) are integers. But here’s the code with some sample data grabbed from a random Google search..

<?
/************** Vars ***************/

$str="id,age,sex,region,income,married,children,car,save_act,current_act,mortgage,pep
ID12101,48,FEMALE,INNER_CITY,17546.0,NO,1,NO,NO,NO,NO,YES
ID12102,40,MALE,TOWN,30085.1,YES,3,YES,NO,YES,YES,NO
ID12103,51,FEMALE,INNER_CITY,16575.4,YES,0,YES,YES,YES,NO,NO
ID12104,23,FEMALE,TOWN,20375.4,YES,3,NO,NO,YES,NO,NO
ID12105,57,FEMALE,RURAL,50576.3,YES,0,NO,YES,NO,NO,NO
ID12106,57,FEMALE,TOWN,37869.6,YES,2,NO,YES,YES,NO,YES
ID12107,22,MALE,RURAL,8877.07,NO,0,NO,NO,YES,NO,YES
ID12108,58,MALE,TOWN,24946.6,YES,0,YES,YES,YES,NO,NO
ID12109,37,FEMALE,SUBURBAN,25304.3,YES,2,YES,NO,NO,NO,NO
ID12110,54,MALE,TOWN,24212.1,YES,2,YES,YES,YES,NO,NO
ID12111,66,FEMALE,TOWN,59803.9,YES,0,NO,YES,YES,NO,NO
ID12112,52,FEMALE,INNER_CITY,26658.8,NO,0,YES,YES,YES,YES,NO
ID12113,44,FEMALE,TOWN,15735.8,YES,1,NO,YES,YES,YES,YES
ID12114,66,FEMALE,TOWN,55204.7,YES,1,YES,YES,YES,YES,YES
ID12115,36,MALE,RURAL,19474.6,YES,0,NO,YES,YES,YES,NO";

$tags2find_arr=array();
$tags2find_arr['ID12106']=array(1=>1,4=>100);  //additive numbers, or replacing?
$tags2find_arr['ID12102']=array(1=>1,4=>200);
$tags2find_arr['ID12114']=array(1=>1,4=>300);

$fn='test.txt';
/************** Runtime ***************/

writeCSV($fn,$str);
writeRandCSV($fn,$tags2find_arr,'add');

/************** Functions ***************/

function writeCSV($fn='',$str=''){

$fh=fopen($fn,'w');
fwrite($fh,$str);
fclose($fh);
}
/****************************/
function writeRandCSV($fn,$tags2find_arr,$addreplace='add'){
$fl=filesize($fn);
$fh=fopen($fn,'r+'); //open for reading, and writing, but don't kill the contents
$str=fread($fh, $fl);

foreach($tags2find_arr as $tag2find=>$csv_data_addreplace){  //$tag2find='ID12108';
//find the line in the str			//alt: explode by '\n' or '\r' &amp;amp; get an array &amp;amp; it's size.. find in array, truncate array,implode &amp;amp; find strlen's for loc &amp;amp; write-len
$readtagloc=strpos($str,$tag2find.',');   //this could be a problem for smaller tags found in larger.. throw a \n before &amp;amp; a , after?
//echo "\r<br/>".$tag2find." @".$readtagloc;

//find it's corollary in the file
fseek($fh,$readtagloc);
$fcsv_arr=fgetcsv($fh); //should only get one line!
//for($i=0;$i<count($fcsv_data);$i++){
//$fcsv_arr[$i]=$fcsv_arr[$i]+$csv_data_addreplace[$i]; //58->59
foreach($csv_data_addreplace as $csv_idx=>$csv_addreplace){
  if($addreplace=='add') $fcsv_arr[$csv_idx]+=$csv_addreplace; //58->59
  else $fcsv_arr[$csv_idx]=$csv_addreplace;
}
//print_r($fcsv_arr);

/******************************/
//echo '\r<br/>'.ftell($fh).' or '.(ftell($fh)-strlen(implode(',',$csv_arr))-1 );
fseek($fh,$readtagloc); //back to beginning of line to write now
//$read=fread($fh, $readlen);
//hoping the pointer is still in the same loc &amp;amp; not @ line-end!

$ok[$tag2find]=fputcsv($fh,$fcsv_arr,',');
$sz=(strlen(implode(',',$fcsv_arr))+1);

//if($ok===false){ echo "FAILURE"; }
//if($ok==$sz){ echo "\r<br/>written length ok:".$ok; }
//else { "\r<br/>written length not ok:".$ok.'<'.$sz; }

} //end foreach tag
$ok[]=fclose($fh);
return $ok;

} //close function
/******************************/
?>

WordPress Skills (How to hire a WP guy!)

My job just asked me to make a list of what a sister agency should look for in WP ppl. Googling left me with nothing (as all search results seem to have been taken over by SEO ppl lately), so here’s my addition to the mix:

Basic (unquestioned assumptions):
* XHTML syntax, CSS2,
* Browser testing-abilities: IE6-8, FF1-3,Saf3-4, Chrome1-2

WP Basics:
* Upgrading (and fixing when broken!)
* Knowledge of a set of plugins for these common problems:
* “I want a contact form (with these 9 fields)”
* “I want backups”
* “I want a photo gallery (with lightbox)”
* “I want twitter/facebook integration”
* “I want a podcast”
* “I want google maps on my contact page”

WP Intermediate:
* Build/mod a template
* Build/mod a plugin
* jQuery instead of simple, good-ol’-fashioned javascript

Technical/Back-end:
* Can fix ‘broken’ DB’s
* Clean MySQL WP DB from hackers
* phpmyadmin
* MySQL command-line

Users (Teaching skills):
* Guide clients/staff through changing templates, adding special parameters for templates, plugins, upgrades.
* Explain the difference between the 2 editing modes of WP, as well as how a post, page, excerpt are all used.

WP Access controls:
* Should users sign up?
* How to handle editors, admin, readers?
* Public/private posts/pages
* How are comments filtered & what signups required?

SEO:
* What the different HTTP Response numbers mean (#200, 301,302)
* .htaccess mod_rewrite for Apache/Linux servers
* forwarding old sites to WP pages
* forwarding old posts to a archive page
* making ‘pretty urls’ 301 (and why WP default doesn’t do it)
* maing ‘www.’ 301  (and why WP default doesn’t do it)
* The troubles with WP on MS/IIS Servers
* Why XML Sitemaps are good
* Why Google Analytics & Webmaster tools are worth it (and how to interp ‘em to clients)

Anything else out there?

WordPress: Author List by Category

I just keep functioning out WP! (What can I say, it’s my job!)

This is a rework of WP’s own list_authors() function, but with some extra SQL:


<?php

function my_list_authors_by_category($args = '', $cat_id=0) {
global $wpdb;

$defaults = array(
'optioncount' => false, 'exclude_admin' => true,
'show_fullname' => false, 'hide_empty' => true,
'feed' => '', 'feed_image' => '', 'feed_type' => '', 'echo' => true
);

$r = wp_parse_args( $args, $defaults );
extract($r, EXTR_SKIP);

$return = '';

/** @todo Move select to get_authors(). */
//&#160;&#160;&#160; $authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users " . ($exclude_admin ? "WHERE user_login <> 'admin' " : '') . "ORDER BY display_name");
//replace with the 'author by category' SQL
$authors = $wpdb->get_results("SELECT distinct post_author as `ID`, user_nicename FROM `default_posts` as `dp`, `default_terms` as `dt`, `default_term_relationships` as `dtr`,`default_users` as `du` where `dp`.`post_author`=`du`.`ID` and `dp`.`ID`=`dtr`.`object_id` and `dtr`.`term_taxonomy_id`=".$cat_id.";");

$author_count = array();
foreach ((array) $wpdb->get_results("SELECT DISTINCT post_author, COUNT(ID) AS count FROM $wpdb->posts WHERE post_type = 'post' AND " . get_private_posts_cap_sql( 'post' ) . " GROUP BY post_author") as $row) {
$author_count[$row->post_author] = $row->count;
}

foreach ( (array) $authors as $author ) {
$author = get_userdata( $author->ID );
$posts = (isset($author_count[$author->ID])) ? $author_count[$author->ID] : 0;
$name = $author->display_name;

if ( $show_fullname && ($author->first_name != '' && $author->last_name != '') )
$name = "$author->first_name $author->last_name";

if ( !($posts == 0 && $hide_empty) )
$return .= '<li>';
if ( $posts == 0 ) {
if ( !$hide_empty )
$link = $name;
} else {
$link = '<a href="' . get_author_posts_url($author->ID, $author->user_nicename) . '" title="' . sprintf(__("Posts by %s"), attribute_escape($author->display_name)) . '">' . $name . '</a>';

if ( (! empty($feed_image)) || (! empty($feed)) ) {
$link .= ' ';
if (empty($feed_image))
$link .= '(';
$link .= '<a href="' . get_author_rss_link(0, $author->ID, $author->user_nicename) . '"';

if ( !empty($feed) ) {
$title = ' title="' . $feed . '"';
$alt = ' alt="' . $feed . '"';
$name = $feed;
$link .= $title;
}

$link .= '>';

if ( !empty($feed_image) )
$link .= "<img src=\"$feed_image\" style=\"border: none;\"$alt$title" . ' />';
else
$link .= $name;

$link .= '</a>';

if ( empty($feed_image) )
$link .= ')';
}

if ( $optioncount )
$link .= ' ('. $posts . ')';

}

if ( !($posts == 0 && $hide_empty) )
$return .= $link . '</li>';
}
if ( !$echo )
return $return;
echo $return;
}
?>

And then to call, just define the category you want:


<?php

$cat=0;
if (have_posts()){&#160;&#160;&#160; //get the present category, if there is one
if (is_category()) {
$cat = get_query_var('cat');
}
}
if($cat!=0){
?>
<h2>Authors:</h2>
<ul>
<? my_list_authors_by_category('exclude_admin=1',$cat); ?>
</ul>
<? } ?>

Fake out wordpress to pull in another page-content..

Sometimes using <? $thispost=get_post($id); echo $thispost->post_content ?> isn’t enough.

Sometimes, you need a full menu structure to be highlighted or built according to that post.

Sometimes you need a menu parent pull in the ‘first child’ content.

Sometimes, you need to fake wordpress out:


<? //Usage: given, any time this template is called and happens to be on page_id '6' make page '6' act  like page '8'.
$wp_query=fakePage($wp_query->post->ID,"6","8",$wp_query);

function fakePage($currid,$thisid,$fakeid,$wp_query){
if(strcmp($currid,$thisid)==0){
$thispost=get_post($fakeid);

//the fake-out
$wp_query->post->ID=$fakeid;
$wp_query->post->post_content=$thispost->post_content;

$wp_query->queried_object->ID=$fakeid;
$wp_query->queried_object_id=$fakeid;
$wp_query->queried_object->post_content=$thispost->post_content;

$wp_query->posts[0]->ID=$fakeid;
$wp_query->posts[0]->post_content=$thispost->post_content;
}
return $wp_query;
} ?>