Category: Web Development


First of all, Happy New Year! :) I’ve been busy these past weeks. But I would like to spare some time today and share a little but useful tip on how to remove null or empty array values before finally saving it to the database. I recently stumble upon this issue and have found the set::filter core utility really helpful.

In certain situations that you encounter this.

[Product] => Array
        (
            [0] => Array
                (
                    [id] => 35
                    [url] => item35.php
                )

            [1] => Array
                (
                [id] =>     
                [url] => 
                )

        )

Basically you just add the utility before saving the data to remove the array values.

<?php 
$this->data = Set::filter($this->data);
$this->Product->save($this->data);
?>

That’s about it. :)

It took me a couple of searches before finally got to solve the issue with having a validation for select box and not being able to display the error message. Tried a couple of solutions over the net then finally got the simple and efficient one. :)

Add this below your form select.

<?php echo $form->error('nameofselectbox');?>

That’s it! :)

I’ve spent almost a week and so just figuring out on how to be able to use icons as point values on the chart. Thanks to this post , it worked like a charm. I did made some additional coding to make it possible to display an icon over the chart.

Here is the code:

On your index page or from the page the flot is located.


var options = {

points: { show: true, radius: 3, type: "o" }

/* Note I added the "type" with either x or o value, in order to set it to the usual circle (which is "o") or custom image (which is "x") */
...


On the jquery.flot.js file, search for ” function plotPoints(” this is where we will update and do some coding…



function plotPoints(datapoints, radius, fillStyle, offset, circumference, axisx, axisy) {
                
var points = datapoints.points, ps = datapoints.pointsize;
                
	for (var i = 0; i < points.length; i += ps) {
      	var x = points[i], y = points[i + 1];
            if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
            continue;
            
/* Below this line is where we start to do some additional coding...*/   
  
                  if(series.points.type == "x") {
                	
                	  customimage(axisx.p2c(x)-1,axisy.p2c(y)-11);

	              /* we call the function to retrieve and display the image*/
                  
					
			} else if(series.points.type == "o") {
					
				ctx.beginPath();
				ctx.arc(axisx.p2c(x), axisy.p2c(y) + offset, radius, 0, circumference, true);
	                    if (fillStyle) {
	                        ctx.fillStyle = fillStyle;
	                        ctx.fill();
	                    }
	                    ctx.stroke();
			} 
                  
                
               }
            }

/* this is the function that I added to draw the image on the chart canvass*/

function customimage(x,y){

	var img = new Image();
        	
	img.onload = function() {

      ctx.beginPath();    
      ctx.drawImage(img,x,y,24,34);
      ctx.closePath();
      ctx.stroke();

      }
     img.src = 'star.jpg';  	
}

Regarding the LEGEND part of the chart. I’ve made some additional updated to in order to display a thumbnail of the icon beside the Label name.

On the jquery.flot.js file, search for ” function insertLegend(” this is where we will update…


if (i % options.legend.noColumns == 0) {
                    if (rowStarted)
                        fragments.push('</tr>');
                    fragments.push('<tr>');
                    rowStarted = true;
}

if (lf)
/* Below this line is where I made some updates. */                    
               
if (label != 'Star'){  
/* Star is the sample Label name. you can edit it and change it to the actual label name */

	label = lf(label, s);
	fragments.push('<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:13px;height:13px;background-color:' + s.color + ';overflow:hidden"></div></div></td>' +'<td class="legendLabel">' + label + '</td>');

} else {
/* this is where I add the image source of the star icon */
	fragments.push('<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:13px;height:13px;overflow:hidden"><img src="star.jpg"/></div></div></td>' +
'<td class="legendLabel">' + label + '</td>');

}

So that’s about it :) Hope to be of help again, one way or another. Feel free to correct me or add any suggestions.

A month ago I made this Constant Contact component for a specific project. I’ve decided now to share it to you guys, it might save you some time :)

By the way, make sure you have a Constant Contact developer account to be able to access it. For more info read here.

constant_contact.php


<?php

class ConstantContactComponent extends Object {


/**
  * The username for the Constant Contact API
  * @access public
  * @var string
  */
  var $api_user = null;

  /**
  * The password for the Constant Contact API
  * @access public
  * @var string
  */
  var $api_pass = null;

  /**
  * The API key for this product.
  * @access public
  * @var string
  */
  var $api_key = null;


/**
  * Start CURL operation
  * @param $url, $entry, $type
  * @return response and httpcode

  */

function startCurl($url, $entry, $type){

$handle = curl_init();
$userNamePassword = $this->api_key . '%' . $this->api_user . ':' . $this->api_pass ;
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($handle, CURLOPT_USERPWD, $userNamePassword);

if ($type == 'post' ){
curl_setopt($handle, CURLOPT_POST, 1);
curl_setopt($handle, CURLOPT_POSTFIELDS , $entry);
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
} 
if ($type =='put'){
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($handle, CURLOPT_POSTFIELDS, $entry);
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
}

if ($type == 'delete'){
curl_setopt($handle, CURLOPT_POST, 1);
curl_setopt($handle, CURLOPT_POSTFIELDS , $entry);
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "DELETE");
}

if ($type == 'bulk') {
curl_setopt($handle, CURLOPT_POST, 1);
curl_setopt($handle, CURLOPT_POSTFIELDS , $entry);
curl_setopt ($handle, CURLOPT_HTTPHEADER, Array("Content-Type: application/x-www-form-urlencoded"));
}

$response = curl_exec($handle);
$code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);

return array($response, $code);
}

 /**
  * Create Contact
  * @param string $detail contains the array of all the details to added on this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */


