Sample Code

Simple blog with comments

Create a simple blog with comments. Start by creating a multi-entry content bin, and turning on the "use comments" option.

Index.php

<?php

/*
*    Start by creating a multi-entry type content bin, with 'blog' as the slug, and "use comments" turned on.
*/

// Include the Osmek.php library
require_once('Osmek.php');

// Create an instance of the Osmek class.
$osmek = new Osmek('PUT YOUR API KEY HERE');

// Load the account. 
// This allows us to the content bin slug ('blog') instead of the bin id.
$osmek->load_account();

/*
*    If it's a comment being posted, let's do it!
*/
if(isset($_POST['post_id'], $_POST['comment'], $_POST['email']))
{
    
// We'll make comments via AJAX, so echo the JSON response of the make_comment method.
    
echo $osmek->make_comment('blog'$_POST['post_id'], $_POST);        
    exit;
}

?>


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Simple Blog with Osmek</title>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js"></script>
        <script type="text/javascript" src="scripts.js"></script>
    </head>
    <body>
        
        <?php
                
            
// If we have a post being requested, load that post
            
if(isset($_GET['read']))
            {
                
// Pass the template to Osmek and get the post with the matching url_title.
                
echo $osmek->fetch_template('blog'file_get_contents('blog-post-template.php'), array('url_title' => $_GET['read']));
            }
            
            
// Otherwise, load the blog roll
            
else
            {
                
// Pass the template to Osmek and print the result. Limit to 5 posts.
                
echo $osmek->fetch_template('blog'file_get_contents('blog-roll-template.php'), array('limit' => 5));
            }
        
?>
    
    </body>
</html>

Blog-roll.php

<article>

    <!-- Set the permalink value in Osmek to http://yourdomain.com/?read=[url_title] -->
    <h2><a href="[permalink]">[title]</a></h2>
    <div class="meta">Posted on <span class="postdate">[date *F *j*S, *Y]</span> by <span class="author">[author name]</span>. [comment_count] Comments.</div>
    
    <!-- Just get the first page of the description to allow authors to control the length of the post preview -->
    <div class="body">[description page:1]</div>
    
    <a href="[permalink]">Continue Reading</a>
    
</article>

Blog-post.php

<article>

    <h2>[title]</h2>
    <div class="meta">Posted on <span class="postdate">[date *F *j*S, *Y]</span> by <span class="author">[author name]</span></div>
    
    <div class="body">[description]</div>
    
</article>


<div class="comments">
    <h3>Comments</h3>
    
    <!-- Loop through comments -->
    [comments]
    <div class="comment">
        <span class="author">[author link]</span> - <span class="date">[date_added On *M *j*S at *g:*i *A]</span>
        <p>[comment]</p>
    </div>
    [/comments]
</div>



<form id="comment-form" action="index.php" method="post">
    <h2>Leave a Comment</h2>
    <p>
        <label for="author">Your Name</label>
        <input type="text" name="author" id="author" size="50" />
    </p>
    <p>
        <label for="email">Your Email Address</label>
        <input type="text" name="email" id="email" size="50" />
    </p>
    <p>
        <label for="url">Your Website (optional)</label>
        <input type="text" name="url" id="url" size="50">
    </p>
    <p>
        <label for="comment">Say Something</label>
        <textarea id="comment" name="comment" rows="10" cols="10"></textarea>
    </p>
    <input type="hidden" name="post_id" value="[id]">
    <button class="submit">Submit</button>
    <p class="alert"></p>
</form>

Scripts.js

window.addEvent('domready', function(){

    // If there's a comment form, AJAX it!
    if($('comment-form'))
    {
        $('comment-form').addEvent('submit', function(e){
            e.stop();
            this.send();
        });

        $('comment-form').addEvents({
            'request': function(){
                $('comment-form').getElement('button').set({disabled: true, 'html': '<em>Sending…</em>'});
            },
            'complete': function(){
                $('comment-form').getElement('button').set({disabled: false, 'html': 'Submit'});
            },
            'failure': function(){
                alert('Something went wrong');
            },
            'success': function(rsp){
                rsp = JSON.decode(rsp);
                
                if(rsp && rsp.status == 'ok')
                {
                    var comment = rsp.comment;
                    comment.date = new Date().parse(comment.date_added).format('%B %m%o at %I:%M %p');
                    new Element('div', {
                        'class': 'comment', 'html': '<span class="author">{author}</span> - <span class="date">On {date}</span><p>{comment}</p>'.substitute(comment)
                    }).inject($(document.body).getElement('.comments'));
                    
                    $('comment-form').get('reveal').dissolve();
                }
                else
                {
                    alert(rsp.msg);
                }
            }
        });    
    }
});

