MongoDB, Driver, Rocking

I do admit, yes, am rocking with MongoDB

 

The simple adapter:

 

https://github.com/xqpmjh/Trickle/blob/master/include/class.MongoAdapter.php

 

 

 

But also, find a bug : https://bugs.php.net/bug.php?id=60508

 

To be continue…

Posted in MongoDB, PHP | Tagged , | Leave a comment

SVN Setting eol-style

When using SVN in team coding, we need the unified end of file descriptor for all the repository files. Usually it’s LF(line-feed) which is the end of line char under linux.

 

SVN has supportted this feature as svn:eof-style option, making all as easy as below.

 

(1) Config file:

 

For Win (usually):
C:\Documents and Settings\Administrator\Application Data\Subversion\config :

 

For Linux (usually):
~/.subversion/config

 

(2) Add option list:

 

*.php = svn:eol-style=LF
*.phtml = svn:eol-style=LF
*.pl = svn:eol-style=LF;svn:executable=*
*.c = svn:eol-style=LF
*.cpp = svn:eol-style=LF
*.h = svn:keywords=Author Date Id Rev URL;svn:eol-style=LF
*.dsp = svn:eol-style=CRLF
*.dsw = svn:eol-style=CRLF
*.sh = svn:eol-style=LF;svn:executable=*
*.txt = svn:eol-style=LF;svn:keywords=Author Date Id Rev URL;
*.png = svn:mime-type=image/png
*.jpg = svn:mime-type=image/jpeg
*.js = svn:eol-style=LF
*.css = svn:eol-style=LF
*.html = svn:eol-style=LF
Makefile = svn:eol-style=LF
Posted in SVN | Tagged , | Leave a comment

My Sweet Girl

 

Sometimes, some person, somethings, you feel dispointed, feel down… anything can frighten or block me as a protector?

Posted in My Live | Leave a comment

String Cutting Helper in Zend Framework

It’s the string cutting helper which deal with both UTF8 and others encodings. Also it remove html tags by default.

 

/**
 * Takes a string and optionally a maximum length and 'cut' the string to match that length
 * based on words and not on characters.
 *
 * @author kim
 */

class App_View_Helper_Cut extends Zend_View_Helper_Abstract
{
    /**
     * do string cut
     *
     * @param string  $pStr - The string to be cut
     * @param intefer $pMaxLen - The maximum length cut
     * @return string
     */

    public function cut($pStr, $pMaxLen = 40)
    {
        // filter all the tags
        $filter = new Zend_Filter_StripTags();
        $pStr = trim($filter->filter($pStr));
        $returnStr = $this->cutstr($pStr, $pMaxLen, '...');
        return $returnStr;
    }

    /**
     * cut string, utf8 by default
     *
     * @param $string - string to cut
     * @param $length - Max length to cut
     * @param $dot - the tail added to the sub-string
     * @param $encoding - the encoding of string
     * @return string
     */

    public function cutstr($string, $length, $dot = '', $encoding = 'utf8')
    {
        if (strlen($string) <= $length) {
            return $string;
        }

        $strcut = '';
        if (strtolower($encoding) == 'utf8') {
            $n = $tn = $noc = 0;
            while ($n < strlen($string)) {
                $t = ord($string[$n]);
                if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
                    $tn = 1; $n++; $noc++;
                } elseif(194 <= $t && $t <= 223) {
                    $tn = 2; $n += 2; $noc += 2;
                } elseif(224 <= $t && $t < 239) {
                    $tn = 3; $n += 3; $noc += 2;
                } elseif(240 <= $t && $t <= 247) {
                    $tn = 4; $n += 4; $noc += 2;
                } elseif(248 <= $t && $t <= 251) {
                    $tn = 5; $n += 5; $noc += 2;
                } elseif($t == 252 || $t == 253) {
                    $tn = 6; $n += 6; $noc += 2;
                } else {
                    $n++;
                }
                if ($noc >= $length) {
                    break;
                }
            }
            if ($noc > $length) {
                $n -= $tn;
            }
            $strcut = substr($string, 0, $n);
        } else {
            for($i = 0; $i < $length - strlen($dot) - 1; $i++) {
                if (ord($string[$i]) > 127) {
                    $strcut .= $string[$i] . $string[++$i];
                } else {
                    $strcut .= $string[$i];
                }
            }
        }

