Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

http://lordrich.com

« Newer Snippets
Older Snippets »
Showing 11-19 of 19 total

CPP Web Crawler

Another program I found in my old source code directory. This looks like another web crawler designed to run in Windows.

// http.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream.h>
#include <winsock2.h>
#include <stdio.h>


#define MAX_LENGTH 4096


void main()
      {
          int s_len;
          int skt_Smtp;
          int success;
		  int i;
          struct sockaddr_in st_Sockaddr;
		  char                 recv_Buf[MAX_LENGTH];
          char send_Buf[MAX_LENGTH];

          //Initialize Sockets
          WSADATA wsa;
          WSAStartup(MAKEWORD(2, 0), &wsa);


          skt_Smtp = socket(AF_INET,SOCK_STREAM,0);
          if (skt_Smtp < 0)
          {
              cout<< "Error Creating Socket"<<endl;
              return;
          }
         else
         {
              st_Sockaddr.sin_family = AF_INET;
              st_Sockaddr.sin_port = htons(80);

             //Get the IP address and initialize the structure
             st_Sockaddr.sin_addr.s_addr = inet_addr("143.53.238.9");

             success = connect(skt_Smtp,(struct sockaddr *) &st_Sockaddr,sizeof(st_Sockaddr));

             //do stuff
             strcpy(send_Buf,"GET /internal/index.php HTTP/1.1\r\nHost: www.brad.ac.uk\r\n\r\n");

             s_len = send(skt_Smtp,send_Buf,strlen(send_Buf),0);
	do
	{
		i = recv(skt_Smtp, recv_Buf, MAX_LENGTH, 0);
		if(i < 0)
		{
			printf("recv() returned %d, errno=%d\n", i, errno);
			break;
		}
		if(i > MAX_LENGTH)
			i = MAX_LENGTH;
		printf("%-*.*s", i, i, recv_Buf);
	}
	while(i != 0);


         WSACleanup();
}
}

Perl Crawler

The following code is designed to print all the links found on the google home page. I found it laying around in my old source-code folder, it may not be fully working.

#!/usr/bin/perl
use IO::Socket;

$socket = IO::Socket::INET->new(PeerAddr => 'google.com',
				PeerPort => 80,
				Proto => 'tcp',
				Type => SOCK_STREAM)
	or die "Couldn't connect";
print $socket "GET / HTTP/1.0\n\n";
#$page = <$socket>;
while (defined($line = <$socket>)) {
	$line =~ m{href="(.*?)"}ig;
	print "$1";
    }
close($socket);

Output feedwordpress database for use in Planet

You'll need to change the initial settings as I didn't bother to read them from the Wordpress config file. You may also need to change the table name (wp_links) in the sql query.

<?php
$username = "myuser";
$password = "P455w0rd";
$database = "db_name";
$hostname = "127.0.0.1";

$query = "SELECT link_name, link_rss FROM wp_links WHERE link_category=2";

mysql_connect($hostname, $username,$password);
@mysql_select_db($database) or die("Unable to select database");
$result = mysql_query($query);
$num = mysql_numrows($result);
mysql_close();

$i=0;
while($i < $num) {
        $rss = mysql_result($result,$i,"link_rss");
        $name = mysql_result($result,$i,"link_name");

        echo "[".$rss."]\r\n";
        echo "name = ".$name."\r\n";
        $i++;
}
?>

Feedwordpress mod

A simplified version of update-feeds.php from the Feedwordpress project. This version doesn't bother checking for authentication as there's really no point. It doesn't check whether it's being run at the commandline either, it simply assumes it is being called by wget as a cron job. This is designed to be run with version 0.98

<?php

// Help us to pick out errors, if any.
ini_set('error_reporting', E_ALL & ~E_NOTICE);
ini_set('display_errors', true);
define('MAGPIE_DEBUG', true);

// Are we running from a web request or from the command line?
                $update_feeds_display = 'text/plain';
                $update_feeds_invoke = 'post';
                $update_feeds_verbose = false;

require_once ('../wp-blog-header.php');

