summaryrefslogtreecommitdiff
path: root/BigLine.php
blob: 87c023df65badadbe73c0956c0107547923b12b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<?php
/**
  *
		Licensed under WTFPL - DoWhatTheFuckYouWant Public License
		(c) Hugues Hiegel 2006-2008 <hugues@hiegel.fr>

		Thanks to Pavel ZbytovskĂ˝ - www.zby.cz
			for saving me time with the MySQL stuff !


CREATE TABLE `users` (
	`username` varchar(100) NOT NULL,
	`statsstart` bigint(11) NOT NULL,
	`playcount` int(10) unsigned NOT NULL,
	`lastupdate` bigint(11) unsigned NOT NULL,
	`lastchecked` bigint(11) unsigned NOT NULL,
	PRIMARY KEY  (`username`)
) ;

CREATE TABLE `badges` (
	`username` varchar(100) NOT NULL,
	`type` varchar(100) NOT NULL,
	`style` varchar(100) NOT NULL,
	`color` varchar(100) NOT NULL,
	`lastupdate` bigint(11) default NULL,
	`hits` bigint(20) unsigned NOT NULL,
	`lasthit` bigint(11) unsigned default NULL,
	`png` varchar(100) NOT NULL,
	PRIMARY KEY  (`username`,`type`)
);

  *
  */

/*get the parameters*/
$Pathinfo=$_SERVER['PATH_INFO'];
$pathinfo=explode("/", $Pathinfo);
$script=explode("/", $_SERVER['SCRIPT_NAME']);

$username=$pathinfo[1];
$type=$pathinfo[2];
$style=$pathinfo[3];
$color=$pathinfo[4];


include("Config.BigLine.php");


mysql_connect(MYSQL_HOST, MYSQL_USER);
mysql_select_db(MYSQL_DB);

/*make cache data (array $data)*/
$res = mysql_query("SELECT * FROM users WHERE username='" . gpc_addslashes(strtolower($username)) . "'");
$data = mysql_fetch_assoc($res);

if(($username AND !mysql_num_rows($res))
// Check once every hour.
OR ($data['lastchecked'] AND $data["lastchecked"]+3600 < time()))
  make_db_cache($username);

/*output image cache*/
$user=strtolower(rawurlencode($username))
$Cache=CACHE_FOLDER."/Pictures/".substr($user, 0, 2)."/".$user."_$type-$style-$color.png";

//clearstatcache();

if (is_file($Cache))
{
	SendCacheHeaders($data["lastupdate"], CACHE);
}

/*-----------------------------------------------------------
	Expired.
		Ok, now we are ready to create the image with GD.
*/

$Lines = array();
$Lines[] = new Text;

