Thứ Ba, 2 tháng 7, 2013

Zend_Queue simple example for offline processing


1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
28
29
3031
32
33
34
3536
37
38
39
4041
42
43
44
4546
47
48
49
5051
52
53
54
5556
57
58
59
6061
62
63
64
6566
67
68
69
7071
72
73
74
7576
77
78
79
8081
82
83
84
8586
87
88
89
9091
92
93
94
9596
97
98
99
100101
102
103
104
105106
107
108
109
110111
112
113
114
115116
117
118
119
120121
122
123
124
125126
127
128
129
130131
132
133
134
135136
137
138
139
140141
142
143
144
145146
147
148
## Adapted class
<?php
/**
 * Zend_Queue offline processing hack example
 * * @author      Dave Marshall 
 * @version     $Rev: $
 * @since       $Date: $
 * @link        $URL: $
 */class EmailSender {
 
    private static $queue = null;
 
    /**     * Set Queue
     *
     * @param Zend_Queue $queue
     */
    public static function setQueue($queue)    {
        self::$queue = $queue;
    }
 
    /**     * Takes an array of addresses and sends an email to each one.
     *
     * @see reallySendEmail
     * @see sendQueuedEmails
     * @param array $address     */
    public static function sendEmail($address)
    {
        if (self::$queue === null) {
            // just send them now if we don't have a queue instance            return self::reallySendEmail($address);
        }
 
        self::$queue->send(serialize(func_get_args()));
    } 
    /**
     * Takes an array of addresses and sends an email to each one.
     *
     * @see sendEmail     * @param array $address
     */
    private static function reallySendEmail($address)
    {
        /**         * Code in here
         */
        echo 'Sending email to ' . implode(', ', $address) . PHP_EOL;
    }
     /**
     * Reads emails from the queue and sends them
     *
     * @param int $count - The number of queued items to process
     */    public static function sendQueuedEmails($count)
    {
        /**
         * Should really check the queue is good here
         */ 
        $messages = self::$queue->receive(intval($count));
        foreach($messages as $msg) {
            $args = unserialize($msg->body);
            call_user_func_array(array(__CLASS__, 'reallySendEmail'), $args);            self::$queue->deleteMessage($msg);
        }
    }
}
 ## Usage in application code
<?php
 
set_include_path(
    'path/to/zend/framework' . PATH_SEPARATOR    . 'path/to/zend/framework/incubator' . PATH_SEPARATOR
    . get_include_path()
);
 
require_once "Zend/Loader.php";Zend_Loader::registerAutoload();
 
define('DB_SERVER', 'localhost');
define('DB_PORT', 3306);
define('DB_USER', 'root');define('DB_PASS', 'password');
define('DB_NAME', 'emailsender');
 
$config = array(
    'name' => 'transmittal',    'driverOptions' => array(
        'host'     => DB_SERVER,
        'port'     => DB_PORT,
        'username' => DB_USER,
        'password' => DB_PASS,        'dbname'   => DB_NAME,
        'type'     => 'pdo_mysql'
    )
);
 // Create a database queue
$queue = new Zend_Queue('Db', $config);
$queue->createQueue('myqueue'); // called for good measure
 
EmailSender::setQueue($queue);EmailSender::sendEmail(array('yourname@gmail.com'));
 
## Usage for crontab script
<?php
 set_include_path(
    'path/to/zend/framework' . PATH_SEPARATOR
    . 'path/to/zend/framework/incubator' . PATH_SEPARATOR
    . get_include_path()
); 
require_once "Zend/Loader.php";
Zend_Loader::registerAutoload();
 
define('DB_SERVER', 'localhost');define('DB_PORT', 3306);
define('DB_USER', 'root');
define('DB_PASS', 'password');
define('DB_NAME', 'emailsender');
 $config = array(
    'name' => 'transmittal',
    'driverOptions' => array(
        'host'     => DB_SERVER,
        'port'     => DB_PORT,        'username' => DB_USER,
        'password' => DB_PASS,
        'dbname'   => DB_NAME,
        'type'     => 'pdo_mysql'
    ));
 
// Create a database queue
$queue = new Zend_Queue('Db', $config);
$queue->createQueue('myqueue'); // called for good measure 
EmailSender::setQueue($queue);
EmailSender::sendQueuedEmails(5);

