Jump to content

Recommended Posts

Posted

I couldnt Find a topic like this in here so, Post your source code that only you have made dont steal anyone elses stuff. Say what language you did it in and what it dose.

 

Language: Java

Purpose: Simple 8 ball program

 

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;


public class CopyOfEightBall {
public static void main(String[] args) {

	final JTextField question = new JTextField();
	final List<String> list = Arrays.asList(
			"Yes",
			"My sources say no.",
			"Yes, in due time.",
			"Definitely not.",
			"You will have to wait.",
			"I have my doubts.",
			"Outlook so so.",
			"Looks good to me!",
			"Who knows?",
			"Looking good!",
			"Probably.",
			"Are you kidding?",
			"Go for it!",
			"Don't bet on it."
			);

	Action askAction = new AbstractAction("Ask") {
		public void actionPerformed(ActionEvent e) {
			final int num = (int)(Math.random()*list.size());
			question.setText(list.get(num));
		}

	};


	JButton ask = new JButton (askAction);


	FormLayout layout = new FormLayout("30dlu, 4dlu, 30dlu, 30dlu, min",
	"pref, 2dlu, pref, 2dlu, pref, 2dlu, pref");


	layout.setRowGroups(new int[][] { { 1, 3, 5 } });

	JPanel panel = new JPanel(layout);

	CellConstraints cc = new CellConstraints();
	panel.add(new JLabel("Ask a Question"), cc.xy(1, 1));
	panel.add(question, cc.xyw(3, 1, 3));
	panel.add(ask, cc.xy(3,3 )  );


	JFrame frame = new JFrame();
	frame.setContentPane(panel);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.setTitle("Finding Slope");
	frame.pack();
	frame.setBackground(Color.black);
	frame.setVisible(true);
}

}


 

Language: Java

Purpose: Do my some math homework and show the work

 

import java.awt.Color;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;


public class Coordinates {
public static void main(String[] args) {

	final JTextField coordinateOneField = new JTextField();
	final JTextField coordinateTwoField = new JTextField();
	final JTextField answerField = new JTextField();
	final JTextField step1 = new JTextField();
	JTextField step2 = new JTextField();
	step1.setEnabled(false);
	step2.setEnabled(false);
	answerField.setEnabled(false);

	Action sumAction = new AbstractAction("sum") {
		private static final long serialVersionUID = 0L;

		public void actionPerformed(ActionEvent e) {
			int[] coordinate1 = extractCoordinateFrom(coordinateOneField);
			int[] coordinate2 = extractCoordinateFrom(coordinateTwoField);
			step1.setText("m = " + "(" + coordinate2[1] + "-" +
				coordinate1[1] + ")" + "/" + "(" + coordinate2[0] + "-" + 
				coordinate1[0] + ")");
			answerField.setText("m = " +
					(coordinate2[1] - coordinate1[1])
					+ "/" + 
					(coordinate2[0] - coordinate1[0]));
		}

		private int[] extractCoordinateFrom(JTextField textField) {
			String text = textField.getText().replaceAll("\\(|\\)", "");
			String[] values = text.split(",");
			int[] numbers = new int[values.length];
			for(int i = 0; i < values.length; ++i) {
				numbers[i] = Integer.parseInt(values[i]);
			}
			return numbers;
		}
	};

	Action clearAction = new AbstractAction("Clear") {
		public void actionPerformed(ActionEvent e) {
			coordinateOneField.setText("");
			coordinateTwoField.setText("");
			step1.setText("");
			answerField.setText("");

		}

	};

	JButton detailsButton = new JButton(sumAction);
	JButton clear = new JButton(clearAction);

	FormLayout layout = new FormLayout("pref, 4dlu, 50dlu, 4dlu, min", // columns
	"pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref");


	layout.setRowGroups(new int[][] { { 1, 3, 5, 7, 9 } });

	JPanel panel = new JPanel(layout);

	CellConstraints cc = new CellConstraints();
	panel.add(new JLabel("Coordinate 1"), cc.xy(1, 1));
	panel.add(coordinateOneField, cc.xyw(3, 1, 2));
	panel.add(new JLabel("Coordinate 2"), cc.xy(1, 3));
	panel.add(coordinateTwoField, cc.xyw(3, 3, 2));
	panel.add(new JLabel("Step 1"), cc.xy(1,5));
	panel.add(step1, cc.xyw(3,5,2));
	panel.add(new JLabel("Answer"), cc.xy(1, 7));
	panel.add(answerField, cc.xyw(3, 7, 2));
	panel.add(detailsButton, cc.xy(1, 9));
	panel.add(clear, cc.xy(3,9 ));

	JFrame frame = new JFrame();
	frame.setContentPane(panel);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.setTitle("Finding Slope");
	frame.pack();
	frame.setVisible(true);
}

}

 

Language: Java

purpose: Lets you type text and then lets you type in a new file name

that it will create and put the text in.

 

import java.awt.event.ActionEvent;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;


public class Dspbb {
public static void main(String[] args) {

final JTextArea numField = new JTextArea("");
final JTextField nameField = new JTextField("");

Action SubmitAction = new AbstractAction("Submit") {
	public void actionPerformed(ActionEvent e) {
		final String file2 = nameField.getText();
		final String sum = numField.getText();
		String[] lines = sum.split("\n");

		FileOutputStream fout;
		 try {
			fout = new FileOutputStream (file2);
			new PrintStream(fout).println(sum);
			fout.close();
		 }
			catch(IOException e1){
				System.err.println("Unalbe to complete");
		}
			}
	};


JButton submit = new JButton(SubmitAction);



FormLayout layout = new FormLayout("pref, 4dlu, 50dlu, 4dlu, min", // columns
"pref, 2dlu, pref, 2dlu, pref, 2dlu, pref, 2dlu, pref");


layout.setRowGroups(new int[][] { { 1, 3, 5, 7, 9 } });

JPanel panel = new JPanel(layout);

CellConstraints cc = new CellConstraints();
panel.add(submit, cc.xy(1, 1));
panel.add(nameField, cc.xy(3, 1));
panel.add(numField, cc.xy(1, 3));


JFrame frame = new JFrame();
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Finding Slope");
frame.pack();
frame.setVisible(true);
}


}

Posted

This implements "the ring problem" in Erlang, i.e. construct a ring of N nodes and send a message M times around it, then benchmark the performance:

 

-module(ring).
-export([around/2]).

start(0, Parent) -> Parent;
start(N, Parent) -> 
 start(N - 1, spawn(?MODULE, child_loop, [Parent])).

child_loop(Parent) ->
 receive 
   Message ->
     Parent ! Message,
     child_loop(Parent)
 end.

around(ProcCount, Times) ->
 Pid = start(ProcCount, self()),
 Pid ! Times,
 parent_loop(Pid).

parent_loop(Pid) ->
 receive
   0 ->
     void;
   N ->
     Pid ! N - 1,
     parent_loop(Pid)
 end.

Posted

webcrawler using yahoo api in c++. not finished. dont feel like explaining it..just look at code. coded everything cept the queue class, which is part of the stl.

 

#include "cyahoo.h"

