Zaki Saadeh

Blog & Technical Playground

How to include javascript libraries in Yii?

without comments

To include a javascript library (file) in Yii, just add the following line on your PHP page. For organizational purposes I create a /js directory under my application’s root directory. This means that I place /js at the same level of /protected. So /js is a sibling of /protected.

<?php Yii::app()->clientScript->registerScriptFile(
				Yii::app()->baseUrl . '/js/FooBoo.js'); ?>

Also note, that the application’s root folder can be retrieved by using

 Yii::app()->baseUrl; 

Related Posts:

Written by Zaki

May 22nd, 2011 at 11:00 pm

How to use jQuery in Yii?

without comments

Yii comes bundled with jQuery and its UI. To use them, you have to include the following line in the pages you are using them:

<?php Yii::app()->clientScript->registerCoreScript('jquery'); ?>
<?php Yii::app()->clientScript->registerCoreScript('jquery.ui'); ?>

Related Posts:

Written by Zaki

May 22nd, 2011 at 10:47 pm

Yii Framework Tutorial

without comments

Yii framework tutorial will cover:

  • What is Yii? (covered below)
  • Why Yii? (covered below)
  • Setup and installation (work in progress)
  • Build your first application (work in progress)
  • Build a restaurant website, with a nice backend to manage the menu and other items (work in progress)

What is Yii?

Yii stands for Yes it is! It is a high-performance PHP framework best for developing web applications. Yii comes rich with features: Model View Controller (MVC) pattern, DAO/ActiveRecord, Localizaton and Internationlization I18N/L10N support, smart and fast caching, authentication and role-based access control, scaffolding, testing, and other tools for rapid development. It can reduce your development time significantly. Hang on and you will see how fast this you will become with Yii.

Why Yii?

Yii is based on PHP which is a very popular scripting / object oriented programming language. It has the following features:

  • Model View Controller design pattern (BetterExplained has a good introduction to MVC): MVC emphasizes the separation of the business logic from the presentation logic, from the data access logic. The model deals with CRUD operations, the controllers coordinates between the other two layers and contains most of your application’s business logic. The view is what the end-user will see. It’s the presentation layer (html, images, css, javascript, etc…)
  • ORM via Active Record: There’s no need to write native sql (unless you want to). To make your life simpler as a developer, Yii makes it very easy for us to deal with data in a persistent storage like a database by dealing with objects that represent the data sets in your storage.
  • Security: Yii comes with very good security features. The fact that you deal with objects instead of direct database statements makes your applications much more secure, since you will be writing less sql-injection vulnerable code. In addition to protecting against this kind of attack and making your application a little more stable, Yii protects against cross-site scripting, cookie tampering, and cross-site request forgery attacks.  Additionally, it supports role-based authorization, and natively supports form and input validation.
  • AJAX: a lot of the widgets that come with Yii support AJAX for a better end-user experience. You can also use jQuery and it’s AJAX features inside Yii.
  • Extensions: Yii comes with a huge library of core features, widgets, and helpers. And if these couldn’t satisfy you, then go ahead and take a look at the vast library of plugins and extensions available to be plugged in to your core installation with ease. One thing before I go. Yii comes with jQuery support. You can enable it with a single line, placed in a single file!
  • Testing, internationalization and localization, caching, themes, and more!
  • Open source! Yii is released under the BSD License.

I always liked this diagram:

Taken from Yii's website: http://www.yiiframework.com/performance/

 

3 Day Startup 2011 @ Austin Technology Incubator: Awesome!

without comments

Participating in 3 Day Startup last week was probably one of the best decisions I’ve made this month, if not this year! I met amazing and extremely talented people and enjoyed working with very creative ideas. I really recommend this event to anyone who is interested in meeting the right people to start a business. The diversity of participants and their majors/professional backgrounds was a great factor in making this event a successful one. I met people from computer science, mechanical engineering, electrical engineering, math, studio arts, design, business, and other backgrounds. It was simply an amazing gathering. The organizational momentum behind the event was also an important factor in making it awesome. The organizers made sure to make this event as exciting as it can be. They supplied us with everything we need, including 8 cases of Red Bull! The Austin Technology Incubator (ATI) and other sponsors also played an awesome role in connecting participants with well established figures in the technology industry, like Bob Metcalfe (UTAustin Professor of Innovation), Joshua Baer (Managing Director of Capital Factory), Stewart Alsop (VC), Bill Boebel (VP Strategy / Corporate Development of Rackspace), Ross Buhrdorf (CTO of HomeAway).