        return $strcut . $dot;
    }
}
Posted in Zend Framework | Tagged , | Leave a comment

Cron Job Script in Zend Framework

To create a cron job script in Zend Framework, we just need 3 steps :

 

1. Create a new directory called “scripts” which is the storage of all the scripts(.sh, .php, etc.).

 

2. Copy public/index.php into “scripts” and rename it to your cron job name, for example “cron.php”.

 

 

3. Modify the code. Instead running the application, we now only do the bootstrap:

 

// Define path to application directory
defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'development'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));

date_default_timezone_set('America/New_York');

/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

// only do bootstrap
//$application->bootstrap()->run();
$application->bootstrap();

// get the options and run CLI
try {
    $opts = new Zend_Console_Getopt('abc:');
    if (isset($opts->a)) {
        echo "I got the a option.\n";
    }
    if (isset($opts->b)) {
        echo "I got the b option.\n";
    }
    if (isset($opts->c)) {
        echo "I got the c option.\n";
    }
} catch (Zend_Console_Getopt_Exception $e) {
    echo $e->getUsageMessage();
    exit;
} catch (exception $e) {
    echo $e->getMessage();
    exit;
}
Posted in Zend Framework | Tagged , | Leave a comment

Setup ZFDebug for Debuging your Zend Framework Project

“ZFDebug is a plugin for the Zend Framework for PHP5, providing useful debug information displayed in a small bar at the bottom of every page.”

 

We just need two steps to setup ZFDebug:

 

1. Download it from https://github.com/jokkedk/ZFDebug, place it inside library just next to Zend Framework

 

 

2. Modify application/Bootstrap.php to add initialized function:

 

/**
 * include ZFDebug console in development environment
 */

protected function _initZFDebug()
{
    // normally only section [development] has the "zfdebug" option
    if ($this->getOption('zfdebug')) {
        // namespace "ZFDebug" for autoloader
        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->registerNamespace('ZFDebug');

        // initialize front controller
        $this->bootstrap('FrontController');
        $front = $this->getResource('FrontController');

        // enable zfdebug options
        $options = array('plugins' => array(
            'Variables',
            'Memory',
            'Time',
            'Registry',
            'Exception',
        ));

        // add caching backend option if specified
        if ($this->hasPluginResource('cache')) {
            $this->bootstrap('cache');
            $cache = $this->getPluginResource('cache')->getDbAdapter();
            $options['plugins']['Cache']['backend'] = $cache->getBackend();
        }

        // add db option if specified
        if ($this->hasPluginResource('db')) {
            $this->bootstrap('db');
            $db = $this->getPluginResource('db')->getDbAdapter();
            $options['plugins']['Database']['adapter'] = $db;
        }

        // register ZFDebug with front controller
        $zfdebug = new ZFDebug_Controller_Plugin_Debug($options);
        $front->registerPlugin($zfdebug);
    }
}

 

And that’s all, now you should see a debug bar just at the bottom of your project like this:

 

Posted in Zend Framework | Tagged , | Leave a comment

Create Multiple Websites with One Shared Library by Zend Framework

When we try to generate the project by Zend_Tool by command line like this:

$ zf create project myProject

 

We get a standard structure which is recommended by Zend Framework:

It works very fine as “one” website project. But how about if we want to create multiple websites without rewriting too many code?
The main idea is to share as much as possible the libraries meanwhile keeping independence of each website, especially the designs/templates/publics.

 


 

Here is one simple way which makes the minimal modifications and satisfy our needs:

 

(1) Move the folder “library” out of the project.

 

(2) Modify /public/index.php as below to make sure the library/ is in include paths:

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    //realpath(APPLICATION_PATH . '/../library'),
    realpath(APPLICATION_PATH . '/../../library'),
    get_include_path(),
)));

 

(3) Modify /application/config/application.ini :

;includePaths.library = APPLICATION_PATH "/../library"
includePaths.library = APPLICATION_PATH "/../../library"

 


 

Assume that we have project1, project2 and project3, all applied the same treatment. And finally the websites could like this:

In the picture above, assume that our global namespace is “Projlib”. We have a model class Projlib/Model/Foo.php

class Projlib_Model_Foo
{
    // ...
}

 

Then we can just put this configuration inside application/configs/application.ini to make it autoloaded:

; --- my library prefix -----------------------------------------------------------------
autoloadernamespaces.global = "Projlib_"

 
 