int CYahoo::SendWinsockData(string& hostName, string& headerData, string& recvBuffer)
{
WSADATA wsaData ;
SOCKET yahooSocket ;
sockaddr_in yahooService ;
hostent *socketAddress ;

char recvData[999999] ;
memset(recvData, 0, 999999) ;

int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData) ;
if(iResult != NO_ERROR)
{
	cout << "Error @ WSAStartup" ;
	return -1 ;
}

timeval timeoutValue ;

timeoutValue.tv_sec = 5000 ;


yahooSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP) ;

int optionResult = setsockopt(yahooSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeoutValue, sizeof(timeoutValue)) ;

if(yahooSocket == INVALID_SOCKET)
{
	cout << "Error at socket()" ;
	WSACleanup() ;
	return -1 ;
}

socketAddress = gethostbyname(hostName.c_str()) ;

if(socketAddress == NULL)
{
	cout << "Invalid Hostname" ;
	return -1 ;
}

yahooService.sin_family = AF_INET ;
yahooService.sin_addr.s_addr = *((unsigned long *) socketAddress->h_addr) ;
yahooService.sin_port = htons(80) ;

if(connect(yahooSocket, (SOCKADDR*)&yahooService, sizeof(yahooService)) == SOCKET_ERROR)
{
	cout << "Failed to connect" ;
	WSACleanup() ;
	return -1 ;
}

int dataSent = send(yahooSocket, headerData.c_str(), headerData.length() + 1, 0) ;
send(yahooSocket, "\r\n\r\n", 7, 0) ;

int get = 1 ;

while((get = recv(yahooSocket, recvData, sizeof(recvData), 0)) > 0)
{
	recvBuffer.append(recvData, get) ;
}

if(recvBuffer.length() <= 0)
	return -1 ;

return 1 ;
}
int CYahoo::GetQuery(string queryName, int maxResults)
{
string xmlData ;
string hostName = "search.yahooapis.com" ;
char resultsToChar[5] ;
int searchResultAppend = 0 ;

if(maxResults <= 100)
{
	_itoa_s(maxResults, resultsToChar, 10) ;
	string headerData = "POST /WebSearchService/V1/webSearch?appid=YahooDemo&query=" ;
	headerData += queryName ;
	headerData += "&results=" ;
	headerData += resultsToChar ;
	headerData += "&format=html HTTP/1.0\r\n" ;
	headerData += "Host: search.yahooapis.com\r\n\r\n" ;

	SendWinsockData(hostName, headerData, xmlData) ;

}else {
	int totalQueries =  maxResults / 100 ;
	int modQueries = maxResults % 100 ;

	totalQueries = totalQueries*100 ;

	for(int loopCounter = 1; loopCounter <= totalQueries;)
	{
		_itoa_s(loopCounter, resultsToChar, 10) ;

		string headerData = "" ;
		headerData = "POST /WebSearchService/V1/webSearch?appid=YahooDemo&query=" ;
		headerData += queryName ;
		headerData += "&results=100" ;
		headerData += "&start=" ;
		headerData += resultsToChar ;
		headerData += "&format=html HTTP/1.0\r\n" ;
		headerData += "Host: search.yahooapis.com\r\n\r\n" ;
		SendWinsockData(hostName, headerData, xmlData) ;

		loopCounter += 100 ;
		searchResultAppend += loopCounter ;
	}
	if(modQueries > 0)
	{
		modQueries += searchResultAppend ;

		_itoa_s(modQueries, resultsToChar, 10) ;

		string headerData = "POST /WebSearchService/V1/webSearch?appid=YahooDemo&query=" ;
		headerData += queryName ;
		headerData += "&results=" ;
		headerData += resultsToChar ;
		headerData += "&format=html HTTP/1.0\r\n" ;
		headerData += "Host: search.yahooapis.com\r\n\r\n" ;
		SendWinsockData(hostName, headerData, xmlData) ;
	}
}

//int retVal = SendWinsockData(hostName, headerData, xmlData) ;

ParseHTML(xmlData) ;

return 1 ;
}
void CYahoo::ParseHTML(string& htmlData) 
{
int firstLen = 0 ;
int secondLen = 0 ;
int tempLen = 0 ;
int pos = 0 ;

do {
	firstLen =  htmlData.find("<Url>", pos) ;
	secondLen = htmlData.find("</Url>", firstLen) ;
	string URL  = htmlData.substr(firstLen + 12, (secondLen - (firstLen + 12))) ;

	if(URL.find("wrs.") == -1)
	{
		urlQueue.push(URL.c_str()) ;
	}

	pos = secondLen ;
	tempLen = htmlData.find("<Url>", pos) ;
}while(tempLen != -1) ;
}
int CYahoo::SaveHTMLData(string& hostName, string fileName)
{
string htmlData ;

int findSlash =  hostName.find("/") ;
hostName = hostName.substr(0, findSlash) ;

cout << hostName ;

string headerData = "GET / HTTP/1.0\r\n" ;
headerData += "Host: " ;
headerData += hostName ;
headerData += "\r\n\r\n" ;

urlQueue.pop() ;

int retVal = SendWinsockData(hostName, headerData, htmlData) ;
if(retVal != -1)
{
	int headerFind = htmlData.find("<html>") ;
	int headerFind2 = htmlData.find("<HTML>") ;
	int headerFind3 = htmlData.find("<HTMl>") ;
	int dockTypeFind = htmlData.find("<!DOCTYPE") ;

	// <!DOCTYPE

	if(headerFind > 0)
	{
		htmlData = htmlData.substr(headerFind, htmlData.length()) ;
	} else 
	if(dockTypeFind > 0)
	{
		htmlData = htmlData.substr(dockTypeFind, htmlData.length()) ;
	}else
	if(headerFind2 > 0)
	{
		htmlData = htmlData.substr(headerFind2, htmlData.length()) ;
	}else
	if(headerFind3 > 0)
	{
		htmlData = htmlData.substr(headerFind3, htmlData.length()) ;
	}

	if(!(htmlData.size() < 200))
	{
		char size[10] ;

		_itoa_s(urlQueue.size(), size, 10) ;

		string folderSave = fileName.c_str() ;
		hostName.append("_") ;
		hostName.append(size) ;
		hostName.append(".htm") ;
		folderSave.append(hostName.c_str()) ;

		ofstream fileData ;
		fileData.open(folderSave.c_str()) ;
		fileData << htmlData.c_str() ;
		fileData.close() ;
	}
}
return 1 ;
}

 

#include "cyahoo.h"
using namespace std ;

