вторник, 24 декабря 2013 г.

Installing ejabberd from sources

wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb
dpkg -i erlang-solutions_1.0_all.deb
apt-get update

apt-get install make gcc git libyaml-dev libexpat1-dev libssl erlang

git clone https://github.com/processone/ejabberd

cd ejabberd

./configure --enable-odbc
make

make install

These commands will:
 - Install the configuration files in /etc/ejabberd/
 - Install ejabberd binary, header and runtime files in /lib/ejabberd/
 - Install the administration script: /sbin/ejabberdctl
 - Install ejabberd documentation in /share/doc/ejabberd/
 - Create a spool directory: /var/lib/ejabberd/
 - Create a directory for log files: /var/log/ejabberd/

вторник, 22 октября 2013 г.

Virtual Box Console commands

As something of a follow-up post to the previous entry, here’s a quick recipe for creating a Virtual Machine using the VirtualBox command line tools:

We’re using Windows Server 2008 64bit as an example, modify to taste.

$ VM='Windows-2008-64bit'

Create a 32GB “dynamic” disk.

$ VBoxManage createhd --filename $VM.vdi --size 32768

You can get a list of the OS types VirtualBox recognises using:

$ VBoxManage list ostypes

Then copy the most appropriate one into here.

$ VBoxManage createvm --name $VM --ostype "Windows2008_64" --register

Add a SATA controller with the dynamic disk attached.

$ VBoxManage storagectl $VM --name "SATA Controller" --add sata \
> --controller IntelAHCI
$ VBoxManage storageattach $VM --storagectl "SATA Controller" --port 0 \
> --device 0 --type hdd --medium $VM.vdi

Add an IDE controller with a DVD drive attached, and the install ISO inserted into the drive:

$ VBoxManage storagectl $VM --name "IDE Controller" --add ide
$ VBoxManage storageattach $VM --storagectl "IDE Controller" --port 0 \
> --device 0 --type dvddrive --medium /path/to/windows_server_2008.iso

Misc system settings.

$ VBoxManage modifyvm $VM --ioapic on
$ VBoxManage modifyvm $VM --boot1 dvd --boot2 disk --boot3 none --boot4 none
$ VBoxManage modifyvm $VM --memory 1024 --vram 128
$ VBoxManage modifyvm $VM --nic1 bridged --bridgeadapter1 e1000g0

Configuration is all done, boot it up! If you’ve done this one a remote machine, you can RDP to the console via vboxhost:3389.

$ VBoxHeadless -s $VM

Once you have configured the operating system, you can shutdown and eject the DVD.

$ VBoxManage storageattach $VM --storagectl "IDE Controller" --port 0 \
> --device 0 --type dvddrive --medium none

Finally, it’s a good idea to take regular snapshots so that you can always revert back to a known-good state rather than having to completely re-install.

$ VBoxManage snapshot $VM take <name of snapshot>

And, if you need to revert back to a particular snapshot:

$ VBoxManage snapshot $VM restore <name of snapshot>

Enjoy!

Readline shortcuts

Readline shortcuts

GNU Readline is the library used to make advanced command-line wizardry convenient and conistent across a multitude of command-line applications. These programs include bash, bc, ftp, gnuplot, gpg, ksh, mysql, psql, python, smbclient, xmllint and zsh.
The cheatsheet at the right contains a summary of many of the useful line editing command shortcuts which are available in all applications that use libreadline.
See the documentation on the Readline website for even more shortcuts with more elaborate descriptions.