And that’s all! Enjoy it.

Posted in Zend Framework | Tagged | Leave a comment

Replace Accents by Normal Unaccented in PHP

Sometimes we need the string to only contain unaccented characters, for example urls, xml, filename etc.

 

Expecially before PHP6, You may think of function setlocale() and iconv(), but they are evil…

 

If you’re writing code for yourself, to be used on a server you control, locales could be made to work if your server has locales installed which support UTF-8. That would mean functions like strtolower behave correctly.

But this is no use if you’re writing applications which will be installed by third parties (like these for example) because it’s system specific (it’s not even just OS specific). If the default system locale does not support UTF-8, in theory your application could change the locale “on the fly” using setlocale but in practice that requires two things; that there is a locale available on the system which supports UTF-8 (not guaranteed) and that the correct locale identifier string can be found (there a definately differences between Windows and *Nix locale identifiers and even amongst the Unixes believe there are variations e.g. FreeBSD). What’s more, you can’t rely on users to be able to change the locale correctly to suit your applications needs – on a shared host they probably won’t be able to change the locale for the user that Apache is running with. Bottom line - locales are not the way to go for applications intended to be “write once, run anywhere”.
– http://www.phpwact.org/php/i18n/utf-8

 

Here is just the function to replace accented characters by normal english letters.

 

It contain a long list of characters matching table and use strstr() to replace accents.

 