int main()
{
int filePasses = 0 ;
string queueTest ;
string data ;
string path ;
ifstream readData ;
readData.open("C:\\savelemma.txt") ;

CYahoo yahooRequest ;

ifstream readSavedData;
readSavedData.open("C:\\search_settings.txt") ;

if(readSavedData)
{
	readSavedData >> filePasses ;

	for(int loopCounter = 0; loopCounter < filePasses; loopCounter++)
	{
		readData >> data ;
	}

	while(!readSavedData.eof())
	{
		readSavedData >> queueTest ;
		yahooRequest.urlQueue.push(queueTest) ;
	}
}



while(!readData.eof())
{
	readData >> data ;
	path = "C:\\YahooSearch2\\" + data + "\\" ;
	CreateDirectory(path.c_str(), NULL) ;

	if(yahooRequest.urlQueue.empty())
	{
		cout << "\nGathering queries...please wait...." << endl ;
		yahooRequest.GetQuery(data, 1000) ;
	}


	while(!yahooRequest.urlQueue.empty())
	{
		//Save Data
		ofstream saveData ;
		saveData.open("C:\\search_settings.txt") ;
		saveData << filePasses << endl ;
		for(int loopCounter = 0; loopCounter < yahooRequest.urlQueue.size(); loopCounter++)
		{
			string currentQueue = yahooRequest.urlQueue.front() ;
			saveData << currentQueue.c_str() << endl ;
			yahooRequest.urlQueue.push(currentQueue) ;
			yahooRequest.urlQueue.pop() ;
		}
		saveData.close() ;



		string hostName = yahooRequest.urlQueue.front() ;
		cout << endl << yahooRequest.urlQueue.size() << "** " ;
		yahooRequest.SaveHTMLData(hostName, path) ;
	}

	filePasses++ ;
}

cin.get() ;
return 0 ;
}

 

#ifndef CYAHOO_H
#define CYAHOO_H
#include <iostream>
#include <winsock2.h>
#include <string>
#include <fstream>
#include <windows.h>
#include <queue>
using namespace std ;

class CYahoo
{
int SendWinsockData(string& hostName, string& headerData, string& recvBuffer) ;
void ParseHTML(string& htmlData) ;
public:
queue<string>urlQueue ;
int GetQuery(string queryName, int maxResults) ;
int SaveHTMLData(string& hostName, string fileName) ;
} ;

#endif

Posted

Language: Java

Purpose: Simple calculator that not finished yet I just have most of the layout down.

 

import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;


public class newCalc {
public static void main(String[] args) {

	JTextField Field = new JTextField("");

	JButton one = new JButton("1");
	JButton two = new JButton("2");
	JButton three = new JButton("3");

	JButton four = new JButton("4");
	JButton five = new JButton("5");
	JButton six = new JButton("6");

	JButton seven = new JButton("7");
	JButton eight = new JButton("8");
	JButton nine = new JButton("9");

	JButton cero = new JButton("0");
	JButton enter = new JButton("e");
	JButton clear = new JButton("c");

	JButton plus = new JButton("+");
	JButton minus = new JButton("-");
	JButton divide = new JButton("/");
	JButton times = new JButton("x");


	FormLayout layout = new FormLayout("25dlu, 1dlu, 25dlu, 1dlu, 25dlu, 1dlu, 25dlu, 25dlu, 40dlu",
	"pref, 1dlu, pref, 1dlu, pref, 1dlu, pref, 1dlu, pref");


	layout.setRowGroups(new int[][] { { 1, 3, 5, 7, 9 } });

	JPanel panel = new JPanel(layout);

	CellConstraints cc = new CellConstraints();
	panel.add(Field, cc.xyw(1,1,7));
	panel.add(one, cc.xy(1,3));
	panel.add(two, cc.xy(3,3));
	panel.add(three,cc.xy(5,3));
	panel.add(divide, cc.xy(7,3));
	panel.add(four, cc.xy(1,5 )  );
	panel.add(five, cc.xy(3,5));
	panel.add(six, cc.xy(5,5));
	panel.add(minus, cc.xy(7,5));
	panel.add(seven, cc.xy(1,7));
	panel.add(eight, cc.xy(3,7));
	panel.add(nine, cc.xy(5,7));
	panel.add(plus, cc.xy(7,7));
	panel.add(enter, cc.xy(1,9));
	panel.add(cero, cc.xy(3, 9));
	panel.add(clear, cc.xy(5, 9));
	panel.add(times, cc.xy(7,9));


	JFrame frame = new JFrame();
	frame.setContentPane(panel);
	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	frame.setTitle("Calculator");
	frame.pack();
	frame.setBackground(Color.lightGray);
	frame.setVisible(true);



}

}

Posted

NOTE: This is an early program, the code is messy, uncommented, and could probably

be shortened considerably with a skilled eye. I however have lost most of my interest in

updating the program, if I was going to do it again it would be a complete re-write. I'm far

too busy to do that now. This was written as a way to reinforce programming techniques that

I was learning and to waste a boring day. It works as far as I know, if anybody wants to

add/remove/edit the program, have fun. Save your criticisms for somebody who cares.

 

Pyspoof 2.0

------------------------------

A pseudo-anonymous email spoofer with address collecting.

 

 

 

 

What is it?

=+=+=+=

 

Pysp00f started off as a very simple email spoofer written in Python,

essentially that's what it still is. It's written in Python so you'll

need to have Python installed on your system to run it. You must be

warned though,if you don't use an anonymous smtp server you can be

traced. Most people wont even get into that unless you try something

really stupid such as bomb threats or any other similar bad idea.

 

 

Features

=+=+=+

 

A) Can send a single spoofed email.

B) Can read in addresses from a text file and send the same email to all of them.

C) Can take a URL from the user and pull just about every email address off of the page.

D) Can take a text file from the user and find and pull out just about every email address.

E) Can check old and new lists for duplicate entries.

 

 

A) Single Email

=+=+=+=+=+

 

If you select this from the menu, you'll be prompted for a 'From'

address, this is the address that will show up to the receiver of this

email as the sender. That's the 'spoofing' part of this program. It

will ask for the address of the receiver, then a subject, then it will

prompt for the body. Enter the body, press enter twice when you finish.

Once you do, it will ask you for an SMTP server, if you don't know

one use Google, or contact your ISP and ask for theirs. Next, just press

enter and it will send the email to the specified address.

 

 

B) Mass Email

=+=+=+=+=+

 

If you select this from the menu, you'll be prompted for a list of

email addresses, this list should be formatted as one address per line

and needs to be in the same directory as this program. Give it the file

name including the extension (.txt) and it will load the addresses. It

will let you know how many it's loaded and ask you for the receiver,

the sender address, subject, body, and server just like the single

email function.

 

Fill these out and it will send the email to all of the address in the

file, it will notify you every time it attempts to send a message, and

every time it successfully sends a message. It has a 10 email limit,

once it reaches this, it will disconnect from the server, pause for 12

seconds, then reconnect and keep going. Some servers will limit the

amount of emails you can send per session. Usually 10 is low enough to

keep from having any troubles, if not then change it in the source.

 

C) Web page scan

=+=+=+=+=+=+

 

By selecting this option in the menu, you'll be prompted

with another two options, to scan a web page or a file. In this case

we'll discuss a web page. Select the option 'a' and it will prompt you

for a URL. Enter the full URL of the page you want it to scan, once you

do this it will connect to the server and grab the page. It will then

ask you for a domain to scan for, this would be @hotmail.com, or

@yahoo.com. If you want it to scan for everything that looks like an

email address, simply enter an asterisk * instead of a domain.

It will scan through the page for email addresses and let you know

when it's finished how many its found.

 

It will then prompt you for a filename including the extension that

it will save these to, good thing about this is that it saves them in

