Category: Programlama

Refresh wp_editor instance after cloning

While I was working on an extension within Redux Framework, I needed to initialize uninitialized copies of wp_editor instances to apply lazy loading. First I loaded uninitialized types of jQuery fields on the page, then I cloned them and and initialized them to have multiple forms in jQuery accordions. Everything was easy until I came to initialize wp_editor instance, because it was already initialized by wordpress, and you needed to give that field new parents, new id, and make it all work again. So, I developed this code to initialize a already-initialized wp_editor instance in a different DOM parent:

$(element)
  .parents(".wp-editor-container")
  .empty()
  .append($(element));
var ed_id = $(element).attr("id");
// find if an instance with the same id was created before, and remove it.
// -------------------------------------------------------------------------
// it's a critical point when the users adds a group item, and then removes it, and then re-adds the group,
// then this item would have an already-created editor instance on the memory. To work things correctly, we
// must remove it first completely from the memory, and then recreate it.

for (
  var ed_instance_idx = tinymce.editors.length - 1;
  ed_instance_idx >= 0;
  ed_instance_idx--
) {
  if (tinymce.editors[ed_instance_idx].editorId === ed_id) {
    tinymce.remove(tinymce.editors[ed_instance_idx]);
  }
}

// create editor settings with using the dummy editor settings as reference
tinyMCEPreInit.mceInit[ed_id] = JSON.parse(
  JSON.stringify(tinyMCEPreInit.mceInit[$(element).data("old-id")])
);
tinyMCEPreInit.mceInit[ed_id].body_class = ed_id;
tinyMCEPreInit.mceInit[ed_id].elements = ed_id;
tinyMCEPreInit.mceInit[ed_id].id = ed_id;
tinyMCEPreInit.mceInit[ed_id].mode = "tmce";
// initialize wp_editor tinymce instance
tinymce.init(tinyMCEPreInit.mceInit[ed_id]);
// create quicktags instance with using the dummy editor instance settings
tinyMCEPreInit.qtInit[ed_id] = JSON.parse(
  JSON.stringify(tinyMCEPreInit.qtInit[$(element).data("old-id")])
);
tinyMCEPreInit.qtInit[ed_id].id = ed_id;
// make the editor area visible
$(element)
  .addClass("wp-editor-area")
  .show();
// initialize quicktags
new QTags(ed_id);
QTags._buttonsInit();
// force the editor to start at its defined mode.
switchEditors.go(ed_id, tinyMCEPreInit.mceInit[ed_id].mode);

It copies it’s data from the dummy field (the clone source), so when cloning, don’t forget to retrieve it’s ID from somewhere (I used $(element).data("old-id")inside the element to pass to the clone). Another option here is choosing the default editor to show:

tinyMCEPreInit.mceInit[ed_id].mode = "tmce";

line of this script shows that all the clones would return to “TinyMCE” editor as default visible edior on cloning. You may change that to “html” if you want to make the code/text editor as default after cloning.

Fit Cufon texts to its container

Well, I ran into a situation that my design messed up when the cufon title width passed it’s container width, so I needed to lower the font-size automatically to make it fit into it’s container staying still an one-line title. And I wanted to share here. Here’s the function I wrote:

function Cufon_Fit_Title(element) {
  var TotalWidth = 0;
  element.children().each(function() {
    TotalWidth += $(this).width();
  });
  if (TotalWidth > element.width()) {
    element.css("font-size", parseInt(element.css("font-size")) - 1 + "px");
    element.css(
      "padding-bottom",
      parseInt(element.css("padding-bottom")) + 1 + "px"
    );
    Cufon.refresh();
    Cufon_Fit_Title(element);
  } else {
    return true;
  }
}

And here’s the important part of it, because jQuery’s $(document).ready() function won’t work well with Cufon texts (insert it anywhere in your document body – and don’t forget to change the selector):

Cufon.DOM.ready(function() {
  Cufon_Fit_Title($(".title"));
});

jQuery Scrolite Plugin

This plugin appends a vertical scrollbar to any element which you need to limit its dimensions like an image, a div or an ul list etc. This is the initial release of this plugin, so feel free to test it and give me some feedback so I can update this plugin with new improvements or with bug free versions. (horizontal scrollbar will be added later.)

