• Home
  • Contact
bogge.info

The brain dump of bogge.

  • Contact
  • Blog
    • Computer
    • Food
    • Fun stuff
    • Graphic
    • msi
    • Pirate
      • Scripting
        • AutoIT
        • Crystal syntax
        • Etomite CMS
        • HTML
        • PHP
        • VBScript
    • Software
  • Photo
    • Interior
    • Landscape
    • Nature
    • Sky

Browsing Category Scripting

Page 1 of 212»

Changeing timezone in crystal reports

Posted on July 7, 2011 by bogge

I have a data source that is in UTC (Coordinated Universal Time) and iam in the CET (Central European Time) timezone. So a need too change this time to the relevant timezone so that the data can be understood.

For example if some one is adding a post to the database in 1300 CET, the database says 1200 UTC and when the report is created it says that the post was created 1200 and the reader thinks that this is in CET.

So you can do it litke this:

local datetimevar x:=*Some Date*;
DateTime (YEAR(x), Month(x), day(x), hour(x)+1, minute(x), second(x))

But there is a problem with this approach and that is when is summer time we have Daylight savings so CET (Central European Time) becomes CEST (Central European Summer Time). So CET is +1h to UTC

So a better way to do this is to do it like this:

local datetimevar x:=*Some Date*;
ShiftDateTime (DateTime (YEAR(x), Month(x), day(x), hour(x), minute(x), second(x)), "CET,-60,CEST,0", "")

Explaining the syntax

ShiftDateTime shifts a DateTime value from one time zone to another time zone.

ShiftDateTime (inputDateTime, inputTimeZone, newTimeZone)

inputDateTime: a DateTime value to be shifted.
inputTimeZone: a “TimeZoneString” representing the time zone of the inputDateTime.
newTimeZone: a “TimeZoneString” representing the time zone to which the inputDateTime is shifted

The last empty string in my example indicates the local time zone is taken from the OS settings.

My TimeZoneString is constructed like this:
CET = String name of the standard time zone (eg Central European Time).
-60 = Offset, in minutes, of the standard time zone (CET is -1 hence -60 minutes).
CEST = String name of the DST time zone (eg Central European Summer Time).
0 = Optional DST offset from standard, defaults to one hour ahead of standard offset.

Calculate number of workdays in crystal reports

Posted on August 12, 2010 by bogge

In Sweden we typically work between Monday to Friday and are not working Saturdays and Sundays.

So for calculating how many days we work in a month we can use this formula in crystal reports:

Local DateTimeVar Start := #2010-01-01#;
Local DateTimeVar End := #2010-01-31#;
Local NumberVar Weeks;
Local NumberVar Days;

Weeks:= (Truncate (End - dayofWeek(End) + 1
- (Start - dayofWeek(Start) + 1)) /7 ) * 5;
Days := DayOfWeek(End) - DayOfWeek(Start) + 1 +
(if DayOfWeek(Start) = 1 then -1 else 0)  +
(if DayOfWeek(End) = 7 then -1 else 0); 

Weeks + Days

This returns the number of workdays in January when used in a formula in crystal reports.

Share variables between main crystal report and subreport

Posted on August 10, 2010 by bogge

To share a variable in crystal reports between a subreport and the main report you can do the following.

In the sub report create a formula and add this:

Shared NumberVar TheAnswer := 41;

Then in the main report you just add this in a formula:

Shared NumberVar TheAnswer;
TheAnswer

This will print out 41 in the main report.

Bur remember that the sub report must be executed before the formula in the main report, else the answer is 0 or null.

vbscript to run a bat against several computers

Posted on February 20, 2010 by bogge

This is a real simple vbscript to run a bat file with computer name as a parameter.
Computer names is in a string that splits in a array, then loop the array to send a command for each computer.

strMachines = "Computer1;Computer2;Computer3;Computer4;Computer5"
aMachines = split(strMachines, ";")
For Each machine in aMachines
 Set WshShell = WScript.CreateObject("WScript.Shell")
 WshShell.Run "\ServerSourceavdeploymentpush.bat " & machine
Next
Wscript.Echo("Done")

In the bat file you just add the variable %1 to capture the computer name.

Finding first and last day of a week in crystal reports

Posted on February 8, 2010 by bogge

If you have one day and want to select a whole week in crystal reports then you can do like this.

{@Today} is any date in a week and the only date we know.

This returns the date of the first day in the week if the first day is a Monday.

If DayOfWeek({@Today}) = 2 Then 
{@Today}
Else If DayOfWeek({@Today}) = 3 Then 
dateadd ("d",-1,{@Today})
Else If DayOfWeek({@Today}) = 4 Then 
dateadd ("d",-2,{@Today})
Else If DayOfWeek({@Today}) = 5 Then 
dateadd ("d",-3,{@Today})
Else If DayOfWeek({@Today}) = 6 Then 
dateadd ("d",-4,{@Today})
Else If DayOfWeek({@Today}) = 7 Then 
dateadd ("d",-5,{@Today})
Else If DayOfWeek({@Today}) = 1 Then 
dateadd ("d",-6,{@Today})

This returns the last date in the week (if its a Sunday) and the last time of the week.

Local DateTimeVar d := DateTime (DatePart ("yyyy", {@Today}), _
DatePart ("m", {@Today}), DatePart ("d", {@Today}), 23, 59, 59);
 
If DayOfWeek({@Today}) = 2 Then 
dateadd ("d",+6,d)
Else If DayOfWeek({@Today}) = 3 Then 
dateadd ("d",+5,d)
Else If DayOfWeek({@Today}) = 4 Then 
dateadd ("d",+4,d)
Else If DayOfWeek({@Today}) = 5 Then 
dateadd ("d",+3,d)
Else If DayOfWeek({@Today}) = 6 Then 
dateadd ("d",+2,d)
Else If DayOfWeek({@Today}) = 7 Then 
dateadd ("d",+1,d)
Else If DayOfWeek({@Today}) = 1 Then 
d;