the proper format for the mass mailer. If the file you specify already

exists, it will append the addresses to it. In the latest update, it

now checks the file for duplicate entries, removes them and updates

the file with only unique addresses. It's a good idea to look over the

email address list before you use it. This is handy when you want to

grab a bunch of emails from a site and send them all a message and be

pseudo-anonymous in under a minute. Usually something that can take quite a

long time.

 

 

D) File Address Scan

=+=+=+=+=+=+=+

 

This is very similar to the URL scan except in this case it scans a

file. This is useful for when you've either got a bunch of email

addresses in a file and want them to be formatted for the mass email

function, or you've got something like an html file with addresses

hidden away in the source. As with the URL scan, it will scan for

addresses either with a specified domain or if you use the * option, it

will scan for anything that looks like an address. As I said before,

it's a good idea to look over the list before you use it for false

addresses. It will notify you of how many addresses it found just after

the scan so you can be sure early on of how many addresses you'll have.

Just like in the URL scan, it will perform a duplicate scan over the

file and let you know how many duplicates it found and removed leaving

you with a file full of unique addresses.

 

E) Duplicate Scan

=+=+=+=+=+=+

 

This will allow you to enter a file name for it to scan for

duplicates, it will scan the file line by line to see if it contains

the same address twice, if it does, it will remove it. After it finds

all of the duplicates it will tell you how many it's found and then

overwrite the old file with a new list containing only unique

addresses. Make sure you've got it formatted as one address per line, if

you don't feel like doing it yourself, just run a file address scan (see D)

and it'll format it for you. If you don't set it up this way, it wont work.

 

 

F) Command Line Arguments

=+=+=+=+=+=+=+=+=+=+

 

In the latest update, I have added support for command line

options. This is useful if you want to run it while you're not home

or away from the computer, every option can now be set automatically

in a script and fully automated. When using a script to send emails,

mass or single, you must have the body in a text file in the same

directory. When specifying the subject, use underscores for spaces.

 

Command Line Usage For Single Line Automation

=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=

 

0pti0ns
=+=+=+=
pyspoof.py -[mode] [mode_parameters]
Code:

   Modes
   =====
   -menu   -->   use menu interface
   -grab   -->   search file or webpage for addresses
   -mail   -->   send email single or mass
       -single -->   send single spoofed email
       -mass   -->   read emails from list and message all of them, opt spoof
   -dupe   -->   search email list for duplicates

   Mode_parameters
   ===============
   -grab
       -w 'URL'               --> search webpage
       -f 'Filename'          --> search file
       -d 'domain or 'all''   --> domain to search for ex: @yahoo.com or all
                                  all is a wildcard, type 'all' without quotes
       -o 'outputfile.txt'    --> the output file for the addresses
   -mail
       -single
           -to 'to@domain.com'      --> address to send to
           -from 'from@domain.com'  --> address to spoof
           -sub 'subject'           --> subject, use underscores for spaces
           -server 'smtp.server.com'--> smtp server to use
           -bod_file 'body_file.txt'--> text file containing body of email
       -mass
           *see -single
           -a_list 'a_list.txt'     --> list containing email addresses
   -dupe
       file_to_scan.txt             --> list containing email addresses

Example: to send an spoofed email to me at fake-email@gmail.com
   with the smtp server smtp.comcast.net, the subject "example"
   the body in a text file called email_body.txt, and the spoofed
   address spoofed@sp00fer.com, you would use the line...

pyspoof -mail -single -to fake-email@gmail.com -from spoofed@sp00fer.com
-sub example -server smtp.comcast.net -bod_file email_body.txt

 

Source Code

=+=+=+=+

 

 



################
# Pysp00f_CLI  #
#              #
# V 2.0        #
################

import time, sys, smtplib, string, urllib2, re

run = 0
def splash():
   print """
############################################################################
# __________                      _______  _______   _____                 #
# \______   \___.__. ____________ \   _  \ \   _  \_/ ____\                      #
#  |     ___<   |  |/  ___/\____ \/  /_\  \/  /_\  \   __\                 #
#  |    |    \___  |\___ \ |  |_> >  \_/   \  \_/   \  |                   #
#  |____|    / ____/____  >|   __/ \_____  /\_____  /__|                   #
#            \/         \/ |__|Command   \/Line   \/Interface              #
#                                                              Version 2.0 #
############################################################################

Disclaimer: If you screw up it's not my fault...


===============================================================================
"""
   time.sleep(2)

def send_mail(toaddy, spoofaddy, sub, server, bod):
   try:
       HOST = server
       FROM = spoofaddy
       TO = toaddy
       SUBJECT = sub
       BODY = bod
       body = string.join((
           "From: %s" % FROM,
           "To: %s" % TO,
            "Subject: %s" % SUBJECT,
            "",
           BODY), "\r\n")
       server = smtplib.SMTP(HOST)
       print "[*] Connecting to server..."
       time.sleep(2)
       server.sendmail(FROM, [TO], body)
       print "[*] Sending email..."
       time.sleep(3)
       server.quit()
       print "[*] Closing connection with server..."
       time.sleep(2)
       print "[*]Message Successfully Sent."
       time.sleep(3)
   except:
       print "Error: Email could not be sent, try a different server."
       menu()

def send_mail_var():
   toaddy = raw_input("TO: ")
   spoofaddy = raw_input("From: ")
   sub = raw_input("Subject: ")
   bl = 0
   bod=""
   while bl < 1:
       rff = raw_input("Read body from file(y/n): ").lower()
       if rff == "y":
           bfn = raw_input("File: ")
           try:
               bf = open(bfn, "r")
               bod = bf.read()
               bl+=1
           except:
               print "Unable to locate %s" % bfn
               time.sleep(1)
               rff = 'n'
       elif rff == "n":
           print "Enter message, end with ^D (Unix) or ^Z (Windows) if that doesn't work, press enter twice: "
           while 1:
               try:
                   line = raw_input()
               except EOFError:
                   break
               if not line:
                   break
               bod = bod +'\n'+line
           print "Message length is " + repr(len(bod))
           bl+=1
       else:
           print "Not an option"
   server = raw_input("Mail Server: ")
   send_mail(toaddy, spoofaddy, sub, server, bod)

def list_mail_var():
   e_list = raw_input("Text file with email addresses: ")
   spoofaddy = raw_input("From address: ")
   server = raw_input("SMTP server: ")
   sub = raw_input("Subject: ")
   bl = 0
   bod=""
   while bl < 1:
       rff = raw_input("Read body from file(y/n): ").lower()
       if rff == "y":
           bfn = raw_input("File: ")
           try:
               bf = open(bfn, "r")
               bod = bf.read()
               bl+=1
           except:
               print "Unable to locate %s" % bfn
               time.sleep(1)
               rff = 'n'
       elif rff == "n":
           print "Enter message, end with ^D (Unix) or ^Z (Windows): (Press enter twice)"
           while 1:
               try:
                   line = raw_input()
               except EOFError:
                   break
               if not line:
                   break
               bod = bod +'\n'+line
           print "Message length is " + repr(len(bod))
           bl+=1
       else:
           print "Not an option"
   list_bomb(e_list, spoofaddy, server, sub, bod)


