Tuesday, 23 December 2014

Maintaining Contact Form in YII or sending mail using phpmailer in YII as well as php

We Know that we have default Contact form in YII , User can entered his query by providing his mail id and clicks submit button,

I have written code for the submit button, which send mail to my maid id along with user provided mail id, to use this please download "PHPMailer-5.2.4" using below link

http://code.google.com/a/apache-extras.org/p/phpmailer/downloads/detail?name=PHPMailer_5.2.4.zip&can=2&q=

and extract the zip file save it to protected/extensions folder, rename the PHPMailer_5.2.4 to PHPMailer so the path of the folder should be 'protected/extensions/PHPMailer' . Give full permission to folder before proceeding

The code as follows

We have model, "ContactForm" extends CFormModel in our application and we have generated view for contact form in our views '/site/contact.php'  located in site folder of views.

Now edit your contact form according to requirement, I left the view as it is .. Now we have move actionContact() method in site controller

The actionContact is modified as follows:

public function actionContact()
{
$model=new ContactForm;               // Object created for ContactForm model
if(isset($_POST['ContactForm']))
{
$model->attributes=$_POST['ContactForm'];
if($model->validate())
{
$status=$model->sendMail();          // User Defined method, demonstration follows

if($status===0)            // If Mail sent failed the code 0 is returned by above method
Yii::app()->user->setFlash('ERROR','Mail Sending Error Please contact Administrator');

else

Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');

$this->refresh();
}
}
$this->render('contact',array('model'=>$model));
}

Now coming to the method in ContactForm model , add the below method to the model note that $this is contactform.

public function sendMail(){

require_once(Yii::app()->basePath.'/extensions/PHPMailer/class.phpmailer.php');

$mail = new PHPMailer();
// Dialog::message('Mail', "Mail object created with $this->email");
$uname=Yii::app()->user->name;
$mail->IsSMTP();
$mail->CharSet="UTF-8";
$mail->SMTPSecure = 'ssl';
$mail->Host = 'mail.nic.in';
$mail->Port = 465;                                // give SMTP port, I have given my organisation port
$mail->Username = 'xxxxx@xxx.xx';
$mail->Password = '************';   // provide password from the above username the
                                                                              //    mail is sent

$mail->SMTPAuth = true;          // Set false if there is no SMTPAuth

$mail->From = 'xxxxx@xxx.xx';    // same as Username .. it is displayed in from field of mail

$ipadd='';
$ipadd=$this->getRealIp();          // obtaining IP address of the client
// $mail->FromName = 'xxxx';
/* $mail->From = "$this->email";    This displays the mail id of the contact form provided by
                                                                       user in from field of mail, I dont want this in from field so
                                                                      commented this if one want this Just comment the above
                                                                      one and use this */
$mail->FromName = "$this->name";  
$mail->AddAddress('xxxxx@xxx.xx');   // our mail address to which we are going to receive
                                                                                 // complaints/issues or suggestions

$mail->AddReplyTo("$this->email", "$this->name");   // The response sent to user mail
                                                                                                      // address
$ip=Yii::app()->request->userHostAddress;
$mail->IsHTML(true);
$mail->Subject = "regarding $this->subject";
$mail->AltBody = "Mail From HYD Urban NIC Server. To view the message, please use an HTML compatible email viewer!";
$mail->Body = "From Email : $this->email <br/> Logged in fms as <b>$uname</b>";


if(($ipadd!=null)and($ipadd!=''))
$mail->Body= $mail->Body." through Ip address $ipadd or $ip <br/> Content: ".$this->body;
else
$mail->Body= $mail->Body."<br/> Content: ".$this->body;

if(!$mail->Send())
{
 echo "Mailer Error: " . $mail->ErrorInfo;
 return 0;
}
else
{
 echo "Message sent!\n";
 return 1;
}
}
public function getRealIp()             // To obtain real IP address
        {
            if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
            {
                $ip=$_SERVER['HTTP_CLIENT_IP'];
            }
            elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
            {
                $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
            }
            else
            {
                $ip=$_SERVER['REMOTE_ADDR'];
            }
            return $ip;
        }