if (! $data["playcount"])
{
	header('Location: /out-of-order.png');
	exit();
}
else
{
	$playcount = $data['playcount'];
	$statsstart = $data['statsstart'];

	$res = mysql_query("SELECT * FROM badges WHERE username='" . gpc_addslashes(strtolower($username)) . "' AND type='$type' AND style='$style' AND color='$color';");
	$badge = mysql_fetch_assoc($res);

	if (  !is_file($Cache)
	   OR (filemtime($Cache) < $data['lastupdate'])
	   OR !filesize($Cache)
	   )
	{

		$duration =  $_SERVER['REQUEST_TIME'] - $statsstart;
		$months = $duration / (60*60*24*30);
		$weeks  = $duration / (60*60*24*7);
		$days   = $duration / (60*60*24);

		$TracksPerDay = floor($playcount / $days);
		$TracksPerWeek = floor($playcount / $weeks);
		$TracksPerMonth = floor($playcount / $months);
		define("TRACKS_PER_ALBUM", 13);
		$AlbumsPerDay = floor($TracksPerDay / TRACKS_PER_ALBUM);
		$AlbumsPerWeek = floor($TracksPerWeek / TRACKS_PER_ALBUM);
		$AlbumsPerMonth = floor($TracksPerMonth / TRACKS_PER_ALBUM);

		$formats = array("DEFAULT"	=> "\$number \$albumtrack per \$dayweekmonth",
						 "Total"	=> "\$number \$albumtrack played",
						 "Trueness"	=> "\$username is \$trueness listener",
						 "Since"	=> "Since \$since");

		switch($type)
		{
			case "AlbumsPerDay":
			case "AlbumsPerWeek":
			case "AlbumsPerMonth":
			case "TracksPerDay":
			case "TracksPerWeek":
			case "TracksPerMonth":
				$format="DEFAULT";
				preg_match("/^(Album|Track)sPer(Day|Week|Month)$/",$type,$match);
				$albumtrack=$match[1];
				$dayweekmonth=$match[2];
				eval("\$number=\$".$albumtrack."sPer".$dayweekmonth.";");
				$albumtrack .= ($number != 1 ? 's' : '');
				break;
			case "Trueness":
				$format=$type;
				$trueness = ($TracksPerMonth < TRUENESS ? "a true" : "an untrue");
				break;
			case "Since":
				$format=$type;
				$since=strftime("%B %Y", $statsstart);
				break;
			case "TotalTracks":
			case "TotalAlbums":
				$format="Total";
				preg_match("/^Total(Track|Album)s$/",$type,$match);
				$albumtrack=$match[1];
				switch ($albumtrack.'s')
				{
					case "Tracks":
						$number=$playcount;
						$albumtrack.=($number != 1 ? 's' : '');
						break;
					case "Albums":
						$number = floor($playcount / TRACKS_PER_ALBUM);
						$albumtrack.=($number != 1 ? 's' : '');
						break;
				}
				break;
			default:
				header('Location: /out-of-order.png');
				exit();
				break;
		}

		define("ANGLE",2);
		$y=0;

		$username=ucfirst($username);
		foreach ($Lines as $Line)
		{
			eval("\$Line->value=\"$formats[$format]\";");
			$Line->font = "" . $Styles[$style];
			$Line->angle=ANGLE;

			$size=imageftbbox($Line->size, $Line->angle, $Line->font, $Line->value);
			$Line->initiate($size);
			$y+=$Line->height + 20;
			$Line->y = $y - 15;
			$Line->x += 10;
		}
		$username=strtolower($username);

		$Image = new Text;
		$Image->width   = WIDTH + 20;
		$Image->height  = $y;

		$img=imagecreatetruecolor($Image->width, $Image->height);
		imagealphablending($img, FALSE);
		imagesavealpha($img, TRUE);

		foreach ($Lines as $Line)
		{
			$Line->color=imagecolorallocate($img, GetColor("r", $Colors[$color]),
												  GetColor("g", $Colors[$color]),
												  Getcolor("b", $Colors[$color]));
		}
		$transparent=imagecolorallocatealpha($img, 255, 255, 255, 127);

		imagefilledrectangle($img, 0, 0, $Image->width, $Image->height, $transparent);

		foreach ($Lines as $Line)
		{
			//if ($username == "gugusse") imagerectangle($img, 0, 0, $Image->width - 1, $Image->height - 1, $Line->color);
			imagettftext($img, $Line->size, $Line->angle, $Line->x, $Line->y, $Line->color, $Line->font, $Line->value);
		}


		imagepng($img, $Cache);
		imagedestroy($img);

		$QUERY=sprintf("REPLACE INTO badges (username, type, style, color, lastupdate, png) VALUES ('%s','%s','%s','%s', %s, '%s');", 
			  $username,
			  $type,
			  $style,
			  $color,
			  time(),
			  $Cache );
		//echo $QUERY;
		mysql_query($QUERY);
	}

	if (is_file($Cache))
	{
		touch_badge($username, $type, $style, $color);
		header("Content-Type: image/png");
		echo @file_get_contents($Cache);
	}
}

//------------ END -----------------------------------------------//



function GetGMT($time)
{
	return gmdate("D, d M Y H:i:s", $time) . " GMT";
}