def list_bomb(e_list, spoofaddy, server, sub, bod):
   email_list = open(e_list, "r").readlines()
   e_count = 1
   es_count = len(email_list)
   num = len(email_list)
   print "Successfully loaded %s addresses" % num
   try:
       HOST = server
       FROM = spoofaddy
       SUBJECT = sub
       BODY = bod

       print "[*] Connecting to server..."
       server = smtplib.SMTP(HOST)
       print "[*] Connected to server..."
       time.sleep(2)
       loops = 0
       count = 0
       for address in email_list:
           if loops < 1:
               print "[*] Formatting email text..."
           else:
               pass
           body = string.join((
           "From: %s" % FROM,
           "To: %s" % address,
           "Subject: %s" % SUBJECT,
           "",
           BODY), "\r\n")
           if loops < 1:
               print "[*] Text Formatted..."
           else:
               pass
           time.sleep(0.3)
           print "[*] (%s/%s) Sending email to %s" % (e_count, es_count, address)
           e_count += 1
           server.sendmail(FROM, [address], body)
           time.sleep(1)
           print "[*] Sent!"
           time.sleep(3)
           loops+=1
           count+=1
           if count == 10:
               server.quit()
               print "\n[*] Connection closed for 10 message loop limit"
               print "\n[*] Reconnection will occur momentarily..."
               time.sleep(11)
               print "\n[*] Reconnecting to server..."
               server = smtplib.SMTP(HOST)
               time.sleep(2)
               print "\n[*] Reconnection successful..."
               count = 0
           else:
               pass
       print "[*] All %s emails successfully sent!" % es_count
       time.sleep(1)
       print "[*] Closing connection with server..."
       server.quit()
       time.sleep(0.7)
       print "[*] Connection successfully closed"
       time.sleep(2)
       exit()

   except:
       print "Error: Email could not be sent, try a different server, if some of the addresses were successful, you may have to edit them out of the list and try again in a few minutes."
       exit()



def load_addr_loc_var():
   clin = 0
   exp = ""
   print "Search for address in w) webpage or f) text file\n"
   selection = raw_input("w or f: ").lower()
   if selection == 'w' or 'webpage' 'web page':
       page_url = raw_input("Page URL to scan: ")
       nof = raw_input("Output file: ")
       load_addr_loc(selection, page_url, nof, clin, exp)
   elif selection == 'f' or 'file' or 'textfile' or 'text file':
       txt_file = raw_input("Name of file (must be in same directory as this program): ")
       nof = raw_input("Output file: ")
       load_addr_loc(selection, txt_file, nof, clin, exp)
   else:
       print "Not an option"
       menu()

def load_addr_loc(selection, e_loc, nof, clin, exp):
   if clin < 1:
       time.sleep(1)
       dm = raw_input("\nDomain to search for ex: @hotmail.com, enter * to search search for all: ")
       if dm == '*':
           time.sleep(1)
           print "[*] Compiling regular expression..."
           exp = '\w*[\.]*\w*[\.]*\w*[\.]*\w*[\.]*\w*@\w*[-]?\w*[\.]?\w{2,3}?[\.]?\w{2,3}[\.]?\w*'
       else:
           time.sleep(1)
           print "[*] Compiling regular expression..."
           exp = '\w*[\.]*\w*[\.]*\w*[\.]*\w*[\.]*\w*%s' % dm
   else:
       pass
   if selection == 'w':
       page_url = e_loc
       try:
           print "[*] Connecting to %s" % page_url
           page = urllib2.urlopen(page_url)
           time.sleep(1)
           print "[*] Reading page source into scannable format..."
           source = page.readlines()
           reg_grab(source, nof, clin, exp)

       except:
           print "[*] Unable to connect to %s" % page_url
           if clin < 1:
               raw_input("\n\nPress enter to continue")
               menu()
           else:
               raw_input("\nPress enter to exit")

   elif selection == 'f':
       txt_file = e_loc
       try:
           print "[*] Loading %s" % txt_file
           page = open(txt_file, 'r')
           time.sleep(2)
           print "[*] Reading file into scannable format..."
           source = page.readlines()
           reg_grab(source, nof, clin, exp)

       except:
           print "[*] Unable to find/open %s" % txt_file
           if clin < 1:
               raw_input("\n\nPress enter to continue")
               menu()
           else:
               raw_input("\nPress enter to exit")

   else:
       print "Not an option"
       menu()

def reg_grab(source, nof, clin, exp):   

   pa = re.compile(exp)
   time.sleep(1)
   count = 0
   print "[*] Attempting to extract addresses from source, be patient..."
   e_address = []
   for line in source:
       find = pa.search(line)
       if find:
           address = find.group()
           e_address += address+'\n'
           count+=1
       else:
           pass
   time.sleep(2)
   if count > 0:
       print "[*] Successfully extracted %s address(es) from source." % count
       time.sleep(1.4)
       print "[*] Preparing to write address(es) to a text file"
       time.sleep(0.7)
       print "If the file already exists, the address(es) will be appended to it."
       time.sleep(3)
       print "[*] Opening %s" % nof
       ftw = open(nof, 'a+')
       time.sleep(1)
       print "[*] Writing address(es) to %s" % nof
       for e_add in e_address:
           addr = e_add
           ftw.write(addr)
       time.sleep(1.2)
       print "[*] Successfully wrote %s address(es) to %s" % (count, nof)
       time.sleep(1)
       ftw.close()
       find_dupes(nof)
       print "It is recommended that you review the file before using it."   
       if clin < 1:
           raw_input("\n\nPress enter to return to the menu.")
           menu()
       else:
           print "Message Successfully Sent."
           raw_input("\nPress enter to exit")
   else:
       print "[*] No valid addresses found."
       if clin < 1:
           raw_input("\n\nPress enter to return to the menu")
           menu()
       else:
           print "Message Successfully Sent."
           raw_input('\nPress enter to exit')

def exit():
   print "Message Successfully Sent."

def find_dupes(fto):
   print "[*] Preparing to scan %s for duplicate entries..." % fto
   time.sleep(1)
   f_dupes = 0
   try:
       d_source_f = open(fto, "r")
       d_source = d_source_f.readlines()
       final_list = []
       print "[*] Searching %s for duplicate entries..." % fto
       time.sleep(2)
       for e_a in d_source:
           if e_a in final_list:
               f_dupes+=1
               pass
           else:
               final_list.append(e_a)
       d_source_f.close()
       if f_dupes < 1:
           print "[*] 0 duplicates found."
           time.sleep(1)
       else:
           print "[*] Successfully found and removed %s duplicate(s)" % f_dupes
           u_add = len(final_list)
           time.sleep(0.3)
           print "[*] %s unique address(es) remain" % u_add
           f_add = open(fto, "w+")
           time.sleep(1)
           print "[*] Overwriting %s with unique addresses only..." % fto
           for e_add in final_list:
               f_add.write(e_add)
           f_add.close()
           time.sleep(2)
           print "[*] Duplicates removed and list updated successfully"
           time.sleep(2)
   except:
       print "!Unable to open %s" % fto
       time.sleep(2)