HTML img tag

Posted on January 26, 2010 by bogge

The HTML img tag shows an image.

<img height="90" width="90" src="angry.gif" alt="Angry" title="Angry Smiley" />

Speed

The height and width tags are added for speed.

“When the height and width tags are included the browser will automatically know the size of the image. As a consequence it will be able to hold a place for the image and load the rest of the page contemporaneously. Apart from the improvement on the load time of the page this method is also more user friendly since the visitor can start reading the text or other information while the image is being downloaded.” From Daily Blog Tips

Search engine optimization (SEO)

The title tag is added for seo purpose, but alt tag is more important in seo.

“Make sure that your TITLE and ALT tags are descriptive and accurate.” From Google

Accessibility

The title tag is also added for accessibility, with a maximum of 100 chars.

Section 508
WCAG 1.0

Etomite Tagcloud script

Posted on January 24, 2010 by bogge

This TagCloud script is useless “as-is” but it will create a tagcloud.

/****************************************************
* Name: Tagcloud
* Version: 0.2
* Desc: Displays the containing words of documents in a "tag cloud"
* Based on the Tagcloud 1.1. snippet created by Marc Hinse, [email protected]
* Converted to EtomiteCMS by Bogge, bogge.com
*
* Change 0.1 => 0.2 Removed explode $parent and optimized sql query. Thanks to adamzyg.
*
* Usage: [[tagcloud?parent=`1,3,5,6,7,14`&min=`3`&landing=`12`
* Parameters: 
* 	parent: comma separated list of the folders that conatin the documents which are to be counted
*	min: Minimum occurrences of a word to be displayed
*	landing: the id of your search result page. If you don´t have one, create it like: [!FlexSearchForm?FSF_showResults=`1` &FSF_showForm=`0`!]
*   (this is required for linking the tags)
* ***************************************************/
 
//Start Config
	$parent = isset($parent)? $parent : "0"; 
	$min = isset($min)? $min : "2";
	$landing = isset($landing)? $landing : "[~[*id*]~]";
	$minChars = 4; //Minimum number of chars in word
	$exclude = array('',' ','  ','   ','and','a','-','—','&ndash;','the','&mdash;','to','.',':',',','p&aring;','&nbsp;'); //exclude list
	$indication = array(',','.',':');		//array of chars to be deleted
//End Config
 
If (!$tags) {
	$select = $etomite->getIntTableRows($fields="pagetitle,longtitle,description,content", $from="site_content", $where="parent IN ($parent) AND published = 1 AND searchable=1 AND deleted=0", $sort="", $dir="", $limit="", $push=false, $addPrefix=true); 
 
	while ($contents = $etomite->fetchRow($select, $mode='both')) {
		$content.=$contents['pagetitle'].' '.$contents['longtitle'].' '.$contents['description'].' '.$contents['content'];	
	}
	$content=strtolower(str_replace($indication,' ',strip_tags($content)));	//all to lower and without HTML
	$array_content=explode(' ',$content);	//split them in separate words
	$number=array_count_values($array_content);		//count the words
	$words=array();
 
	foreach($number as $key => $worth) {
		if($worth>$min && (!in_array($key,$exclude) && (strlen($key) >= $minChars))) { 	//look if the word counts the required minimum and is not in the exclude list 
			$words[$key] = $worth;	//put them in a new array
		}
	} 
}
else {
	$words=array();
	foreach($tags as $tag) {
		if($tag['count']>=$min && (!in_array($tag['tag'],$exclude))) { 
			$words[$tag['tag']] = $tag['count'];
		}
	}
}
 
//unset($words['etomite']);  //if you want to override the value of words (in this case 'etomite'), uncomment it and put in your word
$max_size=max($words); //word with most hits
//$words['etomite']=8; // put in again your deleted word and value from two lines above
ksort($words); //sort them alphabetically (just comment that out, then they will be unsortet
 
$multiplier=400/$max_size; //define the multiplier for the size (play with that to fit your site!)
$min_size=80; //minimum size
 
$output='<div class="tagcloud">';
foreach($words as $key => $worth) {
	$font_size=$multiplier*$worth;
	//$countvalues='('.$worth.')'; //uncomment this for displaying the hits next to the links 
	$output.='<span><a style="font-size:'.max($font_size,$min_size).'%;" href="[~'.$landing.'~]&amp;FSF_search='.$key.'">'.$key.'</a>'.$countvalues.'</span>  ';
	$output.="rn";
}
 
$output.='</div>';
return $output;

Lifestream Script for Etomite CMS

Posted on January 21, 2010 by bogge

Lifestream is a chronological aggregated view of your life activities online. It is only limited by the content and sources that you use to define it.

This snippet generates a lifestream with the Etomite CMS. You must have a working SimplePie “installation” for this snippet to work.

If you not use Etomite CMS, it will be easy to convert to a regular PHP script.

/*
 lifestream v1.0
 A Etomite script by bogge, bogge.com
 I take no responsibility for any thing, even if I'm to blame.

 "Installing"
 1. Download SimplePie (http://simplepie.org/downloads/), it´s tested with 1.1.3.
 2. Extract and Upload to webserver, upload everything. (http://simplepie.org/wiki/setup/setup)

 Usage
 [ [lifestream]] Shows lifestream
 [ [lifestream?limit=20m&amp;cachelen=3600]] Shows lifestream fetching 20 posts from each feed and with 1h cache.
  I think you get it...

 Settings
*/
$cachelen = isset($cachelen)? $cachelen: "5400"; //Set the minimum time (in seconds) for which a feed will be cached.
$limit = isset($limit)? $limit: "10"; //Set the maximum number of items to return per feed
$path = isset($path)? $path: "/external/simplepie"; //path to simplepie folder, must not end with /, You may need to change this to match the location of simplepie.
$iscontentking = isset($iscontentking)? $iscontentking: "2"; //0=No (no content) 1=Yes (show content), 2=Yes (show descriptions)
$showfav = isset($showfav)? $showfav: "1"; //Show favicon? 1=Yes, 0=No
$addto = isset($addto)? $addto: "1"; //Show "add to" section? 1=Yes, 0=No
$subscribeto = isset($subscribeto)? $subscribeto: "1"; //Show "subscribe" section? 1=Yes, 0=No
$oldpost = mktime(0, 0, 0, date("n")-1, date("j"), date("Y")); // This sets that no post in lifestream is older than today -1 month.

