Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Wednesday, 24 September 2014

Date Compare in YII model search function


View : Search form

label($model,'fromdate'); ?> widget('zii.widgets.jui.CJuiDatePicker',array( 'id'=>'HolidayHolidayrange_fromdate', 'name'=>'HolidayHolidayrange[fromdate]', 'value'=>$model->fromdate==''?'':date('d-m-Y',strtotime($model->fromdate)), 'options'=>array( 'dateFormat' => 'dd-mm-yy', 'showAnim'=>'slide', 'showButtonPanel'=>true, 'changeMonth'=>true, 'changeYear'=>true, 'yearRange'=>'1900:'.date('Y'), ), 'htmlOptions'=>array( 'style'=>'', 'placeHolder'=>'End Date' ), )); ?>
label($model,'todate'); ?> widget('zii.widgets.jui.CJuiDatePicker',array( 'id'=>'HolidayHolidayrange_todate', 'name'=>'HolidayHolidayrange[todate]', 'value'=>$model->todate==''?'':date('d-m-Y',strtotime($model->todate)), 'options'=>array( 'dateFormat' => 'dd-mm-yy', 'showAnim'=>'slide', 'showButtonPanel'=>true, 'changeMonth'=>true, 'changeYear'=>true, 'yearRange'=>'1900:'.date('Y'), ), 'htmlOptions'=>array( 'style'=>'', 'placeHolder'=>'End Date' ), )); ?>
Model's Search function
public function search()
 {
           ....................
        if(!empty($this->fromdate))  
        $criteria->addCondition('fromdate > "'.date("Y-m-d",strtotime($this->fromdate)).'" ');
   
        if(!empty($this->todate))
        $criteria->addCondition('todate < "'.date("Y-m-d",strtotime($this->todate)).'" ');
         .......................
       }

Tuesday, 23 September 2014

Dropdown Filter in CGridView