def help():
   print """              0pti0ns
             =+=+=+=
   pyspoof.py -[mode] [mode_parameters]

   Modes
   =====
   -menu   -->   use menu interface
   -grab   -->   search file or webpage for addresses
   -mail   -->   send email single or mass
       -single -->   send single spoofed email
       -mass   -->   read emails from list and message all of them, opt spoof
   -dupe   -->   search email list for duplicates

   Mode_parameters
   ===============
   -grab
       -w 'URL'               --> search webpage
       -f 'Filename'          --> search file
       -d 'domain or 'all''   --> domain to search for ex: @yahoo.com or all
                                  all is a wildcard, type 'all' without quotes
       -o 'outputfile.txt'    --> the output file for the addresses
   -mail
       -single
           -to 'to@domain.com'      --> address to send to
           -from 'from@domain.com'  --> address to spoof
           -sub 'subject'           --> subject, use underscores for spaces
           -server 'smtp.server.com'--> smtp server to use
           -bod_file 'body_file.txt'--> text file containing body of email
       -mass
           *see -single
           -a_list 'a_list.txt'     --> list containing email addresses
   -dupe
       file_to_scan.txt             --> list containing email addresses
   Example: pyspoof -mail -single -to o0family.guy0o@gmail.com -from spoofed@sp00fer.com
            -sub example -server smtp.comcast.net -bod_file email_body.txt       
"""

def cli():
   arg = sys.argv
   if len(arg) > 1:
       clin = 0
       clin += 1
       if arg[1] == '-grab':
           if '-w' and '-o' and '-d' in arg:
               selection = 'w'
               if arg[arg.index('-w')+1]:
                   if 'http://' or 'www' in arg[arg.index('-w')+1]:
                       e_loc = arg[arg.index('-w')+1]
                       if arg[arg.index('-o')+1]:
                           if '.txt' in arg[arg.index('-o')+1]:
                               nof = arg[arg.index('-o')+1]
                               if arg[arg.index('-d')+1]:
                                   if '@' or 'all' in arg[arg.index('-d')+1]:
                                       if '@' in arg[arg.index('-d')+1]:
                                           dm = arg[arg.index('-d')+1]
                                           splash()
                                           print "\n[*] Compiling regular expression..."
                                           time.sleep(1)
                                           exp = '\w*[\.]*\w*[\.]*\w*[\.]*\w*[\.]*\w*%s' % dm
                                           load_addr_loc(selection, e_loc, nof, clin, exp)
                                       elif 'all' in arg[arg.index('-d')+1]:
                                           splash()
                                           print "\n[*] Compiling regular expression..."
                                           time.sleep(1)
                                           exp = '\w*[\.]*\w*[\.]*\w*[\.]*\w*[\.]*\w*@\w*[-]?\w*[\.]?\w{2,3}?[\.]?\w{2,3}[\.]?\w*'
                                           load_addr_loc(selection, e_loc, nof, clin, exp)
                                       else:
                                           print "Specify a domain: EX: -d @yahoo  or use the wildcard all"
                                   else:
                                       print "Specify a domain: EX: -d @yahoo  or use the wildcard all"
                               else:
                                   print "Specify a domain: EX: -d @yahoo or use the wildcard all"
                           else:
                               print "Use: pyspoof.py -grab -w  -o  -d "
                               raw_input("\nPress enter to exit")
                       else:
                           print "Need an output file... -o "
                   else:
                       print "Need a URL... -w "
               else:
                   print "Need a URL... -w "
           elif '-f' and '-o' in arg:
               selection = 'f'
               if arg[arg.index('-f')+1]:
                   if '.' in arg[arg.index('-f')+1]:
                       e_loc = arg[arg.index('-o')+1]
                       if arg[arg.index('-o')+1]:
                           if '.txt' in arg[arg.index('-o')+1]:
                               nof = arg[arg.index('-o')+1]
                               if arg[arg.index('-d')+1]:
                                   if '@' or 'all' in arg[arg.index('-d')+1]:
                                       if '@' in arg[arg.index('-d')+1]:
                                           dm = arg[arg.index('-d')+1]
                                           splash()
                                           print "\n[*] Compiling regular expression..."
                                           time.sleep(1)
                                           exp = '\w*[\.]*\w*[\.]*\w*[\.]*\w*[\.]*\w*%s' % dm
                                           load_addr_loc(selection, e_loc, nof, clin, exp)
                                       elif 'all' in arg[arg.index('-d')+1]:
                                           splash()
                                           print "\n[*] Compiling regular expression..."
                                           time.sleep(1)
                                           exp = '\w*[\.]*\w*[\.]*\w*[\.]*\w*[\.]*\w*@\w*[-]?\w*[\.]?\w{2,3}?[\.]?\w{2,3}[\.]?\w*'
                                           load_addr_loc(selection, e_loc, nof, clin, exp)
                                       else:
                                           print "Specify a domain: EX: -d @yahoo  or use the wildcard all"
                                   else:
                                       print "Specify a domain: EX: -d @yahoo  or use the wildcard all"
                               else:
                                   print "Specify a domain: EX: -d @yahoo or use the wildcard all"
                           else:
                               print "Need an output text file...EX: -o "
                       else:
                           print "Specify an output file...EX: -o "
                   else:
                       print "Use full filename to search...EX: -f "
               else:
                   print "Specify a file to search...EX: -f "
           else:
               print "Use: -grab {-f/-w} (filename/webpage) -o "
       elif arg[1] == '-mail':
           if '-from' and '-sub' and '-server' and '-bod_file' in arg:
               if '-single' or '-mass' in arg:
                   if '-single' in arg and '-mass' not in arg:
                       type = 'single'
                   elif '-mass' in arg and '-single' not in arg:
                       type = 'mass'
                   else:
                       print "Specify either '-single' or '-mass' but not both"

                   if arg[arg.index('-from')+1]:
                       if '@' in arg[arg.index('-from')+1]:
                           from_add = arg[arg.index('-from')+1]
                           if arg[arg.index('-sub')+1]:
                               subj = arg[arg.index('-sub')+1]
                               if arg[arg.index('-server')+1]:
                                   serv = arg[arg.index('-server')+1]
                                   if arg[arg.index('-bod_file')+1]:
                                       f_name = arg[arg.index('-bod_file')+1]
                                       try:
                                           f_open = open(f_name, 'r')
                                           t_bod = f_open.read()
                                           f_open.close()
                                       except:
                                           print "Unable to find %s" % f_name
                                           exit()
                                       if type == 'single':
                                           if arg[arg.index('-to')+1]:
                                               if '@' in arg[arg.index('-to')+1]:
                                                   to_add = arg[arg.index('-to')+1]
                                                   send_mail(to_add, from_add, subj, serv, t_bod)
                                               else:
                                                   print "Usage: -to 'to@domain.com'"
                                                   exit()
                                           else:
                                               print "Usage: -to 'to@domain.com'"
                                               exit()

                                       elif type == 'mass':
                                           if '-a_list' in arg:
                                               if arg[arg.index('-a_list')+1]:
                                                   e_list = arg[arg.index('-a_list')+1]
                                                   list_bomb(e_list, from_add, serv, subj, t_bod)
                                               else:
                                                   print "Usage: -a_list 'youraddresslist.txt'"
                                           else:
                                               print "Type '-mass' requires an email address list. (-a_list 'yourlist.txt')"
                                       else:
                                           print "Specify a type, -single or -mass"
                                   else:
                                       print "Usage: -file 'body_file.txt'"
                                       exit()
                               else:
                                   print "Usage: -server 'smtp.server.com'"
                                   exit()
                           else:   
                               print "Usage: -sub 'subject'"
                               exit()
                       else:
                           print "Usage: -from 'from@domain.com'"
                           exit()
                   else:
                       print "Usage: -from 'from@domain.com'"
                       exit()

               else:
                   print "Specify either -mass or -single"
                   exit()
           else:
               print """Must contain: -to -from -sub -server and -bod_file
                                     arguments, -mass requires -a_list too"""
               exit()
       elif arg[1] == '-dupe':
           if arg[arg.index('-dupe')+1]:
               try:
                   dupe_test = open(arg[arg.index('-dupe')+1], 'r')
                   dupe_test.close()
                   find_dupes(arg[arg.index('-dupe')+1])
               except:
                   print "Unable to locate %s" % dupe_test
                   exit()
           else:
               print "Usage: -dupe 'file_to_scan.txt'"
               exit()
       elif arg[1] == '-menu':
           menu()
       elif arg[1] == '-help' or arg[1] == '-h':
           help()


   else:
       help()

