Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

09 May, 2012

How to create custom module in TikiWiki

TikiWiki or simply Tiki, is a free and open source wiki-based, content management system and Online office suite written primarily in PHP. Tiki is a powerful all-in-one web-based application, offering collaboration, publishing, commerce, social networking, CRM and office productivity tools. If you have just started your Tiki development then you will frequently need to create custom modules in TikiWiki. In this article I will tell you how to create your custom TikiWiki module from scratch. For creating you own module, you need to add two files in TikiWiki:
  • A php module file
  • A smarty template file

Create the PHP module file

Suppose the name of your module is 'Custom Module', then your module file will be named as 'mod-func-custom_module.php'. This file will contain two important functions. The function with '_info' as suffix will contain the basic information of your module like name, description, required parameters etc. The second function 'module_<module_name>' will contain the core functionality of your module.
<?php
//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}

function module_custom_module_info() {
return array(
'name' => tra('Custom Module'),
'description' => tra('This is a custom module.'),
'prefs' => array( ),
'params' => array(
'username' => array(
'required' => true,
'name' => tra('Username'),
'description' => tra('Please enter username.')
),
'Email' => array(
'required' => true,
'name' => tra('email'),
'description' => tra('Please enter Password')
'required' => true,
'name' => tra('db'),
)
'common_params' => array('nonums', 'rows')
);
}

#Create the module function
function module_custom_module( $mod_reference, $module_params ) {
global $smarty, $tikilib, $user;

#Get module parameters
$username = $module_params['username'];
$email = $module_params['email'];

$smarty->assign('username', $username);
$smarty->assign('email', $email);
}

Create the PHP smarty template file

TikiWiki uses smarty as the template engine. Template file is mandatory for module creation. Each module has a separate template file. The convention for naming the template file is as 'mod-<module_name>.tpl'. So our module template file will be 'mod-custom_module.tpl'. In this file we will print the smarty variables assigned in the module PHP file.
Username: {$username}
Email: {$email}
Don't forget to clear your TikiWiki cache before the new module can appear in the modules list.

How to create custom module in TikiWiki

TikiWiki or simply Tiki, is a free and open source wiki-based, content management system and Online office suite written primarily in PHP. Tiki is a powerful all-in-one web-based application, offering collaboration, publishing, commerce, social networking, CRM and office productivity tools. If you have just started your Tiki development then you will frequently need to create custom modules in TikiWiki. In this article I will tell you how to create your custom TikiWiki module from scratch. For creating you own module, you need to add two files in TikiWiki:
  • A php module file
  • A smarty template file

Create the PHP module file

Suppose the name of your module is 'Custom Module', then your module file will be named as 'mod-func-custom_module.php'. This file will contain two important functions. The function with '_info' as suffix will contain the basic information of your module like name, description, required parameters etc. The second function 'module_<module_name>' will contain the core functionality of your module.
<?php
//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}

function module_custom_module_info() {
return array(
'name' => tra('Custom Module'),
'description' => tra('This is a custom module.'),
'prefs' => array( ),
'params' => array(
'username' => array(
'required' => true,
'name' => tra('Username'),
'description' => tra('Please enter username.')
),
'Email' => array(
'required' => true,
'name' => tra('email'),
'description' => tra('Please enter Password')
'required' => true,
'name' => tra('db'),
)
'common_params' => array('nonums', 'rows')
);
}

#Create the module function
function module_custom_module( $mod_reference, $module_params ) {
global $smarty, $tikilib, $user;

#Get module parameters
$username = $module_params['username'];
$email = $module_params['email'];

$smarty->assign('username', $username);
$smarty->assign('email', $email);
}

Create the PHP smarty template file

TikiWiki uses smarty as the template engine. Template file is mandatory for module creation. Each module has a separate template file. The convention for naming the template file is as 'mod-<module_name>.tpl'. So our module template file will be 'mod-custom_module.tpl'. In this file we will print the smarty variables assigned in the module PHP file.
Username: {$username}
Email: {$email}
Don't forget to clear your TikiWiki cache before the new module can appear in the modules list.

08 May, 2012

How to Test PHP Emails on Localhost

While developing web applications on localhost you must have always missed the functionality to send mails. As localhost does not support email service, so it has always been a bottleneck for email testing on localhost. But I have found a simple way to test emails on localhost using PHP. I have overridden the default mail() function of PHP to create a text/html file based on the email format. If the email is in html format, an HTML file is created otherwise a text file is created. You can see in this file what exactly is the content sent in your mail. See how does it work.

Live demo Download Script

Overriding the mail() function

To override the PHP mail() function, we need to create our namespace and then define the function in that namespace.
#Create your own namespace
namespace localMail;

#Override the default mail function
function mail( $to, $subject, $message, $additional_headers='', $additional_parameters='' ) {
if (empty($to) || empty($subject) || empty($message)) {
return false;
}

#Check if email is sent as HTML or plaintext
if (isHTML($additional_headers)) {
$ext = 'html';
}else{
$ext = 'txt';
}

#Write the file
$myFile = "mail_".time().".".$ext;
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $message);
fclose($fh);
}

#Function to detect HTML headers
function isHTML($isithtml) {
if (strpos($isithtml, 'html')) {
return true;
} else {
return false;
}
}

Usage

<html>
<head>
<title>Test Emails on localhost ! WebSpeaks.in</title>
</head>
<body>
<form method="post" action="send_mail.php">
<table align="center">
<tr>
<td>
Type your message<br />
<textarea name="message" cols="50" rows="5"><div style="color:#c3c;">This <i>email</i> is <u>sent</u> through <a href="#">localhost</a>.</div></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" class="button" name="send_text" value="Send as Plain Text" />
<input type="submit" class="button" name="send_html" value="Send as HTML" />
</td>
</tr>
</table>
</form>
</body>
</html>

send_mail.php

<?php
namespace localMail;
#Override the default mail function
function mail( $to, $subject, $message, $additional_headers='', $additional_parameters='' ) {
if (empty($to) || empty($subject) || empty($message)) {
return false;
}

#Check if email is sent as HTML or plaintext
if (isHTML($additional_headers)) {
$ext = 'html';
}else{
$ext = 'txt';
}

#Write the file
$myFile = "mail_".time().".".$ext;
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $message);
fclose($fh);

header('Content-disposition: attachment; filename='.$myFile);
if (isHTML($additional_headers)) {
header('Content-type: application/html');
} else {
header('Content-type: application/text');
}
readfile($myFile);
unlink($myFile);
die();
}