It uses Brandon Aaron’s beautiful mousewheel plugin for mouse wheel scrolling support.

It can be configured with many ways as scrollbar width, color, edge radius, scrollbar bed width, color, edge radius, scroll panel width, scroll panel height, mouse scroll sensitivity.

File sizes are 7.36 kBytes for the development version, 4.08 kBytes for the minified version (as for alpha stage), and 206 bytes for the CSS file. (The zip file is big because of the included jQuery library and png image.)

Demo

You can see a working example here

Download

You can download the package here (Demo page included):

Installation

Include these lines into your script’s <head> declaration:

<script src="lib/jquery.min.js" type="text/javascript"></script><script src="lib/jquery.scrolite.min.js" type="text/javascript"></script><script src="lib/jquery.mousewheel.js" type="text/javascript"></script>

Usage

Then use this script with :

$(".scrollable").scrolite({
width:500,
height:300
});

It will create something like this:

Options

The plugin options are:

'barColor' : The color of the scrollbar handle
'bedColor' : The color of the scrollbar bed
'bedWidth' : Width of the scrollbar bed
'bedCornerRadius' : CSS3 border-radius of scrollbar bed
'barWidth' : Scrollbar handle width
'barCornerRadius' : CSS3 border-radius of scrollbar handle
'width' : scrollable area width
'height' : scrollable area height
'scrollSensitivity' : pixel scrolling value of one tick of the mousewheel
'bedMarginTop' : pixel margin for top of the scroller bed
'bedMarginBottom' : pixel margin for bottom of the scroller bed
'bedMarginLeft' : pixel margin for left of the scroller bed
'bedMarginRight' : pixel margin for right of the scroller bed

CSS Elements

You can change other CSS values by referring to these classes in your styles file:

'.scrolite' : refers to container of all the elements below
'.scrolite-bed' : refers to scrollbar bed element
'.scrolite-bar' : refers to scrollbar handle element
'.scrolite-container' : refers to the scrollable area wrapper

Public Functions

If you are using an AJAX script to load it’s contents from somewhere, you can refresh the scrollbar’s calculations by this function (included in the demo file):

$(".scrollable").data("scrolite").refresh()

The “.scrollable” refers to your initial element which you’ve added the scrollbar.

 

Yine yarışmadayım!

PHPClasses.org’a eklediğim PHP Animated Gif Resizer class’ım Şubat 2012 innovasyon ödülü için yarışıyor. Desteğinizi esirgemeyin. Sayfaya girip oy vermek için önce üye olmanız gerekiyor. Üyelik işleminizi yaptıktan sonra oylama sayfasına giderek oyunuzu verebilirsiniz. Linkler burada :

GIF Animation Resizer

Oylama Sayfası

İnovasyon Ödülleri Hakkında Bilgi

Hepinize desteğiniz için şimdiden çok çok teşekkür ediyorum.

 

Edit : 17.07% oyla 3. olduk. Neyse önemli olan katılmak 😛

SASS User Tool for Editplus

I needed to simplify things to use the SASS scripting language for writing CSS, and I came up with an user tool for Editplus.

Editplus is a useful software to write any kind of code, because it is very flexible that if you know how to do it, you can write your own tools to co-op with this software for example user tools like html tidy, css tidy or indent code, or auto completion for any language that you can think, code colorization, remote file editing directly from FTP, managing projects.. it has too many specialities to tell, you should give it a try.

 

Well, it’s a bit complicated but not impossible. Here’s how it works:

You write a .scss or .sass file in editplus and while it is the active window in it, just pressing one shortcut key compiles it to .css file at the same folder.

It’s too easy to use but was hard for me to write it 🙂 I’m used to any VB code since VB6 but lately I’ve been busy with C# and PHP like curly braced and semi-colon’ed languages, so it took a while to remember the good ol’ VB days. it was good though.

Well, here’s how you can install it on your own computer.

 

First, you need SASS and Ruby etc. installed and running.

Second, create a “sassy.vbs” file inside your editplus application folder and paste this code inside:

Set ArgObj = WScript.Arguments