function replaceAccents($str)
{
    $normalizeChars = array(
        "\xC3\x80" => "A", "\xC3\x81" => "A", "\xC3\x82" => "A", "\xC3\x83" => "A", "\xC3\x84" => "A",
        "\xC3\x85" => "A", "\xC3\x86" => "AE", "\xC3\x87" => "C", "\xC3\x88" => "E", "\xC3\x89" => "E",
        "\xC3\x8A" => "E", "\xC3\x8B" => "E", "\xC3\x8C" => "I", "\xC3\x8D" => "I", "\xC3\x8E" => "I",
        "\xC3\x8F" => "I", "\xC3\x90" => "D", "\xC3\x91" => "N", "\xC3\x92" => "O", "\xC3\x93" => "O",
        "\xC3\x94" => "O", "\xC3\x95" => "O", "\xC3\x96" => "O", "\xC3\x98" => "O", "\xC3\x99" => "U",
        "\xC3\x9A" => "U", "\xC3\x9B" => "U", "\xC3\x9C" => "U", "\xC3\x9D" => "Y", "\xC3\x9E" => "P",
        "\xC3\x9F" => "ss", "\xC3\xA0" => "a", "\xC3\xA1" => "a", "\xC3\xA2" => "a", "\xC3\xA3" => "a",
        "\xC3\xA4" => "a", "\xC3\xA5" => "a", "\xC3\xA6" => "ae", "\xC3\xA7" => "c", "\xC3\xA8" => "e",
        "\xC3\xA9" => "e", "\xC3\xAA" => "e", "\xC3\xAB" => "e", "\xC3\xAC" => "i", "\xC3\xAD" => "i",
        "\xC3\xAE" => "i", "\xC3\xAF" => "i", "\xC3\xB0" => "o", "\xC3\xB1" => "n", "\xC3\xB2" => "o",
        "\xC3\xB3" => "o", "\xC3\xB4" => "o", "\xC3\xB5" => "o", "\xC3\xB6" => "o", "\xC3\xB8" => "o",
        "\xC3\xB9" => "u", "\xC3\xBA" => "u", "\xC3\xBB" => "u", "\xC3\xBC" => "u", "\xC3\xBD" => "y",
        "\xC3\xBE" => "p", "\xC3\xBF" => "y", "\xC4\x80" => "A", "\xC4\x81" => "a", "\xC4\x82" => "A",
        "\xC4\x83" => "a", "\xC4\x84" => "A", "\xC4\x85" => "a", "\xC4\x86" => "C", "\xC4\x87" => "c",
        "\xC4\x88" => "C", "\xC4\x89" => "c", "\xC4\x8A" => "C", "\xC4\x8B" => "c", "\xC4\x8C" => "C",
        "\xC4\x8D" => "c", "\xC4\x8E" => "D", "\xC4\x8F" => "d", "\xC4\x90" => "D", "\xC4\x91" => "d",
        "\xC4\x92" => "E", "\xC4\x93" => "e", "\xC4\x94" => "E", "\xC4\x95" => "e", "\xC4\x96" => "E",
        "\xC4\x97" => "e", "\xC4\x98" => "E", "\xC4\x99" => "e", "\xC4\x9A" => "E", "\xC4\x9B" => "e",
        "\xC4\x9C" => "G", "\xC4\x9D" => "g", "\xC4\x9E" => "G", "\xC4\x9F" => "g", "\xC4\xA0" => "G",
        "\xC4\xA1" => "g", "\xC4\xA2" => "G", "\xC4\xA3" => "g", "\xC4\xA4" => "H", "\xC4\xA5" => "h",
        "\xC4\xA6" => "H", "\xC4\xA7" => "h", "\xC4\xA8" => "I", "\xC4\xA9" => "i", "\xC4\xAA" => "I",
        "\xC4\xAB" => "i", "\xC4\xAC" => "I", "\xC4\xAD" => "i", "\xC4\xAE" => "I", "\xC4\xAF" => "i",
        "\xC4\xB0" => "I", "\xC4\xB1" => "i", "\xC4\xB2" => "IJ", "\xC4\xB3" => "ij", "\xC4\xB4" => "J",
        "\xC4\xB5" => "j", "\xC4\xB6" => "K", "\xC4\xB7" => "k", "\xC4\xB8" => "k", "\xC4\xB9" => "L",
        "\xC4\xBA" => "l", "\xC4\xBB" => "L", "\xC4\xBC" => "l", "\xC4\xBD" => "L", "\xC4\xBE" => "l",
        "\xC4\xBF" => "L", "\xC5\x80" => "l", "\xC5\x81" => "L", "\xC5\x82" => "l", "\xC5\x83" => "N",
        "\xC5\x84" => "n", "\xC5\x85" => "N", "\xC5\x86" => "n", "\xC5\x87" => "N", "\xC5\x88" => "n",
        "\xC5\x89" => "n", "\xC5\x8A" => "N", "\xC5\x8B" => "n", "\xC5\x8C" => "O", "\xC5\x8D" => "o",
        "\xC5\x8E" => "O", "\xC5\x8F" => "o", "\xC5\x90" => "O", "\xC5\x91" => "o", "\xC5\x92" => "CE",
        "\xC5\x93" => "ce", "\xC5\x94" => "R", "\xC5\x95" => "r", "\xC5\x96" => "R", "\xC5\x97" => "r",
        "\xC5\x98" => "R", "\xC5\x99" => "r", "\xC5\x9A" => "S", "\xC5\x9B" => "s", "\xC5\x9C" => "S",
        "\xC5\x9D" => "s", "\xC5\x9E" => "S", "\xC5\x9F" => "s", "\xC5\xA0" => "S", "\xC5\xA1" => "s",
        "\xC5\xA2" => "T", "\xC5\xA3" => "t", "\xC5\xA4" => "T", "\xC5\xA5" => "t", "\xC5\xA6" => "T",
        "\xC5\xA7" => "t", "\xC5\xA8" => "U", "\xC5\xA9" => "u", "\xC5\xAA" => "U", "\xC5\xAB" => "u",
        "\xC5\xAC" => "U", "\xC5\xAD" => "u", "\xC5\xAE" => "U", "\xC5\xAF" => "u", "\xC5\xB0" => "U",
        "\xC5\xB1" => "u", "\xC5\xB2" => "U", "\xC5\xB3" => "u", "\xC5\xB4" => "W", "\xC5\xB5" => "w",
        "\xC5\xB6" => "Y", "\xC5\xB7" => "y", "\xC5\xB8" => "Y", "\xC5\xB9" => "Z", "\xC5\xBA" => "z",
        "\xC5\xBB" => "Z", "\xC5\xBC" => "z", "\xC5\xBD" => "Z", "\xC5\xBE" => "z", "\xC6\x8F" => "E",
        "\xC6\xA0" => "O", "\xC6\xA1" => "o", "\xC6\xAF" => "U", "\xC6\xB0" => "u", "\xC7\x8D" => "A",
        "\xC7\x8E" => "a", "\xC7\x8F" => "I", "\xC7\x90" => "i", "\xC7\x91" => "O", "\xC7\x92" => "o",
        "\xC7\x93" => "U", "\xC7\x94" => "u", "\xC7\x95" => "U", "\xC7\x96" => "u", "\xC7\x97" => "U",
        "\xC7\x98" => "u", "\xC7\x99" => "U", "\xC7\x9A" => "u", "\xC7\x9B" => "U", "\xC7\x9C" => "u",
        "\xC7\xBA" => "A", "\xC7\xBB" => "a", "\xC7\xBC" => "AE", "\xC7\xBD" => "ae", "\xC7\xBE" => "O",
        "\xC7\xBF" => "o", "\xC9\x99" => "e",
    );

    $str = strtr($str, $normalizeChars);
    $str = trim(preg_replace('/[^\w\d_ -]/si', '', $str)); //remove all illegal chars
    $str = preg_replace('/\s+/', ' ', $str);
    return $str;
}
Posted in PHP | Tagged , | Leave a comment