#Function to detect HTML headers
function isHTML($isithtml) {
if (strpos($isithtml, 'html')) {
return true;
} else {
return false;
}
}

if (isset($_POST) && !empty($_POST)) {
$to="bhardwajs.on.height@gmail.com";
$subject="Test Local Mail on WebSpeaks";
$message = $_POST['message'];
if (isset($_POST['send_text']) && !empty($_POST['send_text'])) {
mail($to, $subject, $message);
} else {
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers);
}
}
?>

How to Test PHP Emails on Localhost

While developing web applications on localhost you must have always missed the functionality to send mails. As localhost does not support email service, so it has always been a bottleneck for email testing on localhost. But I have found a simple way to test emails on localhost using PHP. I have overridden the default mail() function of PHP to create a text/html file based on the email format. If the email is in html format, an HTML file is created otherwise a text file is created. You can see in this file what exactly is the content sent in your mail. See how does it work.

Live demo Download Script

Overriding the mail() function

To override the PHP mail() function, we need to create our namespace and then define the function in that namespace.
#Create your own namespace
namespace localMail;

#Override the default mail function
function mail( $to, $subject, $message, $additional_headers='', $additional_parameters='' ) {
if (empty($to) || empty($subject) || empty($message)) {
return false;
}

#Check if email is sent as HTML or plaintext
if (isHTML($additional_headers)) {
$ext = 'html';
}else{
$ext = 'txt';
}

#Write the file
$myFile = "mail_".time().".".$ext;
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $message);
fclose($fh);
}

#Function to detect HTML headers
function isHTML($isithtml) {
if (strpos($isithtml, 'html')) {
return true;
} else {
return false;
}
}

Usage

<html>
<head>
<title>Test Emails on localhost ! WebSpeaks.in</title>
</head>
<body>
<form method="post" action="send_mail.php">
<table align="center">
<tr>
<td>
Type your message<br />
<textarea name="message" cols="50" rows="5"><div style="color:#c3c;">This <i>email</i> is <u>sent</u> through <a href="#">localhost</a>.</div></textarea>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" class="button" name="send_text" value="Send as Plain Text" />
<input type="submit" class="button" name="send_html" value="Send as HTML" />
</td>
</tr>
</table>
</form>
</body>
</html>

send_mail.php

<?php
namespace localMail;
#Override the default mail function
function mail( $to, $subject, $message, $additional_headers='', $additional_parameters='' ) {
if (empty($to) || empty($subject) || empty($message)) {
return false;
}

#Check if email is sent as HTML or plaintext
if (isHTML($additional_headers)) {
$ext = 'html';
}else{
$ext = 'txt';
}

#Write the file
$myFile = "mail_".time().".".$ext;
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $message);
fclose($fh);

