Yii2 advanced – Hide frontend/web and backend/web from url

Step 1
Create .htaccess file in root folder, i.e advanced/.htaccess and write below code.
—————

Options +FollowSymlinks
RewriteEngine On

# deal with admin first
RewriteCond %{REQUEST_URI} ^/(admin) <------
RewriteRule ^admin/assets/(.*)$ backend/web/assets/$1 [L]
RewriteRule ^admin/css/(.*)$ backend/web/css/$1 [L]

RewriteCond %{REQUEST_URI} !^/backend/web/(assets|css)/ <------
RewriteCond %{REQUEST_URI} ^/(admin) <------
RewriteRule ^.*$ backend/web/index.php [L]

RewriteCond %{REQUEST_URI} ^/(assets|css) <------
RewriteRule ^assets/(.*)$ frontend/web/assets/$1 [L]
RewriteRule ^css/(.*)$ frontend/web/css/$1 [L]

RewriteCond %{REQUEST_URI} !^/(frontend|backend)/web/(assets|css)/ <------
RewriteCond %{REQUEST_URI} !index.php
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ frontend/web/index.php

—————

Note : if you are trying in local server then replace ^/ with ^/project_name/ where you see arrow sign.
Remove those arrow sign

Step 2
Now create a components/Request.php file in common directory and write below code in this file.
—————

namespace common\components;


class Request extends \yii\web\Request {
    public $web;
    public $adminUrl;

    public function getBaseUrl(){
        return str_replace($this->web, "", parent::getBaseUrl()) . $this->adminUrl;
    }


    /*
        If you don't have this function, the admin site will 404 if you leave off 
        the trailing slash.

        E.g.:

        Wouldn't work:
        site.com/admin

        Would work:
        site.com/admin/

        Using this function, both will work.
    */
    public function resolvePathInfo(){
        if($this->getUrl() === $this->adminUrl){
            return "";
        }else{
            return parent::resolvePathInfo();
        }
    }
}

—————

Step 3
Installing component. Write below code in frontend/config/main.php and backend/config/main.php files respectively.
————————-


//frontend, under components array
'request'=>[
    'class' => 'common\components\Request',
    'web'=> '/frontend/web'
],
'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
],

// backend, under components array
'request'=>[
    'class' => 'common\components\Request',
    'web'=> '/backend/web',
    'adminUrl' => '/admin'
],
'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
],

————————-

Step 4 (Optional, if doesn’t work till step three)

create .htaccess file in frontend/web and backend/web directories
————————-


RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?/$1 [L]

————————-

Note: make sure you have enabled your mod rewrite in apache

Thats it! You can try your project with
http://www.project.com/admin, http://www.project.com

in local server
localhost/project_name/admin, localhost/project_name

Copy from: http://stackoverflow.com/questions/28118691/yii2-htaccess-how-to-hide-frontend-web-and-backend-web-completely

Install Yii2 advanced in Ubuntu

Step 1. Create an advanced project with composer

root@manager:/var/www/html# composer create-project --prefer-dist yiisoft/yii2-app-advanced yii2advanced

Step 2. Change to the yii2advanced folder and run the init command

root@manager:/var/www/html# cd yii2advanced
root@manager:/var/www/html/yii2advanced# php init
Yii Application Initialization Tool v1.0
Which environment do you want the application to be initialized in?
[0] Development
[1] Production

Your choice [0-1, or “q” to quit] 0

Initialize the application under ‘Development’ environment? [yes|no] y

Start initialization …

generate backend/config/main-local.php
generate backend/config/params-local.php
generate backend/web/index-test.php
generate backend/web/index.php
generate common/config/main-local.php
generate common/config/params-local.php
generate console/config/main-local.php
generate console/config/params-local.php
generate frontend/config/main-local.php
generate frontend/config/params-local.php
generate frontend/web/index-test.php
generate frontend/web/index.php
generate yii
generate cookie validation key in backend/config/main-local.php
generate cookie validation key in frontend/config/main-local.php
chmod 0777 backend/runtime
chmod 0777 backend/web/assets
chmod 0777 frontend/runtime
chmod 0777 frontend/web/assets
chmod 0755 yii

… initialization completed.

Step 3. Create the database

mysql> create database yii2advanced;

Open common/config/main-local.php set your mysql connection.

 'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=localhost;dbname=yii2advanced',
'username' => 'root',
'password' => 'redhat',
'charset' => 'utf8',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
'viewPath' => '@common/mail',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
],
];

