Kohana 2.3 NGINX htaccess like URL rewrite

Um Kohana 2.3 auf NGINX mit sauberen URLs zu konfigurieren geht folgende NGINX server config:

server {
        server_name example.com www.example.com;
        listen   80;

        root /srv/www/example.com/pages/;
        access_log /srv/www/example.com/logs/access.log;
        error_log /srv/www/example.com/logs/error.log;

        index index.php index.html index.htm;

        try_files $uri $uri/ @rewrite;

        location @rewrite {
                rewrite ^/(.*)$ /index.php/$1;
        }

        location ~ \.php {
                fastcgi_index index.php;
                fastcgi_pass 127.0.0.1:9000;

                include fastcgi_params;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;
                fastcgi_param PATH_INFO $fastcgi_path_info;
                fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param ENV "production";
        }
}

resolved – twitter api image upload

wer auch per twitter api posts senden will, hat evtl. auch schonmal mit dem gedanken gespielt, images gleich mit hochzuladen.
hier die syntax die tatsächlich funktioniert. api url ist in allen fällen https://api.twitter.com/1.1/

    public function updateStatusWithImage($title, $link, $desc, $img)
    {
        if(empty($img))
        {
            return $this->updateStatus($title, $link, $desc);
        }

        $status = $title.PHP_EOL.PHP_EOL.$link;
        $params = array( 
           'media[]' => '@'.$img,
           'status'   => $status
        );

        return $this->send('statuses/update_with_media.json', 'POST', $params);
    }

der vollständigkeit halber die ganze klasse (kohana style)

<?php defined('SYSPATH') OR die('No direct script access.');

class Gtwitter
{
    protected $api_url;
    protected $oauth_access_token;
    protected $oauth_access_token_secret;
    protected $consumer_key;
    protected $consumer_secret;

    public function __construct()
    {
        $twitter_config                     = Kohana::$config->load('gtwitter');
        $this->api_url                      = $twitter_config->get('api_url');
        $this->oauth_access_token           = $twitter_config->get('access_token');
        $this->oauth_access_token_secret    = $twitter_config->get('access_token_secret');
        $this->consumer_key                 = $twitter_config->get('consumer_key');
        $this->consumer_secret              = $twitter_config->get('consumer_secret');
    }

    public function getCredentials()
    {
        return $this->send('account/verify_credentials.json');
    }

    public function getTimeline()
    {
        return $this->send('statuses/user_timeline.json');
    }

    public function getFriends()
    {
        return $this->send('friends/list.json');
    }

    public function getFollowers()
    {
        return $this->send('followers/list.json');
    }

    public function updateStatus($title, $link, $desc)
    {
        $status = $title.PHP_EOL.PHP_EOL.$link;
        return $this->send('statuses/update.json', 'POST', array('status' => $status));
    }

    public function updateStatusWithImage($title, $link, $desc, $img)
    {
        if(empty($img))
        {
            return $this->updateStatus($title, $link, $desc);
        }

        $status = $title.PHP_EOL.PHP_EOL.$link;
        $params = array( 
           'media[]' => '@'.$img,
           'status'   => $status
        );

        return $this->send('statuses/update_with_media.json', 'POST', $params);
    }

    protected function buildBaseString($base_uri, $method, $params)
    {
        $retval = array();
        ksort($params);
        foreach($params as $key=>$value)
        {
            $retval[] = $key . '=' . rawurlencode($value);
        }
        return $method . '&' . rawurlencode($base_uri) . '&' . rawurlencode(implode('&', $retval));
    }

    protected function buildAuthorizationHeader($oauth)
    {
        $retval = 'Authorization: OAuth ';
        $values = array();
        foreach($oauth as $key=>$value)
        {
            $values[] = $key . '="' . rawurlencode($value) . '"';
        }
        $retval .= implode(', ', $values);
        return $retval;
    }

    protected function getOAuth()
    {
        return array(
            'oauth_consumer_key'        => $this->consumer_key,
            'oauth_nonce'               => time(),
            'oauth_signature_method'    => 'HMAC-SHA1',
            'oauth_token'               => $this->oauth_access_token,
            'oauth_timestamp'           => time(),
            'oauth_version'             => '1.0'
        );
    }

