ReferenceError #1065: can not create property 0 on … (and #1069)

Last week, I was trying to create a shuffle function on my array class which extends the native Array class. I got the ReferenceError when running the code bellow. The reason is that Array is a dynamic class and my is not. Since Array is dynamic, it will try to create new property when you try to assign some value to a nonexistent instance variable but MyArray prevents this. If you try this you will see that reference error #1065 is occurred when the array is constructed. If you remove the constructor you will get reference error #1069 instead and it hapens when you try to swap the elements in shuffle method (trying to access a nonexistent instance variable). So make sure that you declare dynamic if you extend a dynamic class or better if editor or compiler gives a warning if you forget …

 
package vnmedia.common.lang
{
	import vnmedia.common.lang.math.Random;
 
	public class MyArray extends Array
	{
		public function MyArray(...parameters)
		{
			super(parameters);
		}
 
		public function shuffle():void
		{
			var a:*, k:int, i:int, r:Random = new Random();
			for(i = this.length; i > 1; i--){
				// 0 <= k <= i - 1
				k = r.nextInt(i);
				a = this[k];
				this[k] = this[i-1];
				this[i-1] = a;
			}
		}
	}
}

However, I think the best way to provide a shuffle function for arrays is to define a static ArrayUtil.shuffle as bellow

package vnmedia.common.lang
{
	import vnmedia.common.lang.math.Random;
 
 
	public class ArrayUtil
	{
		public function ArrayUtil()
		{
		}
 
		public static function shuffle(arr:Array):void
		{
			var a:*, k:int, i:int, r:Random = new Random();
			for(i = arr.length; i > 1; i--){
				k = r.nextInt(i);
				a = arr[k];
				arr[k] = arr[i-1];
				arr[i-1] = a;
			}
		}
 
	}
}

Limit access with firewall ufw

Here is some links on how you can reject requests using firewall ufw.

http://manpages.ubuntu.com/manpages/jaunty/en/man8/ufw.8.html
http://www.ubuntu-unleashed.com/2008/05/howto-take-use-setup-and-advantage-of.html

Limit http methods

I you have an apache server which you only use GET and POST methods I think it is better that you limit the access. Since there are many methods it is more convinient to use the opposite functions, limitExcept. Bellow is an example how it would look like. The limitExcept directive allows only GET and POST. All other request methods will be rejected.

NameVirtualHost xxx.xxx.xxx:80
<VirtualHost xxx.xxx.xxx:80>
        ServerName example.com
 
        DocumentRoot /path/to/doc/root
        <Directory /path/to/doc/root/>
                <LimitExcept POST GET>
                         Require valid-user
                </LimitExcept> 
                Options Indexes MultiViews FollowSymLinks
                Order Allow,Deny
                Allow from all
        </Directory>
...
</VirtualHost>

If you want to deny from the access you can use “Deny from all” instead of “Require valid-user”

Deny requests from specific ips, configured in virtual host

Bad thing has hapened to me this holliday. The server has been attacked from serveral ips or more precis they used my server as proxy for attacking other targets. Lucky for me that my server is not configured for this kind of attacks. However, they kept request my server and I wanted that apache would deny all requests from those ips. This one is really tricky. I have configured for denying all except some ips, such as local, but never configured for denying some ips and allow the rest. I started reading apache docs and tried to understand. The result is as following:

NameVirtualHost xxx.xxx.xxx:80
<VirtualHost xxx.xxx.xxx:80>
        ServerName example.com
 
        DocumentRoot /path/to/doc/root
        <Directory /path/to/doc/root/>
                Options Indexes MultiViews FollowSymLinks
                Order Deny,Allow
                Deny from xx.xxx.xxx.xxx
                Deny from xxx.xxx.xxx.xxx
                Deny from ...
                # ips that not matched deny list will be permitted
        </Directory>
...
</VirtualHost>

Be aware that you can not use “Allow from all” in the end since apache deny a request only if it does not match an allow condition. So we have a deny list to match against. Ips that are not matched ips in this list will be permitted.

It says that there are no good way to protect against this kind of attacks. I hope that I can get in touch with those ip-owners and hopefully they can help me.

Some good pages
http://wiki.apache.org/httpd/ProxyAbuse
http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html

How to get/kill process in ubuntu

For example if process name is php, you can get a list of jobs by using the command bellow

ps aux | grep php

Result

root      7749  0.0  0.1   3236   796 pts/2    S+   16:09   0:00 grep php
root     19292  1.8  5.6  90624 28528 ?        S    01:36  16:09 php test.php

To kill a process you can use kill with a specific pid, for instance 19292 above

kill 19292

And kill all php process

killall -9 php

Howto enable ssl and create self-signed ssl certificate

Enable ssl
In my case it was simple. I just ran this line

a2enmod ssl

Generate self-signed ssl certificate
Solution: http://www.akadia.com/services/ssh_test_certificate.html

Just follow instruction carefully. Make sure that i step 2 you need to enter a correct “Common Name”, ie your domain. Step 5 and 6 also different for different distributions and installation …

Summary in case link above is not available anymore:
Step 1: Generate a Private Key