function createContact($detail){

$entry = '
<entry xmlns="http://www.w3.org/2005/Atom">
<title type="text"> </title>
<updated>' . date('c') . '</updated>
<author></author>
<id>data:,none</id>
<summary type="text">Contact</summary>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/">
<EmailAddress>'. $detail['email_address'] .'</EmailAddress>
<EmailType>HTML</EmailType>
<Name>'. $detail['name'] .'</Name>
<FirstName>'. $detail['first_name'] .'</FirstName>
<MiddleName>'. $detail['middle_name'] .'</MiddleName>
<LastName>'. $detail['last_name'] .'</LastName>
<JobTitle>'. $detail['job_title'] .'</JobTitle>
<CompanyName>'. $detail['company_name'] .'</CompanyName>
<HomePhone>'. $detail['home_phone'] .'</HomePhone>
<WorkPhone>'. $detail['work_phone'] .'</WorkPhone>
<Addr1>'. $detail['address_1'] .'</Addr1>
<Addr2>'. $detail['address_2'] .'</Addr2>
<Addr3>'. $detail['address_3'] .'</Addr3>
<City>'. $detail['city'] .'</City>
<StateCode>'. $detail['state_code'] .'</StateCode>
<StateName>'. $detail['state_name'] .'</StateName>
<CountryCode>'. $detail['country_code'] .'</CountryCode>
<CountryName>'. $detail['country_name'] .'</CountryName>
<PostalCode>'. $detail['postal_code'] .'</PostalCode>
<SubPostalCode>'. $detail['subpostal_code'] .'</SubPostalCode>
<Note>'. $detail['note'] .'</Note>
<CustomField1>'. $detail['custom_field_1'] .'</CustomField1>
<CustomField2>'. $detail['custom_field_2'] .'</CustomField2>
<CustomField3>'. $detail['custom_field_3'] .'</CustomField3>
<CustomField4>'. $detail['custom_field_4'] .'</CustomField4>
<CustomField5>'. $detail['custom_field_5'] .'</CustomField5>
<CustomField6>'. $detail['custom_field_6'] .'</CustomField6>
<CustomField7>'. $detail['custom_field_7'] .'</CustomField7>
<CustomField8>'. $detail['custom_field_8'] .'</CustomField8>
<CustomField9>'. $detail['custom_field_9'] .'</CustomField9>
<CustomField10>'. $detail['custom_field_10'] .'</CustomField10>
<CustomField11>'. $detail['custom_field_11'] .'</CustomField11>
<CustomField12>'. $detail['custom_field_12'] .'</CustomField12>
<CustomField13>'. $detail['custom_field_13'] .'</CustomField13>
<CustomField14>'. $detail['custom_field_14'] .'</CustomField14>
<CustomField15>'. $detail['custom_field_15'] .'</CustomField15>
<OptInSource>ACTION_BY_CUSTOMER</OptInSource>
<ContactLists>
<ContactList id="http://api.constantcontact.com/ws/customers/' . $this->api_user . '/lists/1" />
</ContactLists>
</Contact>
</content>
</entry>';


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts";

list($response, $code) = $this->startCurl($url, $entry, 'post'); 

//var_dump($code);

if ($code > 199 && $code < 300){ $output =  "Added Contact" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;


}


 /**
  * Obtain Contact Information
  * @param string $id contains the specific id for this contact.
  * @return xml 
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function obtainContactInfo($id){

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, '', ''); 

return $response;


}


 /**
  * Update Contact Information
  * @param string $id contains the id for this contact.
  * @param string $detail contains the array of all the details to be updated to this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function updateContactInfo($id, $detail){

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, ' ', ' '); 

$test = $this->xml2array($response);


$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<link href="/ws/customers/' . $this->api_user . '/contacts/'.$id.'" rel="edit" />
<id>http://api.constantcontact.com/ws/customers/' . $this->api_user . '/contacts/'. $id .'</id>
<title type="text">Contact: </title>
<updated>2010-02-01T00:03:11.502Z</updated>
<author>
<name>Constant Contact</name>
</author>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/" id="http://api.constantcontact.com/ws/customers/' . $this->api_user . '/contacts/'. $id .'">
<Status>Active</Status>';
if (isset($detail['email_address'])){ $entry .= '<EmailAddress>'.$detail['email_address'].'</EmailAddress>'; } else { $entry .= '<EmailAddress>'.$test[0]['elements'][4]['text'].'</EmailAddress>';  }
if (isset($detail['email_type'])){ $entry .= '<EmailType>'.$detail['email_type'].'</EmailType>'; } else { $entry .= '<EmailType>'.$test[0]['elements'][5]['text'].'</EmailType>';  }
if (isset($detail['name'])){ $entry .= '<Name>'.$detail['name'].'</Name>'; } else { $entry .= '<Name>'.$test[0]['elements'][6]['text'].'</Name>';  }
if (isset($detail['first_name'])){ $entry .= '<FirstName>'.$detail['first_name'].'</FirstName>'; } else { $entry .= '<FirstName>'.$test[0]['elements'][7]['text'].'</FirstName>';  }
if (isset($detail['middle_name'])){ $entry .= '<MiddleName>'.$detail['middle_name'].'</MiddleName>'; } else { $entry .= '<MiddleName>'.$test[0]['elements'][8]['text'].'</MiddleName>';  }
if (isset($detail['last_name'])){ $entry .= '<LastName>'.$detail['last_name'].'</LastName>'; } else { $entry .= '<LastName>'.$test[0]['elements'][9]['text'].'</LastName>';  }
if (isset($detail['job_title'])){ $entry .= '<JobTitle>'.$detail['job_title'].'</JobTitle>'; } else { $entry .= '<JobTitle>'.$test[0]['elements'][10]['text'].'</JobTitle>';  }
if (isset($detail['company_name'])){ $entry .= '<CompanyName>'.$detail['company_name'].'</CompanyName>'; } else { $entry .= '<CompanyName>'.$test[0]['elements'][11]['text'].'</CompanyName>';  }
if (isset($detail['home_phone'])){ $entry .= '<HomePhone>'.$detail['home_phone'].'</HomePhone>'; } else { $entry .= '<HomePhone>'.$test[0]['elements'][12]['text'].'</HomePhone>';  }
if (isset($detail['work_phone'])){ $entry .= '<WorkPhone>'.$detail['work_phone'].'</WorkPhone>'; } else { $entry .= '<WorkPhone>'.$test[0]['elements'][13]['text'].'</WorkPhone>';  }
if (isset($detail['address_1'])){ $entry .= '<Addr1>'.$detail['address_1'].'</Addr1>'; } else { $entry .= '<Addr1>'.$test[0]['elements'][14]['text'].'</Addr1>';  }
if (isset($detail['address_2'])){ $entry .= '<Addr2>'.$detail['address_2'].'</Addr2>'; } else { $entry .= '<Addr2>'.$test[0]['elements'][15]['text'].'</Addr2>';  }
if (isset($detail['address_3'])){ $entry .= '<Addr3>'.$detail['address_3'].'</Addr3>'; } else { $entry .= '<Addr3>'.$test[0]['elements'][16]['text'].'</Addr3>';  }
if (isset($detail['city'])){ $entry .= '<City>'.$detail['city'].'</City>'; } else { $entry .= '<City>'.$test[0]['elements'][17]['text'].'</City>';  }
if (isset($detail['state_code'])){ $entry .= '<StateCode>'.$detail['state_code'].'</StateCode>'; } else { $entry .= '<StateCode>'.$test[0]['elements'][18]['text'].'</StateCode>';  }
if (isset($detail['state_name'])){ $entry .= '<StateName>'.$detail['state_name'].'</StateName>'; } else { $entry .= '<StateName>'.$test[0]['elements'][19]['text'].'</StateName>';  }
if (isset($detail['country_code'])){ $entry .= '<CountryCode>'.$detail['country_code'].'</CountryCode>'; } else { $entry .= '<CountryCode>'.$test[0]['elements'][20]['text'].'</CountryCode>';  }
if (isset($detail['country_name'])){ $entry .= '<CountryName>'.$detail['country_name'].'</CountryName>'; } else { $entry .= '<CountryName>'.$test[0]['elements'][21]['text'].'</CountryName>';  }
if (isset($detail['postal_code'])){ $entry .= '<PostalCode>'.$detail['postal_code'].'</PostalCode>'; } else { $entry .= '<PostalCode>'.$test[0]['elements'][22]['text'].'</PostalCode>';  }
if (isset($detail['subpostal_code'])){ $entry .= '<SubPostalCode>'.$detail['subpostal_code'].'</SubPostalCode>'; } else { $entry .= '<SubPostalCode>'.$test[0]['elements'][23]['text'].'</SubPostalCode>';  }
if (isset($detail['note'])){ $entry .= '<Note>'.$detail['note'].'</Note>'; } else { $entry .= '<Note>'.$test[0]['elements'][24]['text'].'</Note>';  }
if (isset($detail['custom_field_1'])){ $entry .= '<CustomField1>'.$detail['custom_field_1'].'</CustomField1>'; } else { $entry .= '<CustomField1>'.$test[0]['elements'][25]['text'].'</CustomField1>';  }
if (isset($detail['custom_field_2'])){ $entry .= '<CustomField2>'.$detail['custom_field_2'].'</CustomField2>'; } else { $entry .= '<CustomField2>'.$test[0]['elements'][26]['text'].'</CustomField2>';  }
if (isset($detail['custom_field_3'])){ $entry .= '<CustomField3>'.$detail['custom_field_3'].'</CustomField3>'; } else { $entry .= '<CustomField3>'.$test[0]['elements'][27]['text'].'</CustomField3>';  }
if (isset($detail['custom_field_4'])){ $entry .= '<CustomField4>'.$detail['custom_field_4'].'</CustomField4>'; } else { $entry .= '<CustomField4>'.$test[0]['elements'][28]['text'].'</CustomField4>';  }
if (isset($detail['custom_field_5'])){ $entry .= '<CustomField5>'.$detail['custom_field_5'].'</CustomField5>'; } else { $entry .= '<CustomField5>'.$test[0]['elements'][29]['text'].'</CustomField5>';  }
if (isset($detail['custom_field_6'])){ $entry .= '<CustomField6>'.$detail['custom_field_6'].'</CustomField6>'; } else { $entry .= '<CustomField6>'.$test[0]['elements'][30]['text'].'</CustomField6>';  }
if (isset($detail['custom_field_7'])){ $entry .= '<CustomField7>'.$detail['custom_field_7'].'</CustomField7>'; } else { $entry .= '<CustomField7>'.$test[0]['elements'][31]['text'].'</CustomField7>';  }
if (isset($detail['custom_field_8'])){ $entry .= '<CustomField8>'.$detail['custom_field_8'].'</CustomField8>'; } else { $entry .= '<CustomField8>'.$test[0]['elements'][32]['text'].'</CustomField8>';  }
if (isset($detail['custom_field_9'])){ $entry .= '<CustomField9>'.$detail['custom_field_9'].'</CustomField9>'; } else { $entry .= '<CustomField9>'.$test[0]['elements'][33]['text'].'</CustomField9>';  }
if (isset($detail['custom_field_10'])){ $entry .= '<CustomField10>'.$detail['custom_field_10'].'</CustomField10>'; } else { $entry .= '<CustomField10>'.$test[0]['elements'][34]['text'].'</CustomField10>';  }
if (isset($detail['custom_field_11'])){ $entry .= '<CustomField11>'.$detail['custom_field_11'].'</CustomField11>'; } else { $entry .= '<CustomField11>'.$test[0]['elements'][35]['text'].'</CustomField11>';  }
if (isset($detail['custom_field_12'])){ $entry .= '<CustomField12>'.$detail['custom_field_12'].'</CustomField12>'; } else { $entry .= '<CustomField12>'.$test[0]['elements'][36]['text'].'</CustomField12>';  }
if (isset($detail['custom_field_13'])){ $entry .= '<CustomField13>'.$detail['custom_field_13'].'</CustomField13>'; } else { $entry .= '<CustomField13>'.$test[0]['elements'][37]['text'].'</CustomField13>';  }
if (isset($detail['custom_field_14'])){ $entry .= '<CustomField14>'.$detail['custom_field_14'].'</CustomField14>'; } else { $entry .= '<CustomField14>'.$test[0]['elements'][38]['text'].'</CustomField14>';  }
if (isset($detail['custom_field_15'])){ $entry .= '<CustomField15>'.$detail['custom_field_15'].'</CustomField15>'; } else { $entry .= '<CustomField15>'.$test[0]['elements'][39]['text'].'</CustomField15>';  }
$entry .='
<ContactLists>
<ContactList id="http://api.constantcontact.com/ws/customers/' . $this->api_user . '/lists/1">
<link xmlns="http://www.w3.org/2005/Atom" href="/ws/customers/' . $this->api_user . '/lists/1" rel="self" />
<OptInSource>ACTION_BY_CONTACT</OptInSource>
<OptInTime>2010-02-01T00:03:11.439Z</OptInTime>
</ContactList>
</ContactLists>
<Confirmed>false</Confirmed>
<InsertTime>2010-02-01T00:03:11.335Z</InsertTime>
<LastUpdateTime>2010-02-01T00:03:11.502Z</LastUpdateTime>
</Contact>
</content>
</entry>';


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;


list($response, $code) = $this->startCurl($url, $entry, 'put'); 

//var_dump($code);

if ($code > 199 && $code < 300){ $output =  "Updated Contact" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;


}


 /**
  * Search Contact By Email Address
  * @param email $email contains email address to be search on and return contact information.
  * @return xml
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function searchContactByEmail($email){

$emailAddress = str_replace("%40", "@", $email);

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts?email=".$emailAddress;

list($response, $code) = $this->startCurl($url, ' ', ' '); 

return $response;

}


 /**
  * Create Contact List - Add a group
  * @param string $detail contains the array of all the details to be created for this group.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function createContactList($detail){

$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<id>data:,</id>
<title/>
<author/>
<updated>2008-04-16</updated>
<content type="application/vnd.ctct+xml">
<ContactList xmlns="http://ws.constantcontact.com/ns/1.0/">
<OptInDefault>false</OptInDefault>
<Name>'. $detail['name'] .'</Name>
<SortOrder>'. $detail['sort_order'] .'</SortOrder>
</ContactList>
</content>
</entry>';

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/lists";

list($response, $code) = $this->startCurl($url, $entry, 'post'); 

//var_dump($code);

if ($code > 199 && $code < 300)
    { $output =  "Added Contact list" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;


}

 /**
  * Obtain Contact List - returns all groups on the list
  * @return xml
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function obtainListContact(){

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/lists";

list($response, $code) = $this->startCurl($url, ' ', ' '); 

return $response;

}


 /**
  * Obtain Contact List (group) Information
  * @param string $id contains the id for this Contact list.
  * @return xml
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function obtainContactListInfo($id){

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/lists/".$id;

list($response, $code) = $this->startCurl($url, ' ', ' '); 

return $response;


}


 /**
  * Update Contact List Information
  * @param string $id contains the id for this Contact list (group).
  * @param string $detail contains the array of all the details to be updated to this Contact List (group).
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */
function updateContactListInfo($id, $detail){

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/lists/".$id;

list($response, $code) = $this->startCurl($url, ' ', ' '); 

$test = $this->xml2array($response);


$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<link href="/ws/customers/'. $this->api_user .'/lists/'. $id .'" rel="edit" />
<id>http://api.constantcontact.com/ws/customers/'. $this->api_user .'/lists/'. $id .'</id>
<title type="text"></title>
<updated>2010-02-01T00:09:52.589Z</updated>
<author>
<name>Constant Contact</name>
</author>
<content type="application/vnd.ctct+xml">
<ContactList xmlns="http://ws.constantcontact.com/ns/1.0/" id="http://api.constantcontact.com/ws/customers/'. $this->api_user .'/lists/'. $id .'">
<OptInDefault>false</OptInDefault>';
if (isset($detail['name'])){ $entry .= '<Name>'.$detail['name'].'</Name>'; } else { $entry .= '<Name>'.$test[0]['elements'][4]['text'].'</Name>';  }
if (isset($detail['short_name'])){ $entry .= '<ShortName>'.$detail['short_name'].'</ShortName>'; } else { $entry .= '<ShortName>'.$test[0]['elements'][5]['text'].'</ShortName>';  }
$entry .= '<DisplayOnSignup>No</DisplayOnSignup>';
if (isset($detail['sort_order'])){ $entry .= '<SortOrder>'.$detail['sort_order'].'</SortOrder>'; } else { $entry .= '<SortOrder>'.$test[0]['elements'][7]['text'].'</SortOrder>';  }
$entry .='     
<Members id="http://api.constantcontact.com/ws/customers/'. $this->api_user .'/lists/'. $id .'"></Members>
</ContactList>
</content>
</entry>';

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/lists/".$id;

list($response, $code) = $this->startCurl($url, $entry, 'put'); 

//var_dump($code);

if ($code > 199 && $code < 300){ $output =  "Updated Contact List" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;



}



 /**
  * Add Contact to a Contact List (group)
  * @param string $id contains the id for this contact.
  * @param string $detail contains the array of all the details to be updated to this contact.
  * @param string $contact contains the array of all the ids of Contact Lists (groups) that will be added to this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */


function addContactToContactList($id, $detail, $contact){


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, ' ', ' '); 

$test = $this->xml2array($response);


$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<link href="/ws/customers/' . $this->api_user . '/contacts/'. $id .'" rel="edit" />
<id>http://api.constantcontact.com/ws/customers/' . $this->api_user . '/contacts/'. $id .'</id>
<title type="text"></title>
<updated>2010-02-01T00:03:11.502Z</updated>
<author>
<name>Constant Contact</name>
</author>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/" id="http://api.constantcontact.com/ws/customers/' . $this->api_user . '/contacts/'. $id .'">
<Status>Active</Status>
<EmailAddress>'.$test[0]['elements'][4]['text'].'</EmailAddress>
<OptInSource>ACTION_BY_CONTACT</OptInSource>
<ContactLists>';

for($a=0; count($contact) > $a; $a++ ){
        
$entry .= '<ContactList id="http://api.constantcontact.com/ws/customers/' . $this->api_user .'/lists/'.$contact[$a].'"></ContactList>';
}
 

$entry .= '</ContactLists>
<Confirmed>false</Confirmed>
<InsertTime>2010-02-01T00:03:11.335Z</InsertTime>
<LastUpdateTime>2010-02-01T00:03:11.502Z</LastUpdateTime>
</Contact>
</content>
</entry>';


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, $entry, 'put'); 

var_dump($code);

if ($code > 199 && $code < 300){ $output =  "Added Contact to List" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;



}


 /**
  * Add Multiple Contact to a Contact List (group)
  * @param string $detail contains the array of all the email addresses, first names and last names.
  * @param string $contact contains the id of Contact List (group).
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function addMultipleContactToContactList($detail, $contact){


$parameters = "activityType=SV_ADD";
$parameters .= "&data=";
$csvContacts = "Email+Address%2CFirst+Name%2CLast+Name%0A";


foreach ($detail as $key => $value):

$csvContact[] = str_replace("@", "%40", $key).'%2C+'.$value['first_name'].'%2C+'.$value['last_name'].'%0A';

endforeach;

$csvContacts .= implode("", $csvContact); 

//$parameters .= urlencode($csvContacts);
$parameters .= $csvContacts;
$parameters .= "&lists=".urlencode( 'http://api.constantcontact.com/ws/customers/'. $this->api_user .'/lists/'.$contact);

$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/activities";

list($response, $code) = $this->startCurl($url, $parameters, 'bulk'); 

var_dump($code);

if ($code > 199 && $code < 300)
    { $output =  "Added Multiple Contact" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;

}


 /**
  * Opting in a Subscriber - Add Contact to a specific group and be removed to the do not mail list.
  * @param string $id contains the id for this contact.
  * @param string $email contains the email address for this contact.
  * @param string $contact contains the array of all the ids of Contact Lists (groups) that will be added to this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function OptInSubscriber($id, $email, $contact){


$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<link href="/ws/customers/' . $this->api_user . '/contacts/'.$id.'" rel="edit" />
<id>http://api.constantcontact.com/ws/customers/' . $this->api_user . '/contacts/'.$id.'</id>
<title type="text">Contact: </title>
<updated>2010-01-28T11:33:03.035Z</updated>
<author>
<name>Constant Contact</name>
</author>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/" id="http://api.constantcontact.com/ws/customers/' . $this->api_user .' /contacts/'.$id.'">
<Status>Do Not Mail</Status>
<EmailAddress>' . $email.'</EmailAddress>
<OptInSource>ACTION_BY_CONTACT</OptInSource>
<ContactLists>';

for($a=0; count($contact) > $a; $a++ ){
      
$entry .= '<ContactList id="http://api.constantcontact.com/ws/customers/' . $this->api_user .'/lists/'.$contact[$a].'">
<link xmlns="http://www.w3.org/2005/Atom" href="/ws/customers/' . $this->api_user .'/lists/'.$contact[$a].'" rel="self" /></ContactList>';
}


$entry .= '</ContactLists>
<Confirmed>false</Confirmed>
<InsertTime>2010-01-28T10:20:23.857Z</InsertTime>
<LastUpdateTime>2010-01-28T11:33:03.035Z</LastUpdateTime>
</Contact>
</content>
</entry>';



$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, $entry, 'put'); 

var_dump($code);

if ($code > 199 && $code < 300)
    { $output =  "Added Contact" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;


}


 /**
  * Opt out a Subscriber - Contact will added to the do not mail list.
  * @param string $id contains the id for this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */


function OptOutSubscriber($id){


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, ' ', 'delete'); 

var_dump($code);

if ($code > 199 && $code < 300)
    { $output =  "Opt Out Subscriber" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;


}


 /**
  * Remove Contact from Contact List - Remove Contact from all lists.
  * @param string $id contains the id for this contact.
  * @param string $email contains the email address for this contact.
  * @return string
  * @see ConstantContactComponent::api_pass
  * @see ConstantContactComponent::api_user
  * @see ConstantContactComponent::api_key
  */

function removeContactFromContactList($id, $email){

$entry = '<entry xmlns="http://www.w3.org/2005/Atom">
<link href="/ws/customers/' . $this->api_user .' /contacts/'.$id.'" rel="edit" />
<id>http://api.constantcontact.com/ws/customers/' . $this->api_user .' /contacts/'.$id.'</id>
<title type="text"></title>
<updated>2010-01-28T11:33:03.035Z</updated>
<author>
<name>Constant Contact</name>
</author>
<content type="application/vnd.ctct+xml">
<Contact xmlns="http://ws.constantcontact.com/ns/1.0/" id="http://api.constantcontact.com/ws/customers/' . $this->api_user .' /contacts/'.$id.'">
<Status>Do Not Mail</Status>
<EmailAddress>'.$email.'</EmailAddress>
<Confirmed>false</Confirmed>
<InsertTime>2010-01-28T10:20:23.857Z</InsertTime>
<LastUpdateTime>2010-01-28T11:33:03.035Z</LastUpdateTime>
</Contact>
</content>
</entry>';


$url ="https://api.constantcontact.com/ws/customers/" . $this->api_user . "/contacts/".$id;

list($response, $code) = $this->startCurl($url, $entry, 'delete'); 

var_dump($code);

if ($code > 199 && $code < 300)
    { $output =  "Remove Contact from any subscription" ;  }
else{ $output = "<br> There a Problem <br>Error Code: ". $code ; }

return $output;

}


 /**
  * Convert an xml to array form
  * @param string $xml contains the xml.
  * @return array

  */

function xml2array($xml) {
        $xmlary = array();
                
        $reels = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*)<\/\s*\\1\s*>)/s';
        $reattrs = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/';

        preg_match_all($reels, $xml, $elements);

        foreach ($elements[1] as $ie => $xx) {
                $xmlary[$ie]["name"] = $elements[1][$ie];
                
                if ($attributes = trim($elements[2][$ie])) {
                        preg_match_all($reattrs, $attributes, $att);
                        foreach ($att[1] as $ia => $xx)
                                $xmlary[$ie]["attributes"][$att[1][$ia]] = $att[2][$ia];
                }

                $cdend = strpos($elements[3][$ie], "<");
                if ($cdend > 0) {
                        $xmlary[$ie]["text"] = substr($elements[3][$ie], 0, $cdend - 1);
                }

                if (preg_match($reels, $elements[3][$ie]))
                        $xmlary[$ie]["elements"] = $this->xml2array($elements[3][$ie]);
                else if ($elements[3][$ie]) {
                        $xmlary[$ie]["text"] = $elements[3][$ie];
                }
        }

        return $xmlary;
}

 


}

