/ Gists

Gists

On gists

Download třída - pro starší projekty

PHP

download.php #

<?php 

/**
 * trida pro stazeni souboru
 * tato trida umoznuje stejnou funkcnost jak v IE tak ve firefoxu
 * 
 * @author Dostal Ales
 * @version 1.1
 * @date 13.4.2006
 *
 */
 
class DownloadFile
{

/****************************** METODY TRIDY ******************************/

    /**
     * konstruktor tridy pro stazeni souboru
     * 
     * @param    String        $file        zdroj k souboru, ktery se bude stahovat
     * 
     */
    function ExecuteDL($file)
    {
        // zjisteni, zda soubor existuje
        if (!is_file($file)) { 
            die("<b>404 Soubor neexistuje!</b>"); 
        }
    
        // ziskani informaci o souboru
        $len = filesize($file);
        $filename = basename($file);
        $file_extension = strtolower(substr(strrchr($filename,"."),1));
    
        // nastaveni content-type pro vybrane soubory
        switch( $file_extension ) 
        {
            case "pdf": $ctype="application/pdf"; break;
            case "exe": $ctype="application/octet-stream"; break;
            case "zip": $ctype="application/zip"; break;
            case "doc": $ctype="application/msword"; break;
            case "xls": $ctype="application/vnd.ms-excel"; break;
            case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
            case "gif": $ctype="image/gif"; break;
            case "png": $ctype="image/png"; break;
            case "jpeg":
            case "jpg": $ctype="image/jpg"; break;
            case "mp3": $ctype="audio/mpeg"; break;
            case "wav": $ctype="audio/x-wav"; break;
            case "mpeg":
            case "mpg":
            case "mpe": $ctype="video/mpeg"; break;
            case "mov": $ctype="video/quicktime"; break;
            case "avi": $ctype="video/x-msvideo"; break;
    
            # tyto soubory nemohou byt stazeny
            case "php":
            case "htm":
            case "html":
            case "txt": die("<b>Není možné stahovat ". $file_extension ." soubory!</b>"); 
            break;
    
            default: $ctype="application/force-download";
        }
    
        # odeslani hlavicek
        session_cache_limiter("private"); # v IE nelze stáhnout dokument pres HTTPS
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
      
        # generuje typ pro content-type
        header("Content-Type: $ctype");
    
        # co stahuji
        $header="Content-Disposition: attachment; filename=".str_replace("./download/", "", $file).";";
        header($header );
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".$len);
        readfile($file);
        exit;
        
    } # public function __construct($file)
    
} # class APIDownloadFile

?>

On gists

Ukázková komponenta

Nette-Controls

Open Graph Component.php #

<? 

class OpenGraphControl extends Nette\Application\UI\Control
{

    /** @var Nette\Utils\Html[] */
    private $tags = [];


    public function addOgTag($property, $content)
    {
        $this->tags[] = Nette\Utils\Html::el('meta', [
            'property' => $property,
            'content' => $content,
        ]);
        return $this;
    }


    public function render()
    {
        $el = Nette\Utils\Html::el();

        foreach ($this->tags as $tag) {
            $el->add($tag);
        }

        echo $el;
    }

}

$this['openGraph']->addOgTag('og:video', 'http://www.youtube.com/watch?v=' . $this->content->url);

On gists

Psaní do obrázků - PHP

Nette

drawingIntoImage.php #

<?php
 

$im = imagecreatefromjpeg("match-trailer.jpg");

$font = 'fonts/calibrib.ttf';  
$fontNormal = 'fonts/calibri.ttf';  


$teams = mb_strtoupper("FC Combix - FC Bohemians Praha B", 'UTF-8');

$white = ImageColorAllocate($im, 255, 255, 255);   
$orange = ImageColorAllocate($im, 255, 127, 0);
$black = ImageColorAllocate($im, 0, 0, 0);

// Týmy
ImagettfText($im, $fontSize = 34, 0, 30, 80, $white, $font, $teams); 


// Kde
ImagettfText($im, $fontSize = 20, 0, 30, 170, $orange, $font, 'KDY:'); 
ImagettfText($im, $fontSize = 20, 0, 95, 170, $white, $fontNormal, '25.8.2014'); 


// Kde
ImagettfText($im, $fontSize = 20, 0, 30, 220, $orange, $font, 'KDE:'); 
ImagettfText($im, $fontSize = 20, 0, 95, 220, $white, $fontNormal, 'Stadiony Bohemians, Přípotoční 27/a'); 


// Vstupné
ImagettfText($im, $fontSize = 24, 0, 30, 420, $black, $font, 'VSTUPNÉ:'); 
ImagettfText($im, $fontSize = 30, 0, 180, 420, $orange, $font, '60 Kč'); 


// Vystup
imageJpeg($im, "upoutavka.jpg");  
ImageDestroy($im);

 
header('Content-type: image/jpg');
echo $image;

On gists

Youtube parser videa ( get info )

PHP

youtube-parser.php #

<?