The above getRealIp() can be used if needed, this is to trace from which machine the request/complaint fired. once the submit clicked the user details and the form entries comes to our mail and when we click reply the user email address added automatically to the mail as we have given 'AddReplyTo' in our method.

Hope this helps!!!


Thursday, 18 December 2014

Ubuntu::How to run permission as root

To fully access your folder or files operational,
ubuntu 11.04 (natty):
1. Right click on desktop
2. Select Create Laucher
3. Enter this:
Name: GKSudo launcher
Command: gksudo “gnome-open %u”
Comment: Open files with root privilege

Ubuntu:: Mount windows partition permanently

Open terminal.
1. Create folder
sudo mkdir -p /media/www
2.  View disk info
$ sudo fdisk -l
3. Mount disk
sudo mount -t ntfs -o nls=utf8,umask=0222 /dev/sda3 /media/www

Mysql:: Stored Procedure:: Looping Daily Date With Time Range

PROCEDURE abc(pmId INT, dateFrom DATE, dateTo DATE)
BEGIN
        DECLARE str TEXT;
        DECLARE dff DATETIME;
        DECLARE dnn DATETIME;
        DECLARE dn DATE;
    DECLARE df DATE;
    SET df = dateFrom;
    WHILE DATE(df) <= DATE(dateTo) DO
            SET dn = DATE_ADD(df, INTERVAL 1 DAY);
  
            SET dff = CONCAT(df, ‘ 08:00:00′);
            SET dnn = CONCAT(dn, ‘ 07:59:00′);
  
            SELECT ‘CT1′ as trip, DATE_FORMAT(date,’%d-%m-%Y’) as date,GROUP_CONCAT(DISTINCT CAST(driver_id AS CHAR)) as  
                        dri, count( IF(size=20, 1, NULL ) ) AS ctOne20, count( IF(size=40, 1, NULL ) ) AS ctOne40
            FROM trip_ct WHERE pm_id=pmId AND DATE_ADD(date, INTERVAL time HOUR_SECOND) BETWEEN dff AND dnn;
            SET df = DATE_ADD(df, INTERVAL 1 DAY);
               
    END WHILE;
END

Replace space in Java Script

var course = “The Style And CSS”;
var rep_course = course.replace(/ /g, “-“); //replace all space with -

Jquery:: add table row, remove table row