filename = Right(ArgObj(0),Len(ArgObj(0)) - InstrRev(ArgObj(0),"\"))
extension = Right(ArgObj(0),Len(ArgObj(0)) - InstrRev(ArgObj(0),"."))

If extension<>"sass" and extension<>"scss" Then
    WScript.StdOut.WriteLine "Error: Sorry. Only works with .sass and .scss files."
    WScript.Quit
End If 

var2 = Left(filename,InstrRev(filename,".")) & "css"
var3 = Left(ArgObj(0),InstrRev(ArgObj(0),"\")) & var2

str = """" & ArgObj(1) & "\sassy.bat"" """ & ArgObj(0) & """ """ & var3 & """"

Function ExecuteWithTerminalOutput(cmd)
    Set sh = WScript.CreateObject("WScript.Shell")
    Set exec =  sh.Exec(cmd)
    Do While exec.Status = 0
        WScript.Sleep 100
        WScript.StdOut.Write(exec.StdOut.ReadAll())
        WScript.StdErr.Write(exec.StdErr.ReadAll())
    Loop
    ExecuteWithTerminalOutput = exec.Status
End Function

Call ExecuteWithTerminalOutput(str)

 

Then create a “sassy.bat” file in the same directory and paste this code inside it:

@echo off
sass %1 %2
@echo on

Now our files are ready to integrate into Editplus.

 

  • Open Editplus, Go to the “Tools” Menu
  • Choose “Configure User Tools”
  • Click “Add Tool >>”
  • Write to the Menu text anything you want.
  • To the “Command” input this:
    • cscript //NoLogo “C:\Program Files (x86)\EditPlus 3\sassy.vbs”
  • Into Arguments input (with quotes):
    • “$(FilePath)” “$(AppDir)”

Set the others like in the picture above. Note that the Command Input contains the path to the sassy.vbs file and it should be the correct path for our script to work.

 

sass3

The setup seems complete. Now give it a try. Create a .scss or .sass file which you are familiar with or which example you have in your hand. Then fill the file with some SASS code and save.

Now open the “Tools” menu from above and select the SASS Converter you just created from the bottom of the menu. It should show you the errors if there’s one in the bottom console. If you hear a system sound after you click this, it means that the compilation is successful. Otherwise, there are some errors in your SASS file.

I built it only to use with .sass and .scss files, so you may want to open the preferences -> settings and syntax page and add .sass and .scss extensions to your CSS extension list.

Installing SASS on Windows

In this post, I introduced some of the powers of SASS language, and I left the rest of the exploration to you, because I didn’t really go deep yet. But first you need to install it on your system to use it of course.

In their website, they explained how to install it on Linux and MacOS, and mentioned how to install on a Windows system but i needed to figure it out because before that, I never had a relationship with Ruby. And lucky me(!), SASS uses Ruby to operate.

Let me explain what I did.

First get the latest Ruby installer here : http://rubyinstaller.org/downloads/

Second, double click and start the installation, accept the licence agreement, and on the second page, check all of the checkboxes and click Install.

When the installation finishes, open a Command Prompt window (Win+R then type “cmd” and press enter)

Then type this:

ruby -S gem install sass

and wait for the script to install SASS. (It feels like using apt-get or yum :P). when you finish installing SASS, type this:

sass --help

and if you see a list of parameters and explanations, then your SASS is ready to be used.

SASS – Syntatically Awesome Stylesheets

As the official website says, Sass is an extension of CSS3, adding nested rules, variables,mixins, selector inheritance, and more. It’s translated to well-formatted, standard CSS using the command line tool or a web-framework plugin.

Sass has two syntaxes. The new main syntax (as of Sass 3) is known as ‘SCSS’ (for ‘Sassy CSS’), and is a superset of CSS3’s syntax. This means that every valid CSS3 stylesheet is valid SCSS as well. SCSS files use the extension: .scss.

The second, older syntax is known as the indented syntax (or just “Sass”). Inspired by Haml’s terseness, it’s intended for people who prefer conciseness over similarity to CSS. Instead of brackets and semicolons, it uses the indentation of lines to specify blocks. Although no longer the primary syntax, the indented syntax will continue to be supported. Files in the indented syntax use the extension: .sass.

For example: A SCSS file looks like this:

$blue: #0000ff;
$margin: 10px;

@mixin table-base {
  th {
	@extend td;
	background-color: darken($blue, 10%);
    text-align: center;
    font-weight: bold
  }
  td, th {
	padding: 2px;
	font-size:11px;
	font-family: Tahoma, Arial, sans-serif
	}
}

@mixin left($dist) {
  float: left;
  margin: $margin/2;
  margin-left: $dist;
}

#data {
  @include left(10px);
  @include table-base;
}
and when you compile it with SASS tool, it gives this output:

/* CSS */
#data {
  float: left;
  margin: 5px;
  margin-left: 10px; }
  #data th {
    background-color: #0000cc;
    text-align: center;
    font-weight: bold; }
  #data td, #data th, #data th {
    padding: 2px;
    font-size: 11px;
    font-family: Tahoma, Arial, sans-serif; }

 

In my next post, I’ll explain how to install it on Windows systems. Meanwhile, you could check it’s beautiful website which contains tutorials about SASS language and a detailed documentation.

Bir isim koyma hikayesi: nelm.io

Ortaya bir ürün, bir proje çıkarmak isteyen kişileri projenin kendisi fazla zorlamamıştır şimdiye kadar, genelde en çok zorlanılan kısım projeye verilecek isim bulma olmuştur. çoğu projeler iki üç defa isim ve tasarım değiştirmiştir belki bu yüzden. isviçreli nelm.io firmasının kuruluş hikayesi de buna benzer bir başlangıca sahip ama biraz farklı bir çözümle sonuçlanmış.

Elemanlar düşünmüş taşınmış, ortaya koymak istedikleri isim ile ilgili kriterlerini dökmüşler kağıda. Birincisi, “Biz geek’iz”, ikincisi, “yaptığımız işlerde en iyisi biziz”, üçüncüsü de “bizimle gerçekten çalışmak istersiniz” şeklinde müşteriye yansıtmak ve kendileri de görmek istedikleri hedefler belirlemişler ve en başta “inc6” diye bir isim atılmış ortaya. Tabi ismin önemli olması yanısıra uygun domain’lerin de boş olması gerekiyor eğer internet işiyle uğraşıyorsanız. Bu isim için iki ihtimal de uygunmuş aslında.

ama tabi bir ismi kullanmadan önce onun daha önce kullanılıp kullanılmadığını araştırmanız gerekiyor. Başka birisinin kullandığı bir ismi kullanmak demek, en başta ticari anlamda iş yapmak için bir engel, patenti var, lisansı var, izinleri var, vesaire, hadi o kısmı atlattınız, aynı ismi veya andıran bir ismi kullandığınızda isim sahibi eğer iyi iş yapıyorsa “taklit, onların ismini kullanarak prim yapmaya çalışıyorlar” gibi gereksiz durumlara düşebilir, eğer isim sahibi kötü bir üne sahipse de maça 2-0 yenik başlamak gibi bir dezavantaja sahip olabilirsiniz.

piyasaya sormuş soruşturmuşlar “inc6 isminde bir şirket duydunuz mu?”,”böyle bir marka gördünüz mü?” gibilerinden. inc6’nın inc kısmını tabi geek jargonuna uysun diyerekten “incremental”‘ın kısaltması olarak düşünmüşler. ama piyasaya araştırmasını yaparken şunu anlamışlar, bilişimle ilgisi az olan veya olmayan kimseler, bunu “incorporated” olarak düşünmüşler hep. tabi marka olmak isterseniz herhangi bir isim karışıklığına da mahal vermemeniz önemli. bu yüzden yeni bir isim bulmaları gerektiğini anlamışlar.

ve bu esnada şunu farketmişler. çoğu marka aslında anlamı olan kelimeler değiller. nike, sony, mozilla vesaire kelimeler anlamlı kelimeler olmasalar da, bu isimler için çalışan yüzlerce kişinin emekleri sonucu bu kadar üne sahip kelimeler olmuşlardır.

nitekim rastgele ve güzel görünen, kulağa hoş gelen kelimeler üretmekte aramışlar çözümü. Ve rastgele düşünmekte kimin üzerine yoktur? tabi ki bilgisayarların. bu düşünceyle yola çıkarak bir bilgisayar yazılımı geliştirmişler. mantığını dokuwiki yazılımının random şifre üreten auth_pwgen() fonksiyonunda bulmuşlar ve bu fonksiyonu biraz modifiye ederek 100 tane rastgele isim üreten bir script yazmışlar. daha sonra bir starbucks’ta buluşmuşlar. 3 saat sürmüş bu isimleri bulma çalışmaları. e tabi kolay değil. o kadar random kelimenin arasından bir kelime hoşunuza gitse bile, onun kulağa, dile yatkınlığı, google’da araştırması, domainlerin uygunluğu falan araştırılması gerekiyor.

binlerce kelimeyi ingilizce fransızca almanca aksanlarıyla sesli bir biçimde okuduktan sonra “nelmio” kelimesinde karar kılmışlar. “aslında ilk görüşte aşk değildi bu kelime” diyorlar, ama tabi içleri ısınmış ve son günlerin modası “.io” uzantılı domain de boşta olduğu için “nelm.io” onlara pek çekici gelmiş. bu isim listelerindeki 3. isimmiş ama 5 tane daha böyle hoşlarına giden isim bulmuşlar ve gelecekteki projeleri için ellerinde tutuyorlarmış.

kodu merak edenler için:

<?php 

$c  = 'bcdfghjklmnprstvwz'; //consonants except hard to speak ones
$v  = 'aeiou';              //vowels
$a  = $c.$v;                //both

for ($i = 1; $i <= 100; $i++) {
    $pw = '';

    //use two syllables...
    for($j=0;$j < 2; $j++){
        $pw .= $c[rand(0, strlen($c)-1)];
        $pw .= $v[rand(0, strlen($v)-1)];
        $pw .= $a[rand(0, strlen($a)-1)];
    }

    echo $pw . "\n";
} ?>

Buradan da canlı olarak test edebilirsiniz.

 

Kaynak : http://nelm.io/blog/2011/08/the-algorithm-that-named-us-nelmio/

PHP Animated Gif Resizer

There are many sites that use avatars and sometimes they use animated GIF files. But when it comes to resizing them, it really becomes a pain when your server doesn’t support ImageMagick. So I decided to write an animated GIF resizer based on GD Library (Because GD doesn’t support it directly either.)

It works like this:

  1. Extract frames from GIF animations into a temporary folder.
  2. Resizes all the frames
  3. Combines them into one file

Using this class is really simple. Here is the code

<?php
include_once "gifresizer.php";
$gr = new gifresizer;
$gr->temp_dir = "frames"; //note that it doesn't end with a "/"
$gr->resize("gif/1.gif","resized/1.gif",200,300);

// $gr->temp_dir = {a folder with a write permission (777)}; // The temporary folder which frames will be extracted to.
// $gr->resize({file to be resized}, {new file to be created}, {new width}, {new height});
?>

Here’s an example:

 

Original GIF file :


Resized Image:


Here you can download the class, documentation and examples.

PHPClasses.org class main page

 

Note: I’m expecting some feedback. Here or at phpclasses.org. Doesn’t matter. If you are using it, tell me how it works.

Saving passwords submitted by jQuery $.post function

Today I was struggling with “How can I make Chrome show the remember password form after I use a AJAX submit approach then after a success result redirect to a successful login page?” and it took my one hour to figure it out. I couldn’t find many solutions on the blogs that satisfied me on forums etc. so I wanted to write my own solution here.

First, assume you have a form like this:

<form id="loginform">
    <input name="username" type="text" />
    <input name="password" type="password" />
    <input type="submit" value="Log in" />
</form>

and your AJAX login javascript etc..

And you would like to submit it to “login.php” (or login.aspx – doesn’t matter), after successful login you want to redirect to “main.php”, here’s the trick:

1. point your form’s action to “main.php” (there wouldn’t be any database checking or field validation just opening the post-login page)

2. move the onsubmit=”return Login” part to input type=submit as onclick=”” event.

3. then change your javascript code like this

    function Login(){
        $.post("login.php",$("#loginform").serialize(),function(data){
	    if(data=="OK"){ //I assume you're returning "OK" after login from login.php
		$("#loginform").submit();
	    }else{
		//write your error showing statements here
            }
        }
    }

this way, you’re actually setting a session or cookie in “login.php” to state that your user has been successfully logged on and you just need to check that session or cookie at “main.php” if the user really is logged in. If not, just redirect the user to the login form to prevent misleads to main.php.

Featured Plugins

GiottoPress by Enrique Chavez