function update_feeds_mention ($feed) {
        global $update_feeds_display;

        if ($update_feeds_display=='text/html') :
                echo "<li>Updating <cite>".$feed['link/name']."</cite> from &lt;<a href=\""
                        .$feed['link/uri']."\">".$feed['link/uri']."</a>&gt; ...</li>\n";
        else :
                echo "* Updating ".$feed['link/name']." from <".$feed['link/uri']."> ...\n";
        endif;
        flush();
}

# -- Don't change these unless you know what you're doing...
define ('RPC_MAGIC', 'tag:radgeek.com/projects/feedwordpress/'); // update all

// Query secret word from database
$rpc_secret = get_settings('feedwordpress_rpc_secret');

header("Content-Type: {$update_feeds_display}; charset=utf-8");


        // Henceforward, we can proceed on the assumption that we have an authenticated user
        $uri = (isset($_REQUEST['uri']) ? $_REQUEST['uri'] : RPC_MAGIC.$rpc_secret);

        if ($update_feeds_display=='text/html') :
                echo <<<EOHTML
<?xml version="1.0" encoding="utf-8"?>
<html>
<head>
<title>update-feeds :: FeedWordPress</title>
</head>

<body>
<h1>update-feeds: make FeedWordPress check for new syndicated content</h1>

EOHTML;
        endif;

$feedwordpress =& new FeedWordPress;

if ($update_feeds_display=='text/html' or $update_feeds_verbose) :
        add_action('feedwordpress_check_feed', 'update_feeds_mention');
endif;

if ($update_feeds_display=='text/html') : // HTTP GET or HTTP POST: add some web niceties


        echo "<form action=\"\" method=\"POST\">\n";
        echo "<select name=\"uri\">\n";
        echo "<option value=\"".RPC_MAGIC.$rpc_secret."\">All feeds</option>\n";
        foreach ($feedwordpress->feeds as $feed) :
                echo "<option value=\"{$feed['link/uri']}\"";
                if ($feed['link/uri']==$_REQUEST['uri']) : echo ' selected="selected"'; endif;
                echo ">{$feed['link/name']}</option>\n";
        endforeach;
        echo "</select> ";
        echo "<input type=\"submit\" name=\"update\" value=\"Update\" />\n";
        echo "</form>\n";
endif;

