21 Sep

How to use Smarty if else?

Let’s assign a discount amount from PHP to the tpl file as shown below.

$smarty->assign('discount', 0); 
{if $discount gt 0}
   You have a discount and discount amount is: {$discount}
{else}
	You don't have any discount.
{/if}

Now let’s assign some string to the tpl file as shown below.
Here we compare two strings equality using ‘eq’

$smarty->assign('category', 'Electronics'); 

Then in the tpl file, we can check the category as shown below.

{if $category eq 'Electronics'}
    As you are booking an electronics product, you will get a discount of 15%.
{else}
    For this product, we have a discount of 5%.
{/if}

For detailed explanation regarding the usage of if else in tpl,
go to the link https://www.smarty.net/docsv2/en/language.function.if.tpl

21 Sep

How to use Smarty foreach?

You can pass an array to the smarty tpl file as shown below.

<?php
$user_details = array(
	"name" => "x",
	"address" => "Y",
        "phone" => "Z"
);
$smarty->assign('my_array', $user_details);  //my_array can be replaced with anything

Then in the tpl file you can loop through the array as shown below

<ul>
{*    
   Note: We used my_array here because we passed array as
   assign('my_array', $user_details);
*}

{foreach from=$my_array key=k item=v}
   <li>{$k}: {$v}</li>
{/foreach}
</ul>

If we are passing an array without key in it say

$user_details = array(
	"x", "y", "z"
);
$smarty->assign('my_array', $user_details); 

Then we can display the values in the tpl as shown below

<ul>
{foreach from=$my_array item=v}
   <li>{$v}</li>
{/foreach}
</ul>
6 Jun

Hostbill plugin development

1)Create a folder with plugin name.
If plugin name is example, create a folder with name ‘example’.

2)Create a file named
class.example.php. Also a folder named admin in it.

3)In the admin folder create a file named
class.example_controller.php
also can create tpl files here.

Let’s create a tpl named default.tpl here.

4)Let’s create client side basic code in the file class.example.php.


<?php

class example extends OtherModule {

protected $modname = 'Example';
protected $description = 'Sampple Plugin';
protected $version = '0.1';

protected $info = array(
        'haveadmin'    => true,  // is module accessible from adminarea
        'haveuser'     => false, // is module accessible from client area
        'havelang'     => false, // does module support multilanguage
        'havetpl'      => false, // does module have template
        'havecron'     => false, // does module support cron calls
        'haveapi'      => false, // is module accessible via api
        'needauth'     => false, // does module needs authorisation
        'isobserver'   => false, // is module an observer
        'clients_menu' => false, // listing in adminarea->clients menu
        'support_menu' => false, // listing in adminarea->support menu
        'payment_menu' => false, // listing in adminarea->payments menu
        'orders_menu'  => false, // listing in adminarea->orders menu
        'extras_menu'  => true, // listing in extras menu
        'mainpage'     => true, // listing in admin/client home
        'header_js'    => false, // does module have getHeaderJS function
    );

protected $configuration=array(
         'Field1' => array(
            'value' => '',
            'type' => 'input',
            'description' => 'My description'
        ),
        'Field2' => array(
            'value' => '',
            'type' => 'input',
            'description' => 'My description'
        ),
        'Field3' => array(
            'value' => '0',
            'type' => 'check',
            'description' => 'My description'
        )
    );

public function install() {
  echo "Install";
  return true;
}

}

5)

<?php


class example_controller extends HBController {
    /*
	?cmd=example
    */


    function _default($request) {
	//default function, just like our default index.php
        $showheaderandfooter = true;
        $module_type = 'Other';
        $this->template->assign('test', 'test');
        $this->template->render(
                APPDIR_MODULES .
                $module_type . '/example/admin/default.tpl', [], $showheaderandfooter
        );

    }

    /*
	?cmd=example&action=testfunction
    */

    function testfunction($param) {
	//action=testfunction, even for post action we can do like this
        $showheaderandfooter = true;
        $module_type = 'Other';
        $this->template->assign('test', 'test');
        $this->template->render(
                APPDIR_MODULES .
                $module_type . '/example/admin/testfunction.tpl', [], $showheaderandfooter
        );
    }


}

6)The content added to the file admin/default.tpl is
{$test}

11 Apr

Domain verification using Let’s Encrypt DNS Challenge Type (dns-01)

From the link https://github.com/analogic/lescript, we will get a nice script to create SSL Certificates. The script has code to verify domain after uploading a file to a folder .well-known/acme-challenge in the document root. If the domain is not yet hosted , we have to verify the domain using DNS TXT record.

This post explains about domain verification using DNS method.

