Drupal Notes 7: module custom content type, hook_filter(), custom hook, mail API, sends themed email to all members, creates an action and a trigger

September 6th, 2010

a few of the hooks utilized in this module:

hook_help(), hook_node_info(), hook_form(), hook_filter(), hook_filter_tips(),
hook_action_info(), hook_theme(), hook_mail(), hook_install()

Biggest concept herein: module_invoke_all()

Step 1: sitenews.info

; $Id$
name = “sitenews”
description = “Sends an email news message to all members”
core = 6.x
php = 5.1
; dependencies = “trigger”

Step 2: sitenews.module

<?php

// $Id$
/**
* sitenews Module
* Adds … READ MORE

Drupal Notes 6: module + new content type (non CCK)

September 5th, 2010

Description: Module that uses a new content type (non CCK), that uses the Schema API, Node API, Database API, Forms API and the following hooks:

hook_form(), hook_install(), hook_uninstall(), hook_schema(), hook_node_info(), hook_perm(), hook_access(), hook_insert(), hook_update(), hook_delete(), hook_nodeapi(), hook_load(), hook_view(), hook_theme()

Step 1: sites/all/modules/personality folder

Step 2: personality.info

; $Id$
name … READ MORE

Drupal Notes 5: admin module emails users from profile: hook_mail(), hook_mail_alter(), hook_help(), hook_menu(), Forms API, hook_user()

September 4th, 2010

For this module it’s best that your development environment is configured to send live emails.
If it’s local, xampp perhaps, and not currently configured as such,
you may want to refer to this post first:
http://alexyz.com/sending-mail-xampp-gmail/

Step 1, of course, create a new folder entitled emailusers in sites/all/modules

Step 2, in that folder, create emailusers.info, containing the following
(if you’ve read Notes 1-4 this should all be very familiar already):

;$Id$
name = “emailusers”
description = “admin module for emailing users from … READ MORE

Drupal Notes 4: enhance our module with jQuery AJAX/JSON

September 3rd, 2010

create quoteDisplay.js to contain:

var quoteDisplay = {}; // JS Namespace Object Creation
if(Drupal.jsEnabled){
$(document).ready(
function(){
$(“#quoteDisplay-origin”).after(“<a>Next &raquo;</a>”).next().click(quoteDisplay.randQuote);
}
);
/**
* A function to fetch quotes from the server,
* and display in the designated area.
*/