Đếm thành viên online

Như các ban đã biết hiện nay việc đếm số lượng người truy cập đang được rất nhiều website sử dụng. Tuy nhiên việc đếm có chuẩn xác hay không thì chỉ có người lập trình mới có thể biết rõ được. Vấn đề về lập trình như thế nào thì tôi ko bàn tới, mà chỉ muốn giới thiệu đến các bạn cách để tạo ra một bộ đếm trên website.

Thường thì khi người dùng truy cập vào website sẽ có thông tin về địa chỉ IP và một vài thông tin khác (như thông tin về trình duyệt mà họ sử dụng), sau đó, nếu họ đăng nhập bằng tài khoản thì ta có thêm thông tin về thành viên này.
$username    = empty($_GET['usn'])?$_SERVER['REMOTE_ADDR']:$_GET['usn'];

đoạn code trên tôi giả sử user đăng nhập vào là giá trị được nhập từ URL, $_SERVER['REMOTE_ADDR'] là địa chỉ IP của máy client. Nó có nghĩa là nếu chưa có thông tin về thành viên thì lấy địa chỉ IP của người dùng đó.

Sau đó, chúng ta cần một đoạn mã javascript để request về server thông tin mà ta có được về thành viên này để server xử lý:
var data = {'username':'<?php echo $username?>'};
$(document).ready(function(){
   setInterval(function(){
      $.ajax({
           url: 'counter.php',
            type: 'POST',
            data: {'username':data.username},
            dataType: 'json',
            success: function(data){
            var xhtml = "";
               $('.online').html(data.total);
            $.each(data, function(i, item){
                   if(i != 'total'){
                       xhtml += '<li>'+item+'</li>';
                   }
               });
               $('ul.list').html(xhtml);
         },
         error: function(XMLHttpRequest, textStatus, errorThrown){
               //làm gì nhỉ?
         }
      });
    }, 1000);//Request sau 1s
});

Với đoạn mã trên, nó sẽ request về server (cụ thể là tập tin counter.php) liên tục 1 giây 1 lần, nó gửi thông tin về username, và nhận thông tin phản hồi từ server về số lượng người đang truy cập và danh sách các thành viên đang truy cập, gán vào các thẻ HTML mà ta đã có trước:
<div style="border:1px solid #ccc;padding 10px;width: 79px;">
   Online: <span class="online">&nbsp;</span>
</div>
<div class="olist">List:
   <ul class="list"></ul>       
</div>.

Như vậy, nội dung counter.php cần có những gì?
function Online($params) {
   $folder = 'counter';
   if(!is_dir($folder)) mkdir($folder, 0777);   // Tạo thư mục counter nếu chưa có
 
   //Tạo file khi có thành viên mới 
   //$visiter = md5($params['user']);//mã hóa filename
   $filename = $folder.'/'.$params['user'].'.onl';
   $f = fopen($filename, "w");
   fwrite($f, '');
   fclose($f);
 
 
   $online = array();
   $online['total'] = 0;
   $current_time = time();
   $timeout = 5;//60 = 1 minute => đếm trong vòng 5s

   //Load danh sách các file đã được tạo
   $flist = scandir($folder); 
   foreach($flist as $num => $file) {
      $filer = $folder.'/'.$file;
      if(substr($filer, strrpos($filer, '.') + 1) == 'onl') {
         $ftime = filemtime($filer);       
         if ($current_time - $ftime > $timeout)   unlink($filer);// Xóa file
         else{
            $online[] = preg_replace("#\.onl#","",$file);
            $online['total']++;
         }
   }   }
   return $online;
}
$params = array('user'=>$_POST['username']);
$result = Online($params);
echo json_encode($result);

Hàm Online nhận một tham số $params có chứa giá trị là thông tin người truy cập, trả về số lượng người đang truy cập cùng với danh sách những thành viên đang truy cập.
Hàm này tạo ra một file với tên là tên của thông tin thành vên đó, sau đó nó lấy toàn bộ các file trong thư mục counter, kiểm tra các file đã hết hạn để xóa nó đi, nếu chưa hết hạn thì tiến hành đếm và lấy thông tin các thành viên khác