main_controller.php – Sample Usage of the component

<?php
class MainController extends AppController {

	var $name = 'Main';
	var $helpers = array('Html', 'Form');
	var $components = array('ConstantContact');

	function index(){

	$this->ConstantContact=& new ConstantContactComponent(null);

	$this->ConstantContact->api_key = 'API KEY YOU GOT'; 
	$this->ConstantContact->api_user = 'YOUR USERNAME';
	$this->ConstantContact->api_pass = 'AND PASSWORD'; 


	
	//Create Contact

	$detail = array(
	'first_name'=>'Heinz',
	'last_name'=>'Montenegro',
	'name'=>'Heinz Montenegro',
	'email_address'=>'heinzmontenegro@gmail.com'
        );
	$output = $this->ConstantContact->createContact($detail);
	echo $output;
	
	
	//Obtain Contact Information
	$id = 5;
	$output = $this->ConstantContact->obtainContactInfo($id);
	echo '<pre>'.htmlentities($output).'</pre>';
	

	//Update Contact Information
	$id = 5;
	$detail = array(
	'first_name'=>'Tomas',
	'last_name'=>'Gatchalian',
	'name'=>'Tomas Gatchalian',
	'email_address'=>'tomasgatchalian@mail.com'
        );
	$output = $this->ConstantContact->updateContactInfo($id, $detail);
	echo $output;
       

	//Search Contact by Email
	$email = 'tomasgatchalian@mail.com';
	$output = $this->ConstantContact->searchContactByEmail($email);
	echo '<pre>'.htmlentities($output).'</pre>';
	

	//Create Contact List

	$detail = array(
	'name'=>'Heinz Club',
	'sort_order'=>'80'
        );
	$output = $this->ConstantContact->createContactList($detail);
	echo $output;
	

	//Obtain List of Contacts
	$output = $this->ConstantContact->obtainListContact();
	echo '<pre>'.htmlentities($output).'</pre>';


	//Obtain Contact List Information
	$id = 5;
	$output = $this->ConstantContact->obtainContactListInfo($id);
	echo '<pre>'.htmlentities($output).'</pre>';


	//Update Contact List Information
	$id = 5;
	$detail = array(
	'name'=>'Tomas Club',
	'sort_order'=>'80'
        );
	$output = $this->ConstantContact->updateContactListInfo($id, $detail);
	echo $output;
	
	
	//Add Contact to Contact Lists
	$id = 6;
	$contact = array('4','5');
	$output = $this->ConstantContact->addContactToContactList($id, $detail, $contact);
	echo $output;
	

	//Bulk Adding of Contacts to a Contact List
	$detail = array (
	'heinzmontenegro@gmail.com'=> array(
	'first_name'=>'Heinz',
	'last_name'=>'Montenegro'
	), 
	'tomasgatchalian@mail.com'=>array(
	'first_name'=>'Tomas',
	'last_name'=>'Gatchalian'
	)
	);
	$contact = 3;
	$output = $this->ConstantContact->addMultipleContactToContactList($detail, $contact);
	echo $output;
	

	//OptInSubscriber
	$id = 5;
	$email = 'tomasgatchalian@mail.com';
	$contact = array('1','5','3','4');
	$output = $this->ConstantContact->OptInSubscriber($id, $email, $contact);
	echo $output;
	

	//Opt out a Subscriber
	$id = 6;
	$output = $this->ConstantContact->OptOutSubscriber($id);
	echo $output;


	//Remove Contact from any list
	$id = 6;
	$email = 'tomasgatchalian@mail.com';
	$output = $this->ConstantContact->removeContactFromContactList($id, $email);
	echo $output;
		
	}
}
?>