/*
Feeds, add all feed that you would like to show in lifestream.
This sets an array of URLs that you want to parse.
If there is not a feed at this location, auto-discovery is used.
Tested with: Delicious, WordPress blog, Twitter, Flickr, Last.fm, YouTube
Twitter needs more work read more http://simplepie.org/wiki/faq/problematic_feeds
*/
$feedurls = array(
	'http://feeds.delicious.com/v2/rss/bogge',
	'http://feedproxy.google.com/bogge/blog'
);

//No editing below

require_once($_SERVER['DOCUMENT_ROOT'].$path.'/simplepie.inc'); // Make sure SimplePie is included.

$feed = new SimplePie(); // Create a new SimplePie object
$feed-&gt;set_feed_url($feedurls); // Passing feeds
$feed-&gt;set_item_limit($limit); //Set the maximum number of items to return per feed with Multifeeds.
$feed-&gt;set_output_encoding('UTF-8'); //Allows you to override SimplePie's output to match that of your webpage.
$feed-&gt;set_cache_duration($cachelen); //Set the minimum time (in seconds) for which a feed will be cached.
$feed-&gt;init(); // Initialize the feed object. This is what makes everything happen.
$feed-&gt;handle_content_type(); // This method ensures that the SimplePie-enabled page is being served with the correct mime-type and character encoding HTTP headers (character encoding determined by the set_output_encoding() config option.

// If a SimplePie error was thrown, it will display it here.
if ($feed-&gt;error) {
	$output = '

'.$feed-&gt;error().'

';
}

function getClass($url)
{
	//This is a modified version that was orginaly written by http://github.com/trey.
	preg_match('/https{0,1}:\/\/([^\/]*)\/*.*/i', $url, $matches);
	$class = $matches[1];
	$class = preg_replace("/www./", "", $class); // Remove `www.`.
	$class = preg_replace("/.(com|org|net)/", "", $class); // Remove top level domains. Add more as you see fit.
	$class = preg_replace("/./", "_", $class); // Replace `.`s with `_`s.
	return $class;
}

function doRelativeDate($posted_date) {
    /**
        This function returns either a relative date or a formatted date depending
        on the difference between the current datetime and the datetime passed.
            $posted_date should be in the following format: YYYYMMDDHHMMSS

        Relative dates look something like this:
            3 weeks, 4 days ago
        Formatted dates look like this:
            on 02/18/2004

        The function includes 'ago' or 'on' and assumes you'll properly add a word
        like 'Posted ' before the function output.

        By Garrett Murray, http://graveyard.maniacalrage.net/etc/relative/
    **/
    $in_seconds = strtotime(substr($posted_date,0,8).' '.
                  substr($posted_date,8,2).':'.
                  substr($posted_date,10,2).':'.
                  substr($posted_date,12,2));
    $diff = time()-$in_seconds;
    $months = floor($diff/2592000);
    $diff -= $months*2419200;
    $weeks = floor($diff/604800);
    $diff -= $weeks*604800;
    $days = floor($diff/86400);
    $diff -= $days*86400;
    $hours = floor($diff/3600);
    $diff -= $hours*3600;
    $minutes = floor($diff/60);
    $diff -= $minutes*60;
    $seconds = $diff;

    if ($months&gt;0) {
        // over a month old, just show date (yyyy-mm-dd format)
        return 'on '.substr($posted_date,0,4).'-'.substr($posted_date,4,2).'-'.substr($posted_date,6,2);
    } else {
        if ($weeks&gt;0) {
            // weeks and days
            $relative_date .= ($relative_date?', ':'').$weeks.' week'.($weeks&gt;1?'s':'');
            $relative_date .= $days&gt;0?($relative_date?', ':'').$days.' day'.($days&gt;1?'s':''):'';
        } elseif ($days&gt;0) {
            // days and hours
            $relative_date .= ($relative_date?', ':'').$days.' day'.($days&gt;1?'s':'');
            $relative_date .= $hours&gt;0?($relative_date?', ':'').$hours.' hour'.($hours&gt;1?'s':''):'';
        } elseif ($hours&gt;0) {
            // hours and minutes
            $relative_date .= ($relative_date?', ':'').$hours.' hour'.($hours&gt;1?'s':'');
            $relative_date .= $minutes&gt;0?($relative_date?', ':'').$minutes.' minute'.($minutes&gt;1?'s':''):'';
        } elseif ($minutes&gt;0) {
            // minutes only
            $relative_date .= ($relative_date?', ':'').$minutes.' minute'.($minutes&gt;1?'s':'');
        } else {
            // seconds only
            $relative_date .= ($relative_date?', ':'').$seconds.' second'.($seconds&gt;1?'s':'');
        }
    }
    // show relative date and add proper verbiage
    return $relative_date.' ago';
}

$output .= '
<div id="lifestream">
<ul>'; //Start outputing
$stored_date = ''; //Make sure variable is empty