Sau khi hoàn tất xử lý, ta dùng hàm json_encode mà PHP hỗ trợ sẵn để tạo đối tượng chứa thông tin trên, gửi về cho client.

Set Permission - Linux and Unix chmod command

About chmod
Changes the permission of a file.
Syntax
chmod [OPTION]... MODE[,MODE]... FILE...
chmod [OPTION]... OCTAL-MODE FILE...
chmod [OPTION]... --reference=RFILE FILE...
-c, --changeslike verbose but report only when a change is made
--no-preserve-rootdo not treat `/' specially (the default)
--preserve-rootfail to operate recursively on `/'
-f, --silent, --quietsuppress most error messages
-v, verboseoutput a diagnostic for every file processed
--reference=RFILEuse RFILE's mode instead of MODE values
-R, --recursivechange files and directories recursively
--helpdisplay this help and exit
--versionoutput version information and exit
Permissions
u - User who owns the file.
g - Group that owns the file.
o - Other.
a - All.
r - Read the file.
w - Write or edit the file.
x - Execute or run the file as a program.
Numeric Permissions: 
CHMOD can also to attributed by using Numeric Permissions:
400 read by owner
040 read by group
004 read by anybody (other)
200 write by owner
020 write by group
002 write by anybody
100 execute by owner
010 execute by group
001 execute by anybody
Examples
The above numeric permissions can be added to set a certain permission, for example, a common HTML file on a Unix or Linux server accessible over the Internet would be given the below permissions.
chmod 644 file.htm
This gives the file read/write by the owner and only read by everyone else (-rw-r--r--).
Files such as scripts that need to be executed need more permissions. Below is another example of a common permission given to scripts.
chmod 755 file.cgi
This would be the following 400+040+004+200+100+010+001 = 755 where you are giving all the rights except the capability for anyone to write to the file.cgi file(-rwxr-xr-x).
chmod 666 file.txt
Finally, another common CHMOD permission is 666, as shown below, which is read and write by everyone.
Tip: The above commands are all done through the command line. However, if you upload a file using FTP these permissions can also be adjusted through many FTP clients by right-clicking the file and choosing permissions.
Additional information
Below is an example of how a file may be listed when typing ( ls -l ) at the prompt as well as information on how to interpret it.
-rw-rw-r-- 1   hope 123   Feb 03 15:36   file.txt
-rwrw-r--1hope123Feb 03 15:36file.txt
Fileownergroupeveryone elselinksownersizemod datefile name
AND MORE

What is chmod?

chmod stands for change mode, which changes the file or directory mode bits. To put it simply, use chmod command to change the file or directory permissions.
Following is a sample of ls -l command output. In this, the 9 characters from 2nd to 10th position represents the permissions for the 3 types of users.
-rw-r--r--  1 john john  272 Mar 17 08:22 test.txt
In the above example:
  • User (john) has read and write permission
  • Group has read permission
  • Others have read permission
Three file permissions:
  • read: permitted to read the contents of file.
  • write: permitted to write to the file.
  • execute: permitted to execute the file as a program/script.
Three directory permissions:
  • read: permitted to read the contents of directory ( view files and sub-directories in that directory ).
  • write: permitted to write in to the directory. ( create files and sub-directories in that directory )
  • execute: permitted to enter into that directory.
Numeric values for the read, write and execute permissions:
  • read 4
  • write 2
  • execute 1
To have combination of permissions, add required numbers. For example, for read and write permission, it is 4+2 = 6.

3 chmod Examples

Give read, write and execute to everybody (user, group, and others)

read, write and execute = 4 + 2 + 1 = 7.
$ chmod 777 file.txt
(or)
$ chmod ugo+rwx file.txt

Give execute privilege to user. Leave other privileges untouched

execute = 1. If you want to just add execute privilege to users and leave all other privileges as it is, do the following.
$ chmod u+x file.txt

Give read, write and execute privileges to group (including all the files in the sub-directories)

Use -R, as shown below to provide the recursive privileges for the directory and sub-directories (including the files in it).
$ chmod -R g+rwx /u01

Syntax and Options

