Shaked Klein Orbach echo 'Just smile';

21Jan/120

Zend Framework, Gmail, SMTP and SSL

Posted by Shaked

Topic says everything, isn't it?

Description

I had a problem sending emails while using Zend Framework with Gmail account. So I had to handle different types of errors:

  • "Unable to connect via TLS" - being created by Zend Framework Exception.
  • "Unable to find the socket transport "https" - did you forget to enable it when you configured PHP?" - PHP built in error message

Suggestions

8Jan/120

WordPress – avoiding wpautop method

Posted by Shaked

Long time ha?

So I`m working on a WordPress plugin for a while, and I found some common issues with plugins that need to be integrated with WordPress's posts.

One of the main issues is the wpautop method.

Description

From WordPress's website:

Changes double line-breaks in the text into HTML paragraphs (<p>...</p>).

WordPress uses it to filter the content and the excerpt.

Now lets dig a bit more inside ha?

function wpautop($pee, $br = 1) {
        if ( trim($pee) === '' )
                return '';
        $pee = $pee . "\n"; // just to make things a little easier, pad the end
        $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
        // Space things out a little
        $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
        $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
        $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
        $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
        if ( strpos($pee, '<object') !== false ) {
                $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
                $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
        }
        $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
        // make paragraphs, including one at the end
        $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
        $pee = '';
        foreach ( $pees as $tinkle )
                $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
        $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
        $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
        $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
        $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
        $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
        $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
        $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
        $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
        if ($br) {
                $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
                $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
                $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
        }
        $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
        $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
        if (strpos($pee, '<pre') !== false)
                $pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
        $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
        return $pee;
}

You may find more at http://core.trac.wordpress.org/browser/tags/3.3.1/wp-includes/formatting.php

As you can see, this function changes a lot of things in WordPress's posts, such as:

  • Adding \n after (almost) each HTML tag
  • Fixing new lines to cross platform newlines (\r\n to \n)
  • Changing the <object> tag
  • Adding <p> tags.
  • Cleaning empty <pre> tags

So I marked the most important issue about this function "Adding <p> tags".

Why is it so important for me?

As I wrote before it seems that one of the biggest problems for developers that develop WordPress plugins is the wpautop plugin. When they are trying to modify the user's posts, they always need to struggle with the <p> tags and sometimes they don't know how to handle them right.

Suggestions...

18Dec/110

PHP Managing zip files with ZipArchive

Posted by Shaked

Requirements

  1. PHP 5.2 or greater (would be a bit sad to know that someone is still using PHP 4) 
  2. Upgrade PEAR to latest version 
  3. Upgrade PECL to latest version 
  4. Installing PHP ZipArchive library by using PECL's zip package

Installation 

I will use pecl to install ZipArchive PHP library.

  1. Open terminal and execute pecl install zip
  2. Updating your php.ini:
  1. Linux: find your php.ini file and add "extension=zip.so"
  2. Windows: same as one, just add "extension=zip.dll
  • Restart httpd\apache 
    1. service httpd restart
    2. apache2ctl restart
    3. or any other way that you like

    Usage Example

    There are many different ways to use and build Zip helpers. I will just demonstrate an example for using ZipArchive. 

     Pastebin: http://pastebin.com/J2M0jjQG

     Inline... 

    18Dec/110

    How to find your php.ini file

    Posted by Shaked

    Finding your php.ini is pretty straight forward task: 

    1. open terminal or cmd 
    2. execute php --ini if php is undefined you should add it to your PATH or just execute "/your/path/to/php --ini"
    3. php.ini has several modes (path is different sometimes...):
      1. using one file: 

        Configuration File (php.ini) Path: /etc/php5/cli
        Loaded Configuration File: /etc/php5/cli/php.ini

      2. using several different files (will help to maintain common settings between cli php.ini and httpd php.ini

        Scan for additional .ini files in: /etc/php5/conf.d
        Additional .ini files parsed: /etc/php5/conf.d/ctype.ini,
        /etc/php5/conf.d/curl.ini, 
        /etc/php5/conf.d/dom.ini,
        /etc/php5/conf.d/gd.ini,
        /etc/php5/conf.d/hash.ini,
        ............more .ini files here............  

        files content could be "extension=gd.so" (unix) or "extension=gd.dll" (windows)

    4. there are two more options to get your ini files: 
      1. execute in cli mode: "php --i | grep .ini"
      2. write your own script and check via browser:
        <?php phpinfo(); ?>  

    That's it, now you can just edit your php.ini with anything you think you will need for future PHP programming. 
    More about php.ini may be found at http://php.net/manual/en/ini.php 

    23Nov/110

    MySQL Split String Function Fix (split_str)

    Posted by Shaked

    While working on one my projects, I was needed to use split_str function in MySQL. I Googled for it and found two answers (which are exactly the same - one is leading to the other): 

    Federico Cargnelutti - MySQL Split String Function


    Stackoverflow - MYSQL - Array data type, split string

    Everything worked great while using different delimiters, such as: "," , "||", "@@@", "###" or any other delimiter. I was using delimiters which their length > 1, exmaple: 
    select split_str(‘ABC,,BA,,abc’,',,’,3);
    //result: “abc”
    

    Seems good, ha? But then I`v noticed that there is a problem. When my full string contains two bytes characters (e.g: ¼), everything is breaking a part. Lets see the following exmaple:

    select split_str(‘ABC¼,,BA,,abc’,',,’,3);
    //result: “,abc” (delimiter was still there)
    

    So how do we fix it?  Seems that we need to change split_str function, all we have to do is to use CHAR_LENGTH() and not LENGTH(). There is a difference between those functions which you can read at MySQL.com website or just read the following quote: 

    CHAR_LENGTH(str)

    Returns the length of the string str, measured in characters. A multi-byte character counts as a single character. This means that for a string containing five two-byte characters, LENGTH() returns 10, whereas CHAR_LENGTH()returns 5.

     Enough talking. This is the function after my little fix: 


    CREATE FUNCTION SPLIT_STR( x VARCHAR(255), delim VARCHAR(12), pos INT ) RETURNS VARCHAR(255) RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos), CHAR_LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1), delim, '');


    Then using the same example I`v used above:


    select split_str(‘ABC¼,,BA,,abc’,',,’,3); //result: “abc”


    I want to say thank to Federico Cargnelutti that helped us by writing the above function.


    Shak.

    Or Ovadia liked this post
    20Nov/112

    Setup\Configure Zend Debugger

    Posted by Shaked

    Using a debugger is very important while writing code, so lets see how to do it with PHP and Zend Debugger: 

    1. Install Eclipse or Zend Studio 
    2. If you have installed Eclipse, you should install two more things:
      1.  PDT (PHP Development Tools)
      2. Zend Debugger
    3. After extracting everything, search for ZendDebugger.so path
    4. Edit your php.ini or create another ini --> zend.ini which will have to be loaded by your PHP and add:
       
      ; Loading Zend Debugger Extension
      zend_extension=/your/path/to/ZendDebugger.so
      ;
      ; use 127.0.0.1 for local host, or you another local network IP
      zend_debugger.allow_hosts=127.0.0.1
      ;
      ;
      Expose Zend Debugger
      ;
      ;
      never - do not expose (default)
      ;
      always - expose to whoever want to know
      ;
      allowed_hosts - expose only if request comes from an IP listed above
      ;
      zend_debugger.expost_remotely=always
      
    5. Save & Restart Apache
    6. Verify your phpinfo()
    7. Download FireFox or Chrome Extension (Chrome extension is not official extension by Zend) 
    8. Configure Eclipse \ Zend Studio settings:
    9. Configure your extension settings:
    10. Start debugging!:) 
    Helpful links: 
     

     

    Note for Zend Studio 8.x users:

    I suggest that you will update your Zend Studio application by using the following instructions: 

    http://forums.zend.com/viewtopic.php?f=59&t=10468

    Enjoy!

    Yuval Halfon liked this post
    18Nov/110

    PHP: Insert\Update MySQL BIT(1) field

    Posted by Shaked

    Today I`v noticed to interested things: 

    1. A nice sentence or a motto that I really liked: 

      "When you do a search, and it comes back with no results, it’s a sign that you need to write something." (Taken from Here
       

    2. Didn't find any straight answer on Google for my question: "How to insert\update a bit field with PHP": 

    So with MySQL you would use:

    INSERT INTO t SET b = b'1'; // Or b'0' 

     And with PHP you would use boolean type: 

    
    //$db instanceof ActiveRecord, that's only for the following example
    //you can use other ways to insert\update your MySQL DB. 
    
    $db->insert(array('b'=>true,'c'=>false)); //true = b'1' , false = b'0'
    
    $db->update(array('b'=>true,'c'=>false)); //true = b'1' , false = b'0'
    

    Hope I helped,
    Shak.


    14Oct/110

    Zend Framework – How to redirect/get application base URL

    Posted by Shaked

    What is exactly base URL ? 

    Base URL is sub.domain.end, for example: 
    if your full URI is http://www.yoursite.com/some/params/id/1, so base URL will be www.yoursite.com

    Redirect to application base URL

    Sometimes you would want to be able to redirect from one page to  your main homepage, for example:

    1. User A enter Site B.com login page
    2. User B enter username and password and he had been successfully logged in
    3. User B is being redirect to Site B.com

    As I like to say, if you are reading this post, you would probably need some help about its subject:

    There are two ways:

    public function loginAction(){
    .
    .
      if (user is logged in successfully) {
          $this->_helper->redirector->gotoUrl();    //Option 1
          // OR setGotoUrl() uses gotoUrl() when no param is being passed
          $this->_helper->redirector->setGotoUrl(); //Option 2
      }
    .
    .
    }
    

     How do I get base URL string?  

    public function loginAction(){
     $baseURL = $this->getRequest()->getHttpHost();
     /*
       When using redirect helper and full URL
       you will have to attach http(s)://
       which means you will have to use isSSL() method
     */
    }
    

     

    Note:

    My suggestion is to create  BaseControoler that will handle your current HTTP request & base URL: 

    class BaseController extends Zend_Controller_Action{
     	/**
     	 *  @var Zend_Controller_Request_Http $_request
             */
    	protected $_request;
    
    	protected function init(){
     	 	//Save request
     	 	$this->_request = $this->getRequest();
     	        //Save httpHost (base URL)
     	 	$this->_httpHost = $this->_request->getHttpHost();
     	 	$this->siteInit();
      	} 
    
     	protected siteInit(){
     	 	/*
     	 	 	You don't really need it
     	 	 	I just prefer to know that if someone creates
     	 	 	another controller he won't have to call parent::init()
     	 	*/
     	}
    }
    

    After creating BaseController you have to setup your own controller(s): 

    //Extend BaseController
    class IndexController extends BaseController {
    
     	public function indexAction(){
     	 	var_dump($this->_httpHost,$this->_request->getParams());
     	}
    }

    That it for today, 

    Shak

    13Oct/110

    Opensuse – Asus yXXy (n53j) – Speakers Audio

    Posted by Shaked

    Hey, 

    For long time I had an annoying problem with my speakers on my Asus n53j laptop. I`v googled this problem for long time and nothing. But finally I`v found the VERY-EASY solution: 

    1. Open alsamixer in terminal
    2. Choose your sound card (F6) 
    3. Continue till you see this screen:
       
    4. Go to "Speakers" and make volume up to 100 
    Thats it. I hope that it will help you.
    Shak

    6Oct/110

    Highlight your text and share short URL

    Posted by Shaked

    Today I wanted to share a text with my brother so I thought about making new tool that will highlight my text and create short URL. After some googling I have found a very nice tool that already implement it "Yellow highlighter pen for web". This plugin is working on Chrome and may be found athttp://www.marker.to or at Google chrome extension web store 

    Use it carefully ;)  

     

    Shak.