Emacs keys Action Scope Direction/Place
Moving around Ctrl-b Move the cursor one character ⇦ to the left
Ctrl-f Move the cursor one character ⇨ to the right
Alt-b Move the cursor one word ⇦ to the left
Alt-f Move the cursor one word ⇨ to the right
Ctrl-a Move the cursor ⇤ to the start of the line
Ctrl-e Move the cursor ⇥ to the end of the line
Ctrl-x-x[1] Move the cursor ⇤⇥ to the start, and to the end again
Cut, copy
and paste
Backspace Delete the character ⇦ to the left of the cursor
DEL
Ctrl-d
Delete the character underneath the cursor
Ctrl-u Delete everything ⇤ from the cursor back to the line start
Ctrl-k Delete everything ⇥ from the cursor to the end of the line
Alt-d Delete word ⇨ untill before the next word boundary
Ctrl-w Delete word ⇦ untill after the previous word boundary
Ctrl-y Yank/Paste prev. killed text at the cursor position
Alt-y Yank/Paste prev. prev. killed text at the cursor position
History Ctrl-p Move in history one line ⇧ before this line
Ctrl-n Move in history one line ⇩ after this line
Alt-> Move in history all the lines ⇩ to the line currently being entered
Ctrl-r Incrementally search the line history ⇧ backwardly
Ctrl-s[2] Incrementally search the line history ⇩ forwardly
Ctrl-J End an incremental search
Ctrl-G Abort an incremental search and restore the original line
Alt-Ctrl-y Yank/Paste arg. 1 of prev. cmnd at the cursor position
Alt-.
Alt-_
Yank/Paste last arg of prev. cmnd at the cursor position
Undo Ctrl-_
Ctrl-x
Ctrl-u
Undo the last editing command; you can undo all the way back to an empty line
Alt-r Undo all changes made to this line
Ctrl-l Clear the screen, reprinting the current line at the top
Ctrl-l Clear the screen, reprinting the current line at the top
Completion TAB Auto-complete a name
Alt-/[3] Auto-complete a name (without smart completion)
Alt-? List the possible completions of the preceeding text
Alt-* Insert all possible completions of the preceeding text
Transpose Ctrl-t Transpose/drag char. before the cursor ↷ over the character at the cursor
Alt-t Transpose/drag word before the cursor ↷ over the word at/after the cursor

вторник, 8 октября 2013 г.

Installing b43 wireless on ubuntu

Download this:
http://downloads.openwrt.org/sources/wl_apsta-3.130.20.0.o
and
http://mirror2.openwrt.org/sources/broadcom-wl-4.150.10.5.tar.bz2
Copy them into your installation flashdrive
Install b43-fwcutter from /cdrom/pool/main/b/ there will be .deb package
Than:

tar -xjvf broadcom-wl-4.150.10.5.tar.bz2
sudo b43-fwcutter -w /lib/firmware wl_apsta-3.130.20.0.o
sudo b43-fwcutter --unsupported -w /lib/firmware broadcom-wl-4.150.10.5/driver/wl_apsta/wl_prebuilt.o
sudo chmod 775 /lib/firmware/b43
sudo chmod 775 /lib/firmware/b43legacy
sudo modprobe -r b43
sudo modprobe b43

Thats it :) Works on Ubuntu 13.04

пятница, 4 октября 2013 г.

Sphinx on Gentoo

# Обновить portage
emerge --sync
emerge portage

# Установить sphinx
USE="debug id64 mysql -postgres stemmer test" emerge app-misc/sphinx

# Скопировать или переименовать конфигурационный файл
cd /etc/sphinx
cp sphinx.conf.dist sphinx.conf