openssl genrsa -des3 -out server.key 1024

Step 2: Generate a CSR (Certificate Signing Request)

openssl req -new -key server.key -out server.csr

Step 3: Remove Passphrase from Key

cp server.key server.key.org
openssl rsa -in server.key.org -out server.key

Step 4: Generating a Self-Signed Certificate

openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Step 5: Installing the Private Key and Certificate
(or the location you want to store)

cp server.crt /usr/local/apache/conf/ssl.crt
cp server.key /usr/local/apache/conf/ssl.key

Step 6: Configuring SSL Enabled Virtual Hosts

SSLEngine on
SSLCertificateFile /usr/local/apache/conf/ssl.crt
SSLCertificateKeyFile /usr/local/apache/conf/ssl.key
SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown

Step 7: Restart Apache and Test

New problem:
ssl_error_ssl2_disabled
Solution in ssl.conf:
# enable only secure protocols: SSLv3 and TLSv1, but not SSLv2
## disabled this one
#SSLProtocol all -SSLv2
## use this instead
SSLProtocol all

See also http://httpd.apache.org/docs/2.0/ssl/ssl_howto.html

New problem:
sec_error_untrusted_issuer due to self-signed SSL Certificate
But it is no problem for me since this is for my own usage and test…

How to set default OS in boot.ini

This is a boot setup for Microsoft Windows XP Professional and Ubuntu (wubi) where we have Windows XP as default and will be preselected on start of computer. This content can be found in c:\boot.ini (be aware this is a hidden system file).

[boot loader]
timeout=15
default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS
 
[operating systems]
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP Professional" /fastdetect /NoExecute=OptIn
c:\wubildr.mbr="Ubuntu"

If we wish to start with Ubuntu instead we change default operative system as following

[boot loader]
timeout=15
default=c:\wubildr.mbr
 
[operating systems]
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP Professional" /fastdetect /NoExecute=OptIn
c:\wubildr.mbr="Ubuntu"

Howto use vnkeys with TextField

vnkeys is originally designed to work with flash.text.TextField and you can feel it when typing. The replacement happens smoothly. It is easy to use and the code bellow will explain how to…

package {
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.text.TextFieldType;
 
	import org.vnmedia.vnkeys.KeyConverter;
	import org.vnmedia.vnkeys.mapping.VNIMap;
	// define swf dimension
	[SWF(width=160, height=60)]
	// this is an application class
	public class vnmedia_vnkeys extends Sprite
	{
		public function vnmedia_vnkeys()
		{
			var textinput:TextField = new TextField();
			// give this text input a size
			// and positioning it
			textinput.width = 150;
			textinput.height = 50;
			textinput.x = 5;
			textinput.y = 5;
			// use multiline, ie textarea
			textinput.multiline = true;
			textinput.type = TextFieldType.INPUT;
			// give it background white
			// so we can see what we are typing
			textinput.backgroundColor = 0xFFFFFF;
			textinput.background = true;
			// NOW create a converter
			// for this TextField instance
			var converter:KeyConverter =
				new KeyConverter(textinput,VNIMap.NAME);
			// add this text input to application
			this.addChild(textinput);
		}
	}
}

The result:

Type using VNI input method

How to bootstrap, autoload modules and classes with Zend framework

This post is for you that have read this quick start from Zend and our goal is to create a bootstrap like this one. We assume that you know how to create a project, layout, module, controller and action by using zf.bat, zf.sh or manually and further that you are able to create a helloworld application with structure as bellow (I used zf.bat)

application
   configs
      application.ini
   layouts
      scripts
         layout.phtml
   modules
      default
         controllers
            ErrorController.php
            HelloworldController.php
            IndexController.php
         forms
            HelloWorld.php
         models
         views
            filters
            helpers
            scripts
              error
                 error.phtml
              helloworld
                 hello.phtml
              index
                 index.phtml
      second
         controllers
            HelloworldController.php
            IndexController.php
         forms
            HelloWorld.php
         models
         views
            filters
            helpers
            scripts
              helloworld
                 hello.phtml
              index
                 index.phtml
   Bootstrap.php
library
   Zend
   Foo
     Bar.php
public
   index.php
tests

We have now created two modules “default” and “second”. So far I can not create a project with default module inside folder modules so you need to move controllers, forms, models, views into default (create it first). However, the main purpose here is to show how to alter the Bootstrap that generated by zf.bat so that modules will be loaded and classes within modules, such as forms, models, can be autoloaded. In this example we will test for the form HelloWorld which is loaded in controller Helloworld. Here is the content of those files

default/controllers/HelloworldController.php

<?php
 
class HelloworldController extends Zend_Controller_Action
{
 
    public function init()
    {
        /* Initialize action controller here */
    }
 
    public function indexAction()
    {
        // action body
    }
 
    public function helloAction()
    {
        $request = $this->getRequest(); 
        $form = new Default_Form_HelloWorld();
        if ($request->isPost()) {
        	print $request->getParam('hello');
        }
        $this->view->form = $form;
    }
}
?>

default/forms/HellowWorld.php