Written by Zaki

April 23rd, 2011 at 9:29 pm

Python and Security

without comments

Introduction:

You might be thinking: the security of an algorithm depends on the programmer’s ability to write secure code. This statement is absolutely true and cannot be underestimated. Yet, I believe that an extensive number of secure tools and certain design features in a programming language will make a programmer’s life easier in securing his or her code. This article will try to focus on some interesting Python design features and tools (built-in functionality and provided standard libraries) and see how they affect the security of coding in Python, in general.

A brief history of security in Python:

  • In 1995, a module called rexec (for restricted execution) was introduced. It’s purpose was to provide an enforcement of a security policy for running Python scripts. It provided a way for the safe execution of code by isolation (sandboxing) and provided ways for controlling the global namespace.
  • In 2003, when Python’s 2.3 version was released, this module was dropped and hasn’t been replaced with a built-in module that covers the same functionality since then.

The problems with the current model:

  • Unsafe code execution possible: with the absence of a module enforcing a security policy, malicious code can be executed on a machine running a bare Python interpreter. Fundamentally, there’s no way for the interpreter to differentiate between different sets of codes running (Brett Cannon and Eric Wohlstadter). So imagine a set of code U (Unsafe) which contains code that you just downloaded off the Internet which contains a lot of useful code but 5 lines of code that modify some resources on your file system in some bad way. It would be impossible to restrict the interpreter’s reach for these resources from within the interpreter. This could be devastating. Furthermore, the interpreter allows the importing of compiled Python code (more on this below).
  • Importing compiled Python code is plausible (and dangerous): Let’s examine the previous point for a second. To import code in a compiled format means that you don’t necessarily have access to an easily readable code to check before executing. Note: the set U above could have been compiled! The inability of the Python interpreter to verify the soundness of imported byte-code could possibly result in a DOS attack by crashing the interpreter (Brett Cannon and Eric Wohlstadter).
  • No private namespace: Unlike Java, Python does not contain the ability to restrict an object’s access to another’s private domain. However, there’s a primitive attempt to define a pseudo-private notation. For ex: __BANK_ACCOUNT_BALANCE. This attempt is insufficient if used as a tool to protect an attribute. Note that importing using import <your-module> will get you all the attributes, but some need a little trick to access (see: ClassVariables.py). Since I can always use this import directive with the trick, the notation __<VAR> is useless when there’s a need for an effectively secure programming model in Python.

Programmer tools and libraries to enhance security:

  • Preventing SQL injections: Python is rich in different libraries that will allow a programmer to interface with many popular databases. Although, Python programmers don’t like using SQL directly, there are many functions that come in handy when looking to parse user input and make sure it is safe to execute via an SQL query. Even better, Python has libraries that support ORM.
  • Buffer Overflows: Since objects are allocated dynamically on the heap, the possibility of buffer overflows is minimal in a sound environment. Also bounds checking and other techniques can prevent a programmer from encoutering a buffer overflow. The question that you might be thinking about now is: Is Python buffer overflow proof? Simply put No. I found an elegant answer to this question on a forum post. It can be formulated into a proof by contradiction.
  • The Python interpreter is written in C. Python extension modules are
    written in C (or something similar). If you find an unprotected buffer
    in this C code, you can possibly overflow this buffer. This can be
    used for nasty things like corrupting the stack and injecting
    malicious code. There is a reason why the Python sandbox (rexec and
    Bastion modules) was disabled in Python 2.3.
  • Garbage Collection: Garbage collection in Python is automatic and that helps. Automatic garbage collection is superior to manual garbage whithin a security context. Managing the allocation and deallocation manually could result in logical errors as well as runtime ones (possibly buffer overflows). These errors (depending on how you use them and when you get them) could be a threat to your application.
  • Crypto libraries: There are a bunch of libraries available to Python programmer to use for hashing and other related security needs. You can MD5, SHA-1, and others. (see Python documentation). There are also other open source (and in the standard library) tools that can be used to implement many security solutions (see PyCrypto).
  • Open-source: Python’s source code is published for anyone to look at and modify. Having a large community of volunteer programmers greatly enhances the probability of producing bug-minimum code.