If you have any questions to this post, I’d be glad to know. :)

Switch IE8 to IE7

Hi. A week ago, I was instructed to fix some bugs related to IE7. The initial problem was that I have an IE8 installed. I was looking for net renderer to screenshot the bugs on IE7 and spent most of the day fixing it in that manner. Atlast, I’ve fixed it. Later that day, my guru Tonio told me that his friend has some really good news to share. And we just found out that IE8 browser can be switched to IE7 with three steps! toink :S

Here are the three simple steps.

1. Open your IE8 browser.
2. Press F12. A New window, Web Developer Tools, will open and from there you could see Browser Mode: IE8
3. Just Select on Internet Explorer 7 from the selection.
4. then there’s the MAGIC. :D

Hope to be of help, as always!

Six things I know now. :)

It’s been awhile :) Happy New Year, by the way. I’ve been busy with work. But glad to have the time tonight. On this particular project that I did, I’ve come to realize that with every project, there will always be something new. The most fun part is the learning experience you have along while working on it. Tonight, I will share new (but might not be new to you) stuffs I’ve learned.

1. Creating transparency on existing image.

Not until today that I’ve realized the importance of GD Library.There was a particular task that I need to modify and add transparency to an existing image. GD library worked like charm on this. To be able to do it effectively, the existing image should have a dark color that could easily be distinguish and separated from the entire image. Here is the snippet:

<?php

$imagefile = "image/sample.png";
	
$im = imagecreatefrompng($imagefile);
$black = imagecolorallocate($im, 0, 0, 0); // search for the color, which is black
imagecolortransparent($im, $black); // replace all black pixel values to be transparent
imagepng($im, $imagefile);
imagedestroy($im);

?>

2. Determine if the value is odd or even.

This becomes handy when you need to display alternate table row colors.

<?php
function is_odd($num)
{
  return( $num& 1 );
} 
?>

3. Return two or more variables from a function.

Shame on me that I’m not aware of this. Oh well… good for me now. :)

<?php 

function basicMath($a, $b){

$sum = $a + $b;
$difference = $a - $b;

return array($sum, $difference); //return as array values.

}

$a = 5;
$b = 3;
list($sum, $difference) = basicMath( $a, $b); //returns two variables via list()

echo $a." + ".$b." = ".$sum;
echo $a." - ".$b." = ".$difference;

?>

4. Sort arrays and retain its original keys.

There was a particular query that I need to add sorting features. But the hard part was, the query was so complicated that sorting couldn’t be possible from there. What I did was to get all the necessary fields and rows, put them on arrays. On the specific array that will be the lead and sorted out. I’ve used the asort and arsort function. Retaining the keys helped in organizing and order the other fields that are associated to it.