<?php
class Default_Form_HelloWorld extends Zend_Form
{
	public function init()
	{
		$this->setMethod('post');
		$this->addElement('text', 'hello', array(
            'label'      => 'Hello default:',
            'required'   => true,
            'filters'    => array('StringTrim')
		));
		$this->addElement('submit', 'submit', array(
            'ignore'   => true,
            'label'    => 'Say',
		));
 
	}
}
?>

second/controllers/HelloworldController.php

<?php
class Second_HelloworldController extends Zend_Controller_Action
{
 
    public function init()
    {
        /* Initialize action controller here */
    }
 
    public function indexAction()
    {
        // action body
    }
 
    public function helloAction()
    {
        $request = $this->getRequest();
        $form    = new Second_Form_HelloWorld();
        if ($request->isPost()) {
        	print $request->getParam('hello');
        }
        $this->view->form = $form;
    }
}
?>

second/forms/HelloWorld.php

<?php
class Second_Form_HelloWorld extends Zend_Form
{
    public function init()
    {
        $this->setMethod('post');
        $this->addElement('text', 'hello', array(
            'label'      => 'Hello second:',
            'required'   => true,
            'filters'    => array('StringTrim')
        ));
        $this->addElement('submit', 'submit', array(
            'ignore'   => true,
            'label'    => 'Say',
		));
    }
}
?>

default/views/scripts/helloworld/hello.phtml
second/views/scripts/helloworld/hello.phtml

<?php 
$this->form->setAction($this->url());
echo $this->form;
?>

The first step we will try to do is to make sure that we can load the modules. We start to alter Bootstrap.php What we need to do is telling Front Controller where our modules are located

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
	protected function _initDoctype()
	{
	}
 
	protected function _initApplication()
	{
		$this->bootstrap('FrontController');
		$front = $this->getResource('FrontController');
		$front->throwExceptions(false);
		$front->addModuleDirectory(APPLICATION_PATH . '/modules');
	}
}
 
?>

Be aware that this can also be done in bootstrap file (public/index.php). One can do that by adding follow

$frontController = Zend_Controller_Front::getInstance();
$frontController->addModuleDirectory(APPLICATION_PATH . '/modules');

Or add this line in application.ini that is generated by zf.bat

resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"

Now you should be able to navigate to http://yourserver/helloworld/hello or http://yourserver/second/helloworld/hello without any complain about “missing default module in front controller”. We got instead a fatal error which says that our form classes Default_Form_HelloWorld/Second_Form_HelloWorld is not found. The next is to enable autoloading of those form classes. To do that we start to edit Bootstrap.php again by adding init method _initAutoload() which will be called automatically

<?php
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
 
	protected function _initDoctype()
	{
	}
 
	protected function _initApplication()
	{
		$this->bootstrap('FrontController');
		$front = $this->getResource('FrontController');
		$front->throwExceptions(false);
		$front->addModuleDirectory(APPLICATION_PATH . '/modules');
	}
 
	protected function _initAutoload()
	{
		// BLOCK 1
		// this is a fallback to autoload our own classes in library
		$autoLoader = Zend_Loader_Autoloader::getInstance();
		$autoLoader->setFallbackAutoloader(true);
 
		// BLOCK 2
		// this is for loading forms classes in default module
		$autoloader = new Zend_Application_Module_Autoloader(array(
        		'namespace' => 'Default_',
            		'basePath'  => APPLICATION_PATH . '/modules/default',
        		'resourceTypes' => array(
                		'forms'=>array('path'=>'/forms',
					'namespace'=>'Form')
				)
			)
		);
 
		// BLOCK 3
		// this is for loading form classes in second module
		$autoloader = new Zend_Application_Module_Autoloader(array(
        		'namespace' => 'Second_',
          		'basePath'  => APPLICATION_PATH . '/modules/second',
        		'resourceTypes' => array(
                 		'forms'=>array('path'=>'/forms',
					'namespace'=>'Form')
				)
			)
		);
	}
}
?>

BLOCK 1:
By default Zend_Loader_Autoloader will only load Zend classes. This code block tells Zend_Loader_Autoloader to include class files in arbitrary libraries. For instance, when you create a new “Bar”

$bar = new Foo_Bar();

It will try to include the file by looking in includepath/Foo/Bar.php and in our case it will include the file Foo/Bar.php

BLOCK 2 & 3:
Since Zend_Loader_Autoloader replaces _ in classname with / when loading the class file. But this will not work for classes in module folder. In these two code blocks we register the namespace and the corresponding path, ie if a class start with Second_ then it should look for the class file in application/modules/second/. When loading the form, in our case, it will add basePath and path, ie it will look for the class file in applicaton/modules/second/forms/.

Be aware that the namespace for your classes in forms and classes in library should distinct, for instance if I create a Foo class for module second in my library I should start with application name (helloworld) Helloworld_Second_Foo instead of Second_Foo which has the start namespace for the form, ie start-namespace conflict. I hope that this is the answer you are looking for …

How to install a .deb file

To install package called package.deb type the following command (make sure that all dependencies are installed)

sudo dpkg -i /path/to/folder/package.deb