def menu(): 
   splash()
   print """
           Menu
           =++=
       1) Send one email
       2) Send mass email
       3) Grab email addresses from a webpage or file
       4) Search list for duplicate addresses
       5) Quit
       \n"""
   method = int(raw_input("Choice (number): "))
   if method == 1:
       send_mail_var()
   elif method == 2:
       list_mail_var()
   elif method == 3:
       load_addr_loc_var()
   elif method == 4:
       f = raw_input("File to search (include file extension): ")
       find_dupes(f)
   elif method == 5:
       exit()
   else:
       print "\n%s is not an option!" % method
cli() 

  • 3 weeks later...
Posted

In the spirit of sharing, here's my news module.

 

Language: PHP/mySQL

Purpose: Complete News Marquee module for dynamic websites. Includes a control panel.

 

Control Panel (named 'news.php'):

<?php
/*
Site News Module v1.0
by mooeypoo http://moriel.schottlender.net/
mooeypoo@gmail.com
***** You may use the code if you give proper credit. *****
*/
session_start();
//put whatever connection string you use
//to connect to your mySQL database here

//--- This is the Control Panel Page: ---

if (isset($ErrMSG))
{
?>
<table width=60% border="1" align="center" cellpadding="5" cellspacing="0" bordercolor="#990000" bgcolor="#FFCC33"><tr><td><font size=2><b><?php print $ErrMSG;?></b></font></td></tr></table><br />
<?php
}
?>
 <hr align="center" width="80%" size="1" />
<table width="40%" align="center" cellpadding="5" cellspacing="0"><tr><td align="left" valign="middle" bgcolor="#999999"><font size="1"><strong>Site News</strong></font></td></tr><tr><td align="left" valign="middle" bgcolor="#CCCCCC">
<?php
$Query="SELECT * FROM tNewsTable WHERE newsValid='YES' ORDER BY newsDate DESC";
$queryexe = mysql_query($Query);
if (mysql_num_rows($queryexe)==0) {
	print "No News Items available.";
} else {
?>
	   <marquee onMouseOver="this.scrollAmount=0" onMouseOut="this.scrollAmount=2" scrollamount=2 direction=up height=120>
<?php
	while($Row = mysql_fetch_array($queryexe)) {
		$validVALUE = "YES";
		$buttonBG = "#339933";
		$buttonTEXT = "Make Visible";
		$IsVisible="invisible";
		$fontCOLOR="#666666";
		if ($Row["nValid"] == "YES") {
			$IsVisible="visible";
			$fontCOLOR="#333333";
			$validVALUE = "NO";
			$buttonBG = '#FF6666';
			$buttonTEXT = 'Make Invisible';
		}
		print "<font size=2><b>".stripslashes($Row["newsCaption"])."</b></font><br>";
		print "<font size=1><i>".date("l, F jS, Y",$Row["newsDate"])." at ".date("H:i",$Row["newsDate"])."</i></font><br>";
		print "<font size=1>".stripslashes($Row["newsContent"])."</font><br>";
		if ($Row["newsLink"]!="") {
			print "<font size=1><a href='".stripslashes($Row["newsLink"])."'>more info</a></font><br><br>";
		}
	}
?>
</marquee>
<?php
}
?>
	</td>
   </tr>
 </table>  
 <hr align="center" width="80%" size="1" />
 <table width="90%" align="center" cellpadding="3" cellspacing="0" class="tblBorderOnly">
   <tr>
     <td colspan="8" align="center" valign="middle" bgcolor="#999999"><font size="1"><strong>Manage Site News</strong></font></td>
   </tr>