$month_list=array('1'=>'JAN','2'=>'FEB');
$this->widget('zii.widgets.grid.CGridView', array(
 'id'=>'form-grid',
 'dataProvider'=>$model->search(),
 'filter'=>$model,
 'columns'=>array(
        array(
            'name'=>'festivals.festival_name',
            'filter' => CHtml::activeTextField($model, 'festival_name'),
            ),      
  'day',
        array(
            'name'=>'month',
             'value'=>function($data,$row) use ($month_list){
                            return $month_list[$data->month];
                        },
             'filter'=>CHtml::activeDropDownList($model,'month',$month_list,array('empty'=>'Select Month')),
            ),
...........

Thursday, 29 May 2014

Multiple Row Updates in MySQL

CREATE TABLE  `testimonial_setting` (
  `testimonial_setting_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `testimonial_label` varchar(255) NOT NULL,
  `testimonial_key` varchar(45) NOT NULL,
  `testimonial_value` varchar(45) NOT NULL,
  PRIMARY KEY (`testimonial_setting_id`)
);

Table :-  testimonial_setting
testimonial_setting_id, testimonial_label,    testimonial_key, testimonial_value
            1,                       'Background Color',    'bgcolor',            ''
            2,                        'Text Color',               'textcolor',          ''
            3,                      'Heding Text Color',    'headtextcolor',    ''
            4,               'Heding Background Color', 'headbgcolor',    ''

Query :-

UPDATE `testimonial_setting` SET
`testimonial_value` = IF(`testimonial_key`="bgcolor","#ff00ff",`testimonial_value`),
`testimonial_value` = IF(`testimonial_key`="textcolor","#ffffff",`testimonial_value`),
`testimonial_value` = IF(`testimonial_key`="headtextcolor","#ff0000",`testimonial_value`),
`testimonial_value` = IF(`testimonial_key`="headbgcolor","#ff0fff",`testimonial_value`);

After update table :-  testimonial_setting


testimonial_setting_id, testimonial_label,    testimonial_key, testimonial_value
            1,                       'Background Color',    'bgcolor',            '#ff00ff'
            2,                        'Text Color',               'textcolor',          '#ffffff'
            3,                      'Heding Text Color',    'headtextcolor',    '#ff0000'
            4,               'Heding Background Color', 'headbgcolor',    '#ff0fff'

Saturday, 1 February 2014

PHP find value by index in multidimensional/associative array

Following function has easily to find and retrieve value by index from multidimensional/associative array
function array_key_exists_value($searchkey, $assocarray)
{
 $output='';
    $result = array_key_exists($searchkey, $assocarray);
    if ($result)
 {
  $output =$assocarray[$searchkey];
 }
else
{ 
    foreach ($assocarray as $val) {
        if (is_array($val)) {
            $output = array_key_exists_value($searchkey, $val);
        }
    }
} 
    return $output;
}

Convert a PHP Object to an Array

Following function has easily to convert an associative array from object data


function object_to_array($result) 
{ 
    $arraydata = array(); 
    foreach ($result as $key=>$value) 
    { 
        if (is_object($value)) 
        { 
            $arraydata [$key]=object_to_array($value); 
        } 
        elseif (is_array($value)) 
        { 
            $arraydata [$key]=object_to_array($value); 
        } 
        else 
        { 
            $arraydata [$key]=$value; 
        } 
    } 
    return $arraydata ; 
}  

Wednesday, 27 November 2013

My client isn't accepting my username and password for SMTP emails

We suggest making some adjustments in your mail client's settings so you aren't always prompted to enter your username and password. Please check the following settings in your mail client:
  • Make sure that you've entered your full email address (e.g. username@gmail.com)
  • Re-enter your password to ensure that it's correct. Keep in mind that passwords are case-sensitive.
  • Make sure your mail client isn't set to check for new mail too often. If your mail client checks for new messages more than once every 10 minutes, your client might repeatedly request your username and password.
Now, please follow the steps below to resolve the problem:
  1. Open your web browser and sign in to Gmail at http://mail.google.com/mail. If you see a word verification request, type the letters in the distorted picture and finish signing in.
  2. Close your browser and try accessing your messages in your email client again.
  3. If you're still having problems, visit http://www.google.com/accounts/DisplayUnlockCaptcha and sign in with your Gmail username and password. If necessary, enter the letters in the distorted picture.
  4. Click Continue.
  5. Restart your mail client and try accessing messages in your email client again.

Remove Wordpress Logo in Admin Bar

Add following code in your themes function.php
add_action( 'admin_bar_menu', 'remove_wp_logo', 999 );

function remove_wp_logo( $wp_admin_bar ) {
	$wp_admin_bar->remove_node( 'wp-logo' );
}

Add Custom Logo in Wordpress

1)Add following function in your themes function.php
2)upload customlogo.png image in your themes image folder
function custom_login_logo() {
	echo '';
}
add_action('login_head', 'custom_login_logo');

Hide / Remove Menu and SubMenu in wordpress Admin Panel

Remove a top level admin menu.
remove_menu_page( $menu_slug )
Here menu_slug has menu's slugname or page


Remove an admin submenu.
remove_submenu_page( $menu_slug, $submenu_slug )

Use following php code for theme's function.php
Ex:- for slug name
add_action( 'admin_menu', 'adjust_the_wp_menu', 999 );
function adjust_the_wp_menu() {
  $page =remove_menu_page( 'plugins' );
  $page = remove_submenu_page( 'themes', 'widgets' ); // widget page under themes
}
Ex:- for filename/page
add_action( 'admin_menu', 'adjust_the_wp_menu', 999 );
function adjust_the_wp_menu() {
  $page =remove_menu_page( 'plugins.php' );  
  $page = remove_submenu_page( 'themes.php', 'widgets' ); // widget page under themes
}

Wednesday, 30 October 2013

Moodle course list in every where for custom php

You can copy & paste following php code for every where
 
$con = mysql_connect("hostname","username","password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moodledatabase", $con) or die(mysql_error());
$query_course_list = "SELECT c.id AS courseid, c.fullname FROM mdl_course c where category != 0";
$courses = mysql_query($query_course_list);
$output = '';
echo $output;

Monday, 30 September 2013

Add Pagination for Blog/Post list at custom Page

Download the following plugin : http://wordpress.org/plugins/wp-pagenavi/
Add Following code in your current shortcode function :

function sc_newsletter_list($atts) {
     extract(shortcode_atts(array('limit' => '10', 'number' => '3','fullpage' => 'no', 'category' => '', 'title' => '',), $atts)); 
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $number = $limit;
    $wp_query = new WP_Query(
    array(
    'post_type' => array('Newsletter'),
    'paged' => $paged,
    'posts_per_page' => $number,
    ));

    $output = '';
    $counter = 0;
    if ( $wp_query->have_posts() ):      
    while( $wp_query->have_posts() ) : $wp_query->the_post();
   ...............................
   .................................
// Pagination : [wp-pagenavi] plugin used
    if(function_exists('wp_pagenavi')) { 
      $output .= ''; 
            }

Friday, 6 September 2013

Customize the wordpress shortcode : recent_blog

Find the php file for shortcode in customtheme :

File Location:

webroot\wp-content\themes\themename\backend\shortcode.php

Find the below code :

 function recent_blog($atts) {
     extract(shortcode_atts(array('limit' => '3', 'number' => '3','fullpage' => 'no' ), $atts));  

    $number = $limit;
 $categoryid = $category; // added category slug here...
    $wp_query = new WP_Query(
    array(
    'post_type' => array('post'),
    'showposts' => $number,
    ));
....................
 add_shortcode('recent_blog', 'recent_blog');
add category , category_name - category slug name to filter the post by category
function recent_blog($atts) {
     extract(shortcode_atts(array('limit' => '3', 'number' => '3','fullpage' => 'no', 'category'=>'' ), $atts));  //added slug category  here......'category'=>'' 

    $number = $limit;
 $categoryslug = $category; // added category slug here...
    $wp_query = new WP_Query(
    array(
    'post_type' => array('post'),
    'showposts' => $number,
 'category_name' => $categoryslug , // added category slug here...
    ));
.............
 add_shortcode('recent_blog', 'recent_blog');
Use following shortcode on page/post in content area
[recent_blog limit="5" fullpage="yes" category="slugname"]

Thursday, 5 September 2013

How to use WordPress Shortcode

 WordPress Shortcode Usage
Example 2 is the simplest version of WordPress Shortcode to execute.
Copy and Paste this onto your WordPress Theme’s functions.php file:
function donatebutton() {
    return '<a href="/donate/" class="donate-button">Donate!</a>';
}
add_shortcode('donate', 'donatebutton');
Use this shortcode in your WordPress post/page’s content:
[donate]
The HTML output will be this:
<a href="/donate/" class="donate-button">Donate!</a>
Using a simple “[foo-bar]” shortcode can output an entire content block across multiple pages, making it easy to update.
More of a blockquote style usage of WordPress Shortcode, like in the first example, requires a little extra, but is still extremely easy to execute.
Copy and Paste this onto your WordPress Theme’s functions.php file:
function postrecap($atts, $content = null) {
 return '<span class="recap">'.$content.'</span>';
}
add_shortcode("recap", "postrecap");
Use this in your WordPress post/page’s content:
[recap]A bit of text content[/recap]
The HTML output will be this:
<span class="recap">A bit of text content</span>
This exact code snippet was used on one of our client’s WordPress sites, AgendaWise, to great effect and made the blog a lot easier to maintain for the site owner. This allows the client to use a pre-built-custom blockquote, and cite someone with unique and consistant styling thanks to WordPress shortcode. It automatically detects if there’s a name and/or url being referenced. If there’s a name and a url, the WordPress Shortcode adds a styled link at the end of the quote, and if there’s a name but no url, it just adds a styled name at the bottom of the blockquote.
Use any of these in your WordPress post/page’s content:
[blockquote]Test content.[/blockquote]
 
[blockquote cite="John Doe"]Test content.[/blockquote]
 
[blockquote cite="John Doe" url="http://example.com/"]Test Content[/blockquote]
Copy and Paste this onto your WordPress Theme’s functions.php file:
function bc($atts, $content = null) {
 extract(shortcode_atts(array(
  "cite" => 'Unknown',
  "url" => 'url'
 ), $atts));
 if ( $cite == 'Unknown' ) {
  return '<blockquote class="bc-full"><p>'.$content.'</p></blockquote>';
 } elseif ( $url == 'url' ) {
  return '<blockquote class="bc-full"><p>'.$content.'</p><p class="bc-cite">- '.$cite.'</p></blockquote>';
 } else {
  return '<blockquote class="bc-full"><p>'.$content.'</p><p class="bc-cite">- <a href="'.$url.'">'.$cite.'</a></p></blockquote>';
 }
}
add_shortcode("blockquote", "bc");
The HTML output will any of these, respectively:
<blockquote class="bc-full"><p>Test content.</p></blockquote>
 
<blockquote class="bc-full"><p>Test content.</p><p class="bc-cite">-John Doe</p></blockquote>
 
<blockquote class="bc-full"><p>Test content.</p><p class="bc-cite">- <a href="http://example.com">John Doe</a></p></blockquote>
This technique could be very well combined with some of the concepts in example 2. Say, if you were to have a blog with multiple authors, you could use [twitter handle="brianpurkiss"] to output a custom styled Twitter follow button that plugs in the specified twitter handle. Again, the possibilites of WordPress shortcode are endless.

Wrap Up

WordPress’ Shortcode has vast amounts of untapped possibilities. It is extremely beneficial in allowing clients to add more complex content areas with no technical knowledge and great ease. WordPress shortcode can even be beneficial for those with lots of technical knowledge to better manage duplicate content areas.
Make website management easier – use WordPress Shortcode.

What is WordPress Shortcode?

WordPress Shortcode :
        It’s a common phenomenon to see a designer’s website in a design class several levels above that of it’s clients web design work. While there are many factors that can play into this occurrence, one in particular is very common. Designers/developers know more about code, whereas many clients don’t try at all to learn any. That is a huge component in making it difficult for those who build WordPress websites to make top notch sites for clients. There are certain site components that require additional code custom to each usage in order to function. Thus, for many jobs, additional code means more advanced components are off limits for client work, limiting the site’s possibilities.
However, it is possible to use WordPress Shortcode to output complex snippets in a simple manner so that people with no HTML/CSS background can output any pre-determined code snippet.
WordPress Shortcode has a wide variety of applications and can be extremely beneficial for website managers of all ranges of technical backgrounds.

What is WordPress Shortcode?

Example 1
[container]Lorem ipsum dolar sit amet[/container]
With that shortcode, you can output whatever you want on your WordPress website. You can build anything – any amont of HTML, CSS, Javascript, PHP, or anything else you may want. The possibilities are endless.
Example 2
The simplest, yet most overlooked, example of using WordPress Shortcode can be extremely simple or extremely complex.
This:
[donate]
Can output this:
<a href="/donate/" class="donate-button">Donate!</a>
This simple technique utilizing WordPress shortcode can output pre-built complex, or simple, code snippets. This one is great for having pre-built content areas that are used on multiple pages and/or articles. It’s less code to maintain and allows you to update all of the pages by editing a single code snippet. Very similar to WordPress’ file structure, but using WordPress shortcode gives you more versatility and applications.
Example 3
The most common example of WordPress’ Shortcode can be derived from BBCode.
This:
[img title="Example Logo"]http://example.com/images/logo.png[/img]
Can output this:
<img src="http://example.com/images/logo.png" alt="Example Logo" />
BBCode, essentially a different form of WordPress Shortcode common on forums, uses the above snippet to output an image. While this isn’t all that different than the  tag, it is simpler enough that, as a general rule, website managers who aren’t very technically savvy have an easier time grasping shortcode than actual html.
Even though it’s an extremely simple concept, the possibilities are endless and WordPress shortcode can open up a whole new world for your client work.

Create custom short code in Wordpress

Wordpress Page content : add short code
[column width="full" place="none" ][recentwork] [/column]
Add function for shortcode creation : File location : webroot\wp-content\themes\currenttheme\functions.php
add_shortcode('recentwork','showrecentworks');

function showrecentworks(){ 
return $content='



 

Recent Work

Digital Video Camera Lens
Digital World
Aenean aliquet pulvinar dui, nec tempus lectus posuere quis. Proin dignissim
'; }

Tuesday, 6 August 2013

File upload size change in Moodle

Windows XP and Server 2003 based Instructions

These instructions presume that you have downloaded the latest PHP 5.3.x Windows zip package and extracted it to C:\PHP. If you have installed PHP to another location then change all references to "C:\PHP" to the location you installed PHP too.
  • Open C:\PHP
  • Right Click the php.ini file in this folder and choose "Open with..." selecting your editor of choice.
  • Press Ctrl + F and type "post_max_size" (click Find...", where needed)
  • Change the value to the number of Mb you want your site to accept as uploads
  • Press Ctrl + F and type "upload_max_filesize" (click Find...", where needed)
  • Change the value to the number of Mb you want your site to accept as uploads
  • Press Ctrl + F and type "max_execution_time" (click Find...", where needed)
  • Change the value to 600
  • Press Ctrl and S or the save button.
  • Exit your editor.
  • Restart your webserver to reload PHP with the edited changes.
    • For IIS
    • Open the Start Menu on your server and select "Run"
    • Type "iisreset /RESTART"
    • For Apache 2 and Windows XP
    • Go to Start > All Programs > Apache > Restart
    • For Apache 2 and Windows Server
    • The following command will work as long as you have installed Apache 2 as a service on your Windows Server
    • Open your Start Menu on your server and select "Run"
    • Type "httpd -k restart"
Your new file size limit should now appear in Administration > Security > Site Policies > Maximum uploaded file size
NOTE: These instructions also cover the Xampp Windows installer. Just replace C:\PHP with C:\Moodle\server\php and to restart your Moodle with a normal stop-start.

Wednesday, 31 July 2013

Moodle and WordPress Single Sign On in 20 minutes – Part 1

Even if i am a Sysadmin, i like to do web things (possibly challenging), and this time, it’s time to make wordpress authentication work on moodle too.
Scenario:
Wordpress installation and Moodle installation.
We are going to use the WordPress database in order to authenticate users within Moodle. Thus, we can sell courses using wordpress ecommerce plugin and have instant access from customers.
The two sites are on the very same machine but on different domains (actually WordPress is in the “www.domain.tld” and “*.domain.tld” subdomains and Moodle is on another subdomain (courses.domain.tld) so we need to authenticate users in both sites using the very same database and table.
The Problem: The Moodle external autentication plugin does not work with WordPress authentication out of the box, instead, it will need a couple of modification very easy to be made, don’t worry, even for a non php skilled person.
We will come back on this later on this post.
Let’s start our 20 minutes modification!
Shop list:
  • WordPress Version 3.4.2
  • WordPress database informations
  • Moodle Version 2.0
  • Moodle External Database Authentication Plugin (already in the Moodle defaultinstallation)
  • Some coding so, all stuff for ftp things/sftp/ssh things and a decent text editor with some failsafe feature (save a copy before modify etc)
That’s enough to start working on.
Once installed the two systems, you will have to properly configure the external database authentication plugin on Moodle platform. To do this you have to authenticate yourself as site administrator, then on the menubar choose and click on “Site Administration” -> “Plugin” -> “Authentication” -> “Manage Authentication”.
You can use the provided image on the left to quickly find out the links path needed to get there.





Once there you will see a list of all authentication plugin, their status (active or inactive) their priority order and their “settings” link.As you can see in the image below, you have to enable and prioritize the plugin in order to make it work. You probably want to disable the self-registration (see picture in bottom part) feature in order to prevent user to signup using moodle platform because, otherwise, all users created within Moodle will not be able to authenticate themselves against WordPress.
This is the list of the moodle authentication plugins. It shows if a plugin is enabled or not, and it exposes a link for each plugin to be configured.
Once you have done, let’s click on the “Setting” link and let’s try to configure this plugin at it best.
We have to enter all info used by Moodle to read the WordPress database.
Fields are:
  • Host, in my case i will use “localhost” and probably you too unless your db is hosted on a different machine, in that case you have to use the Hostname or ip address of that machine
  • Database, in my case “mysqli” (Please, notice the trailer “i” – mysqli and notmysql).
  • Use sybase quotes, we do not need this to be on so we will leave it on “NO
  • Db name, the name of your wordpress database (get it from wp-config.php)
  • Db Usermysql user that can access WordPress db tables
  • Db Passwordmysql password for mysql user
  • Table, the name of the table where username/passwords are stored. The most of the time is “wp_users” unless you changed your table prefix
  • Username Field, the field containing the username, for WordPress: “user_login”
  • Password Field the field containing the password for username for WordPress: “user_pass”.
  • Password Format, we should choose “wordpress” format but there is no such option in this drop down, so what? we will solve this later, don’t worry
  • External db encoding, i use “UTF-8″
  • SQL setup command, you can leave it blank
  • Debug ADOdb, choose “NO
  • Password-change URL, we use the wordpress password recovery page link
These are the needed field to make this thing work, if you want more integration, you can configure the part named “cron syncronization script” and sync information such as first name, surname, user preferences and so.
But now we have to stay focused on the missing dropdown item and find a way to get it out of there.
We need to modify the file in /auth/db/config.html and change this (at line 190)
$passtype = array();
$passtype["plaintext"] = get_string("plaintext", "auth");
$passtype["md5"] = get_string("md5", "auth");
$passtype["sha1"] = get_string("sha1", "auth");
$passtype["internal"] = get_string("internal", "auth");
echo html_writer::select($passtype, "passtype", $config->passtype, false);
to this
$passtype = array();
$passtype["plaintext"] = get_string("plaintext", "auth");
$passtype["md5"] = get_string("md5", "auth");
$passtype["sha1"] = get_string("sha1", "auth");
$passtype["internal"] = get_string("internal", "auth");
$passtype["wordpress"] = "wordpress";
echo html_writer::select($passtype, "passtype", $config->passtype, false);
This modification will make “WordPress” authentication drop down item available, but still not working.
We need to process the password with this class: class-phpass.php [Phpass Website].
This class, can actually process passwords the same way wordpress does, so this is the missing link to make sso work.
Just copy the file class-phpass.php in your /moodle/lib folder
And then add this line right after other requires at the beginning of wp-login.php:
require_once($CFG->libdir."/class-phpass.php");
.
To make our modifications work we need to add a few lines of code to the file /auth/db/auth.php, it’s easy. Open the file and go about line 90, you should see something like this:
if ($this->config->;passtype === 'md5') {   // Re-format password accordingly

$extpassword = md5($extpassword);

} else if ($this->config->;passtype === 'sha1') {
$extpassword = sha1($extpassword);
}

Now, let’s do our final modification and right after the lines here, add this code:

else if ($this->config->passtype === 'wordpress') {
$hash =new PasswordHash(8, false);
$rs = $authdb->Execute("SELECT * FROM {$this->config->table}
WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'");
$check = $hash->CheckPassword( $extpassword, $rs->fields["user_pass"]);
return $check;
}

If you are so lazy as i am, you can download a copy of both file here, but i strongly suggest you to make modification by hand because time goes by and releases change.
Now, finally we can come back to the settings page ad add “WordPress” as “Passwordformat“.
All you have to do to try if this works, is to logout from wordpress, signup intowordpress as new user, and then go and authenticate with the same credentials against Moodle. If all work you will be redirected to the user profile page on moodlewhere you can complete your profile with your informations.