Here is a sample:

<?php

$firstname = array('Ana','Billy','Carol');
$lastname=array('Dela Cruz','Garcia','Rodriguez');
$average=array('85','96','90');

asort($firstname); //sort in ascending order

foreach($firstname as $key => $value)
{
echo  $value." ".$lastname[$key]." average: ".$average[$key];

}

//sample output  Ana Dela Cruz average: 85

?>

5. Get image size.

getimagesize() is handy too. I used this to determine the amount of space needed to adjust the page layout.

<?php

list($width, $height, $type, $attr) = getimagesize("image/sample.png");

?>

6. Adjusting symbol display on fpdf output

I had trouble displaying the registered trademark symbol and apostrophe on generated pdf using fpdf library. Using str_replace() and iconv() solved the issue.


<?php

str_replace("®", iconv("UTF-8", "ISO-8859-1", "¨"), str_replace("™", iconv("UTF-8", "ISO-8859-1", "ª"), $row['title'])); //outputs the title with registered trademark symbol

str_replace('’', iconv('UTF-8', 'ISO-8859-1', " ' "),$title); //outputs the title with apostrophe

?>

So that’s about it. Hope this helps! :)

These are the applications I’m busy with as of the moment

A) Aptana Studio 2.0

It’s a robust web development IDE that is highly configurable. The most amazing part is it’s totally FREE! For those PHP Developers who would like to try it, I would like to share two things that you need to do when installing the software.