Configurations of htaccess for Multi-Sites in Sharehost

It’s the htaccess configurations for multiple websites in sharehost. Cause sometimes you may not be able to modify apache vhosts.

 

Options -Indexes -MultiViews +FollowSymLinks
    Order allow,deny
    Allow from all
    DirectoryIndex index.php index.html index.htm

    RewriteEngine On
    RewriteBase /
    RewriteRule ^\.htaccess$ - [F]

    # 301 redirect, SEO
    RewriteCond %{HTTP_HOST} ^kimbs.cn [NC]
    RewriteRule ^(.*)$ http://kbs.kimbs.cn/$1 [L,R=301]
    RewriteCond %{HTTP_HOST} ^www.kimbs.cn [NC]
    RewriteRule ^(.*)$ http://kbs.kimbs.cn/$1 [L,R=301]
    #RewriteCond %{HTTP_HOST} ^www.kimbs.info [NC]
    #RewriteRule ^(.*)$ http://kimbs.info/$1 [L,R=301]

    # project "kbs"
    RewriteCond %{HTTP_HOST} ^(www.)?kimbs-local.cn$
    RewriteCond %{REQUEST_URI} !^/kbs/kbs/public/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /kbs/kbs/public/$1
    RewriteCond %{HTTP_HOST} ^(www.)?kimbs-local.cn$
    RewriteRule ^(/)?$ kbs/kbs/public/index.php [L]

    # project "duoduo"
    RewriteCond %{HTTP_HOST} ^duoduo.kimbs-local.cn$
    RewriteCond %{REQUEST_URI} !^/duoduo/blog/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /duoduo/blog/$1
    RewriteCond %{HTTP_HOST} ^duoduo.kimbs-local.cn$
    RewriteRule ^(/)?$ duoduo/blog/index.php [L]

    # project "creativo"
    RewriteCond %{HTTP_HOST} ^creativo.kimbs-local.cn$
    RewriteCond %{REQUEST_URI} !^/creativo/creativo/web/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /creativo/creativo/$1
    RewriteCond %{HTTP_HOST} ^creativo.kimbs-local.cn$
    RewriteRule ^(/)?$ creativo/creativo/web/index.php [L]

AddDefaultCharset UTF-8
Posted in Apache | Tagged , | 1 Comment

Custom Url Helper for Zend View

/**
 * url helper
 *
 * @author kim
 */

class App_View_Helper_L extends Zend_View_Helper_Url
{
    /**
     * the current module
     */

    static $currentModule = null;

    /**
     * Generate the link for view
     *
     * @access public
     *
     * @param  string|null $controller - The controller name
     * @param  string|null $action - The action name
     * @param  array $params - The params for url
     * @param  string|null $module - The module name
     * @param  string $router - The router used
     * @param  boolean $reset - Whether to reset the params
     * @param  boolean $encode - Whether to encode the url
     * @return string - Url for the link href attribute.
     */

    public function L($controller = null, $action = null, $params = array(), $module = null, $router = 'default', $reset = true, $encode = true)
    {
        /**
         * set current module if unset
         */

        if (!is_null(self::$currentModule) and is_null($module)) {
            $module = self::$currentModule;
        }

        /**
         * url params
         */

        $p = array(
            'controller' => $controller,
            'action' => $action,
            'module' => $module,
        );

        return $this->url(array_merge($p, $params), $router, $reset, $encode);
    }

}


Then for a user login url :

<?= $this->L('user', 'login'); ?>

Posted in Zend Framework | Tagged , | Leave a comment