Note: this is a re-post from my University of Texas Blog (http://blogs.utexas.edu/zss93/)

Sources:

  1. http://people.cs.ubc.ca/~drifty/papers/python_security.pdf (Very interesting!)
  2. http://us.pycon.org/common/talkdata/PyCon2007/062/PyCon_2007.pdf
  3. http://docs.python.org/howto/webservers.html?highlight=mysql
  4. http://docs.python.org/c-api/memory.html
  5. http://www.pubbs.net/python/200908/1069/
  6. http://docs.python.org/library/crypto.html
  7. http://www.cs.utexas.edu/users/downing/examples/python/ClassVariables.py.html

Written by Zaki

March 30th, 2011 at 8:08 pm

Exploring Python’s map()

without comments

As Dr. Glenn showed us the other day, the performance of map() could be superior to other methods when trying for 100 times to create a list of the square root of 10,000 values. The other methods that competed against map() to comprehend this list were (taken from classpage linked above):

def for_function () :
    l = []
    for v in xrange(s) :
        l.append(math.sqrt(v))
    return l

def list_comprehension_function () :
    return [math.sqrt(v) for v in xrange(s)]

def map_function () :
    return map(math.sqrt, xrange(s))

def generator_function () :
    return list((math.sqrt(v) for v in xrange(s)))

Here are the actual results for running these functions:

"""
Performance.py
2.6.2 (r262:71600, Jul 28 2009, 14:05:43)
[GCC 4.2.2]

for_function
0.82852602005

list_comprehension_function
0.580744028091

map_function
0.353476047516

generator_function
0.658768892288

Done.
"""

I wanted to know why map was faster, so I explored that a little bit. The map() function is faster because it is compiled into C code and then natively ran on the machine. Intuitively this means that it will run faster because we are porting the code to a lower level instead of interpreting it first and running then on a higher abstraction mechanism. The other three methods specified above to construct the equivalent list are only being interpreted and hence will run slower in most cases.

Under Python’s performance wiki (Loops section), I found some documentation about performance and loops:

If the body of your loop is simple, the interpreter overhead of the for loop itself can be a substantial amount of the overhead. This is where themap function is handy. You can think of map as a for moved into C code. The only restriction is that the “loop body” of map must be a function call.

After reading this paragraph above, I have decided to write a little method that uses map but I make map take a lambda:

def map_lambda_function () :
    return map(lambda x:math.sqrt(x), xrange(s))

I ran this against the other functions and I got the results:

Performance.py
2.6.2 (r262:71600, Jul 28 2009, 14:05:43)
[GCC 4.2.2]

for_function
1.85488390923

list_comprehension_function
1.26931381226

map_function
1.26931381226

map_lambda_function
2.04882907867

generator_function
1.48617100716

As shown above, the passing of a lambda (and not a regular function) to map makes it much less faster, and this case it was the slowest of all methods. I hope this will be beneficial to whoever reads it. Peace.

Note: this is a re-post from my University of Texas Blog (http://blogs.utexas.edu/zss93/)

Written by Zaki

March 30th, 2011 at 8:04 pm

My First Application: Sheefra 1.0, A Secure Diary App

without comments

If I am not mistaken, I must have picked up programming when I was in 5th grade. It all started when my dad introduced me to HTML (yes, it was a programming language when I was 10!). Like all typical introductions to new languages, you get to start with an easy part, like a “Hello World!” page. And that’s what we did. I then started marking the text up and coloring it, etc… It was a lot of fun! I was able to create something from nothing, or that’s what I thought anyway.

The days passed by, and I got promoted to 6th grade, at which point I picked up Visual Basic 6. The fact that I was in 6th grade and knew Visual Basic 6 was cool enough for me. Using Visual Basic 6 was a great experience because I got to drag and drop components and see my design as I go.

In seventh grade, I created my first application, Sheefra 1.0! A complete and fully functional application that I used almost on a day-to-day basis to write my diaries and then encrypt them into “secure” text so that no one can read them. We had 2 or 3 computers at that time and everyone shared them, so I had to keep my parents and two brothers off of my diaries. The application worked beautifully.

From what I remember, here’s how it worked. First, you open the application. Second, you authenticate by typing in the username and also password. The password field would actually mask the characters! eeeh?! If the typed password matches the hard-coded password, I was able to gain access to the main window of my application, which looked something like this:

If you type some text in the top box and click encrypt, the application would go through the characters and replace them one by one by a string. Every character mapped to the same string every time. As far as I was concerned, this was security at its best! After encrypting the text, I would click on the File menu, then click Save As… which allowed me to save the encrypted text as a ZAX file (yeah that’s right, I had my own file extension). ZAX files were everywhere in my documents, but no one in my family was able to read them. Man, ZAX files were cool stuff. At a later time, I was able to open a ZAX file and decrypt its contents into plain text.

Side notes:

- Sheefra means cipher in Arabic. That was the name of the application.

- I lost all my ZAX files when my computer crashed. We didn’t have a backup strategy at home. There were some cool thoughts back then.

Written by Zaki

March 25th, 2011 at 10:40 pm

For loops to load params: Don’t do it!

without comments

I have seen code like the block below. If you are a programmer, please do not do this. There’s no need for a for-loop in this situation. In my opinion, the switch statement and the for-loop add more confusion than benefit (if there’s a benefit for such code). This block of code should be replaced by 4 inner if-statements and an outer if-statement that checks for the number of arguments passed into the program.

public static void main (String [] args){
    String url, user, password, fileName;
    for (int i = 0; i < args.length; i++) {
        switch (i) {
        case 0: // Server URL
            url = args[i];
            break;
        case 1: // User name
            user = args[i];
            break;
        case 2: // Password
            password = args[i];
            break;
        case 3: // File to read application config
            fileName = args[i];
            break;
        default:
        }
    }
}

Written by Zaki

March 8th, 2011 at 12:47 am

WordPress keeps logging me out: possible solution

with 2 comments

I have seen that this is a common problem with WordPress. A lot of people out there have been complaining about their WordPress logging them out when they are about to post, publish, edit, etc… I faced the same problem until I solved it an hour ago. Let me describe my solution:

  • I have WordPress installed on main directory of zakisaadeh.com.
  • When I used to log in, I used https, not http to encrypt my credentials and authentication session id (as in https://www.zakisaadeh.com/wp-admin). Under the Settings –>General: WordPress address (URL) was set to http://www.zakisaadeh.com and Site address (URL) was set to the same thing.
  • Since I don’t have time to look at the WordPress code and figure out what the problem is, I assumed that the problem resides in a mechanism (feature) from WordPress which prevents the user from leaking information by jumping from https to http. From a security perspective, this could result in leaking the user’s credentials or session authentication id (since the user is moving from an encrypted medium to an unencrypted one while still sending sensitive info like his/her credentials). To avoid this leakage, WordPress seems to log out automatically when this scenario is triggered. Nice feature!

To solve this problem there are two things you can do:

  1. Go toSettings –>General and set both the WordPress address (URL) and Site address (URL) to http://www.yoursite.com and always login via http://www.yoursite.com/wp-admin. This configuration will allow your credentials to be sent in the clear.
  2. OR you can upgrade and use the more secure approach and set both of these fields above to use https://www.yoursite.com and login via: https://www.yoursite.com/wp-admin. This is a more secure configuration and will force your private information to remain hidden from potential eavesdroppers.

Final note: Do not set either WordPress address (URL) or Site address (URL) to use different protocols. They should either use https or http but not one https and the other http.

Written by Zaki

March 8th, 2011 at 12:39 am

Posted in Everyday,Fix,Security

Tagged with , ,

Useless Alerts and Messages: Nelnet.com

with one comment

I have an outstanding college loan that I manage through nelnet.com. Nelnet sends me email alerts every month to inform me that my statement is ready to be viewed. That’s great, except for the fact that their alerts are useless. How useless are we talking about? Well, if the intention behind these alerts is to get me to check my outstanding balances (and perhaps pay it), then they have miserably failed. Nelnet, get a new marketing executive please! These alerts have failed to make me check my balance 100% of the time. Let me talk a little about these emails I get. First of all, the sender’s name is “onlinenotice”. What a catchy and important name! How am I supposed to attach any degree importance to an email sent from “onlinenotice”? Secondly, the subject line is always “Your statement will be available online within 24 hours”. There are two things that I want to emphasize regarding this subject line. After reading this line, I am still uncertain of who’s talking to me; Mention your company’s name for gawd’s sake!  Second point, why don’t you just tell me when my statement is actually ready? Do you think that I am going to check my statement in 24 hours? Just send me the stupid alert after your archaic system prepares my balance sheet. What ends up happening is that I always forget to go back and check my balance later. Their marketing system failed at making me do what its supposed to do. The system is broken.

Written by Zaki

February 22nd, 2011 at 10:38 pm