header('Content-disposition: attachment; filename='.$myFile);
if (isHTML($additional_headers)) {
header('Content-type: application/html');
} else {
header('Content-type: application/text');
}
readfile($myFile);
unlink($myFile);
die();
}

#Function to detect HTML headers
function isHTML($isithtml) {
if (strpos($isithtml, 'html')) {
return true;
} else {
return false;
}
}

if (isset($_POST) && !empty($_POST)) {
$to="bhardwajs.on.height@gmail.com";
$subject="Test Local Mail on WebSpeaks";
$message = $_POST['message'];
if (isset($_POST['send_text']) && !empty($_POST['send_text'])) {
mail($to, $subject, $message);
} else {
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers);
}
}
?>

02 May, 2012

Add/Update Attribute Option Values Programmatically in Magento

Adding/Updating the attribute option values programmatically in Magento can be tedious sometimes. Adding attribute options through custom codes is not big deal but updating the values for already added attribute options is tricky enough.
Problem:Lets understand this by an example. Suppose we have a product attribute 'manufacturer'. It is of type select/dropdown. And we have few options added in it like Mac, Google, Android etc. Now at some point in our Magento application we want to update these options with Apple, Nexus, HTC etc without using the admin panel, then it is a problem.


Solution:To update the option values programmatically, I came up with a simple solution which is as follows. For this, you need to find the 'option_id' of the attribute options in the 'eav_attribute_option_value' table.

Then create an option array and save it in the appropriate model.


Updating Attribute options

//Get the eav attribute model
$attr_model = Mage::getModel('catalog/resource_eav_attribute');

//Load the particular attribute by id
//Here 73 is the id of 'manufacturer' attribute
$attr_model->load(73);

//Create an array to store the attribute data
$data = array();

//Create options array
$values = array(
//15 is the option_id of the option in 'eav_attribute_option_value' table
15 => array(
0 => 'Apple' //0 is current store id, Apple is the new label for the option
),
19 => array(
0 => 'Nexus'
),
12 => array(
0 => 'HTC'
),
);

//Add the option values to the data
$data['option']['value'] = $values;

//Add data to our attribute model
$attr_model->addData($data);

//Save the updated model
try {
$attr_model->save();
$session = Mage::getSingleton('adminhtml/session');
$session->addSuccess(
Mage::helper('catalog')->__('The product attribute has been saved.'));

/**
* Clear translation cache because attribute labels are stored in translation
*/
Mage::app()->cleanCache(array(Mage_Core_Model_Translate::CACHE_TAG));
$session->setAttributeData(false);
return;
} catch (Exception $e) {
$session->addError($e->getMessage());
$session->setAttributeData($data);
return;
}
This is all and you are done.

Adding new Attribute option

$arg_attribute = 'manufacturer';
$arg_value = 'value to be added';

$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();

$option['attribute_id'] = $attr_id;
$option['value']['any_option_name'][0] = $arg_value;

$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);

Add/Update Attribute Option Values Programmatically in Magento

Adding/Updating the attribute option values programmatically in Magento can be tedious sometimes. Adding attribute options through custom codes is not big deal but updating the values for already added attribute options is tricky enough.
Problem:Lets understand this by an example. Suppose we have a product attribute 'manufacturer'. It is of type select/dropdown. And we have few options added in it like Mac, Google, Android etc. Now at some point in our Magento application we want to update these options with Apple, Nexus, HTC etc without using the admin panel, then it is a problem.


Solution:To update the option values programmatically, I came up with a simple solution which is as follows. For this, you need to find the 'option_id' of the attribute options in the 'eav_attribute_option_value' table.

Then create an option array and save it in the appropriate model.


Updating Attribute options

//Get the eav attribute model
$attr_model = Mage::getModel('catalog/resource_eav_attribute');

//Load the particular attribute by id
//Here 73 is the id of 'manufacturer' attribute
$attr_model->load(73);

//Create an array to store the attribute data
$data = array();

//Create options array
$values = array(
//15 is the option_id of the option in 'eav_attribute_option_value' table
15 => array(
0 => 'Apple' //0 is current store id, Apple is the new label for the option
),
19 => array(
0 => 'Nexus'
),
12 => array(
0 => 'HTC'
),
);

//Add the option values to the data
$data['option']['value'] = $values;

//Add data to our attribute model
$attr_model->addData($data);