if ($update_feeds_invoke != 'get') : // Only do things with side-effects for HTTP POST or command l
ine
        if ($update_feeds_display == 'text/html') : echo "<ul>\n"; endif;
        $delta = @$feedwordpress->update($uri);
        if ($update_feeds_display == 'text/html') : echo "</ul>\n"; endif;

        if (is_null($delta)) :
                if ($update_feeds_invoke == 'cmd') :
                        $stderr = fopen('php://stderr', 'w');
                        fputs($stderr, "update-feeds (".date('Y-m-d H:i:s')."): ERROR: I don't synd
icate <$uri>\n");
                elseif ($update_feeds_display == 'text/plain') :
                        echo "update-feeds (".date('Y-m-d H:i:s')."): ERROR: I don't syndicate <$ur
i>\n";
                else :
                        echo "<p><strong>Error:</strong> I don't syndicate <a href=\"$uri\">$uri</a
></p>\n";
                endif;
        elseif ($update_feeds_display=='text/html' or $update_feeds_verbose) :
                $mesg = array();
                if (isset($delta['new'])) : $mesg[] = ' '.$delta['new'].' new posts were syndicated
'; endif;
                if (isset($delta['updated'])) : $mesg[] = ' '.$delta['updated'].' existing posts we
re updated'; endif;
                if ($update_feeds_display=='text/html') : echo "<p>"; endif;
                echo "Update complete.".implode(' and', $mesg);
                if ($update_feeds_display=='text/html') : echo "</p>"; endif;
                echo "\n"; flush();
        endif;
endif;

if ($update_feeds_display=='text/html') : // HTTP GET or HTTP POST: close off web niceties
        echo <<<EOHTML

<p><a href="../wp-admin">&larr; Return to WordPress Dashboard</a></p>
</body>
</html>
EOHTML;
endif;
?>

Pseudocode for inserting repeating invoices

This is far closer to a suggested solution than actual usable code.

For all in Template
        i = int((date()-Template.lastbilldate)/Frequency.everyxdays)
        while i > 0
                Addbill(Template.templateID)
        end
End

Function Addbill(int Template.templateID)
        Insert into Bill(Amount.AmountID, Date(), "Membership Fees", Template.memberID
End

Random quotes

Called as quotes.php it will display a single random quote. Called as quotes.php?all=1 it will display all quotes in an unordered list. No database is required, and it should be fairly obvious how to add new quotes.

<?php
$quotes[] = "Boys like hugs too.";
$quotes[] = "Ooh! Train!";
$quotes[] = "La rue est a nous.";
$quotes[] = "The future is unwritten.";

if($all==1) {
        echo "<ul>";
        for($i=0; $i<=count($quotes)-1; $i++) {
                echo "<li>".$quotes[$i]."</li>";
        }
        echo "</ul>";
} else {
        srand ((double) microtime() * 1000000);
        $randomquote = rand(0,count($quotes)-1);
        echo $quotes[$randomquote];
}

?>

Textpattern - display log by hostname


<html>
<head>
<link href="/textpattern/textpattern.css" rel="Stylesheet" type="text/css" />
</head>
<body>
<?php
require_once("textpattern/config.php");
mysql_connect($txpcfg['host'], $txpcfg['user'], $txpcfg['pass']) or die(mysql_error());
mysql_select_db($txpcfg['db']) or die(mysql_error());

// Quote variable to make safe
function quote_smart($value)
{
   // Stripslashes
   if (get_magic_quotes_gpc()) {
       $value = stripslashes($value);
   }
   // Quote if not a number or a numeric string
   if (!is_numeric($value)) {
       $value = mysql_real_escape_string($value);
   }
   return $value;
}
$sql = "SELECT * FROM " .$txpcfg['table_prefix'] ."txp_log WHERE host LIKE '%" .quote_smart($_GET['host']) ."%' ORDER BY 'time' DESC LIMIT 0, 30 ";
$result = mysql_query($sql) or die(mysql_error());
echo "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" id=\"list\" align=\"center\">";
echo "<tr><td><b>Time</b></td><td><b>host</b></td><td><b>page</b></td></tr>";
while($row = mysql_fetch_array($result))
{
 echo "<tr><td>".$row['time']."</td><td>".$row['host']."</td><td>".$row['page']."</td></tr>";
}
echo "</table>";
?>
</body></html>


Test message for valid PGP encryption

This code is designed to check whether the parsed text is a valid PGP encrypted message. It's relatively easy to fool, but not much can be done about that.

<?php
# vim: ft=php

function is_pgp($my_string) {

$begin =  strpos($my_string, "-----BEGIN PGP");
if ($begin === false) {
 return false;
}

$sign = strpos($my_string, "----BEGIN PGP SIGN");
if ($sign !== false) {
 return false;
}

$blank = strpos($my_string, "\r\n\r\n");
if ($blank === false) {
 return false;
}

$end = strpos($my_string, "----END");
if ($end === false) {
 return false;
}
if ($end < $begin) {
 return false;
}

return true;
}
?>

<html>
<head><title>is_php</title></head>
<body>
<p>

<?php
if ($_POST['message'] != "") {
if(is_pgp($_POST['message'])==true) {
 echo "I think the following text is a valid pgp encrypted message";
 } else {
 echo "The following text does not validate as a pgp encrypted message";
 }
} else {echo "use the following form to test whether text is pgp encrypted"; }
?>

</p>
<form action=pgp.php method="post">
<textarea name="message"  rows="20" cols="60" wrap="virtual">
<?php echo($_POST['message']); ?>
</textarea>
<input type="submit" value="validate text">
</form>
</body>
</html>

Playlist generator

Bash script to generate a playlist with all your mp3s and oggs in.

rm ~/Desktop/playlist.m3u
find ~/music/ -iname "*.mp3" -print >> ~/Desktop/playlist.m3u
find ~/music/ -iname "*.ogg" -print >> ~/Desktop/playlist.m3u
« Newer Snippets
Older Snippets »
Showing 11-19 of 19 total