# Настроить разрешения, чтоб группа web могла редактировать конфигурационный файл
chmod 664 /etc/sphinx/*
chown root:web /etc/sphinx/*

# Добавить пользователя и группу sphinx
groupadd -g 494 sphinx
useradd -g sphinx -u 494 -d /var/lib/sphinx -s /bin/bash -c "Sphinx server" sphinx

# Создать папки, где будут храниться логи, pid-файлы и данные
mkdir -p /var/log/sphinx
mkdir -p /var/run/sphinx
mkdir -p /var/lib/sphinx/data

# Настроить правильные разрешения на эти папки
chown sphinx:sphinx /var/log/sphinx
chown -R sphinx:sphinx /var/lib/sphinx
chown sphinx:sphinx /var/run/sphinx

# Добавить в /etc/sudoers что-то типа
%web ALL=NOPASSWD:/etc/init.d/searchd
%web ALL=(sphinx) NOPASSWD:/usr/bin/indexer

# Проверить от пользователя группы web
sudo -u sphinx /usr/bin/indexer
sudo /etc/init.d/searchd restart|stop|start

# Установить расширения php
PHP_TARGETS="php5-4" emerge pecl-sphinx

Так же  пришлось немного подправить init скрипт, чтобы запускать свинкс от моего пользователя

среда, 2 октября 2013 г.

AntHillPro: Create, manage and delete environments via BeanShell scripts

Creating new entity (project, environment etc)

Lets assume that we need to create new environment within script
First of all, all new stuff will be applied into database only after step ends. When you create new environment you can't manipulate it, you can only add Properties on it, but you can't add agents or you cant add it into Environment Group, you will get an Exception because environment still not exists in scope of anthill. Same exception will happen if you will try to manipulate newly created project or some other instance. So, remember, if you create something you need to do:
  1. <your_new_entity> = new <Something>;
  2. <you_new_entity>.store();
  3. Finish step.
On next step your new entity will be in database and available for manipulation in anthill, you can add it into server groups, projects etc.

Adding into Environment Group

It is quite simple:
  1. Get environment group: EnvironmentGroup envGroup = EnvironmentGroupFactory.getInstance().restore( envGroupID );
  2. envGroup.addServerGroup( env ) , where env should be instance of ServerGroup
I want to point that you do not need to call .store() method, it will store by itself after the end of the step.

Adding into project's workflows.

There is a one limitation: you can add environment only in non originating workflows.
It also simple:
  1. Get project: Project prj = ProjectFactory.getInstance().restore( projectID );
  2. Get non-originating workflow like Workflow wf = prj.getWorkflow( nonOrigWFID ) or get an array of workflows Workflow[] wfArray = prj.getNonOriginatingWorkflowArray() and iterate over it.
  3. Add environment into it: wf.addServerGroup( env ) , where env should be instance of ServerGroup
Also you do not need to call .store() method here.

Deleting environment

In first part we have created environment and added it into environment group and workflows. Now if you want to delete it from anthill you need to delete it from all workflows where this environment is used.
It's not quite obvious, but... :) Here will be 3 steps in total: 

First step:

  • Get environment: ServerGroup env = ServerGroupFactory.getInstance().restoreForName( "my-env-name" );
  • Get environment's group: EnvironmentGroup[] envGroupArray = EnvironmentGroupFactory.getInstance().restoreAllForEnvironment( env );
Get all non-originating workflows that use this environment. In docs I've found method in WorkflowFactory:
  • Workflow[] wfInEnvArray = WorkflowFactory.getInstance().restoreAllNonOriginatingWorkflowsForEnvGroupsInEnvironment( env, envGroupArray, "*", "*", "*" );
we got all required variables earlier. Then you just need to iterate over this list and use <workflow>.removeServerGroup( env ); 
On this point Job step should finish and all removals will be applied into database, without it we can't delete environment, you'll get en exception that this env is in use.

Second step:

Also before delete you need to remove this environment from the environment group.
We have environment group which this environment belongs to, so just remove: envGroup.removeServerGroup( env ); 

Third step:

Just get ServerGroup object for required environment and call .delete() method.

вторник, 1 октября 2013 г.

NGINX + FastCGI Perl on Gentoo

Adding to make.conf modules required for nginx and cgi wrapper

NGINX_MODULES_HTTP="access auth_basic autoindex charset fastcgi gzip gzip_static limit_req map proxy rewrite scgi ssi stub_status"
NGINX_MODULES_MAIL=""

Emerging nginx
emerge -av nginx www-misc/fcgiwrap www-servers/spawn-fcgi

  • www-misc/fcgiwrap, a FastCGI server for wrapping CGI scripts
  • www-servers/spawn-fcgi, a FastCGI manager for spawning fcgiwrap.
Make any adjustments you like to /etc/nginx/mime.types. I added:
types {
    …
    application/x-python                  py;
    application/x-shell                   sh;
    …
}
 
Configure spawn-fcgi to launch fcgiwrap with:
# cp /etc/conf.d/spawn-fcgi /etc/conf.d/spawn-fcgi.fcgiwrap
# emacs /etc/conf.d/spawn-fcgi.fcgiwrap
# cat /etc/conf.d/spawn-fcgi.fcgiwrap
FCGI_SOCKET=/var/run/fcgiwrap.sock
FCGI_ADDRESS=
FCGI_PORT=
FCGI_PROGRAM=/usr/sbin/fcgiwrap
FCGI_USER=nginx
FCGI_GROUP=nginx
FCGI_EXTRA_OPTIONS="-M 0700"
ALLOWED_ENV="PATH HOME"
HOME=/
FCGI_CHILDREN=1
FCGI_CHROOT=
# cd /etc/init.d/
# ln -s spawn-fcgi spawn-fcgi.fcgiwrap
 
Start fcgiwrap with:
# /etc/init.d/spawn-fcgi.fcgiwrap start
 
Add it to the default runlevel with:
# rc-update add spawn-fcgi.fcgiwrap default
 
NGINX configuration:
server {
...
location / {
    include fastcgi_params;
    fastcgi_pass  unix:/var/run/fcgiwrap.sock-1;
  }
...
}
 
Should work now!

четверг, 26 сентября 2013 г.

Git crib

Git

Git is a free & open source, distributed version control system designed to handle everything from small to very large projects with speed and efficiency.

Configuration

Set Name and Email Address

$ git config --global user.name "Your Name"
$ git config --global user.email "yourname@yourdomain.com"

Set Colors

$ git config color.ui true

General Commands

Create a Repository

$ mkdir project
$ cd project
$ git init

Ignore Files or Directories

Create .gitignore and add file and directory globs:
dist
tmp
log
.DS_Store

See List of Changed Files

$ git status

See Difference of Files

$ git diff

Stage Files for Committing

$ git add foo.txt
$ git add bar.txt

Unstage a File

$ git reset HEAD bar.txt

See Differences of Staged Files

$ git diff --cached

Commit Staged Files

$ commit -m "Your Message Here"

Revert a Changed File

$ git checkout name/of/file

Branching

Create a Branch

$ git branch <branchName>

Switch to a Branch

$ git checkout <branchName>

Create and Switch to Branch

$ git checkout -b <branchName>

Switch back to master Branch

$ git checkout master

List Local Branches

$ git branch

List Remote Branches

$ git branch -r

List Local and Remote Branches

$ git branch -a

Merge changes from another Branch

$ git merge <branchName>

Rename a Branch

$ git branch -m <currentName> <newName>

Force Rename of Branch

$ git branch -M <currentName> <newName>

Delete a Branch if differences have been merged into current branch

$ git branch -d <branchName>

Force Deletion of Branch

$ git branch -D <branchName>

Delete Remote Branch

$ git branch -d -r <remoteName>/<branchName>
$ git push <remoteName> :<branchName>

Remote Repositories

Show List of Remote Repositories

$ git remote

Add a Remote Repository

$ git remote add <remoteName> <url>

Remove a Remote Repository

$ git remote rm <remoteName>

Rename a Remote Repository

$ git remote rename <oldRemoteName> <newRemoteName>

Push to a Remote Repository

$ git push <remoteName> <branchName>

Pushing to Multiple Remote Repositories at Once

If you want to push to multiple remote repositories using a single name you can first add the two remotes separately and then end .git/config to add a third remote that combines both of them together:
[remote "heroku"]
 url = git@heroku.com:bnd-notes.git
 fetch = +refs/heads/*:refs/remotes/heroku/*
[remote "github"]
 url = git@github.com:buildndeploy/notes.git
 fetch = +refs/heads/*:refs/remotes/github/*
[remote "external"]
    url = git@github.com:buildndeploy/notes.git
 url = git@heroku.com:bnd-notes.git
 fetch = +refs/heads/*:refs/remotes/heroku/*
Then you can update them with a single command:
$ git push external

Stashes

git stash / git stash save
git stash list
git stash apply <stash>
git stash apply stash@{0}
git stash pop

GitHub Fork Merge

$ git remote add upstream git://github.com/qgis/Quantum-GIS.git
$ git fetch upstream
$ git merge upstream/master

четверг, 5 сентября 2013 г.

[CENTOS6] Настраиваем алтернативы для Java

export java_home=/usr/java/default
/usr/sbin/update-alternatives --install /usr/bin/java java ${java_home}/bin/java 20000 \
                                --slave /usr/bin/keytool keytool ${java_home}/bin/keytool \
                                --slave /usr/bin/orbd orbd ${java_home}/bin/orbd \
                                --slave /usr/bin/pack200 pack200 ${java_home}/bin/pack200 \
                                --slave /usr/bin/rmid rmid ${java_home}/bin/rmid \
                                --slave /usr/bin/rmiregistry rmiregistry ${java_home}/bin/rmiregistry \
                                --slave /usr/bin/servertool servertool ${java_home}/bin/servertool \
                                --slave /usr/bin/tnameserv tnameserv ${java_home}/bin/tnameserv \
                                --slave /usr/bin/unpack200 unpack200 ${java_home}/bin/unpack200 \
                                --slave /usr/lib/jvm/jre jre ${java_home} \

четверг, 29 августа 2013 г.

[RPM] Встроенные макросы

Built-in macros

RPM includes a host of built-in macros, including the following useful directories:
%_prefix /usr
%_exec_prefix %{_prefix}
%_bindir %{_exec_prefix}/bin
%_sbindir %{_exec_prefix}/sbin
%_libexecdir %{_exec_prefix}/libexec
%_datadir %{_prefix}/share
%_sysconfdir %{_prefix}/etc
%_sharedstatedir %{_prefix}/com
%_localstatedir %{_prefix}/var
%_libdir %{_exec_prefix}/lib
%_includedir %{_prefix}/include
%_oldincludedir /usr/include
%_infodir %{_prefix}/info
%_mandir %{_prefix}/man
The example directories shown above come from the standard RPM macro file, /usr/lib/rpm/macros, instead of the Red Hat-specific file, /usr/lib/rpm/redhat/macros, which holds:
%_prefix /usr
%_sysconfdir /etc
%_localstatedir /var
%_infodir /usr/share/info
%_mandir /usr/share/man
%_initrddir %{_sysconfdir}/rc.d/init.d
%_defaultdocdir %{_usr}/share/doc

[DEBIAN] Устанавливаем локаль ru_RU.UTF8

apt-get install locales - на все вопросы вносим Y. vi /etc/environment - открываем файл на редактирование и удаляем из него любые записи и вносим одну: LANG="ru_RU.UTF-8"
Помощь по использованию vi находится здесь: Vi или откройте файл через WinSCP
Редактируем файл /etc/locale.gen тем же vi: vi /etc/locale.gen - В списке находим ru_RU.UTF-8 UTF-8 и удаляем значек # перед записью. Сохраняем файл.
locale-gen - запускаем команду для генерации локали. Пример ниже:
root@test:~# locale-gen
Generating locales (this might take a while)...
ru_RU.UTF-8... done
Generation complete.
Перезаходим на сервер. В клиенте, который Вы используете для связи с сервером делаем следующее (большинство людей использует Putty: SSH):
После того как Вы вошли на сервер, кликните на верхнюю часть окна Putty правой кнопкой мыши, выше черного. Выберите Change Settings -> Window - Translation -> из списка выберите UTF-8 и нажмите Apply внизу.
Теперь Вы сможете видеть русский язык в окне связи с сервером при выполнении различных команд.

четверг, 30 мая 2013 г.

How do I find what dependencies a rpm file has?

RPM is a Package Manager for popular distribution such as Red Hat, Suse and many others. It is a powerful command line package management system for installing uninstalling, verifying, querying, and updating Linux computer software packages.
You can finding out what dependencies a rpm file has i.e. it will tell you what you need to install package with following command:
rpm -qpR {.rpm-file}
rpm -qR {package-name}


Otherwise you can try to install it end will get error message if some of the deps wouldnot be installed.
rpm -ivh {.rpm-file}

Цинизм в IT: Как собирать RPM под CentOS 5?

Цинизм в IT: Как собирать RPM под CentOS 5?

среда, 10 апреля 2013 г.

Ставим Puppet в CentOS 6

Как ни забавно, но столкнулся со странной проблемой при установке сабжа. Скорее это по моему недосмотру, но все же. Суть -- вылетало с ошибкой при попытке установки ruby-libs.
Пофиксилось командой yum clean all, очень рекомендую ее сделать перед установкой паппета.

Далее, в репе нет puppet, поэтому нам надо добавить репу с паппетом:
rpm -ivh http://yum.puppetlabs.com/el/6/products/x86_64/puppetlabs-release-6-6.noarch.rpm

Далее просто yum install puppet чтобы установить клиент, ну и yum install puppet-master , чтобы установить сервер.


вторник, 9 апреля 2013 г.

[PUPPET] Ставим пакеты из backports

Возникла необходимость поставить пакет из бекпортов через apt-get с помощью паппета.
Для этого необходимо проделать примерно следующее (кусок манифеста из рабочего проекта)

class collectd {
# directories and filenames setup
    $apt_sources_dir = '/etc/apt/sources.list.d'
    $apt_sources_file = 'backports.list'

    file { "{$apt_sources_dir}/{$apt_sources_file}":
        ensure    => file,
        content    => 'deb http://backports.debian.org/debian-backports squeeze-backports main',
    }
#
    exec { "apt-get update":
        command => "/usr/bin/apt-get update",
        onlyif => "/bin/sh -c '[ ! -f /var/cache/apt/pkgcache.bin ] || /usr/bin/find /etc/apt/* -cnewer /var/cache/apt/pkgcache.bin | /bin/grep . > /dev/null'",
    }
# installing package
    package { "collectd-core/squeeze-backports":
        ensure => "latest",
        require => Exec['apt-get update'],
    }
}

понедельник, 1 апреля 2013 г.

[ANDROID] "Переносим" данные из внутренней памяти телефона на флеш-карту

1. Определитесь где у вас на (флешке) будут храниться перенесенные данные и создайте для них папку. Например Bind
2. Создайте в только что созданной папке еще одну папку с именем gameloft
3. Перенесите в нее содержимое папки /mnt/sdcard/gameloft/games
4. Скачайте с маркета бесплатное приложение Script Manager
5. Решите где у вас будет лежать скрипт ==> Создайте папку Scripts.
6. Запустите Script Manager и перейдите в эту папку.
7. Создайте новый скрипт (меню-(+)) и назовите его bind.sh
8. Щелкните по свежесозданному файлу и в появившемся меню нажмите:
Звездочку - это добавит наш скрипт в избранное.
Черепок - запуск скрипта с root привилегиями.
Шестеренку - добавит скрипт в автозагрузку.
Далее жмем кнопку Edit и открываем скрипт любимым текстовым редактором.
9. Настало время для самого сложного
Структура команды:
mount -o bind </что/хотите/смонтировать> </куда/хотите/смонтировать>
Исходя из этого у нас получается:
mount -o bind /mnt/sdcard2/bind/gameloft /mnt/sdcard/gameloft/games
иными словами мы говорим системе что содержимое папки /sdcard/gameloft/games находится в папке /sdcard2/bind/gameloft

10. В открытом файле  пишем:
#!/system/bin/sh
mount -o bind /mnt/sdcard2/bind/gameloft /mnt/sdcard/gameloft/games

exit 0


#!/system/bin/sh
##Cashe gameloft
mount -o bind /mnt/sdcard2/bind/gameloft /mnt/sdcard/gameloft/games
##Cashe Spectral Souls
mount -o bind /mnt/sdcard2/bind/hyperdevbox /mnt/sdcard/hyperdevbox
##Maps 2GIS
mount -o bind /mnt/sdcard2/bind/2gisMobile /mnt/sdcard/2gisMobile
exit 0

11. Сохраняем файл и закрываем текстовый редактор.
12. Жмем кнопку Run и идем в папку /gameloft/games
Если кэши в ней видны, значит вы все сделали правильно, можно запустить и проверить игру.
При следующей перезагрузке скрипт выполнится автоматически.

По аналогии переносим другие данные просто дописывая в этот скрипт.

вторник, 26 марта 2013 г.

[PHP] Useful code snippets

Email PHP errors instead of displaying it

By default, most servers are set to display an error message when an error occured in one of your script. For security reasons, you may want to get an email with the error, instead of displaying it to the public.
// Our custom error handler
function nettuts_error_handler($number, $message, $file, $line, $vars){
 $email = "
  An error ($number) occurred on line
  $line and in the file: $file.
  

$message 

";

 $email .= "
" . print_r($vars, 1) . "
"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Email the error to someone... error_log($email, 1, 'you@youremail.com', $headers); // Make sure that you decide how to respond to errors (on the user's side) // Either echo an error message, or kill the entire project. Up to you... // The code below ensures that we only "die" if the error was more than // just a NOTICE. if ( ($number !== E_NOTICE) && ($number < 2048) ) { die("There was an error. Please try again later."); } } // We should use our custom function to handle errors. set_error_handler('nettuts_error_handler'); // Trigger an error... (var doesn't exist) echo $somevarthatdoesnotexist; 

Detect location by IP

Here is an useful code snippet to detect the location of a specific IP. The function below takes one IP as a parameter, and returns the location of the IP. If no location is found, UNKNOWN is returned.
function detect_city($ip) {
        
        $default = 'UNKNOWN';

        if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
            $ip = '8.8.8.8';

        $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
        
        $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
        $ch = curl_init();
        
        $curl_opt = array(
            CURLOPT_FOLLOWLOCATION  => 1,
            CURLOPT_HEADER      => 0,
            CURLOPT_RETURNTRANSFER  => 1,
            CURLOPT_USERAGENT   => $curlopt_useragent,
            CURLOPT_URL       => $url,
            CURLOPT_TIMEOUT         => 1,
            CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],
        );
        
        curl_setopt_array($ch, $curl_opt);
        
        $content = curl_exec($ch);
        
        if (!is_null($curl_info)) {
            $curl_info = curl_getinfo($ch);
        }
        
        curl_close($ch);
        
        if ( preg_match('{
  • City : ([^<]*)
  • }i', $content, $regs) ) { $city = $regs[1]; } if ( preg_match('{
  • State/Province : ([^<]*)
  • }i', $content, $regs) ) { $state = $regs[1]; } if( $city!='' && $state!='' ){ $location = $city . ', ' . $state; return $location; }else{ return $default; } }

    Display Facebook fans count in full text

    Want to display how many Facebook fans do you have, in full text, on your blog? It’s very easy using the following snippet:
    function fb_fan_count($facebook_name){
        // Example: https://graph.facebook.com/digimantra
        $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
        echo $data->likes;
    }

    Get info about your memory usage

    In order to optimize your scripts, you may definitely want to know how many amount of RAM they use on your server. This snippet will check memory and then print initial, final and peak usages.
    echo "Initial: ".memory_get_usage()." bytes \n";
    /* prints
    Initial: 361400 bytes
    */
    
    // let's use up some memory
    for ($i = 0; $i < 100000; $i++) {
     $array []= md5($i);
    }
    
    // let's remove half of the array
    for ($i = 0; $i < 100000; $i++) {
     unset($array[$i]);
    }
    
    echo "Final: ".memory_get_usage()." bytes \n";
    /* prints
    Final: 885912 bytes
    */
    
    echo "Peak: ".memory_get_peak_usage()." bytes \n";
    /* prints
    Peak: 13687072 bytes
    */

    
    

    четверг, 14 февраля 2013 г.

    [PHP] Заменить 2+ пробелов на "пусто"

    Просто записка:
    $string=preg_replace('/ {2,}/','',$string);
            /*  |          | ||     |   |_в $string
                |          | ||     |_на пустую строку
                |          | ||_и более раз
                |          | |_встреченный 2 
                |          |_пробел (только пробел, для табов и пр символов - \s
                |_заменить 
            */
    

    понедельник, 11 февраля 2013 г.