quoteDisplay.randQuote = function(){
$.get(Drupal.settings.quoteDisplay.json_url, function(data){
myQuote = Drupal.parseJson(data);
if(!myQuote.status || myQuotes.status == 0){
$(“#quoteDisplay-origin”).text(myQuote.quote.origin);
$(“#quoteDisplay-text”).text(myQuote.quote.text);
}
}); // End inline function
}
}

add this lineREAD MORE

Drupal Notes 3: a themed module for a new content type

September 1st, 2010

create a new content type, create some entries
create a new theme (see earlier notes for how)

quoteDisplay.info contains the following:

; $Id$
name = “Quote Display”
description = “Dynamic display of  quotes.”
core = 6.x
php = 5.1

quoteDisplay.module contains this:

<?php

// $Id$
/**
* @file
* Module for dynamic display of pithy philosophy quotes.
*/

/**
* Implementation of hook_help()
*/

function quoteDisplay_help($path, $arg)
{
if ($path == ‘admin/help#quoteDisplay’)
{
$txt = ‘This module displays philosophical quotes in blocks. ‘ .
‘It assumes the existence of a content type named … READ MORE

Drupal Notes 2: sub-theme derivative of bluemarine : Theme inheritance, overriding, preprocessing

August 29th, 2010

add folder to:
sites/all/themes(createThis)/subThemeName(createThis)/

create subThemeName.info (in newly created folder):
; $Id$
name = subThemeName
description = blah blah blah blah blah
version = 1.0
core = 6.x
base theme = bluemarine
stylesheets[all][] = descartes-style.css // copy images from parent theme into sub-theme.
stylesheets[all][] = new.css

finally, create above mentioned new.css (in newly created folder) and add styles you’d like to modify, example:
/*
** Style to override the styles.css in
** bluemarine.css
*/

/*
* Plain white right nav.
*/

#sidebar-right{
border-left: 1px solid #ea940c;
background-color: white;
}

ready to … READ MORE

Drupal Notes 1: module hook_block(), hook_help(), check_plain(), check_url(), watchdog(), t(), l(), placeholders(!,%,@)

August 29th, 2010

Create:
moduleName.info & moduleName.info, save them in sites, all, modules

.info example content:
;$Id$ // This will be substituted by Drupal CVS
name = “ModuleNameHere”
description = “Displays items blah blah blah”
core = 6.x
php = 5.1

.module beginnings…:
// $Id$ // This will be substituted by Drupal CVS
/**
* @file
// This denotes that this comment refers to this whole file
* Description Here Of Module…
* … READ MORE

PHP Interface and Abstract Class example

August 22nd, 2010

<?php

abstract class animal
{
abstract function getowned();
private $age;

protected function __construct($age) {
$this->age = $age;
}

public function getage()
{
return $this->age;
}
}
interface insurable {
public function getvalue();
}

class pet extends animal implements insurable {
private $name;
public function __construct($name,$age) {
parent::__construct($age);
$this->name = $name;
}
public function getname() {
return $this->name;
}
public function getowned() {
return (“Owner String”);
}
public function getvalue() {
return (“Priceless”);
}
}

class house implements insurable {
public function getvalue() {
return (“Rising fast”);
}

}

$charlie = new pet(“Charlie”,6);
$catage = $charlie -> getage();
$catname = $charlie -> getname();
print “$catname is $catage years old!<br><br>”;

if … READ MORE

simple PHP namespace example

August 22nd, 2010

Foo.class.php

<?php
class Foo
{
function Simple()
{
$var = “Hello”;
return $var;
}
}
?>

namespace.php

<?php
namespace Second;
include(‘Foo.class.php’);

class Foo
{
function Simple()
{
$var = “Hello in Second Namespace<br />”;
return $var;
}
}

$fooSecond = new \Second\Foo();
echo $fooSecond->Simple();
//option 1
//$fooFirst = new \Foo();
//$fooFirst->Simple();
//option 2

echo \Foo::Simple();
?>

simple PHP __autoload example

August 22nd, 2010

Foo.class.php

<?php
class Foo
{
public static $varz;
public static function Simple()
{
self::$varz = “Hello”;
return self::$varz;
}
}
?>

index.php (in the same directory)

<?php
function __autoload($classname) {
include(“$classname.class.php”);
}

//include “Foo.class.php”; //no longer needed!

$foo = new Foo();
echo $foo->Simple();
?>

simple ob_start(), flush(), ob_gzhandler, sleep(), HEREDOC examples

August 22nd, 2010

//ob_start()

<?php
ob_start();
print “Hello First!\n”;
ob_end_flush();

ob_start();
print “Hello Second!\n”;
ob_end_clean();

ob_start();
print “Hello Third!\n”;
?>

//outputs “Hello First! Hello Third!”

//flush()

<HTML>
<BODY>
<DIV ID=”flushme”>
Hello, world!
</DIV>
<?php flush(); sleep(2); ?>
<SCRIPT>
d = document.getElementById(“flushme”);
d.innerHTML = “Goodbye, Perl!”;
</SCRIPT>
<?php flush(); sleep(2); ?>
<SCRIPT>
d.innerHTML = “Goodnight, New York!”;
</SCRIPT>
</BODY>
</HTML>

// compressed output

<?php
ob_start(‘ob_gzhandler’);
print “My content\n”;
ob_end_flush();
?>

// sleep

<?php
ob_implicit_flush(true);
for($i=0;$i<5;$i++)
{
$dis=<<<DIS
<div style=”width:200px; background-color:lime;border:1px; text-align:center;text-decoration:blink;”>
$i
</div>
DIS;
echo $dis;

sleep(5);
//flush();
}
?>

memory jogger: Chain of responsibility, Polymorphism, Design Pattern reference, Decorator pattern, Singleton

August 21st, 2010

Good stuff, take a moment to refresh and review:

Chain of responsibility:
http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
Polymorphism:
http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
JavaScript really OOP?:
http://articles.techrepublic.com.com/5100-10878_11-1044656.html
http://mckoss.com/jscript/object.htm
JS Prototype object:
http://www.javascriptkit.com/javatutors/proto4.shtml
Design Patterns reference/list:
http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29
Decorator Pattern:
http://en.wikipedia.org/wiki/Decorator_pattern
Loose Coupling def:
http://en.wikipedia.org/wiki/Loose_coupling
Singleton Pattern:
http://en.wikipedia.org/wiki/Singleton_pattern

MySQl sub query example 2

August 17th, 2010

SELECT
q.questionId,
q.question,
q.questionTopic,
q.questionDate,
q.courseId,
q.customerId,
v.voted_this
FROM
” . $course_database_questions_table_name . ” q
LEFT JOIN
(SELECT questionId voted_this FROM votes WHERE customerId = ‘” . $customer_id . “‘) v
ON
q.questionId = v.voted_this
WHERE
q.courseId = ” . $courseId . ”
ORDER BY q.questionDate DESC

MySQL sub query example – nice

August 16th, 2010

$cp_output = “”;
if(!$get_cp_data = mysql_query(”
SELECT
q.*,
c.*,
vote_counts.Tally
FROM
questions q
LEFT JOIN
(SELECT
questionId,
count(1) as Tally
FROM
votes
GROUP BY
questionId
) vote_counts
ON
q.questionId = vote_counts.questionId
LEFT JOIN
customers c
ON
c.customerId = q.customerId
WHERE
q.courseId = 1
ORDER BY
vote_counts.Tally desc

“)){ echo mysql_error(); }

while($get_cp_data_array = mysql_fetch_array($get_cp_data)){
$q_id = $get_cp_data_array['questionId'];

$q_fname = $get_cp_data_array['customerFName'];
$q_lname = $get_cp_data_array['customerLName'];
$q_email = $get_cp_data_array['customerEmail'];

$q_topic = $get_cp_data_array['questionTopic'];
$q_question = $get_cp_data_array['question'];
$q_date = $get_cp_data_array['questionDate'];
//$q_count = $get_cp_data_array['votecount'];
$q_customer = $get_cp_data_array['customerId'];

if($q_topic == “”){ $q_topic = “–”; }
if($q_fname != “” || $q_lname != “”){
$from = ‘<strong>’ . $q_fname . ‘ ‘ . $q_lname . ‘</strong> – ‘;
}

# Parse the question text.
$old = array(“\n”);
$new   = array(“<br/>”);
$q_question = … READ MORE

clean & simple check your $_SERVER var

August 6th, 2010

<?

echo “<pre>”;
print_r($_SERVER);

?>

WordPress PHP custom theme functions.php hook

July 28th, 2010

In your theme (wp-content/themes/YourNewTheme) create or find functions.php

and start making whatever you need.  It’s a nice clean place to put things without hacking away at your code,

dynamically inserting with JS, or whatever other measure you’ve either employed in the past, or are considering now…

for example,

<?php
//My own footer hook
function my_footer() {

//code to execute

?><div class=”bigText”>blah blah blah</div><?

}

?>

then, wherever you like, call your new function, example, replace … READ MORE

“&” preceeding variable & Passing function parameters by reference variable PHP

July 27th, 2010

& preceeds variable

$original = “foo”;
$ref = &$original;
echo $ref; \\Prints “foo”
// now we change the value of $original
$original = “bar”;
// and then print the value of the referring variable
echo $ref; \\Now prints the new value: “bar”
source: http://www.whypad.com/posts/php-what-is-the-ampersand-preceding-variables/193/

reference variable (&variable)

<?php
function add_some_extra(&$string)
{
$string .= 'and something extra.';
}
$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

Basically, the argument is treated, referenced by the outside variable, as global
Without the &, it would output ‘This is a string’
source: http://php.net/manual/en/functions.arguments.php

Postincrement Preincrement Postdecrement Predecrement PHP careful! ++ –

July 27th, 2010
<?php
echo "<h3>Postincrement</h3>";
$a = 5;
echo "Should be 5: " . $a++ . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Preincrement</h3>";
$a = 5;
echo "Should be 6: " . ++$a . "<br />\n";
echo "Should be 6: " . $a . "<br />\n";

echo "<h3>Postdecrement</h3>";
$a = 5;
echo "Should be 5: " . $a-- . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";

echo "<h3>Predecrement</h3>";
$a = 5;
echo "Should be 4: " . --$a . "<br />\n";
echo "Should be 4: " . $a . "<br />\n";
?>

I always like to have a nice simple AJAX example on hand, you never know…

July 27th, 2010

reference:

http://w3schools.com/php/php_ajax_php.asp

HTML:

<html>
<head>
<script type=”text/javascript”>
function showHint(str)
{
if (str.length==0)
{
document.getElementById(“txtHint”).innerHTML=”";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(“txtHint”).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(“GET”,”gethint.php?q=”+str,true);
xmlhttp.send();
}
</script>
</head
<body>

<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type=”text” onkeyup=”showHint(this.value)” size=”20″ />
</form>
<p>Suggestions: <span id=”txtHint”></span></p>

</body>
</html>

Script:

<?php
// Fill up array with names
$a[]=”Anna”;
$a[]=”Brittany”;
$a[]=”Cinderella”;
$a[]=”Diana”;
$a[]=”Eva”;
$a[]=”Fiona”;
$a[]=”Gunda”;
$a[]=”Hege”;
$a[]=”Inga”;
$a[]=”Johanna”;
$a[]=”Kitty”;
$a[]=”Linda”;
$a[]=”Nina”;
$a[]=”Ophelia”;
$a[]=”Petunia”;
$a[]=”Amanda”;
$a[]=”Raquel”;
$a[]=”Cindy”;
$a[]=”Doris”;
$a[]=”Eve”;
$a[]=”Evita”;
$a[]=”Sunniva”;
$a[]=”Tove”;
$a[]=”Unni”;
$a[]=”Violet”;
$a[]=”Liza”;
$a[]=”Elizabeth”;
$a[]=”Ellen”;
$a[]=”Wenche”;
$a[]=”Vicky”;

//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint=”";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint==”")
{
$hint=$a[$i];
}
else
{
$hint=$hint.” , “.$a[$i];
}
}
}
}

// Set output to “no suggestion” if no hint were found
// or to the … READ MORE

PHP Expat XML Parser refresher

July 27th, 2010

from: http://w3schools.com/php/php_xml_parser_expat.asp

example XML

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don’t forget me this weekend!</body>
</note>

script to parse:

<?php
//Initialize the XML parser
$parser=xml_parser_create();

//Function to use at the start of an element
function start($parser,$element_name,$element_attrs)
{
switch($element_name)
{
case “NOTE”:
echo “– Note –<br />”;
break;
case “TO”:
echo “To: “;
break;
case “FROM”:
echo “From: “;
break;
case “HEADING”:
echo “Heading: “;
break;
case “BODY”:
echo “Message: “;
}
}

//Function to use at the end of an element
function stop($parser,$element_name)
{
echo “<br />”;
}

//Function to use when finding character data
function char($parser,$data)
{
echo $data;
}

//Specify element handler
xml_set_element_handler($parser,”start”,”stop”);

//Specify data handler READ MORE

MySQL refresher

July 27th, 2010

datatypes:

http://w3schools.com/sql/sql_datatypes.asp

Order results by 2 columns:

SELECT column_name(s)
FROM table_name
ORDER BY column1, column2

Simple delete:

<?php
$con = mysql_connect(“localhost”,”peter”,”abc123″);
if (!$con)
{
die(‘Could not connect: ‘ . mysql_error());
}
mysql_select_db(“my_db”, $con);
mysql_query(“DELETE FROM Persons WHERE LastName=’Griffin’”);
mysql_close($con);
?>

PHP custom error handling, log and email and user messaging

July 27th, 2010

http://w3schools.com/php/php_error.asp

<?php
//error handler function
function customError($errno, $errstr)
{
echo “<b>Error:</b> [$errno] $errstr<br />”;
echo “Webmaster has been notified”;
error_log(“Error: [$errno] $errstr”,1,
“someone@example.com”,”From: webmaster@example.com”);
}

//set error handler
set_error_handler(“customError”,E_USER_WARNING);

//trigger error
$test=2;
if ($test>1)
{
trigger_error(“Value must be 1 or below”,E_USER_WARNING);
}
?>

open a file and read it line by line or character by character reference refresher

July 27th, 2010

from http://w3schools.com/php/php_file.asp

Reading a File Line by Line

The fgets() function is used to read a single line from a file.

Note: After a call to this function the file pointer has moved to the next line.

Example

The example below reads a file line by line, until the end of file is reached:

<?php
$file = fopen(“welcome.txt”, “r”) or exit(“Unable to open file!”);
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). “<br />”;
}
fclose($file);
?>

Reading a File … READ MORE

date() and timestamp refresher

July 27th, 2010

date(format,timestamp)

format is required, example:

date(“Y-m-d”)

of course, Y, m, and d stand for Year, month, day, and they may be separated by whatever you like, so the above example returns 2010-07-27, while date(“m/d/Y”) returns 07/27/2010

now for the timestamp parameter

MAKE what should be supplied for the timestamp, with mktime(hour,minute,second,month,day,year,is_dst)

$tomorrow = mktime(0,0,0,date(“m”),date(“d”)+1,date(“Y”))

date(“Y/m/d”,$tomorrow) returns tomorrow!

I never seem to use the “do…while” loop so here it is just to remind me…

July 27th, 2010

example from :

http://w3schools.com/php/php_looping.asp

<?php
$i=1;
do
{
$i++;
echo “The number is ” . $i . “<br />”;
}
while ($i<=5);
?>

Key difference, it ALWAYS executes once, and THEN evaluates

variable variables PHP awesome

July 27th, 2010

variable variables create variables with variable names

$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";

$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a

$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World

//… and so on …//

From:

http://www.php.net/manual/en/language.variables.variable.php

using a PHP variable in a MySQL IN batch query example

July 16th, 2010

Note the ‘s

$product_list = “’1869′, ’1929′, ’549′, ’189′, ’419′, ’176′, ’192′, ’310′, ’291′, ’514′, ’1643′, ’1033′;

$db_name = “dbName”;
//conditional platform logic to support multiple connection scenarios

switch($_SERVER['HTTP_HOST'])
{
case ‘localhost’:
$db_host = “localhost”;
$db_username = “userName”;
$db_password = “Password”;
$dblink = mysql_connect ($db_host, $db_username, $db_password);
mysql_select_db($db_name, $dblink);
break;
case ‘www-staging.site.com’READ MORE

Flash Session Cookie SharedObject

July 7th, 2010

http://help.adobe.com/en_US/AS3LCR/Flash_10.0/flash/net/SharedObject.html

http://en.wikipedia.org/wiki/Local_Shared_Object

http://www.adobe.com/support/flash/action_scripts/actionscript_tutorial/actionscript_tutorial05.html

to change settings:

right click on any flash swf

or

http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager02.html

stored here:

  • Windows XP:
    • For Web sites: %APPDATA%\Macromedia\Flash Player\#SharedObjects\<random code>\<domain>\<path – maybe°>\<object name>.sol
    • And Also: %APPDATA%\Macromedia\Flash Player\macromedia.com\support\flashplayer\sys
  • Windows Vista and later:
    • For Web sites: %APPDATA%\Macromedia\Flash Player\#SharedObjects\<random code>\<domain>\<path – maybe°>\<object name>.sol
    • And also: %APPDATA%\Macromedia\Flash Player\macromedia.com\support\flashplayer\sys
    • For AIR Applications: unknown, likely similar to the above

PHP sprintf() quick example

July 1st, 2010

$template = ‘<div class=”%designIt”><img src=”%s” /><br />%s<br />by %s</div>’;
$designIt = “className”;
$imgSrc = “http://www.imageLivesHere.com/yo.jpg”;
$copyText = “What fabulous and interesting placeholder copy!”;
$sourceAuthor = “Me”;
$altogetherNow = sprintf ( $template, $imgSrc, $linkText, $sourceAuthor);

//Result

<div class=”className“>
<img src=”http://www.imageLivesHere.com/yo.jpg“/>
<br />
What fabulous and interesting placeholder copy!
<br />
by Me
</div>

Close Fancybox from within, old (1.2) and new (1.3)

July 1st, 2010

In 1.2 this worked:

onclick=”$(“#fancy_outer”,window.parent.document).hide(); $(“#fancy_overlay”,window.parent.document).hide();

1.3+ this has changed to:

onclick=”parent.$.fancybox.close();