<?php
$Query="SELECT * FROM tNewsTable ORDER BY newsDate DESC";
$queryexe = mysql_query($Query);
if (mysql_num_rows($queryexe)==0) {
	print "<td align=\"left\" valign=\"middle\" bgcolor=\"#CCCCCC\">";
	print "No News Items available.";
	print "</td>";
} else {
	while($Row = mysql_fetch_array($queryexe)) {
		$validVALUE = "YES";
		$buttonBG = "#339933";
		$buttonTEXT = "Make Visible";
		$IsVisible="invisible";
		$fontCOLOR="#666666";
		if ($Row["nValid"] == "YES") {
			$IsVisible="visible";
			$fontCOLOR="#333333";
			$validVALUE = "NO";
			$buttonBG = '#FF6666';
			$buttonTEXT = 'Make Invisible';
		}
?>
   <tr>
	  <td bgcolor=#CCCCCC><font size=1 color="<?php print $fontCOLOR;?>"><b>This item is <?php print $IsVisible;?></b></font></td>
	  <td bgcolor=#CCCCCC><font size=1 color="<?php print $fontCOLOR;?>"><b><?php print stripslashes($Row["newsCaption"]);?></b></font></td>
		<td bgcolor=#CCCCCC><font size=1 color="<?php print $fontCOLOR;?>"><b><?php print date("l, F jS, Y",$Row["newsDate"])." at ".date("H:i",$Row["newsDate"]);?></b></font></td>
		<td bgcolor=#CCCCCC><font size=1 color="<?php print $fontCOLOR;?>"><b><?php print stripslashes($Row["newsContent"]);?></b></font></td>
		<td bgcolor=#CCCCCC><font size=1 color="<?php print $fontCOLOR;?>"><b><?php print stripslashes($Row["newsLink"]);?></b></font></td>
		<td width="1%" align="center" valign="middle" bgcolor=#CCCCCC>
		<form action="newsaction.php" method=post class="NoMargins">
		<input type=hidden name=action value="ChangeValid" />
		<input type=hidden name=nValidValue value="<?php print $validVALUE;?>" />
		<input type=hidden name=newsID value="<?php print $Row["ID"]?>" />
		<input type=submit class="inpLoginSubmit" value="<?php print $buttonTEXT;?>" style="background-color:<?php print $buttonBG;?>" />
		</form>
	  </td>
		<td width="1%" align="center" valign="middle" bgcolor=#CCCCCC>
		<form action="newsaction.php" method=post class="NoMargins">
		<input type=hidden name=action value="DeleteItem" />
		<input type=hidden name=newsID value="<?php print $Row["ID"]?>" />
		<input type=submit class="inpLoginSubmit" value="Delete" style="background-color: #003366; color:#FFFF33;" />
		</form>
	  </td>
	</tr>
<?php
	}
}
?>
</table>
<form action="newsaction.php" method=post class="NoMargins">
<input type=hidden name=action value="AddNewsItem" />
<table width="60%" align="center" cellpadding="3" cellspacing="0">
   <tr>
     <td colspan="8" align="center" valign="middle" bgcolor="#999999"><strong><font size="1">Add News Item </font></strong></td>
     </tr>
   <tr>
     <td width="25%" align="left" valign="middle" bgcolor="#CCCCCC"><strong><font size="1">Item Title:</font></strong></td>
     <td colspan="4" align="center" valign="middle" bgcolor="#CCCCCC"><input name="nCaption" type="text" class="inpLoginText" id="nCaption" style="width:95%;" /></td>
   </tr>
   <tr>
     <td align="left" valign="top" bgcolor="#CCCCCC"><strong><font size="1">Item Contents :</font></strong></td>
     <td colspan="8" align="center" valign="middle" bgcolor="#CCCCCC"><textarea name="nContent" class="inpLoginText" id="nContent" style="width:95%; height:100px;"></textarea></td>
   </tr>
   <tr>
     <td width="25%" align="left" valign="middle" bgcolor="#CCCCCC"><strong><font size="1">Link:</font></strong></td>
     <td colspan="8" align="center" valign="middle" bgcolor="#CCCCCC"><input name="nLink" type="text" class="inpLoginText" id="nLink" style="width:95%;" /></td>
   </tr>
   <tr>
     <td colspan="8" align="center" valign="middle" bgcolor="#CCCCCC"><input name="submit" type="submit" class="inpSmallButton" value="Add News Item" /></td>
   </tr>
 </table>
</form>

 

The actions page (named 'newsaction.php'):

<?php
session_start();
/*
Site News Module v1.0
by mooeypoo http://moriel.schottlender.net/
mooeypoo@gmail.com
***** You may use the code if you give proper credit. *****
*/
//put whatever connection string you use
//to connect to your mySQL database here

//--- This is the code action page ---
switch ($action)
{
case "ChangeValid":
	$Query="UPDATE tNewsTable SET newsValid='".$nValidValue."' WHERE ID=".$newsID;
	$queryexe = mysql_query($Query);
	//go back to page:
	$err=ErrMessage("News item editted successfully.");
	header("Location: news.php?ErrMSG=".$err);
	exit;
	break;
case "AddNewsItem":
	//protect data:
	$nCaption=mysql_real_escape_string($nCaption);
	$nContent=mysql_real_escape_string($nContent);
	$nLink=mysql_real_escape_string($nLink);

	$Query="INSERT INTO tblSiteNews(newsCaption,newsContent,newsLink,newsValid,newsDate) VALUES('".$nCaption."','".$nContent."','".$nLink."','YES',".time().")";
	$queryexe = mysql_query($Query);
	//go back to page:
	$err=ErrMessage("News item added successfully.");
	header("Location: news.php?ErrMSG=".$err);
	exit;
	break;
case "DeleteItem":
	//first, ask if user is sure:
	print "<center>";
	print "<b><font size=+2 color=blue>Are you sure you want to delete this news item? This action cannot be undone.</font></b><br>";
	print "<b><font size=+2><a href='?ModuleName=NewsModule&action=DeleteItemApproved&ItemID=".$newsID."' style='color:red;'>Yes, Delete!</font></b><br>";
	$err=ErrMessage("News Item was NOT deleted.");
	print "<b><font size=+2 color=red><a href='mod-news.php?ErrMSG=".$err."' style='color:blue;'>No, Don't Delete!</font></b>";
	print "</center>";
	break;
case "DeleteItemApproved":
	$Query="DELETE FROM tblSiteNews WHERE ID=".$ItemID;
	$queryexe = mysql_query($Query);
	//go back to page:
	$err=ErrMessage("News item was deleted permanently.");
	header("Location: news.php?ErrMSG=".$err);
	exit;
	break;
}
?>

 

The presentation snippet (wherever you want it):

<?php
/*
Site News Module v1.0
by mooeypoo http://moriel.schottlender.net/
mooeypoo@gmail.com
***** You may use the code if you give proper credit. *****
*/
session_start();
//put whatever connection string you use
//to connect to your mySQL database here
?>
<!-- News Module by mooeypoo http://moriel.schottlender.net/ -->
<table width=100% border=0 cellpadding=2 cellspacing=0>
<tr>
<td align="center" valign="middle" bgcolor="#6699CC"><font size=1><b>Site News</b></font></td>
</tr>
<tr>
 <td align="left" valign="middle" bgcolor="#aac7e1">

<?php
$Query="SELECT * FROM tNewsTable WHERE newsValid='YES' ORDER BY newsDate DESC";
$queryexe = mysql_query($Query);
if (mysql_num_rows($queryexe)==0) {
	print "No News Items available.";
} else {
?>
	<marquee onMouseOver="this.scrollAmount=0" onMouseOut="this.scrollAmount=2" scrollamount=2 direction=up height="100">
<?php
print "<br><br><br><br><br><br>";
while($Row = mysql_fetch_array($queryexe)) {
	print "<center><font size=2><b>".$Row["newsCaption"]."</b></font></center><br>";
	print "<font size=1><i>".date("l, F jS, Y",$Row["newsDate"])." at ".date("H:i",$Row["newsDate"])."</i></font><br>";
	print "<font size=1>".stripslashes($Row["newsContent"])."</font><br>";
	if ($Row["newsLink"]!="") {
		print "<font size=1><a href='".stripslashes($Row["newsLink"])."'>more info</a></font><br><br>";
	}
}
print "<br><br><br><br>";
?>
</marquee>
<?php
}
?>  </td></tr></table>
<!-- END News Module Snippet -->

 

And, if you wish to create the proper table, here is the SQL command:

-- 
-- Table structure for table `tNewsTable`
-- 

CREATE TABLE IF NOT EXISTS `tNewsTable` (
 `ID` int(11) NOT NULL auto_increment,
 `newsType` text NOT NULL,
 `newsCaption` text NOT NULL,
 `newsContent` text NOT NULL,
 `newsLink` text NOT NULL,
 `newsValid` text NOT NULL,
 `newsDate` int(11) NOT NULL default '0',
 UNIQUE KEY `ID` (`ID`)
) TYPE=MyISAM AUTO_INCREMENT=17 ;

An example of this code can be found here:

http://moriel.schottlender.net/mod-news.php

 

Enjoy, and feel free to use it, with proper credits! ;)

 

~moo

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.