function SendCacheHeaders($lastmodified, $maxage, $limit="public")
{
	$LastModified = GetGMT($lastmodified);
	if (array_key_exists("HTTP_IF_MODIFIED_SINCE", $_SERVER) &&
	    $_SERVER['HTTP_IF_MODIFIED_SINCE'] == "$LastModified")
	{
		header("HTTP/1.1 304 Not Modified");
		exit;
	}

	/* Give a fresh copy */
	$Expires = GetGMT($_SERVER['REQUEST_TIME'] + $maxage);
	header("Cache-Control: max-age=$maxage, $limit");
	header("Last-Modified: $LastModified");
	header("Expires: $Expires");
}



function make_db_cache($username){
  global $data;
  $profile_xml = @file_get_contents("http://ws.audioscrobbler.com/1.0/user/".rawurlencode($username)."/profile.xml");

  $feed=new XMLReader();
  if($profile_xml && $feed->xml($profile_xml)){

	$modified = FALSE;

	while ($feed->read())
	{
		switch ($feed->name)
		{
			case "playcount":
				$feed->read();
				$value = intval($feed->value);
				if ($data['playcount'] != $value)
				{
					$data['playcount']=$value;
					$modified=TRUE;
				}
				$feed->read();
				break;

			case "registered":
			case "statsreset":
				$value = $feed->getAttribute("unixtime");
				if ($data['statsstart'] != $value)
				{
					$data['statsstart']=$value;
					$modified = TRUE;
				}
				$feed->read();
				$feed->read();
				break;

			case "profile":
				$value = $feed->getAttribute("username");
				if ($data['username'] != $value)
				{
					$data['username']=$value;
					$modified = TRUE;
				}
				break;
		}
	}


	if ($data['playcount'] != 0)
	{
		$data['lastchecked']=time();
		if ($modified)
			$data['lastupdate']=$data['lastchecked'];

		$QUERY=(sprintf("REPLACE INTO users (lastupdate,lastchecked,playcount,statsstart,username) VALUES ('%s',%s,'%s','%s','%s');",
		  $data['lastupdate'], $data['lastchecked'], $data['playcount'], gpc_addslashes($data['statsstart']), gpc_addslashes(strtolower($username))));
		mysql_query($QUERY);
	}
  }
}

function touch_badge($username, $type, $style, $color)
{
	$res = mysql_query("SELECT hits FROM badges WHERE username='" . gpc_addslashes(strtolower($username)) . "' AND type='$type' AND style='$style' AND color='$color';");
	$data = mysql_fetch_assoc($res);

	//if(mysql_num_rows($res))
	$hits = @$data["hits"];
	$hits++;

	$QUERY=sprintf("UPDATE badges SET hits=%s, lasthit='%s' WHERE username='%s' AND type='$type' AND style='$style' AND color='$color';", 
		$hits, time(), gpc_addslashes(strtolower($username)));
	//echo $QUERY;
	mysql_query($QUERY);
}

function gpc_addslashes($str){
  return (get_magic_quotes_gpc() ? $str : addslashes($str));
}

function GetColor($color, $code) {
	switch($color)
	{
		case "r":
			return ($code >> 16) & 0xff;
			break;
		case "g":
			return ($code >>  8) & 0xff;
			break;
		case "b":
			return ($code >>  0) & 0xff;
			break;
	}
}


class Text {
	var $width = 0;
	var $height = 0;
	var $x = 0;
	var $y = 0;

	var $font = "";
	var $size = 300; // High values to better quality
	var $angle = 0;
	var $color = 0;
	var $value = "";

	function initiate($size) {
		$this->width = abs(
			max($size[0], $size[2], $size[4], $size[6])
		  - min($size[0], $size[2], $size[4], $size[6])
		  );
		$this->height= abs(
		    max($size[1], $size[3], $size[5], $size[7])
		  - min($size[1], $size[3], $size[5], $size[7])
		  );

		$ratio = WIDTH / $this->width;

		$this->width *= WIDTH;
		$this->height *= $ratio;
		$this->size *= $ratio;
	}
}