<script type=”text/javascript”>
function addRowTable()
{
$(“#myTable > tbody”).append(“<tr><td>row content</td></tr>”);
}
function removeRowTable(rowId)
{
if(confirm(“Are you sure to delete this item?”)){
$(“#”+rowId).remove();
}
}
</script>
<table id=”myTable”>
<thead><th>head1</th></thead>
<tbody></tbody>
</table>
<input type=”button” name=”addtolist” value=”Add To List” onclick=”addRowTable()”>

Php compare strings and compute differences

Here is the php source code on how to compare two strings and compute the differences.
<?php
$text1 = $text1 = $s = ”;
if(isset($_POST[‘submit’]))
{
$text1 = $_POST[‘text1′];
$text2 = $_POST[‘text2′];
$chk = $_POST[‘chk’];
if($chk == ‘y’)
{
$s = ‘checked';
}
}
echo “<form method=post action=’strCompute.php’>
Text 1: <input type=text name=’text1′ value=’$text1′>
Text 2: <input type=text name=’text2′ value=’$text2′>
<input type=’checkbox’ name=’chk’ value=’y’ $s> Case Insensitive?
<input type=submit value=’Submit’ name=’submit’>
</form>”;
if($text1 == ”){ exit; }
$arrResult = computeDiff($text1, $text2, $chk);
$cntResult = count($arrResult);
echo “<p>Total Distance is $cntResult</p>”;
echo “<p>The differences character are:”;
foreach($arrResult as $value)
{
echo ” <font color=red><b>$value</b></font> “;
}
echo “</p>”;
function computeDiff($text1, $text2, $chk)
{
if($chk == ‘y’)
{
$text1 = strtolower($text1);
$text2 = strtolower($text2);
}
$array1 = str_split($text1);
$array2 = str_split($text2);
$result = array_diff_assoc($array1, $array2);
if(count($result) == 0)
{
$result = array_diff_assoc($array2, $array1);
}
return $result;
}
?>

JpGraph – Generate PHP graph and YII Charts

JpGraph is a Object-Oriented Graph creating library for PHP >= 5.1 The library is completely written in PHP.
I’m using this classess to create any graph over the years. It is easy to use and a lot of function to customize your graph output.
Create graphical statistic or analysis using this classess. Obsolutely easy and free also.
Support Supports several plot types,spider-plots, pie-charts (both 2d and 3d) , scatter-plots, line-plots, filled line-plots, accumulated line-plots, bar plots, accumulated bar plots, grouped bar plots, error plots, line error plots, box plots, stock plots.
Get JpGraph here -> JpGraph

Nice and Interactive Chart :: With Yii Extensions

Nice and Interactive Chart With Yii Extensions

For Yii extensions:

Yii:: Jquery Mask Input For Date

1. Download Masked Input Plugin by digitalBush
2. If you’re using Yii, create folder js outside the protected folder, store the js file inside there, put this code in your page.
<?php
$cs=Yii::app()->clientScript;
$cs->registerScriptFile(Yii::app()->baseUrl.’/js/jquery.maskedinput-1.2.2.js’,CClientScript::POS_HEAD);
?>
3. Then, assign the field to be masked
<SCRIPT language=”javascript”>
$(‘#date_1′).mask(“99-99-9999″,{placeholder:”_”});
</SCRIPT>

PHP: Add leading zeros to number and convert time 12 to 24 hours and vice versa

PHP:: Add leading zeros to number
$number = 3;
$invoice_no = sprintf(“%07d”, $number);
//output => 0000003

PHP convert time 12 to 24 hours and vice versa

// 24-hour time to 12-hour time
$time_in_12_hour_format  = DATE(“g:i a”, STRTOTIME(“23:15″));
// 12-hour time to 24-hour time
$time_in_24_hour_format  = DATE(“H:i”, STRTOTIME(“3:20 pm”));

PHP Get previous month and end day of last month

PHP Get previous month and end day of last month
//Get previous month and year
$lastmonth = date(“Y-m”,mktime(0, 0, 0, date(“m”)-1, date(“d”), date(“Y”))); //eg .output 2010-09
//Get end date of previous month (use ‘t’)
$endDateOfLastMonth = date(“Y-m-t”, strtotime(“last month”)); //eg. output 2010-09-30

Php Sendmail with xampp in windows server 2008

Php Sendmail with xampp in windows server 2008
Sending mail using PHP in windows server quite difficult and sometimes need extra works..So here is the setup that works with Apache, Xampp, PHP in my windows server 2008.
1. Setup sendmail.ini
In xampp, there is folder sendmail. Open file sendmail.ini and configure this value:
smtp_server=xxx.xx.xx.xxxx
smtp_port=25 (default)
auth_username=xxxxxx@yourdomainmail.com
auth_password=xxxxxx
2. Then setup php.ini in xampp/php folder
SMTP = xxx.xx.xx.xxxx
smtp_port = 25 (default)
sendmail_path = “\”C:\xampp\sendmail\sendmail.exe\” -t”      //make sure you check your path is correct
3. Ok Done. Restart your webserver.
You can use phpmailer to send email from your application.

PhpList: warning the temporary directory for uploading is not writable

My step to resolve this error.
2. Create folder ‘tmp’ inside your list folder, then set permission 0777
3. Configure config.php eg:
$tmpdir = ‘/var/www/vhosts/pulaidesaru.com/httpdocs/lists/tmp';
//the dir directory base on your DOCUMENT_ROOT

Generate Row Number for CgridView in YII

Yii::CGridView – Generate row number
<code>$this->widget(  'zii.widgets.grid.CGridView',  array(    'columns'=>array(      array(        'header'=>'No.',        'value'=>'$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',      ),
      'emp_no',
      'emp_name',
    ),  ));</code>

Ajax Submit Button, Prevent multiple posts in YII

Yii::ajaxsubmitbutton – Prevent multiple post
To prevent the ajaxsubmitbutton from doing multiple post, add the ‘beforeSend’ option to your code:
<?php echo CHtml::ajaxSubmitButton(‘Save’,
                                   array(‘formWorkHoursDays’),
                                   array(
                                                      ‘success’=>’function(html) { alert(html); }’,
                                                      ‘beforeSend’=>’function(){
                                                                        $(\’body\’).undelegate(\’#submitMe\’, \’click\’);
                                                                    }’,    

                                                        ),
                                    array(‘id’=>’submitMe’, ‘name’=>’submitMe’, ‘class’=>’submitButton’)
                              );
?>

Change Themes Dynamically in YII application

So, plan to change themes dynamically on your page with Yii?? Here is what i do.
1. Add this code to protected/components/Controller.php
public $breadcrumbs=array();
public function beforeAction($action)
        {
            $dynamicTheme = ‘classic';
        
            if(isset($_POST[‘mytheme’]))
            {
                $dynamicTheme = $_POST[‘mytheme’];
                //Yii::app()->request->cookies[‘dynamicTheme’] = new CHttpCookie(‘dynamicTheme’, $dynamicTheme);
                $cookie = new CHttpCookie(‘dynamicTheme’, $dynamicTheme);
                $cookie->expire = time()+60*60*24*180; 
                Yii::app()->request->cookies[‘dynamicTheme’] = $cookie;
            }
            
            if(isset(Yii::app()->request->cookies[‘dynamicTheme’]->value))
            {
                $dynamicTheme = Yii::app()->request->cookies[‘dynamicTheme’]->value;
            }
            else
            {
                //Yii::app()->request->cookies[‘dynamicTheme’] = new CHttpCookie(‘dynamicTheme’, $dynamicTheme);
                $cookie = new CHttpCookie(‘dynamicTheme’, $dynamicTheme);
                $cookie->expire = time()+60*60*24*180; 
                Yii::app()->request->cookies[‘dynamicTheme’] = $cookie;
            }
            
            //$dynamicTheme = (isset(Yii::app()->request->cookies[‘dynamicTheme’]->value)) ?    Yii::app()->request->cookies[‘dynamicTheme’]->value : ‘classic';
            Yii::app()->theme=$dynamicTheme;
            
            return parent::beforeAction($action);
        }
2. Add this code anywhere you want. This code for select list of theme:
<form name=”form1″ id=”form1″ method=’post’ action=”<?php echo CHtml::normalizeUrl(array(‘index’))?>” style=”margin:0;padding:0;”>
                        &nbsp;&nbsp;
                        Theme: <SELECT name=’mytheme’ onchange=”Javascript:document.form1.submit()”>
                                    <?php
                                        $arrTheme = Yii::app()->params[‘arrTheme’];
                                        foreach($arrTheme as $value=>$display)
                                        {
                                            $dynamicTheme = (isset(Yii::app()->request->cookies[‘dynamicTheme’]->value)) ? Yii::app()->request->cookies[‘dynamicTheme’]->value : ”;
                                            $s = ”;
                                            if($value == $dynamicTheme) $s = ‘selected';
                                            echo “<option value=’$value’ $s>$display</option>”;
                                        }
                                    ?>
                                </SELECT>
</form>
3. Add theme list parameter on your protected/config/main.php
‘params’=>array(
// this is used in contact page
‘adminEmail’=>’webmaster@example.com’,
 ‘arrTheme’=>array(
                        ‘classic’=>’Default’,
                        ‘white’=>’White’,
                    ),
),

OK THATS ALL.. Hope your code success..

Expression in Access Rules in YII

Here is one of the way on how we do control user access to some function in our controller.
In your controller file, on public function accessRules(), add this array:
array('allow',
                                'actions'=>array('leaveApproval', 'pendingLeave'),
                                'users'=>array(Yii::app()->user->username),
                                'expression' => '(Yii::app()->user->leave_approval == "Y")',
                        ),

Reset Filter on CGridView in YII

Yii:: Reset Filter on GridView
1. Add this reset button:
<?php echo CHtml::resetButton('Clear!', array('id'=>'form-reset-button')); ?>
2. Add this jquery:
$('#form-reset-button').click(function()
{
   var id='document-grid';
   var inputSelector='#'+id+' .filters input, '+'#'+id+' .filters select';
   $(inputSelector).each( function(i,o) {
        $(o).val('');
   });
   var data=$.param($(inputSelector));
   $.fn.yiiGridView.update(id, {data: data});
   return false;
});

CDetailVIEW in YII -- Make font bold

Yii::CDetailView-> Make the value font bold
This is just the simple solution:
Change your data type to html.
array(
                    'label'=>'Leave Type',
                    'type'=>'html',
                    'value'=>'<b>'.$model->leaveCode->leave_type.'</b>',
                ),

Yii:: Highlight row color in CGridView using rowCssClassExpression

If you’re using CGridView and want to highlight or focus on certain row, you can use rowCssClassExpression attribute in your gridview.
Here is the working method that works with combine even/odd class.
$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'leave-form-grid',
    'dataProvider'=>$model->approve()->search(),
    'filter'=>$model,
        'rowCssClassExpression'=>'($data->cancel_status == "Y")? "cancel" : "row_id_" . $row . " " . ($row%2?"even":"odd")',
    'columns'=>array(
        //'id',
        'staff_id',
                'staff.name',

Dynamic Textbox Creation in DOTNET

--------------------- ASPX CODE --------------------------------------
 
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="dynamictxtboxex.aspx.vb" Inherits="dynamictxtboxex" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">

<title>Untitled Page</title><script type="text/javascript" >function GetAlert(txtDynamic) {if(document.getElementById(txtDynamic).value!="")alert(document.getElementById(txtDynamic).value);
}
function GetPostBack(txtDynamic) {if (window.event.keyCode == 13) {document.getElementById("htxtBox").value = txtDynamic;document.form1.submit();
}

}
</script></head><body><form id="form1" runat="server"><input type="hidden" id="htxtBox" runat="server" value=""/><div><asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder></div></form></body></html>

---------------------------------------- VB CODE -------------------------------
PartialClass dynamictxtboxexInherits System.Web.UI.PageDim Tbl As TableDim tblCell As TableCellDim tblRow As TableRowDim txtDynamic As TextBox
Protected Sub Page_Load(ByVal sender As ObjectByVal e As System.EventArgs) Handles Me.LoadIf Not Page.IsPostBack ThenTbl =New TableTbl.Rows.Add(GetTableRow(1))
PlaceHolder1.Controls.Add(Tbl)
Session(
"DynamicTable") = TblElseTbl = Session("DynamicTable")If htxtBox.Value = "Txt" & Tbl.Rows.Count.ToString ThenTbl.Rows.Add(GetTableRow(Tbl.Rows.Count + 1))
PlaceHolder1.Controls.Add(Tbl)
htxtBox.Value =
""ElsePlaceHolder1.Controls.Add(Session("DynamicTable"))End IfEnd IfEnd SubPublic Function GetTableRow(ByVal Count As StringAs TableRowtxtDynamic =New TextBoxtxtDynamic.ID ="Txt" & CounttxtDynamic.Attributes.Add("onmousedown""GetAlert('" & "Txt" & Count & "')")txtDynamic.Attributes.Add("onkeydown""GetPostBack('" & "Txt" & Count & "')")tblRow =New TableRowtblCell =New TableCelltblCell.Text ="Enter value for " & CounttblRow.Cells.Add(tblCell)
tblCell =
New TableCelltblCell.Controls.Add(txtDynamic)
tblRow.Cells.Add(tblCell)
Return tblRowEnd FunctionEndClass

Computer TIP

à°•ొà°¨్à°¨ి ఆపరేà°Ÿింà°—్ à°¸ిà°¸్à°Ÿà°®్à°¸్ Data Processing సమయంà°²ో Ram memory బదుà°²ుà°—ా hard disk memory à°¨ి use à°šేà°¸ుà°•ుంà°Ÿాà°¯ి . à°ˆ memory à°¨ి Virtual memory à°…ంà°Ÿాà°°ు.మనం shutdown à°šేà°¸ిà°¨ à°µెంà°Ÿà°¨ే à°ˆ data clear à°…à°µ్వటాà°¨ిà°•ి à°ˆ à°µిà°§ంà°—ా à°šేà°¯్à°¯ంà°¡ి.
start ->control panel->Administrative Tools->Local Security Settings à°¨ి Double click à°šేà°¯్à°¯ంà°¡ి. à°…ంà°¦ుà°²ో Local Policies->Security Options->Shutdown: Clear virtual memory pagefile Double click à°šేà°¯్à°¯ంà°¡ి.à°’à°• dialog box వస్à°¤ుంà°¦ి.à°¦ాà°¨్à°¨ి Enable à°šేà°¸ి ok à°šేà°¯్à°¯ంà°¡ి

How to install Call Manager 8.x in VMWare?

How to install Call Manager 8.x in VMWare?  

Step-1

Turn off your Window's Firewall and set a static IP in your Loopback Adapter.  

Step-2
Configure a NTP Server in GNS and connect with VMware through Cloud. 
Step-3 (a)
Now Configure VMware with these settings. Select Typical option. 
 
Step-3 (b)
                  If you have CUCM-8.0 IOS in DVD then select Installer disc option, If you have CUCM-8.0 IOS in your hard disk or flash drive then select Installer disc image file (ios).Do not select option I will install the operating system later. 
 
Step-3 (c)
                 Provide information like Name, User name, Password as you wish.
Step-3 (d)
                 Provide Virtual machine name e.g (CUCM 8) and Browse the location where you want to save the CUCM 8 files. 
 
Step-3 (e)
                 Allocate hard disk size, Minimumm size of hard disk for CUCM 8 is 72 GB and select option Store virtual disk as a single file. 
 
Step-3 (f)
                Allocate Memory more than 2GB to run CUCM 8 properly and also configureNetwork Adapter as a Bridged. 
After step-3 virtual machine settings are complete. Power On this Virtual machine (CUCM 8).
 
Step-4 (a)
                 If you want to check your media resources (e.g hard disk, RAM etc) then selectYes, but if don't select No. This media check is Optional. 
 
Step-4 (b)
                 Cisco Unity Connection and CUCM Business Edition are not supported on current hardware. 
 
Step-4 (c)
                 Select Yes for further installation. 

Step-4 (d)
                 Select Proceed for further installation. 
 
Step-4 (e)
                 If you have any Upgrade patch regarding CUCM 8.0 then select Yes otherwise select No. 
 
Step-4 (f)
                Select Continue for further installation. 
  
Step-4 (g)
                Select your Timezone and select Yes for further installation.
Step-4 (i)
                If you want to change MTU size then select Yes, if don' select Nom, then next step If you want DHCP on this machine select Yes, if you don' select.
 
Step-4 (k)
                Provide Network configuration. 
 
Step-4 (l)
               If you want to enable DNS client on this machine select Yes otherwise No. 
Step-4 (m)
                 Provide Administrator Login Configuration. 
 
Step-4 (n)
                Provide Certificate Information. This option about your organization information.
Step-4 (o)
                Select Yes if this CUCM is Publisher. Select No if you have already a Publisher. 
 
Step-4 (p)
                Provide NTP server's IP address as provided in step-2. 
 
Step-4 (q)
                Provide Security Password. This password is used in Clustering. 
 
Step-4 (r)
                If you want to configure SMTP select Yes but if you don't select No. Now ProvideApplication User Configuration. 
 
Step-4 (t)
               Select Ok if you provide correct information. Select Back if you want to change anything.
 
Cisco Unified Communications Manager Version 8.0 
Cisco Unified Communications Manager Version 8.0 is the powerful call-processing component of the Cisco Unified Communications Solution. It is scalable, distributable, and highly available enterprise IP telephony call-processing solution. Follow the given points to install CUCM 8 in vmware step by step. 
Step-1
             Turn off your Window's Firewall and set a static IP in your Loopback Adapter.  

Step-2
            Configure a NTP Server in GNS and connect with VMware through Cloud