// Here, we'll loop through all of the items in the feed, and $item represents the current item in the loop.
foreach($feed-&gt;get_items() as $item) {

	//Check if item is older than the $oldpost, if older break and stop outputing.
	$currentdate = mktime(0, 0, 0, $item-&gt;get_date('n'), $item-&gt;get_date('j'), $item-&gt;get_date('Y'));
	if ($currentdate &lt; $oldpost) { 		break; 	}   	//Creates the date headers that is used to group items by date. 	$item_date = $item-&gt;get_date('F jS');
	if ($stored_date != $item_date) {
		$stored_date = $item_date;
		$output .= '</ul>
<h2>'.$stored_date.'</h2>
<ul>';
	}

	//Get information about the feed (not the item) and create a CSS class name. ex a feed from flickr.com gets class name "flickr" and the CSS sould me ".flickr".
	$feed = $item-&gt;get_feed();
	$class = getClass($feed-&gt;get_permalink());
	$output .= '
	<li class="'.$class.'">';

	if ($showfav == 1) {
		//Returns the favicon image for the feed's website. If there is no favicon an alternate is shown.
		if (!$favicon = $feed-&gt;get_favicon()) {
			$favicon = $path.'/demo/for_the_demo/favicons/alternate.png';
		}
		//The favicon is linked to the website and the item is linked to the item.
		$output .= '<a href="'.$feed-&gt;get_permalink().'"><img title="'.$feed-&gt;get_title().'" src="'.$favicon.'" alt="'.$feed-&gt;get_title().'" width="16" height="16" /></a>';
	}

	//Link entire item
	$output .= '<a href="'.$item-&gt;get_permalink().'">';

	//Format and output the item title
	if ($title = $item-&gt;get_title()) {
		$output .= '<strong>'.html_entity_decode($title, ENT_QUOTES, "UTF-8").'</strong>';
	}

	//check if Content Is King or should we output description.
	if ($iscontentking == 1) {
		$output .= ' — '.$item-&gt;get_content();
	}elseif ($iscontentking == 2) {
		$output .= ' — '.$item-&gt;get_description();
	}else {}

	//Create and output the relative date for the item. instead of showing "12/01/2009" it shows "2 weeks, 6 days ago". If date over a month old, just show date (yyyy-mm-dd format).
	$reldate = doRelativeDate($item-&gt;get_date("YmdHis"));
	$output .= '<span class="small"> — '.$reldate.'</span></a>';

	//All the Add to code.
	if ($addto == 1) {
		$output .= '

<strong>Add to:</strong> ';
		$output .= '<a href="' . $item-&gt;add_to_delicious() . '"><img title="Add to del.icio.us" src="'.$path.'/demo/for_the_demo/favicons/delicious.png" alt="Add to del.icio.us" width="16" height="16" /></a>';
		$output .= '<a href="' . $item-&gt;add_to_digg() . '"><img title="Digg It!" src="'.$path.'/demo/for_the_demo/favicons/digg.png" alt="Digg It!" width="16" height="16" /></a>';
		$output .= '<a href="' . $item-&gt;add_to_blinklist() . '"><img title="Add to Blinklist" src="'.$path.'/demo/for_the_demo/favicons/blinklist.png" alt="Add to Blinklist" width="16" height="16" /></a>';
		$output .= '<a href="' . $item-&gt;add_to_blogmarks() . '"><img title="Add to Blogmarks" src="'.$path.'/demo/for_the_demo/favicons/blogmarks.png" alt="Add to Blogmarks" width="16" height="16" /></a>';
//		$output .= '<a href="' . $item-&gt;add_to_furl() . '"><img title="Add to Furl" src="'.$path.'/demo/for_the_demo/favicons/furl.png" alt="Add to Furl" width="16" height="16" /></a>';
		$output .= '<a href="' . $item-&gt;add_to_magnolia() . '"><img title="Add to Ma.gnolia" src="'.$path.'/demo/for_the_demo/favicons/magnolia.png" alt="Add to Ma.gnolia" width="16" height="16" /></a>';
		$output .= '<a href="' . $item-&gt;add_to_myweb20() . '"><img title="Add to My Web 2.0" src="'.$path.'/demo/for_the_demo/favicons/myweb2.png" alt="Add to My Web 2.0" width="16" height="16" /></a>';
		$output .= '<a href="' . $item-&gt;add_to_newsvine() . '"><img title="Add to Newsvine" src="'.$path.'/demo/for_the_demo/favicons/newsvine.png" alt="Add to Newsvine" width="16" height="16" /></a>';
		$output .= '<a href="' . $item-&gt;add_to_reddit() . '"><img title="Add to Reddit" src="'.$path.'/demo/for_the_demo/favicons/reddit.png" alt="Add to Reddit" width="16" height="16" /></a>';
		$output .= '<a href="' . $item-&gt;add_to_simpy() . '"><img title="Add to Simpy" src="'.$path.'/demo/for_the_demo/favicons/simpy.png" alt="Add to Simpy" width="16" height="16" /></a>';
		$output .= '<a href="' . $item-&gt;add_to_spurl() . '"><img title="Add to Spurl" src="'.$path.'/demo/for_the_demo/favicons/spurl.png" alt="Add to Spurl" width="16" height="16" /></a>';
		$output .= '<a href="' . $item-&gt;add_to_wists() . '"><img title="Add to Wists" src="'.$path.'/demo/for_the_demo/favicons/wists.png" alt="Add to Wists" width="16" height="16" /></a>';
		$output .= '

';
	}

	//All the Subscribe code and One-Click Subscriptions.
	if ($subscribeto == 1) {
		$output .= '

<strong>Subscribe to this feed:</strong> <a href="' . $feed-&gt;subscribe_url() . '"><img title="Subscribe to this feed" src="'.$path.'/demo/for_the_demo/feed.png" alt="Subscribe to this feed" width="16" height="16" /></a>';
		$output .= ' | <a href="'.$feed-&gt;subscribe_google().'">Subscribe in Google Reader</a>';
		$output .= '

';
	}

	$output .= '</li>
';
}
$output .= '</ul>
<span style="float:right; font-size:9px; color:#888;"><a title="Lifestream script coded by bogge" href="http://www.bogge.com/info/scripting-language/etomitecms/lifestream-script">Script</a> by <a title="You can find tv series information, scripts, services and torrents at Bogge.com" href="http://www.bogge.com/">Bogge</a></span></div>
';