Step 4. Run the Yii Migration Tool

root@manager:/var/www/html/yii2advanced# php yii migrate

Yii Migration Tool (based on Yii v2.0.11.1)

Creating migration history table "migration"...Done.
Total 1 new migration to be applied:
m130524_201442_init

Apply the above migration? (yes|no) [no]:y
*** applying m130524_201442_init
> create table {{%user}} ... done (time: 0.140s)
*** applied m130524_201442_init (time: 0.186s)
1 migration was applied.

Migrated up successfully.

Contact Form 7 -continued

Contact form 7 save uploaded files in server and display uploaded image in mail(not as mail attachment)

Action hook: wpcf7_before_send_mail

The best way is to create a custom post type and save posted datas.

First, create contact form. Here my form name is ‘Application Form’.
add-new-contact-form-wordpress-site-wordpress

Then create post type:

function create_posttype() {
   register_post_type( 'online_applications',
   array(
     'labels' => array(
         'name' => __( 'Online Applications' ),
         'singular_name' => __( 'Online Application' )
      ),
      'public' => true,
      'has_archive' => true,
      'rewrite' => array('slug' => 'online_applications'),
      'supports' => array('title','thumbnail')
    )
    );
}
add_action( 'init', 'create_posttype' );

Then call function to save posted datas:

add_action('wpcf7_before_send_mail', 'save_application_form' );
function save_application_form($wpcf7)
{
    global $wpdb;
    $formtitle  = $wpcf7->title;
    $submission = WPCF7_Submission::get_instance();
    if ($submission) {
        $submited = array();
        $formData       = $submission->get_posted_data();
        $uploaded_files = $submission->uploaded_files(); 
    
        if ( $formtitle == 'Application Form') {
          $newpost = array(
          'post_type' => 'online_applications',
          'post_title' => $formData['name']. ' - ' .$formData['email'],
          'post_status' => 'pending');

          $newpostid = wp_insert_post($newpost);
          add_post_meta($newpostid, 'name', $formData['name']);
          add_post_meta($newpostid, 'email', $formData['email']);
          add_post_meta($newpostid, 'photograph', $formData['photograph']);

          //save photograph
          $wud = wp_upload_dir();
          $image_name     = $formData['photograph'];
          $image_location = $uploaded_files["photograph"];
          $image_content  = file_get_contents($image_location);
          $upload = wp_upload_bits($image_name, null, $image_content);
          $chemin_final = $upload['url'];
          $filename = $upload['file'];
          if ($filename > '') {
              require_once(ABSPATH . 'wp-admin/includes/admin.php');
              $wp_filetype = wp_check_filetype(basename($filename), null);
              $attachment = array(
                  'post_mime_type' => $wp_filetype['type'],
                  'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
                  'post_content' => '',
                  'post_status' => 'inherit'
              );
              $attach_id = wp_insert_attachment($attachment, $filename, $newpostid);
              require_once(ABSPATH . 'wp-admin/includes/image.php');
              $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
              wp_update_attachment_metadata($attach_id, $attach_data);
              update_post_meta($newpostid, "_thumbnail_id", $attach_id);
          }

          //code to display uploaded image in mail template - starts here
          $photo_url = wp_get_attachment_url( get_post_thumbnail_id($newpostid) );
          $photo_url = isset($formData['photo_url']) ? $formData['photo_url'] : $photo_url;
          $photo_url = '<img src="'.$photo_url.'" alt="photo" width="250" height="250" />';
          // do some replacements in the cf7 email body
          $mail         = $wpcf7->prop('mail');
          // Find/replace the "[photo_url]" tag as defined in your CF7 email body
          // and add changes name
          $mail['body'] = str_replace('[photo_url]', $photo_url, $mail['body']);
          $wpcf7->set_properties(array(
              "mail" => $mail
          ));
          //code to display uploaded image in mail template - ends here
        }
        // return current cf7 instance
        return $wpcf7;
  }
}

Contact Form 7

Contact form 7 multiple file upload using single file upload field
https://wordpress.org/plugins/multifile-upload-field-for-contact-form-7/

Contact form 7 set post title in textbox
Install “Contact Form 7 Dynamic Text Extension” plugin.
Then add form tag like this:

[dynamictext* dynamicname readonly "CF7_get_post_var key='title'"]

Contact form dynamic text fields
https://wordpress.org/plugins/contact-form-7-dynamic-text-extension/

Pop up contact form 7
The easy way is show the contact form in a popup window using the plugin “Easy fancy box“.
Once you created the contact form it generate a short code something like this