Banners with Javascript

Create a rotating banner area with Osmek and Javascript. Demo.

Index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Osmek Banners with Javascript</title>
        
        <!-- Get the MooTools core library from google -->
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js"></script>
        
        <!-- Load MooTools More/Request.JSONP -->
        <script type="text/javascript" src="mootools-more.js"></script>
        
        <!-- Load Banners.js -->
        <script src="Banners.js" type="text/javascript"></script>
        
        <script type="text/javascript">
            
            window.addEvent('domready', function(){
                
                // Make the banners
                new Banners('banners', {api_key: 'RJ3MK4SG5rAhPCau97EqHFQ1sD2N0Wx8', bin_id: 4609});
            });
            
        </script>
    </head>
    <body>
        
        <div id="banners">
            
            <!-- Our banners will go here -->
        
        </div>
        
    </body>
</html>

Banners.js

/*
*    Mootools class to load banner images via Osmek, and rotate through them.
*/
var Banners = new Class({
    
    Implements: [Options, Events],
    
    options: {
        api_key: '',
        bin_id: '',
        photo_size: '600x300x1',
        duration: 5000
    },
    
    initialize: function(container, options)
    {
        this.setOptions(options);
        
        this.container = document.id(container);
        this.current = -1;
        
        new Request.JSONP({
            url: 'http://api.osmek.com/feed/jsonp', 
            data: {api_key: this.options.api_key, section_id: this.options.bin_id, vars: 'photo '+this.options.photo_size}
        }).addEvents({
            'success': function(rsp){
                this.items = rsp.items;
                this.start();
            }.bind(this)
        }).send();
    },
    
    start: function()
    {
        this.items.each(function(b){
            this.container.set('html', this.container.get('html') + b.photo);
        }.bind(this));
        
        this.banners = this.container.getElements('img').setStyles({'position': 'absolute', 'opacity': 0});
        
        if(this.banners.length > 1) this.timeout = this.next.periodical(this.options.duration, this);
        this.next();
    },
    
    
    prev: function()
    {
        this.go_to(this.current > 0 ? this.current - 1 : this.banners.length - 1);
        
    },
    
    next: function()
    {
        this.go_to(this.current < this.banners.length - 1 ? this.current + 1 : 0);
    },
    
    go_to: function(i)
    {
        var from = this.current == - 1 ? false : this.banners[this.current];
        this.current = i;
        this.transition(from, this.banners[i]);
    },
    
    transition: function(from, to)
    {
        if(from)
        {
            from.fade('out').setStyle('z-index', 1);
        }
            
        to.setStyle('z-index', 2).fade.delay(from ? 500 : 0, to, ['in']);    
        
        this.fireEvent('current', [to, this.current]);
        this.fireEvent('transition', [from, to]);    
    },
    
    stop: function()
    {
        clearInterval(this.timeout);
        return this;
    }

});

Photo Gallery with light box

Create a simple photo gallery using Osmek's template parsing. Demo.

Index.php

<?php

/*
*    Start by creating a Photo Gallery type content bin.
*/

// Include the Osmek.php library
require_once('Osmek.php');

// Create an instance of the Osmek class, and pass our API key.
$osmek = new Osmek('YOUR API KEY HERE');