return $output;</pre>

<pre lang="css">
#lifestream {
font-size:12px;
width:620px;
margin:15px auto auto;
padding:5px;
}
 
#lifestream ul {
list-style-position:inside;
list-style-type:none;
margin-left:0;
padding-left:0;
}
 
#lifestream li {
margin-bottom:3px;
margin-left:0;
padding:5px;
}
 
#lifestream li a {
text-decoration:none;
color:#111;
}
 
#lifestream li img {
margin-right:5px;
border: 0;
vertical-align: middle;
}
 
#lifestream h2 {
font-family:Arial,'Trebuchet MS',Sans-Serif;
font-weight:700;
font-size:120%;
margin:10px 0;
color:#fff;
background-color:#000;
letter-spacing:0.5px;
padding:4px 0 4px 0;
text-align: center
}
 
.twitter {
background-color:#FF8000;
}
 
.flickr {
background-color:#f8d8e9;
}
 
.delicious {
background-color:#CCCCFF;
}
 
.last_fm {
background-color:#FFCC99;
}
 
.bogge {
background-color:#ECFDCE;
}
 
.youtube {
background-color:#FFAFAF;
}
 
.small {
font-size:10px;
color:#888;
}

Etomite (basic) Flickr script

Posted on January 19, 2010 by bogge

Flickr is a photo management and sharing application where you can upload your photos and share them.

This script displays someones public photos on any page in Etomite. Basic and simple flickr integration, shows public photos or favorite public photos.

/*
 flickr-basic v0.1
 A Etomite script by bogge, bogge.com
 I take no responsibility for any thing, even if I'm to blame.

 Usage
 Get an yahoo API key, and enter it in the settings.
 [ [flickr-basic]] Shows 100 om my latest public photos. Change user in settings to show other photos.
 [ [flickr-basic?picsize=m&amp;per_page=10]] Shows 10 small photos.
 [ [flickr-basic?picsize=t&amp;per_page=2&amp;[email protected]]] Show 2 thumbnail photos of user X
 I think you get it...

 Settings
*/
$api_key = 'API_KEY_REQUIRED'; // API key (Required) www.flickr.com/services/api/keys/apply/
// Cache
$userequestcache = true; // Set to false to disable, using requestcache speeds up the script.
$usephotocache = false; // Set to true to enable.
$cachedir = isset($cachedir)? $cachedir: "cache/"; //cache location
$age = isset($age)? $age: "43200"; // 12h for the requests, not the photos.

// Format
$dateformat = isset($dateformat)? $dateformat: "%G-%m-%d %R"; // See strftime for other settings.
$picsize = isset($picsize)? $picsize: "s"; // "s" = small square 75x75, "t" = thumbnail, 100 on longest side, "m" = small, 240 on longest side, "b" = large, 1024 on longest side (only exists for very large original images)

// Extra information
$extras = isset($extras)? $extras: ""; // A comma-delimited list of extra information to fetch for each returned record. Currently supported fields are: license, date_upload, date_taken, owner_name, icon_server, last_update, geo, tags, machine_tags.

// Pages
$per_page = isset($per_page)? $per_page: "100"; // Number of photos to return per page. Default 100 pictures per page.
$page = isset($page)? $page: "1"; // The page of results to return. Default first page.

// User
$nsid = isset($nsid)? $nsid: "[email protected]"; // Default user, nsid only.. 

// Action, What to do.
$method = isset($method)? $method: "flickr.people.getPublicPhotos"; // Defult method
// flickr.people.getPublicPhotos = Get a list of public photos for the given user.
// flickr.favorites.getPublicList = Returns a list of favorite public photos for the given user.

// Do not edit below
function EtomiteErrorHandler($errno, $errstr, $errfile, $errline)
{
    return true;
}

// build the API URL to call

$params = array(
	'api_key'	=&gt; $api_key,
	'user_id'	=&gt; $nsid,
	'method'	=&gt; $method,
	'per_page'	=&gt; $per_page,
	'page'		=&gt; $page,
	'extras'	=&gt; $extras,
	'format'	=&gt; 'php_serial',
);
$encoded_params = array();
foreach ($params as $k =&gt; $v){
	$encoded_params[] = urlencode($k).'='.urlencode($v);
}

// call the API and decode the response