[contact-form-7 id="150" title="Contact form 1"]

Now just copy the below code and paste it where you want the popup to be

<a href=“#form_pop” class=“fancybox” id=‘fancybox’ >Contact Us</a>
<div style=“display:none” class=“fancybox-hidden”>
    <div id=“form_pop”>
        [contactform7 id=“150” title=“Contact form 1”]
    </div>
</div>

contact form 7 custom mail tag
Eg Code:

add_filter( 'wpcf7_special_mail_tags', 'your_special_mail_tag', 10, 3 );
function your_special_mail_tag( $output, $name, $html ) {
if ( 'yourtagname' == $name ) {
   $output = date('d/m/Y' );
}
return $output;
}

Then add [yourtagname] in your mail template.

Custom validation
Eg code:

add_filter('wpcf7_validate_text','custom_text_validation_filter', 10, 2);
add_filter('wpcf7_validate_text*', 'custom_text_validation_filter', 10, 2);
function custom_text_validation_filter($result, $tag) {
   $type = $tag['type'];
   $name = $tag['name'];
   $value = trim($_POST[$name]);
   if($name == 'subject') {
      if(!empty($value)){
         if(strlen($value)>50){
            $result->invalidate( $tag, "The field is too long.Please keep subject under 50 characters." );
         } else if (preg_match('/[\'^£$%*()}{@#~><>|=_+¬]/', $value)){
            $result->invalidate( $tag, "Invalid characters." );
         }
      }
   }
}

Contact form 7 as registration form
Useful Links:
http://www.mootpoint.org/blog/wordpress-contact-form-7-user-registration/
https://wordpress.org/plugins/frontend-registration-contact-form-7/

 

Install MongoDB on Ubuntu 14.04

Step 1 — Importing the Public Key

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10

Step 2 — Creating a List File

echo "deb http://repo.mongodb.org/apt/ubuntu "$(lsb_release -sc)"/mongodb-org/3.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.0.list

Step 3 – Update the packages list

sudo apt-get update

Step 4 — Installing and Verifying MongoDB

sudo apt-get install -y mongodb-org

Step 5- Check status

service mongod status

If MongoDB is running, you’ll see an output like this(with a different process ID).
mongod start/running, process 8962

Start MongoDB

service mongod start

Stop MongoDB

service mongod stop

Restart MongoDB

sudo service mongod restart

Git Notes – Basics

Initial commit

mkdir my_project
cd my_project
touch .gitignore
git init
git add .
git commit -m "Initial commit"
git remote add origin youruser@yourserver.com:/path/to/my_project.git
git push origin master

———————————————————————
Clone to local repo

git clone git@github.com:whatever folder-name
git add .
git commit -m "Initial commit"
git push origin master

Clone a specific Git branch

git clone -b my-branch git@github.com:user/myproject.git

MySQL Export From Remote Server Through Terminal – Ubuntu

mysqldump from remote server

 mysqldump -P3306  -h192.168.20.151 -uroot -p database > /home/manager/Downloads/my.sql

mysqldump specfic table from remote server

 mysqldump -P3306  -h192.168.20.151 -uroot -p database tablename > /home/manager/Downloads/my.sql

mysqldump multiple tables from remote server

 mysqldump -P3306  -h192.168.20.151 -uroot -p database tablename1 tablename2 tablename3 > /home/manager/Downloads/my.sql

Validate xml via terminal – Ubuntu

To validate xml via terminal

install xmlstarlet or xmlint

To install xmlstarlet,
http://installion.co.uk/ubuntu/vivid/universe/x/xmlstarlet/install/index.html
or
install via ubuntu software center

> apt-get install xmlstarlet

> xmlstarlet val "test.xml"

Output:

test.xml - valid

xmlint,
http://www.linuxask.com/questions/how-to-validate-the-format-of-a-xml-file-in-linux
http://stackoverflow.com/questions/4092812/tool-to-validate-an-xsd-on-ubuntu-linux

> xmllint --noout "file.xml"

Check if there is a url in the text and make the urls hyper links

Sample Code:

$text = "hi http://google.com test http://stackoverflow.com
sd
hhu";

echo nl2br($text);

echo '<br>';

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls
//$text = "The text you want to filter goes here. http://google.com";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

       // make the urls hyper links
       echo preg_replace($reg_exUrl, '<a href="'.$url[0].'" rel="nofollow">'.$url[0].'</a>', $text);

}