    protected function send($url, $method = 'GET', $params = array())
    {
        $url                        = $this->api_url.$url;
        if($method == 'GET' && !empty($params))
        {
            $url                    = $url.'?'.http_build_query($params);
        }
        $oauth                      = $this->getOAuth();
        $base_info                  = $this->buildBaseString($url, $method, $oauth);
        $composite_key              = rawurlencode($this->consumer_secret) . '&' . rawurlencode($this->oauth_access_token_secret);
        $oauth_signature            = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
        $oauth['oauth_signature']   = $oauth_signature;

        // do curl
        $header                         = array($this->buildAuthorizationHeader($oauth), 'Expect:');
        $opt                            = array();
        $opt[CURLOPT_HTTPHEADER]        = $header;
        $opt[CURLOPT_HEADER]            = false;
        $opt[CURLOPT_URL]               = $url;
        $opt[CURLOPT_RETURNTRANSFER]    = true;
        $opt[CURLOPT_FOLLOWLOCATION]    = true;
        $opt[CURLOPT_SSL_VERIFYPEER]    = false;
        if($method == 'POST')
        {
            $opt[CURLOPT_POST]          = true;
            $opt[CURLOPT_POSTFIELDS]    = $params;
        }

        $feed = curl_init();
        curl_setopt_array($feed, $opt);
        $json = curl_exec($feed);
        curl_close($feed);

        return json_decode($json, true);
    }

}

howto get kohana 3.3.x or 3.2.x up and running when default route failes after fresh installation

copy the system/classes/kohana/request.php to your application/classes/kohana/request.php directory and open the file.
edit the file at around line 332 in the detect_uri method.


	public static function detect_uri()
	{

		...

		// cut out the initial base part to make sure the internal routing will get correct input
		$uri = str_replace(Kohana::$base_url.Kohana::$index_file, '', $uri);
		return $uri;
	}

xgchunker – kohana 3 modul konvertiert grosse csv/xml dateien in StdClass objekte

webpiraten opensource auf github hat ein neues repo für den xgchunker als kohana 3 modul.

er konvertiert riesige csv/xml dateien in kleine chunks als StdClass objekt, um sie dann weiter zu verarbeiten.

github.com/webpiraten/xgchunker

der Kohana Script Collector Helper

Um modular und agil in Kohana zu entwickeln, wurde ein Skript Kollektor notwendig, der aus allen Controllern (Template- oder Standard-Controllern) Skripte (CSS, Javascript) sammeln kann.

Diese Scripte werden dann auf den jeweiligen Mastertemplates wieder an den richtigen Stellen eingebunden.
Dazu habe ich einen neuen Helper unter application/helpers/collector.php eingerichtet.


class Collector_Core
{
    /**
     * Arrays containing URL's to scripts/styles (fill with standards)
     * @var string
     */
    static protected $scripts       = array();
    static protected $styles        = array();

    /**
     * Adds a url to store
     * @param string $file the local path to file
     * @return void
     */
    static public function addJs($file)
    {
        self::$scripts[] = $file;
    }

    /**
     * Adds a url to store
     * @param string $file the local path to file
     * @return void
     */
    static public function addCss($file)
    {
        self::$styles[] = $file;
    }

    /**
     * Generates/renders collectors items
     * @param boolean      $print whether to echo the output or just return rendered string
     * @return string      the rendered output
     */
    static public function renderJs($print = false)
    {
        $scripts    = array_unique(self::$scripts);
        $output     = html::script($scripts);
        if ($print)
        {
            echo $output;
        }
        else
        {
            return $output;
        }
    }

    /**
     * Generates/renders collectors items
     * @param boolean      $print whether to echo the output or just return rendered string
     * @param string|array $media type for this style (all, screen, print, media)
     * @return string      the rendered output
     */
    static public function renderCss($print = false, $media = 'all')
    {
        $styles = array_unique(self::$styles);
        $output = html::stylesheet($styles, $media);
        if ($print)
        {
            echo $output;
        }
        else
        {
            return $output;
        }
    }
} // end of Collector_Core

Dieser Helper kann nun aus allen Controllern heraus befüllt werden.


class Welcome_Controller extends Template_Controller
{
    /**
     * set master template
     */
    public $template = 'master_default.tpl';

    /**
     * default constructor
     * @param void
     * @return void
     */
    public function __construct()
    {
        // load parent constructor
        parent::__construct();

        // collect scripts and styles
        collector::addCss('/css/fancybox');
        collector::addJs('/js/jquery.1.3.2');
        collector::addJs('/js/jquery.fancybox');
    }
    /** more code here */
} // end of Welcome_Controller

Nachdem nun alle relevanten Skripte eingesammelt wurden, kann man diese auf dem Template wieder ausgeben lassen.


<?php collector::renderCss(true, 'all'); ?>

<!-- html code here -->

<?php collector::renderJs(true); ?>

Der Kollektor sorgt dafür das keine doppelten Skripte geladen werden.