$url = "http://api.flickr.com/services/rest/?".implode('&amp;', $encoded_params);
if ($userequestcache) {
//Cache start
	$old_error_handler = set_error_handler("EtomiteErrorHandler");
		$filename = $cachedir.md5($url);
		// default to fetch the file
		$fetch = true;
		// but if the file exists, don't fetch if it is recent enough
		if (file_exists($filename)) {
			$fetch = (filemtime($filename) &lt; (time()-$age));
		}
		if ($fetch) {
			$rsp = @file_get_contents($url);
			if($rsp) {
				$fp_dst = fopen($filename,"w");
				if($fp_dst) {
					fwrite($fp_dst,$rsp);
					fclose($fp_dst);
				}else{
					fclose($filename);
					$rsp = @file_get_contents($filename);
				}
			}else{
				$rsp = @file_get_contents($filename);
			}
		}else{
			$rsp = @file_get_contents($filename);
		}
	restore_error_handler();
//Cache end
}else{
$rsp = @file_get_contents($url);
}
if (!$rsp) {
$output .= 'Error connecting to Flickr. Please try again later.';
}else{
$rsp_obj = unserialize($rsp);

// display the photo (or an error if it failed)

if ($rsp_obj['stat'] == 'ok'){
	$output .= 'Page: '.$rsp_obj['photos']['page'].' of '.$rsp_obj['photos']['pages'].' pages. 
';
	$output .= 'Number of photos on this page: '.$rsp_obj['photos']['perpage'].' of '.$rsp_obj['photos']['total'].' photos.
';
	foreach ($rsp_obj['photos']['photo'] as $photo) {
		$bildlink = 'http://www.flickr.com/photos/'.$photo['owner'].'/'.$photo['id'].'';
		$bildname = $photo['id'].'_'.$photo['secret'].'_'.$picsize.'.jpg';
		$bildsrc = 'http://farm'.$photo['farm'].'.static.flickr.com/'.$photo['server'].'/'.$bildname;
		if ($usephotocache) {
		//Cache start
		$old_error_handler = set_error_handler("EtomiteErrorHandler");
		    	$filename = $cachedir.$bildname;
		    	if (file_exists($filename)) {
				$file = $filename;
		    	}else{
				$fetchedpic = @file_get_contents($bildsrc);
				if($fetchedpic) {
					$fp_dst = fopen($filename,"w");
					if($fp_dst) {
						fwrite($fp_dst,$fetchedpic);
						fclose($fp_dst);
						$file = $filename;
					}else{
						$file = $bildsrc;
						fclose($filename);
					}
				}else{
					$file = $bildsrc;
				}
			}
		restore_error_handler();
		//Cache end
		}else{
			$file = $bildsrc;
		}
		$output .= '
<div style="float:left;"><a onclick="javascript:urchinTracker('/outgoing/'.$bildlink.'')" href="'.$bildlink.'">';
		$output .= '<img title="'.$photo['title'].'" src="'.$file.'" alt="'.$photo['title'].'" /></a>
';
		if (isset($photo['license'])) {
			if ($photo['license'] == '1') {
				$license = '<a href="http://creativecommons.org/licenses/by-nc-sa/2.0/">Attribution-NonCommercial-ShareAlike License</a>';
			}elseif ($photo['license'] == '2') {
				$license = '<a href="http://creativecommons.org/licenses/by-nc/2.0/">Attribution-NonCommercial License</a>';
			}elseif ($photo['license'] == '3') {
				$license = '<a href="http://creativecommons.org/licenses/by-nc-nd/2.0/">Attribution-NonCommercial-NoDerivs License</a>';
			}elseif ($photo['license'] == '4') {
				$license = '<a href="http://creativecommons.org/licenses/by/2.0/">Attribution License</a>';
			}elseif ($photo['license'] == '5') {
				$license = '<a href="http://creativecommons.org/licenses/by-sa/2.0/">Attribution-ShareAlike License</a>';
			}elseif ($photo['license'] == '6') {
				$license = '<a href="http://creativecommons.org/licenses/by-nd/2.0/">Attribution-NoDerivs License</a>';
			}else{
			$license = 'All rights reserved.';
			}
			$output .= 'License: '.$license.'
';
		}
		if (isset($photo['dateupload'])) { $photo['dateupload'] = strftime($dateformat,$photo['dateupload']); $output .= 'Date uploaded: '.$photo['dateupload'].'
';}
		if (isset($photo['datetaken'])) { $output .= 'Date taken: '.$photo['datetaken'].'
';}
		if (isset($photo['ownername'])) { $output .= 'Owner: '.$photo['ownername'].'
';}
		if (isset($photo['iconserver'])) {
			if ($photo['iconserver'] &gt; "0") {
				$output .= '<img src="http://farm'.$photo['iconfarm'].'.static.flickr.com/'.$photo['iconserver'].'/buddyicons/'.$nsid.'.jpg" alt="" width="48" height="48" />
';
			}else{
				$output .= '<img src="http://www.flickr.com/images/buddyicon.jpg" alt="" width="48" height="48" />
';
			}
		}
		if (isset($photo['lastupdate'])) { $photo['lastupdate'] = strftime($dateformat,$photo['lastupdate']); $output .= 'Last updated: '.$photo['lastupdate'].'
';}
		if (isset($photo['latitude'])) { $output .= 'Lat: '.$photo['latitude'].', Long: '.$photo['longitude'].', Acc: '.$photo['accuracy'].'
';}
		if (isset($photo['tags'])) { $output .= 'Tags: '.$photo['tags'].'
';}
		if (isset($photo['machine_tags'])) { $output .= 'Machine tags: '.$photo['machine_tags'].'
';}
		$output .= '</div>
';
	}
}else{

	$output = '

'.$rsp_obj['stat'].'

';
	$output = '

'.$rsp_obj['message'].'

';
}
}
return $output;

EtoDelicious

Posted on January 17, 2010 by bogge

This code is not completely finished and can only be used at your own risk!

This snippet use PhpDelicious to post and get data from your del.icio.us account. Some data is sent to chunks that includes all the html design code. Also includes tagcloud generator, backup, restore and random link features.

/**************************************************** 
* All usage att own risk! Bogge not responsible.
* Name: phpdelicious 
* Version: 0.1
* Created by Bogge, bogge.com
*****************************************************
 
Thanks to:
Ed Eliot for:
PhpDelicious, http://www.ejeliot.com/pages/php-delicious
Delicious Stumble, http://www.ejeliot.com/blog/78
Backup & Restore scripts, http://www.ejeliot.com/blog/69
 
Usage: This snippet use PhpDelicious to post and get data from your del.icio.us account. Some data is sent to chunks that includes all the html design code. Also includes tagcloud generator, backup, restore and random link features. Se examples.
 
Installing: Download PhpDelicious @ http://www.ejeliot.com/pages/php-delicious. This script is tested with PhpDelicious last updated 13th January 2006. Upload PhpDelicious to webserver. Change first line at config to point to php-delicious.inc.php.
 
Examples:
[ [phpdelicious?action=getallposts]] Returns all posts.
[ [phpdelicious?action=getallposts&tag=etomite]] Returns all posts with tag etomite.
[ [phpdelicious?action=getrecentposts]] Returns 15 most recent posts.
[ [phpdelicious?action=getrecentposts&tag=etomite]] Returns 15 most recent posts with tag etomite.
[ [phpdelicious?action=getrecentposts&count=20]] Returns 20 most recent posts. Min 15, Max 100.
[ [phpdelicious?action=getrecentposts&tag=etomite&count=30]] Returns 30 most recent posts with tag etomite.
[ [phpdelicious?action=getposts]] Returns all post made today.
[ [phpdelicious?action=getposts&tag=etomite]] Returns latest post with tag etomite
[ [phpdelicious?action=getposts&tag=etomite&date=2007-02-09]] Returns all posts with tag etomite that was posted 2007-02-09.
[ [phpdelicious?action=getposts&tag=etomite&date=2007-02-09&url=http://www.etomite.org/]]
[ [phpdelicious?action=getposts&tag=etomite&url=http://www.etomite.org/]] Returns all post with etomite tag and http://www.etomite.org/ as url.
[ [phpdelicious?action=getposts&url=http://www.etomite.org/]] Returns all post with http://www.etomite.org/ as url.
[ [phpdelicious?action=tagcloud]] Returns a tagcloud.
[ [phpdelicious?action=getlastupdate]] Returns last time the user updated their del.icio.us account.
[ [phpdelicious?action=getdates]] Returns list with number of posts for each date.
[ [phpdelicious?action=getdates&tag=etomite]] Returns list with number of posts for each date for etomite tag.
[ [phpdelicious?action=stumble]] Redirect you to a random site within your posts.
[ [phpdelicious?action=stumble&tag=etomite]] Redirect you to a random site thats tagged with etomite.
[ [phpdelicious?action=getalltags]] Returns all tags in format "tag (count)".
[ [phpdelicious?action=backup]] Backup alla posts to database.
[ [phpdelicious?action=restore]] Restore all posts to del.icio.us.
 
Example chunk { {deliciouspost}}:
<h3><a href="{url}">{desc}</a></h3>
{notes}
<p>
<b>Last updated:</b>&nbsp;{updated}<br />
<b>Tags:</b>&nbsp;{alltags}
</p>
 
Format:
date - YYYY-MM-DD HH:MM:SS
url - Must be an perfect match, http://www.etomite.org/ and http://www.etomite.org is note the same url.
 
Public Methods not included in this snippet:
AddBundle()
AddPost()
DeleteBundle()
DeletePost()
GetAllBundles()
LastErrorNo()
LastErrorString()
RenameTag()
 
SQL Backup Table:
create table if not exists del_posts (
   url varchar(250),
   description varchar(250),
   notes text,
   hash varchar(50),
   updated datetime,
   primary key(hash)
);
create table if not exists del_tags (
   hash varchar(50),
   tag varchar(50)
);
*/
 
/*****Config*****/
/* Include php-delicious, http://www.ejeliot.com/pages/php-delicious */
require("phpdelicious/php-delicious.inc.php");
 
//del.icio.us
$username = 'username'; // your del.icio.us username
$password = 'password'; // your del.icio.us password
 
//Tags
$landing = isset($landing)? $landing : "[*id*]"; //Where to go when you clicked on a tag.
 
//TagCloud
$min = isset($min)? $min : "2"; //Minimum occurrences of a word to be displayed
$font_max = isset($font_max)? $font_max : "400"; //Maximum font-size % (play with that to fit your site)
$font_min = isset($font_min)? $font_min : "80"; //Minimum font-size %
$exclude = array('',' ','  ','   ','and','a','-','—','&ndash;','the','&mdash;','to','.',':',',','&nbsp;'); //exclude list
 
//Backup and Restore
$host = 'localhost'; //Name of mysql server
$dbase = 'db'; //Database name
$user = 'user'; //Mysql user
$pass = 'password'; //Mysql password
$posts_table = 'del_posts'; //Table of posts
$tags_table = 'del_tags'; //Table of tags
/*****************/
 
//Functions
function output_deliciouspost($funcEtomite, $aPosts, $landing) {
	foreach ($aPosts as $aPost) { //Loop posts.
		foreach ($aPost["tags"] as $aPost["tag"]) { //Create "alltags" string.
			$aPost["alltags"] .= '<a href="[~'.$landing.'~]?listtag='.$aPost["tag"].'">'.$aPost["tag"].'</a> ';
		}
		$output .=  $funcEtomite->parseChunk(deliciouspost, $aPost); //Output to chunk.
		/*
		$aPost includes:
		["url"]=> string like "http://www.etomite.com/"
		["desc"]=> string like "Etomite Content Management System"
		["notes"]=> string like "Etomite is a Content Management System."
		["hash"]=> string, hash of url
		["tags"]=> array like array(2) { [0]=> string(7) "etomite" [1]=> string(6) "cms" }
		["updated"]=> string like "2007-02-07 09:47:09"
		["tag"]=> string like "cms", last tag in tags array.
		["alltags"]=> string like "etomite cms", all tags in one line.
		*/
	}
	return $output;
}
 
//GetAllPosts
If ($action == "getallposts") {
	$oPhpDelicious = new PhpDelicious($username, $password);
	$aPosts = $oPhpDelicious->GetAllPosts($tag); //Call php-delicious function.
	$output = output_deliciouspost($etomite, $aPosts, $landing); //Calls output_deliciouspost function.
}
 
//GetDates
elseif ($action == "getdates") {
	$oPhpDelicious = new PhpDelicious($username, $password);
	$dates = $oPhpDelicious->GetDates($tag);
	if(isset($tag)) {
		$output .= '<h2>Number of posts for '.$tag.' tag</h2>';
	}
	else {
		$output .= '<h2>Number of posts for each date</h2>';
	}
	foreach ($dates as $date) {
		$output .= '<b>'.$date['date'].':</b> '.$date['count'].'<br />';
	}
}
 
//GetLastUpdate
elseif ($action == "getlastupdate") {
	$oPhpDelicious = new PhpDelicious($username, $password);
	$output = $oPhpDelicious->GetLastUpdate();
}
 
//GetPosts
elseif ($action == "getposts") {
	$oPhpDelicious = new PhpDelicious($username, $password);
	$aPosts = $oPhpDelicious->GetPosts($tag, $date, $url);
	$output = output_deliciouspost($etomite, $aPosts, $landing);
}
 
//GetRecentPosts
elseif ($action == "getrecentposts") {
	$oPhpDelicious = new PhpDelicious($username, $password);
	$aPosts = $oPhpDelicious->GetRecentPosts($tag, $count);
	$output = output_deliciouspost($etomite, $aPosts, $landing);
}
 
//GetAllTags
elseif ($action == "getalltags") {
	$oPhpDelicious = new PhpDelicious($username, $password);
	$tags = $oPhpDelicious->GetAllTags();
	foreach($tags as $tag) {
		$output .= $tag['tag']." (".$tag['count'].") ";
	}
}
 
//TagCloud
elseif ($action == "tagcloud") {
	$oPhpDelicious = new PhpDelicious($username, $password);
	$tags = $oPhpDelicious->GetAllTags();
	foreach($tags as $tag) {
		if($tag['count']>=$min && (!in_array($tag['tag'],$exclude))) { 
			$words[$tag['tag']] = $tag['count'];
		}
	}
	$max_size=max($words); //word with most hits
	ksort($words, SORT_STRING); //sort them alphabetically (just comment that out, then they will be unsortet
	$multiplier=$font_max/$max_size; //define the multiplier for the size
	$min_size=$font_min; //minimum size
	$output='<div class="tagcloud">';
	foreach($words as $key => $worth) {
		$font_size=$multiplier*$worth;
		//$countvalues='('.$worth.')';		//uncomment this for displaying the hits next to the links 
		$output.='<span><a style="font-size:'.max($font_size,$min_size).'%;" href="[~'.$landing.'~]?listtag='.$key.'">'.$key.'</a>'.$countvalues.'</span>  ';
		$output.="rn";
	}
	$output.='</div><br />';
	if(isset($_GET['listtag'])) {
		$listtag = $_GET['listtag'];
		$output .= '<h2>Links tagged with '.$listtag.'</h2>';
		$oPhpDelicious2 = new PhpDelicious($username, $password);
		$aPosts = $oPhpDelicious2->GetAllPosts($listtag);
		$output .= output_deliciouspost($etomite, $aPosts, $landing);
	}
}
 
//Stumble
elseif ($action == "stumble") {
	$oPhpDelicious = new PhpDelicious($username, $password);
	$aPosts = $oPhpDelicious->GetAllPosts($tag);
	$iPost = array_rand($aPosts);
	header('Location: '.$aPosts[$iPost]['url']);
	exit;
}
 
//BackUp
elseif ($action == "backup") {
	$oDelicious = new PhpDelicious($username, $password);
	if ($aPosts = $oDelicious->GetAllPosts()) {
		//Clean tables
		$query = 'delete from '.$posts_table;
		$etomite->dbExtQuery($host, $user, $pass, $dbase, $query);
		$query = 'delete from '.$tags_table;
		$etomite->dbExtQuery($host, $user, $pass, $dbase, $query);
		$sInsertPosts = 'insert into '.$posts_table.' (url, description, notes, hash, updated) values';
		$sInsertTags = 'insert into '.$tags_table.' (hash, tag) values';
		foreach ($aPosts as $aPost) {
			$sInsertPosts .= sprintf(" ('%s', '%s', '%s', '%s', '%s'),", 
				mysql_real_escape_string($aPost['url']), 
				mysql_real_escape_string($aPost['desc']), 
				mysql_real_escape_string($aPost['notes']),
				mysql_real_escape_string($aPost['hash']), 
				mysql_real_escape_string($aPost['updated'])
			);
			foreach ($aPost['tags'] as $sTag) {
				$sInsertTags .= sprintf(" ('%s', '%s'),", 
					mysql_real_escape_string($aPost['hash']), 
					mysql_real_escape_string($sTag)
				);
			}
		}
		$query = rtrim($sInsertPosts, ',');
		$etomite->dbExtQuery($host, $user, $pass, $dbase, $query);
		$query = rtrim($sInsertTags, ',');
		$etomite->dbExtQuery($host, $user, $pass, $dbase, $query);
		$output .= 'Backup done! (I hope)';
	} 
	else {
		$output .= $oDelicious->LastErrorString();
	}
}
 
//Restore
elseif ($action == "restore") {
	$oDelicious = new PhpDelicious($username, $password);
	$query = 'select url, description, notes, hash, updated from '.$posts_table.' order by updated asc';
	if ($oPosts = $etomite->dbExtQuery($host, $user, $pass, $dbase, $query)) {
		while ($aPost = mysql_fetch_assoc($oPosts)) {
			$aTags = array();
			$query = sprintf("select tag from ".$tags_table." where hash = '%s' order by tag asc", $aPost['hash']);
			if ($oTags = $etomite->dbExtQuery($host, $user, $pass, $dbase, $query)) {
				while ($aTag = mysql_fetch_assoc($oTags)) {
					$aTags[] = $aTag['tag'];
				}
			}
			else {
				$output .= 'Error getting tags!';
			}
			$oDelicious->AddPost($aPost['url'], $aPost['description'], $aPost['notes'], $aTags, $aPost['updated'], true);
		}
		$output .= 'Restore done! (I hope)';
	}
	else {
		$output .= 'Error getting posts!';
	}
}
else {
	$oPhpDelicious = new PhpDelicious($username, $password);
	return $oPhpDelicious->LastErrorString();
}
 
return $output;
Page 1 of 212»
  • Connect with us:
  • RSS
  • © 2021 www.bogge.com
  • bogge.com | bogge.eu | bogge.tv