chmod [OPTION]… MODE[,MODE]… FILE…
chmod [OPTION]… OCTAL-MODE FILE…
chmod [OPTION]… –reference=RFILE FILE…
Short OptionLong OptionOption Description
-c–changeslike verbose but report only when a change is made

–no-preserve-rootdo not treat `/’ specially (the default)

–preserve-rootfail to operate recursively on `/’
-f–silent, –quietsuppress most error messages
-v–verboseoutput a diagnostic for every file processed

–reference=RFILEuse RFILE’s mode instead of MODE values
-R–recursivechange files and directories recursively

–helpdisplay this help and exit

–versiooutput version information and exit

Related Commands


Thứ Hai, 1 tháng 7, 2013

Using Microdata to Markup Structured Data in Your Web Pages and Improve SEO

http://www.ibm.com/developerworks/vn/library/12/x-drupalhtml5/


1. http://www.htmlgoodies.com/html5/Web-Developer-Tutorial-HTML5-Microdata-3920016.htm#fbid=X35M7CEIDnb
2. http://www.entrepreneur.com/article/223074
3. http://blog.teamtreehouse.com/using-microdata-to-markup-structured-data
4. http://html5doctor.com/microdata/#tools
5. https://support.google.com/webmasters/answer/99170?hl=en
6. https://support.google.com/webmasters/answer/176035
7. http://diveintohtml5.info/extensibility.html

Install Drupal

Cài đặt Drupal 7

* Tải về mã nguồn Drupal 7

Thiet ke website

Thiet ke website - Khoi dong voi Drupal 7
Thật vậy, Drupal 7 là một hệ thống quản trị nội dung mã nguồn mở, rất ổn định và mạnh mẽ, được cung cấp miễn phí tại http://drupal.org. Tại đây, bạn bấm vào liên kết Get Start with Drupal để chuyển đến trang tải về Drupal 7.2.

Thiết kế website

Thiet ke website - tải về Drupal 7.2
Tiếp theo, bạn bấm Download Drupal 7.2 và bấm vào liên kết zip (3,01MB) ở phiên bản 7.2. Bạn có thể dùng trình tăng tốc download hoặc tải bằng trình download của Windows.

Thiết kế website - Download

Thiet ke website - download Drupal 7.2
Ngoài ra, bạn có thể tải bản Drupal 7.2 được tích hợp sẵn gói ngôn ngữ tiếng Việt và một số module hữu ích giúp tăng khả năng SEO của Drupal.
Sau khi tải về, bạn giải nén rồi sao chép thư mục drupal-7.2 vào thư mục gốc htdocs của localhost (C:\xampp\htdocs), rồi đổi tên thư mục này lại theo ý thích của bạn, chẳng hạn: news (tên thư mục này được sử dụng cho cả bài viết).

* Cài đặt Drupal 7

Bạn khởi động trình duyệt Mozilla Firefox rồi nhập vào thanh địa chỉ đường dẫn http://localhost/news/install.php(hoặc http://localhost/news/). Quá trình cài đặt Drupal phải trải qua 7 bước. Trong bước đầu tiên Choose profile, bạn sẽ có hai lựa chọn Standard và Minimal. Bạn nên chọn kiểu cài đặt Standard vì nó sẽ giúp bạn cài đặt đầy đủ những tính năng cần thiết cho việc quản lý website, còn kiểu cài đặt Minimal chỉ kích hoạt một số tính năng, bấm Save and continue để tiếp tục.


Thiet ke website

Thiet ke website - Cai dat Drupal 7.2
Đến bước Choose language, mặc định chỉ có duy nhất ô chọn English (built-in). Nếu muốn thêm gói ngôn ngữ khác (ví dụ Tiếng Việt) thì bạn bấm vào liên kết Learn how to install Drupal in other languages để được hướng dẫn cụ thể. Sau khi tải về, bạn hãy sao chép tập tin này vào thư mục C:\xampp\htdocs\info\profiles\standard\translations. Khi đó, ở bước thứ hai này sẽ có thêm lựa chọn Vietnamese (Tiếng Việt). Nhưng để thuận tiện cho việc cài đặt Module sau này thì bạn nên chọn ngôn ngữ English. Khi đã hoàn tất các bước thiết kế thì mới chuyển giao diện về ngôn ngữ Tiếng Việt. Bấm Save and continue để chuyển sang bước tiếp theo.