1) After you have downloaded and successfully installed the software, go to My Studio window -> Plugins (extensions for studio). Select all PHP Development Tools (PDT) necessary plugins from there.

2) I initially thought after installing the plugin, I would now be able to view PHP files on it. But after several attempts, it throws me errors. So what I did was to go to Help->Install Available software. There will be a list of updates you could install, just select “–All Available Sites–” in Work with field . I then selected all PDTs and PHP related plugin. This time, I was able to open the file and view the script.

B) Navicat Lite

All this time, I was working hand in hand with PHPmyAdmin for all database related stuff. But with the project I’m working on right now, It doesn’t have anything like it installed. I was instructed to look for a MySQL gui application. So I thought for a moment, and remembered my former boss used before. I googled “Navicat” and found the link of the website. I decided to download the free version, Navicat Lite. So far I’m liking the simplicity and ease of use it offers.

C) Swiff Chart Generator on Linux

Swiff Chart Generator is a server-side solution that creates graphs. Dynamically created graphs can be exported in jpeg, swf, pdf, and many more. It works with ASP.NET (C# and Visual Basic), ASP, PHP and JSP. I’ve recently installed it on a Linux remote server via SSH. Here are the commands:

1. Login as root.
2. On root go to, cd /usr/local/
3. wget http://
(where the tar.gz is located. you can download an evaluation version )
4. then, tar -xvzf swiffchart.tar.gz
(to extract the file and install)

By the way, You can view the demos and get the sample script from there to try it out.

So that’s it. :) Thanks guru tonio for item C.

Follow

Get every new post delivered to your Inbox.