?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Photo Gallery with light box</title>
        <link media="screen" rel="stylesheet" type="text/css" href="styles.css" />
        
        <!-- Lightbox resources (http://www.shadowbox-js.com) -->
        <script type="text/javascript" src="shadowbox/shadowbox.js"></script>
        <link rel="stylesheet" href="shadowbox/shadowbox.css" type="text/css" media="screen" />
        <script type="text/javascript"> Shadowbox.init(); </script>

    </head>
    <body>
        
        <?php
                
            
// Get each album and all its contents, and turn auto linking off.
            
echo $osmek->fetch_template(4610file_get_contents('photos-template.php'), array('fill_albums' => true'auto_link' => false));
            
        
?>
    
    </body>
</html>

Photos-template.php

<h1>[title]</h1>
[description]

[photos]
<a href="[photo l url]" rel="shadowbox[[album_id]]">[photo sq]</a>
[/photos]

Google Maps

Using Osmek's geocode custom field, we can define points on google map easily. Demo.

Index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Osmek Google Maps integration</title>
        <link media="screen" rel="stylesheet" type="text/css" href="styles.css" />
        
        <!-- Get the MooTools core library from google -->
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/mootools/1.4.5/mootools-yui-compressed.js"></script>
        
        <!-- Load MooTools More/Request.JSONP -->
        <script type="text/javascript" src="mootools-more.js"></script>
        
        <script src="https://maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
        
        <script type="text/javascript">
            
            window.addEvent('domready', function(){
                
                new Request.JSONP({
                    url: 'http://api.osmek.com/feed/jsonp',
                    data: { 
                        api_key: 'z9X8pAKhsr7RtvEMlxYDG5gIfCOWZbw2', 
                        section_id: 4611 
                    }
                }).addEvent('success', function(rsp){
                    
                    // Create the map!
                    var map = new google.maps.Map(document.getElementById('map_canvas'), {zoom: 15, center: new google.maps.LatLng(30.2671530, -97.74306079999999), mapTypeId: google.maps.MapTypeId.ROADMAP,});
                    
                    var LatLngList = [];
                    
                    // Loop through the locations, and add a marker for each one.
                    rsp.items.each(function(item){
                        var location = JSON.decode(item.location);
                        var latlng = new google.maps.LatLng(location.lat, location.lng);
                        LatLngList.push(latlng);
                        var marker = new google.maps.Marker({
                            position: latlng, 
                            map: map,
                            title: item.title
                        });
                        
                        var infowindow = new google.maps.InfoWindow({
                            content: '<h2>'+item.title+'</h2>'+item.postbody
                        });
                        
                        google.maps.event.addListener(marker, 'click', function() {
                          infowindow.open(map, marker);
                        });
                        
                    }.bind(this));
                    
                    // Center the map and zoom to show all markers
                    var bounds = new google.maps.LatLngBounds();
                    for (var i = 0, LtLgLen = LatLngList.length; i < LtLgLen; i++) {
                        bounds.extend(LatLngList[i]);
                    }
                    map.fitBounds(bounds);
                    
                }.bind(this)).send();
            });
            
        </script>
    </head>
    <body>
        
        <div id="map_canvas" style="width: 100%; height: 600px;"></div>
        
    </body>
</html>

Managing config and language files with Osmek and Code Igniter

Osmek's Settings content bin is great for managing bits of data. Here's a great way to utilize that content with Code Igniters config and languauge libraries.

By creating MY_Controller.php, and extending MY_Controller in each of your controllers, your config and language settings will be available. You could use two settings section (one for config values, and one for language values), but in this case we'll use one, and preceed language values with "lang_".

MY_Controller.php

<?php

/*
|
|    Custom Controller to load in config and language settings from Osmek.
|
*/

class MY_Controller extends CI_Controller {

    function 
MY_Controller()
    {
        
parent::__construct();
        
        if(isset(
$this->osmek) && $this->osmek->account_api_key)
        {
            
/*
            *    Load the account, die if there's an error
            */
            
if( ! $this->osmek->load_account())
            {
                die(
'Osmek error: '.$this->osmek->msg);
            }
            
            
/*
            *    Load in site settings
            */
            
if(isset($this->osmek->section_ids['settings']))
            {
                
$this->site_settings json_decode($this->osmek->fetch_json('settings', array('auto_link' => false)));
                
                foreach(
$this->site_settings->items as $name => $item)
                {            
                    
// Set lang if it's a lang
                    
if(substr($name05) == 'lang_')
                    {
                        
$this->lang->language[substr($name5)] = $item->value;
                    }
                    else
                    {
                        
$this->config->set_item($name$item->value);
                    }
                }
            }
        }
    }
}

/* End of file */
/* Location: ./application/core/MY_Controller.php */