//The Youtube's API url
    define('YT_API_URL', 'http://gdata.youtube.com/feeds/api/videos?q=');
     
    //Change below the video id.
    $video_id = '66Wi3isw3NY';
     
    //Using cURL php extension to make the request to youtube API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, YT_API_URL . $video_id);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //$feed holds a rss feed xml returned by youtube API
    $feed = curl_exec($ch);
    curl_close($ch);
     
    //Using SimpleXML to parse youtube's feed
    $xml = simplexml_load_string($feed);
     
    $entry = $xml->entry[0];
    //If no entry whas found, then youtube didn't find any video with specified id
    if(!$entry) exit('Error: no video with id "' . $video_id . '" whas found. Please specify the id of a existing video.');
    $media = $entry->children('media', true);
    $group = $media->group;
     
    $title = $group->title;//$title: The video title
    $desc = $group->description;//$desc: The video description
    $vid_keywords = $group->keywords;//$vid_keywords: The video keywords
    $thumb = $group->thumbnail[0];//There are 4 thumbnails, the first one (index 0) is the largest.
    //$thumb_url: the url of the thumbnail. $thumb_width: thumbnail width in pixels.
    //$thumb_height: thumbnail height in pixels. $thumb_time: thumbnail time in the video
    list($thumb_url, $thumb_width, $thumb_height, $thumb_time) = $thumb->attributes();
    $content_attributes = $group->content->attributes();
    //$vid_duration: the duration of the video in seconds. Ex.: 192.
    $vid_duration = $content_attributes['duration'];
    //$duration_formatted: the duration of the video formatted in "mm:ss". Ex.:01:54
    $duration_formatted = str_pad(floor($vid_duration/60), 2, '0', STR_PAD_LEFT) . ':' . str_pad($vid_duration%60, 2, '0', STR_PAD_LEFT);
     
    //echoing the variables for testing purposes:
    echo 'title: ' . $title . '<br />';
    echo 'desc: ' . $desc . '<br />';
    echo 'video keywords: ' . $vid_keywords . '<br />';
    echo 'thumbnail url: ' . $thumb_url . '<br />';
    echo 'thumbnail width: ' . $thumb_width . '<br />';
    echo 'thumbnail height: ' . $thumb_height . '<br />';
    echo 'thumbnail time: ' . $thumb_time . '<br />';
    echo 'video duration: ' . $vid_duration . '<br />';
    echo 'video duration formatted: ' . $duration_formatted;

On gists

FTP připojení a upload via PHP

PHP

FTP.php #

$connection = ftp_connect($server);

$login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);

if (!$connection || !$login) { die('Connection attempt failed!'); }

$upload = ftp_put($connection, $dest, $source, $mode);

if (!$upload) { echo 'FTP upload failed!'; }

ftp_close($connection);

On gists

Ukázková komponenta - attached

Nette

FooControl.php #

<?php
use Nette\Application\UI;

class FooControl extends UI\Control
{
	public function __construct(...)
	{
		//predani parametru a zavislosti
	}
	
	public function attached($presenter)
	{
		parent::attached($presenter); //nezapomenout zavolat
		
		if($presenter instanceof UI\Presenter) { //jelikoz to muze byt i necho jinyho
			//tady nejdriv muzes pracovat s presenterem - vytvaret linky, plnit sablonu....
		}
		
	}
	
	public function handleFoo($bar) //zpracovani signalu foo s parametrem bar
	{
		//...
	}
	
	public function render()
	{
		
		$this->template->...
		$this->template->render();
	}
	
	/*
	jeste existujou pohledy pro komponenty, ale ty nedoporucuju, nefungujou s ajaxem
	vykreslujou se pomoci {control foo:view}
	v {control} muzes i predavat parametry, {control foo $xx, $yy} ale taky nedoporucuju, stejny problem jako s view
*/
	public function renderView()
	{
		
	}
	}
	

}

On gists

Delete from table with limit (first X rows excluded)

MySql

delete from table with limit.sql #

DELETE FROM table
WHERE ID IN
        (
        SELECT ID
        FROM
            (
                SELECT ID
                FROM table
                WHERE Type = 'TEST'
                ORDER BY ID
                LIMIT 30,60
            ) a
        )

On gists

Checkbox-selectbox (popupbox)

CSS

checkbox-selectbox.html #

<!DOCTYPE html>
<html>
    <head>
        <style>
            form {height:1.2em;border:1px solid black; overflow:hidden; float:left; padding-right:0.5em;}
            form:hover, form:active {height:5.2em; overflow:scroll; overflow-x:hidden;}
        </style>
    </head>
    <body>
        <form>
            Komu poslat<br>
            <input type="checkbox" name="names[]" value="Fero">Fero<br>
            <input type="checkbox" name="names[]" value="Alena">Alena<br>
            <input type="checkbox" name="names[]" value="Tomas">Tomas<br>
            <input type="checkbox" name="names[]" value="Foreveryone">Foreveryone<br>
            <input type="checkbox" name="names[]" value="Patres10">Patres10<br>
        </form>
    </body>
</html>

On gists

Responsive tables (add cell description -- data attribute)

Helpers-Filters-Plugins

Add cell description.js #

function pridatPopisky(el) {
  var popisky = el.getElementsByTagName("th");
  var radky = el.getElementsByTagName("tr");
  for (var i = 1; i < radky.length; i++) {
    var bunky = radky[i].getElementsByTagName("td");
    for (var j = 0; j < bunky.length; j++) {     
      bunky[j].setAttribute("popisek", $(popisky[j]).html());
    }
  }
}

On gists

Toogle input value -- better than placeholder (browser support)

jQuery

toggle input value.js #

$.fn.toggleInputValue = function(){
    return $(this).each(function(){
		var input        = $(this);
		var defaultValue = input.val();

        input.focus(function() {
           if(input.val() == defaultValue) input.val("");
        }).blur(function(){
            if(input.val().length == 0) input.val(defaultValue);
        });
    });
}