/ Gists

Gists

On gists

Z latte sablony sahnuti do presenteru / contextu

Nette-Latte

Z latte sablony pres context.php #

{var $database = $presenter->context->getByType('Nette\Database\Context')}

On gists

Přesmerování z lokální na dev - obrázky

Nette

Local redirect to develop server #

RewriteCond %{REQUEST_URI} ^/storage/images/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ http://domena/$1 [R=301,QSA]

On gists

Nette antispam control

Nette

AntispamControl.php #

<?php

use Nette\Forms\Controls\TextInput,
	Nette\Forms\Form,
	Nette\Utils\Html;



/**
 * AntispamControl
 * add basic antispam feature to Nette forms. 
 *
 * <code>
 * // Register extension
 * AntispamControl::register();
 * 
 * // Add antispam to form
 * $form->addAntispam();
 * </code>
 *
 * @version 0.4
 * @author  Michal Mikoláš <nanuqcz@gmail.com>
 * @license CC BY <http://creativecommons.org/licenses/by/3.0/cz/>
 */
class AntispamControl extends TextInput
{
	/** @var int  minimum delay [sec] to send form */
	public static $minDelay = 5;

	
	/**
	 * Register Antispam to Nette Forms
	 * @return void
	 */
	public static function register()
	{
		Form::extensionMethod('addAntispam', function(Form $form, $name = 'spam', $label = 'Toto pole vymažte', $msg = 'Byl detekován pokus o spam.'){
			// "All filled" protection
			$form[$name] = new AntispamControl($label, NULL, NULL, $msg);
			
			// "Send delay" protection
			$form->addHidden('form_created', strtr(time(), '0123456789', 'jihgfedcba'))
				->addRule(
					function($item){
						if (AntispamControl::$minDelay <= 0) return TRUE;  // turn off "Send delay protection"

						$value = (int)strtr($item->value, 'jihgfedcba', '0123456789');
						return $value <= (time() - AntispamControl::$minDelay);
					}, 
					$msg
				);
			
			return $form;
		});
	}



	/**
	 * @param string|Html
	 * @param int
	 * @param int
	 * @param string
	 */
	public function __construct($label = '', $cols = NULL, $maxLength = NULL, $msg = '')
	{
		parent::__construct($label, $cols, $maxLength);

		$this->setDefaultValue('http://');
		$this->addRule(Form::BLANK, $msg);
	}



	/**
	 * @return TextInput
	 */
	public function getControl()
	{
		$control = parent::getControl();
		
		$control = $this->addAntispamScript($control);
		return $control;
	}



	/**
	 * @param Html
	 * @return Html
	 */
	protected function addAntispamScript(Html $control)
	{
		$control = Html::el('')->add($control);
		$control->add( Html::el('script', array('type' => 'text/javascript'))->setHtml("
				// Clear input value
				var input = document.getElementById('" . $control[0]->id . "');
				input.value = '';				
				
				// Hide input and label
				if (input.parentNode.parentNode.nodeName == 'TR') {
					// DefaultFormRenderer
					input.parentNode.parentNode.style.display = 'none';
				} else {
					// Manual render
					input.style.display = 'none';
					var labels = input.parentNode.getElementsByTagName('label');
					for (var i = 0; i < labels.length; i++) {  // find and hide label
						if (labels[i].getAttribute('for') == '" . $control[0]->id . "') {
							labels[i].style.display = 'none';
						}
					}
				}
			") 
		);

		return $control;
	}

}

On gists

Manuální renderování chyb -- inline

Nette-Forms

Manuall form rendering #


{form $form}
<ul class=error n:if="$form->ownErrors">
<li n:foreach="$form->ownErrors as $error">{$error}</li>
</ul>
<table>
<tr n:foreach="$form->controls as $input" n:class="$input->required ? required">
<th>{label $input /}</th>
<td>{input $input} <span class=error n:ifcontent>{$input->error}</span></td>
</tr>
</table>
{/form}

On gists

Image response - generování obrázků

Nette

ImageResponse.php #

<?php
class ImageResponse extends \Nette\Object implements \Nette\Application\IResponse
{

	/** @var \Nette\Image|string */
	private $image;


	/**
	 * @param \Nette\Image|string
	 */
	public function __construct($image)
	{
		if (!$image instanceof \Nette\Image && !file_exists($image)) {
			throw new \Nette\InvalidArgumentException('Image must be Nette\Image or file path');
		}
		$this->image = $image;
	}


	/**
	 * @param \Nette\Http\IRequest
	 * @param \Nette\Http\IResponse
	 */
	public function send(\Nette\Http\IRequest $httpRequest, \Nette\Http\IResponse $httpResponse)
	{
		if ($this->image instanceof \Nette\Image) {
			$this->image->send();

			return;
		}
		$httpResponse->setContentType(\Nette\Utils\MimeTypeDetector::fromFile($this->image));
		$length = filesize($this->image);
		$handle = fopen($this->image, 'r');

		$httpResponse->setHeader('Content-Length', $length);
		while (!feof($handle)) {
			echo fread($handle, 4e6);
		}
		fclose($handle);
	}
}

On gists

JSONP - hlavičky

PHP

Headers ajax request - no JSONP. #

<?

header("content-type:text/html; charset=utf-8");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');

On gists

Komplexní IP

PHP

Get location by Ip address.php #

<?

function getLocationInfoByIp(){
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = @$_SERVER['REMOTE_ADDR'];
    $result  = array('country'=>'', 'city'=>'');
    if(filter_var($client, FILTER_VALIDATE_IP)){
        $ip = $client;
    }elseif(filter_var($forward, FILTER_VALIDATE_IP)){
        $ip = $forward;
    }else{
        $ip = $remote;
    }
    $ip_data = @json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip));    
    if($ip_data && $ip_data->geoplugin_countryName != null){
        $result['country'] = $ip_data->geoplugin_countryCode;
        $result['city'] = $ip_data->geoplugin_city;
    }
    return $result;
}

On gists

Zjištění LAT / LNG souřadnic - Google maps

Gmaps

Lat Lng.php #

<?


function getLatLng($address)
    {

        $json    = json_decode(file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false"));

        $lat     = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
        $lng    = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};

        return array("lat" => $lat, "lng" => $lng);

    }

On gists

Respond mixin - MQ

SCSS

media-queries-respond.scss #

/*
 @author - Roman Janko, rjwebdesign.cz
 @date - 28.8.2014
*/

@mixin respond($minWidth: false, $maxWidth: false) {
  
  @if $minWidth and $maxWidth 
  {
      @media screen and (min-width: $minWidth) and (max-width: $maxWidth) { @content; }
  }
  
   @else if $minWidth
   {
      @media screen and (min-width: $minWidth) { @content; }
   }
  
   @else if $maxWidth
   {
      @media screen and (max-width: $maxWidth) { @content; }
   }
   @else 
   {
      @warn "error - undefined params";
   }
}

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

?>