//Save the updated model
try {
$attr_model->save();
$session = Mage::getSingleton('adminhtml/session');
$session->addSuccess(
Mage::helper('catalog')->__('The product attribute has been saved.'));

/**
* Clear translation cache because attribute labels are stored in translation
*/
Mage::app()->cleanCache(array(Mage_Core_Model_Translate::CACHE_TAG));
$session->setAttributeData(false);
return;
} catch (Exception $e) {
$session->addError($e->getMessage());
$session->setAttributeData($data);
return;
}
This is all and you are done.

Adding new Attribute option

$arg_attribute = 'manufacturer';
$arg_value = 'value to be added';

$attr_model = Mage::getModel('catalog/resource_eav_attribute');
$attr = $attr_model->loadByCode('catalog_product', $arg_attribute);
$attr_id = $attr->getAttributeId();

$option['attribute_id'] = $attr_id;
$option['value']['any_option_name'][0] = $arg_value;

$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$setup->addAttributeOption($option);

26 February, 2012

Create Custom Tab in Magento Product Add/Edit Page

If you are trying to add a custom tab to the product add/edit page in Magento admin, then you are at the right place. Today I will tell you a damn simple method to add the custom tab to product add/edit page. We will have to add few lines to the xml layout file of your custom module. Then create a phtml file that contains the html part to be shown in the tab.

Here is the detailed description of the process:
1. Create a directory named 'custom' at app\design\adminhtml\default\default\template location.

2. Create file named content.phtml in the above directory so that the full path looks like app\design\adminhtml\default\default\template\custom\content.phtml

3. In content.phtml you can write any php and html code according to your need.
<?php
//Get the current product
$product = Mage::registry('product');
?>

<div class="entry-edit">
<div class="entry-edit-head">
<h4 class="icon-head head-edit-form fieldset-legend">Custom Tab</h4>
</div>
<div id="group_fields4" class="fieldset fieldset-wide">
<?php
var_dump($product);
?>
</div>
</div>

4. Create the block file in app\code\local\<namespace>\<module_name>\Block\Adminhtml\Config.php. Add following content to the file:
<?php
class <namespace>_<module_name>_Block_Adminhtml_Config extends Mage_Core_Block_Template implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
public function __construct(){
$this->setTemplate('custom/content.phtml');
parent::__construct();
}

//Label to be shown in the tab
public function getTabLabel(){
return Mage::helper('core')->__('Custom Tab');
}

public function getTabTitle(){
return Mage::helper('core')->__('Custom Tab');
}

public function canShowTab(){
return true;
}

public function isHidden(){
return false;
}
}

5. Open the app\design\adminhtml\default\default\layout\<module_name>.xml. Add following lines to this file:
<!-- To add a tab on new product page -->
<adminhtml_catalog_product_new>
<reference name="product_tabs">
<action method="addTab">
<name>custom_tab</name>
<block template="custom/content.phtml">module_name/adminhtml_config</block>
</action>
</reference>
</adminhtml_catalog_product_new>
<!-- To add a tab on new product page -->


<!-- To add a tab on edit product page -->
<adminhtml_catalog_product_edit>
<reference name="product_tabs">
<action method="addTab">
<name>custom_tab</name>
<block template="custom/content.phtml">module_name/adminhtml_config</block>
</action>
</reference>
</adminhtml_catalog_product_edit>
<!-- To add a tab on edit product page -->

This is all and you are done! Please share if you like it.

Create Custom Tab in Magento Product Add/Edit Page

If you are trying to add a custom tab to the product add/edit page in Magento admin, then you are at the right place. Today I will tell you a damn simple method to add the custom tab to product add/edit page. We will have to add few lines to the xml layout file of your custom module. Then create a phtml file that contains the html part to be shown in the tab.

Here is the detailed description of the process:
1. Create a directory named 'custom' at app\design\adminhtml\default\default\template location.

2. Create file named content.phtml in the above directory so that the full path looks like app\design\adminhtml\default\default\template\custom\content.phtml

3. In content.phtml you can write any php and html code according to your need.
<?php
//Get the current product
$product = Mage::registry('product');
?>

<div class="entry-edit">
<div class="entry-edit-head">
<h4 class="icon-head head-edit-form fieldset-legend">Custom Tab</h4>
</div>
<div id="group_fields4" class="fieldset fieldset-wide">
<?php
var_dump($product);
?>
</div>
</div>

4. Create the block file in app\code\local\<namespace>\<module_name>\Block\Adminhtml\Config.php. Add following content to the file:
<?php
class <namespace>_<module_name>_Block_Adminhtml_Config extends Mage_Core_Block_Template implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
public function __construct(){
$this->setTemplate('custom/content.phtml');
parent::__construct();
}