Thiet ke website


Thiet ke website - Cai dat Drupal 7.2 (tt)
Bước Verify requirements không cần thiết khi cài đặt trên localhost. Nên tiến trình cài đặt tiếp tục chuyển qua bước Set up database. Trong bước này, bạn giữ mặc định ở mục Database type, nhập tên cơ sở dữ liệu vào ô Database name (ví dụ như drupal đã khai báo trong phần 1), nhập root vào ô Database username, để trống ở ô Database password. Riêng đối với mục Advanced Options, bạn có thể thêm tiền tố vào trước các tên bảng trong cơ sở dữ liệu, ví dụ như drupal_, rồi bấm Save and continue.
Khi bước Install profile hoàn tất thì bạn tiến hành khai báo các thông tin liên quan đến website cần tạo, nhưSite name - tên website, Site email address - địa chỉ email nhận thông tin về tình trạng website, Username - tên tài khoản quản trị, Password và Confirm password - mật khẩu.
Ngoài ra còn có một số thiết lập khác: Default country- chọn quốc gia, Default time zone- chọn múi giờ mặc định, Check for updates automatically- kiểm tra cập nhật tự động, Receive e-mail notifications- nhận thông báo qua email, xong bấm Save and continue. Đến bước Finished, quá trình cài đặt đã hoàn tất, bạn bấm vào liên kết Visit your new site để vào trang chủ của website.

3. Làm quen với hệ thống của Drupal 7

Trên thanh công cụ quản trị hệ thống của Drupal có các menu Dashboard- bảng quản lý các tác vụ thường dùng, Content- quản lý nội dung, Structure- quản lý cấu trúc website, Apperance- quản lý giao diện, People- quản lý tài khoản người dùng, Modules- quản lý cài đặt, kích hoạt, phân quyền module, Configuration- cấu hình website, Reports- các báo cáo về tình trạng hệ thống, Help- trợ giúp, Add content- thêm vào bài viết mới,Find content- tìm kiếm bài viết.

Đầu tiên, bạn cần thay đổi một số thông tin cơ bản của website. Bạn vào menu Configuration rồi bấm Site imformation tại khung System. Ở trang hiện ra, bạn có thể thêm vào câu khẩu hiệu tại ô Slogan, sửa tên website tại ô Site nameNumber of posts on front page- chọn số lượng bài viết hiển thị tại trang chủ. Riêng đối với khung Error Pages, bạn có thể tạo trang báo lỗi 404 (báo lỗi trang không tồn tại) để thân thiện người dùng, rồi thêm đường dẫn vào ô Default 404 (not found) page. Khi xong, bạn bấm Save Configuration để thay đổi có hiệu lực.

Để viết bài cho website, bạn bấm Add content trên thanh công cụ, bấm vào liên kết Article ở trang hiện ra. Tiếp theo, bạn nhập tiêu đề bài viết vào ô b, nhập các từ khóa vào ô Tags (các từ khóa này giúp ích quá trình SEO, ngăn cách giữa các từ khóa là dấu phẩy (,), nhập nội dung vào khung Body (khung nhập nội dung này rất đơn giản, không có các công cụ soạn thảo văn bản, bạn có thể sử dụng các thẻ HTML), chọn định dạng văn bản ở trường Text Format.
Bạn bấm nút Browse ở mục Image để chèn hình ảnh đại diện cho bài viết. Drupal chỉ hỗ trợ các định dạng ảnh png, gif, jpg, jpeg, dung lượng tập tin tải lên không quá 8MB.

Ngoài ra, bạn có thể quy định một số thuộc tính cho bài viết như Menu Settings- đánh dấu chọn vào ô Provide a menu link để tạo menu cho bài viết, Comment settings- mở hoặc đóng tính năng bình luận ở cuối bài viết,Authoring Information- thông tin về tác giả bài viết. Khi viết xong, bạn bấm Save.

Học lập trình web căn bản với PHP

Bài 1: Các kiến thức căn bản Part 1:  https://jimmyvan88.blogspot.com/2012/05/can-ban-lap-trinh-web-voi-php-bai-1-cac.html Part 2:  https://...