First of all download the script from the link https://github.com/analogic/lescript.
Then we can use most of it’s code for domain verification using DNS too.

We have to use response we get for

$response = $this->signedRequest(
                    "/acme/new-authz", array("resource" => "new-authz",
                "identifier" => array("type" => "dns", "value" => $domain)
                    )
);

This array will have challenge details for domain verification using http, dns etc.

To get dns challenge details, use the below code

$dns_challenge = array_reduce($response['challenges'], function ($v, $w) use (&$self) {
                return $v ? $v : ($w['type'] == "dns-01" ? $w : false);
            });

From the dns challenge we can collect token and key authorization.

$dns_token = $dns_challenge['token'];

$dns_payload = $dns_token . '.' 
                    . Base64UrlSafeEncoder::encode(hash('sha256', json_encode($header), true));

You can see that token and key authorization are creating just like we create for http-01. Now the main difference is, how we calculate the DNS TXT Record.

For domain verification using http-01, we create a file named
http://${domain}/.well-known/acme-challenge/${challenge[‘token’]}
and we put the payload as content of the file.

But for dns-01 domain verification, we are not adding TXT value as payload, but we calculate a string by below code.

// name of the domain
$name = '_acme-challenge'. $domain;

//points to
$dns_txt_record = Base64UrlSafeEncoder::encode(hash('sha256',$dns_payload, true));

Then we have to add $name and $dns_txt_record to the dns zone TXT record.
We can check weather the value is added correctly or not by typing below command in terminal.

dig txt _acme-challenge.[domain]

Then we can invoke the domain verification using dns-01 type.

$result = $this->signedRequest_dns(
                $challenge_uri, array(
            "resource" => "challenge",
            "type" => "dns-01",
            "keyAuthorization" => $dns_payload,
            "token" => $dns_token
                )
        );

If anybody need more explanation or help, please do post comments.
Will answer asap.

29 Dec

Fix for Codeigniter WHERE IN query issue due to comma

In the below code we have an array of ids named $list_ids. We would like to mark the status of rows with ‘my_id’ = 1, my_id = 2 and my_id = 3 as Completed.

            $data['status'] = "Completed";
            $list_ids = array(1,2,3);
            $this->db->where_in('my_id', $list_ids);
            $this->db->update('my_table', $data);
            echo $this->db->last_query();

But after executing the above query, you might be surprised. Only row with ‘my_id’ = 1 gets updated. You might notice no change to the other two rows? Why?

Look at the generated query below.

UPDATE `my_table` SET `status` = ‘Completed’ WHERE `my_id` IN(‘1,2,3’)

There is a comma before 1 and after 3. The query should be
UPDATE `my_table` SET `status` = ‘Completed’ WHERE `my_id` IN(1,2,3)
to work it as expected.

For that we need to pass an extra parameter to the where_in function. The working code is given below.

            $data['status'] = "Completed";
            $list_ids = array(1,2,3);
            $this->db->where_in('my_id', 
                   $list_ids, FALSE);
            $this->db->update('my_table', $data);
            echo $this->db->last_query();

You can see that, we changed the where_in code from
$this->db->where_in(‘my_id’, $list_ids) to
$this->db->where_in(‘my_id’, $list_ids, FALSE);

Hope it’s helpful.

5 Dec

CRUD Using Codeigniter

Db operations using codeigniter is explained briefly with codes.

Add a new row
A row can be inserted as shown below. To get the unique id of the row inserted, we have to use the function: $this->db->insert_id().

$data['user_gid'] = $user_gid;
$data['username'] = $user_name;
$data['email'] = $email;
$this->db->insert("mytable", $data);
$user_id = $this->db->insert_id();

Update a row
To update a row, we have to pass a where condition.
mutiple where conditions are possible. Below sample code just used one where condition.

$data['user_gid'] = $user_gid;
$data['username'] = $user_name;
$data['email'] = $email;
$this->db->where('user_id', $user_id);
$this->db->update('mytable', $data);

Select a row
To select a row that matches a where condition, we have to pass a
where condition just like we passed for update.
$this->db->select(“*”) will select all fields of the table.
To select just one field or specific fields we can specify the field names.

//get all fields
$this->db->select("*");
//to get  email and username
//$this->db->select("username,email");
$this->db->from("mytable");
$this->db->where('user_id', $user_id);
$query = $this->db->get();
$row = $query->row_array();
return $row;

Select all rows

$this->db->select("*");
$this->db->from("mytable");
$query = $this->db->get();
$rows = $query->result();
return $rows;

Delete a row

$where = array(
    'user_id' => $user_id
);
$this->db->delete("mytable", $where);