//Label to be shown in the tab
public function getTabLabel(){
return Mage::helper('core')->__('Custom Tab');
}

public function getTabTitle(){
return Mage::helper('core')->__('Custom Tab');
}

public function canShowTab(){
return true;
}

public function isHidden(){
return false;
}
}

5. Open the app\design\adminhtml\default\default\layout\<module_name>.xml. Add following lines to this file:
<!-- To add a tab on new product page -->
<adminhtml_catalog_product_new>
<reference name="product_tabs">
<action method="addTab">
<name>custom_tab</name>
<block template="custom/content.phtml">module_name/adminhtml_config</block>
</action>
</reference>
</adminhtml_catalog_product_new>
<!-- To add a tab on new product page -->


<!-- To add a tab on edit product page -->
<adminhtml_catalog_product_edit>
<reference name="product_tabs">
<action method="addTab">
<name>custom_tab</name>
<block template="custom/content.phtml">module_name/adminhtml_config</block>
</action>
</reference>
</adminhtml_catalog_product_edit>
<!-- To add a tab on edit product page -->

This is all and you are done! Please share if you like it.

23 February, 2012

Create Album and Upload Photo to Facebook Fan Page using PHP

In this series of Facebook API tutorials, today we will continue with creating albums on Facebook Fan Page. The main meat of this tutorial is getting the right access token for your fan page. To get the right access token, follow these steps:
  1. Go to https://developers.facebook.com/tools/explorer?method=GET&path=me%2Faccounts 
  2. Enter https://graph.facebook.com/me/accounts in the second text box 
  3. Click on submit 
  4. Json data will be returned 
  5. From that select the access token of your Fan page. 

Other Facebook Tutorials:
How to upload photos to you Facebook Fan Page
Access Facebook Photo Albums using PHP - v1.0
Upload photos on Facebook using PHP
See it working
Live Demo Download Script
<?php
require_once 'library/facebook.php';
$facebook = new Facebook(array(
'appId' => '<app_id>',
'secret' => '<app_sercret>',
'fileUpload' => true
));
?>
<html>
<head>
<title>WebSpeaks.in | Create album and upload photos to Facebook Fan Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
//It can be found at https://developers.facebook.com/tools/access_token/
$access_token = '<you_access_token>';

$params = array('access_token' => $access_token);

//The id of the fanpage
$fanpage = '<your_fan_page_id>';

/*
* Go to https://developers.facebook.com/tools/explorer?method=GET&path=me%2Faccounts
* Enter https://graph.facebook.com/me/accounts in the second text box
* Click on submit
* Json data will be returned
* From that select the access token of your Fan page
*/
$page_access_token = '<your_page_access_token>';
$facebook->setAccessToken($page_access_token);

$facebook->setFileUploadSupport(true);

//Create an album
$album_details = array(
'message'=> 'Test album',
'name'=> 'Album name'.date('Y-m-d H:i:s') //should be unique each time
);
$album = $facebook->api('/'.$fanpage.'/albums', 'post', $album_details);

//The id of the album
$album_id =$album['id'];

//Replace arvind07 with your Facebook ID
$accounts = $facebook->api('/arvind07/accounts', 'GET', $params);

foreach($accounts['data'] as $account) {
if( $account['id'] == $fanpage || $account['name'] == $fanpage ){
$fanpage_token = $account['access_token'];
}
}

$valid_files = array('image/jpeg', 'image/png', 'image/gif');

if(isset($_FILES) && !empty($_FILES)){
if( !in_array($_FILES['pic']['type'], $valid_files ) ){
echo 'Only jpg, png and gif image types are supported!';
}else{
#Upload photo here
$img = realpath($_FILES["pic"]["tmp_name"]);

$args = array(
'message' => 'This photo was uploaded via WebSpeaks.in',
'image' => '@' . $img,
'aid' => $album_id,
'no_story' => 0,
'access_token' => $fanpage_token
);

$photo = $facebook->api($album_id . '/photos', 'post', $args);
if( is_array( $photo ) && !empty( $photo['id'] ) ){
echo '<p><a target="_blank" href="http://www.facebook.com/photo.php?fbid='.$photo['id'].'">Click here to watch this photo on Facebook.</a></p>';
}
}
}

?>
<!-- Form for uploading the photo -->
<div class="main">
<p>Select a photo to upload on Facebook Fan Page</p>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<p>Select the image: <input type="file" name="pic" /></p>
<p><input class="post_but" type="submit" value="Create album and Upload" /></p>
</form>
</div>
</body>
</html>

 

© 2013 Jquery Giants. All rights resevered. Designed by Templateism

Back To Top