Hey, Would you like to work at Home ?? Just click here No need to pay, just register free and activate your account and get data Entry Work at your Home.
Showing posts with label Code. Show all posts
Showing posts with label Code. Show all posts

Tuesday, November 1, 2011

How to use a CIDR netmask to block an IP address range using .htaccess

This article explains why you must sometimes use CIDR netmask notation to ban an IP address range using Apache .htaccess, and how to do it. It is intended to supplement the basic Apache information about mod_access in the documentation at http://httpd.apache.org/docs/1.3/mod/mod_access.html.


An IP address is a 32-bit binary number that uniquely identifies a computer on the internet


32-bit binary is hard to remember : 11000000010000000000000000000000

Decimal notation isn't much easier: 3225419776

So it is usually written like this     : 192.64.0.0


You get this "dotted-quad notation" by breaking the 32 bits into 4 groups of 8 and then converting each group to decimal:


11000000010000000000000000000000
1926400

192.64.0.0


That makes it easier to remember, but it creates problems if you try to use it for calculations.


An IP address contains two pieces of information:



  1. The leftmost binary digits are the unique ID of the network (usually your Internet Service Provider, ISP) through which you are connected to the internet.

  2. The remaining binary digits are your unique ID as an individual user on that network.



The number of leftmost digits used for network ID is not the same for every network. In CIDR notation, the /nn part says how many of the leftmost bits indicate the network.



If the network uses exactly the leftmost 8, 16, or 24 bits for its ID, then the dividing line between network and user falls on one of the period boundaries of the dotted-quad notation, and one of the partial IP notations will work:


.htaccess partial IP addressEquivalent CIDR
deny from 192deny from 192.0.0.0/8
deny from 192.64deny from 192.64.0.0/16
deny from 192.64.0deny from 192.64.0.0/24

Each quad that you don't specify is treated as a wildcard that can take any value from 0 to 255. So the first example bans any IP address that starts with 192., followed by anything.


When to use CIDR notation


If the network doesn't use exactly 8, 16, or 24 bits for the network part of the IP address, the dividing line between network and user does not fall on a period boundary of dotted-quad notation, and you need to use a CIDR netmask.


Example CIDR/netmask:


192.64.0.0/10


This says the base address of the network is 192.64.0.0 and the first 10 bits are the network:


192 64 0 0 = 11000000 01000000 00000000 00000000


192 is the first 8 bits, but two more bits are part of the network ID, too. The 9th bit is 0 and the 10th is 1, and that is where the 64 comes from.


The full range of this network in quad notation is 192.64.0.0 - 192.127.255.255. Note that the 64 in the second position doesn't remain constant. The first 2 bits are always the same, but the righthand 6 will be different for different users.


The simple notations for an .htaccess ban won't work. Why not?



  • deny from 192 would ban the range 192.0.0.0 - 192.255.255.255, which will ban some users that are not coming from this network.

  • deny from 192.64 would ban the range 192.64.0.0 - 192.64.255.255, which is insufficient to ban all the users that are coming from this network.


So the answer is CIDR notation and an .htaccess line that says:


deny from 192.64.0.0/10


This says the base address is 192.64.0.0, and the first 10 bits identify the network (those are always the same for all users who are on that network).


To ban a specific IP range in htaccess



  1. Figure out, from your website access logs or elsewhere, the IP addresses you want to ban. Look them up in a WhoIs database such as http://whois.domaintools.com/.


  2. Determine whether you need to use a CIDR netmask. If the IP address range in the report looks like one of these, with each quad after the leading one(s) showing a rull range of 0-255, then you can use one of the simpler methods:



    192.0.0.0 - 192.255.255.255   -- Use deny from 192

    192.64.0.0 - 192.64.255.255   -- Use deny from 192.64

    192.64.128.0 - 192.64.128.255 -- Use deny from 192.64.128


  3. For anything else, you need CIDR. At Domain Tools, the CIDR netmask is sometimes shown in the report for that IP address, several lines down in the report. If it is, that's all you need. You're ready to create the line in your .htaccess file. Go to Step 5.


  4. If the CIDR wasn't given, you can calculate it yourself with a netmask calculator such as http://jodies.de/ipcalc.



    a) Enter the base (lowest) address. 



    b) You can simply determine the netmask (the /nn part) by trial and error, or you can calculate the minimum size to start with: take the rightmost nonzero quad of the base address and convert it to binary in your head or in Windows Calculator. Find the rightmost "1". The netmask will have to be sufficient to include all of the previous quads (at 8 bits each), plus all the digits in this quad up to its rightmost "1". That's the minimum. But it might include some of the trailing zeroes, too.



    c) Keep using trial and error for the netmask until HostMin and HostMax match the IP address range you saw in the Domain Tools report.



Note that final quads of 0 and 255 are reserved, so:



The calculated HostMin will be nnn.nnn.nnn.1,  not nnn.nnn.nnn.0

The calculated HostMax will be nnn.nnn.nnn.254 not nnn.nnn.nnn.255



The Hosts/Net line tells you how many users this network might have, which can help decide whether you really want to ban the entire range.




  1. Edit your public_html/.htaccess file to add the "deny from" line:




  1. Go to cPanel > File Manager.

  2. Navigate to the file public_html/.htaccess.

  3. Click on its file name (not the icon next to it).

  4. In the upper right corner of the screen, click Edit File.

  5. Make a backup copy: Copy all the text in the file, and save it into a file on your local computer so you can put it back into .htaccess if something goes wrong.

  6. Backup made? Ok, now you can edit the file. On a blank line in a part of the file that is not between HTML-style tags like <tag></tag>, type the line:



    deny from nnn.nnn.nnn.nnn/nn



    Replace the nnn's with the IP/netmask you calculated for this range.



    Further explanation: some lines of your .htaccess file might be contained between tags that look like HTML tags where the opening tag looks like <tag> and the closing tag looks like </tag>. Insert this new line in a part of the file that is not between any of these pairs of tags.



    Depending on what is in your .htaccess, you might need to use your judgment whether to use the order and allow directives that are also provided by mod_access. See the link to Apache at the top of this article for more information. That is beyond the scope of this article, and it will require your judgment. I'd suggest adding only the "deny from" line at first and seeing if it works as expected. What is expected: you can access your website; most other people can, too; when the denied party tries, your logs will show a result code of 403 Forbidden.



Tuesday, August 9, 2011

Magento Template Path Hints For Admin side

If you love template path hints in Magento for quickly figuring out which template file or block you need to edit or override and have a requirement for some admin side coding, you are going to love this.


You might not have thought it was possible to enable template path hints in admin, but it is!


Just run this query:



SQL:



INSERT INTO core_config_data (scope, scope_id, path, value)
VALUES ('default', 0, 'dev/debug/template_hints', 1),
('default', 0, 'dev/debug/template_hints_blocks', 1);





To disable them again, run this query



SQL:


UPDATE core_config_data SET value = 0 WHERE scope = 'default' AND scope_id = 0 AND path ='dev/debug/template_hints'




To enable again run this query



SQL:


UPDATE core_config_data SET value = 1 WHERE scope = 'default' AND scope_id = 0 AND path ='dev/debug/template_hints'




Saturday, October 10, 2009

Back Up and Restore a MySQL Database

Back up From the Command Line (using mysqldump)


If you have shell or telnet access to your web server, you can backup your MySQL data by using the mysqldump command. This command connects to the MySQL server and creates an SQL dump file. The dump file contains the SQL statements necessary to re-create the database. Here is the proper syntax:


$ mysqldump --opt -u [uname] -p[pass] [dbname] > [backupfile.sql]


  • [uname] Your database username

  • [pass] The password for your database (note there is no space between -p and the password)

  • [dbname] The name of your database

  • [backupfile.sql] The filename for your database backup

  • [--opt] The mysqldump option


For example, to backup a database named 'Tutorials' with the username 'root' and with no password to a file tut_backup.sql, you should accomplish this command:


$ mysqldump -u root -p Tutorials > tut_backup.sql

This command will backup the 'Tutorials' database into a file called tut_backup.sql which will contain all the SQL statements needed to re-create the database.


With mysqldump command you can specify certain tables of your database you want to backup. For example, to back up only php_tutorials and asp_tutorials tables from the 'Tutorials' database accomplish the command below. Each table name has to be separated by space.


$ mysqldump -u root -p Tutorials php_tutorials asp_tutorials > tut_backup.sql

Sometimes it is necessary to back up more that one database at once. In this case you can use the --database option followed by the list of databases you would like to backup. Each database name has to be separated by space.


$ mysqldump -u root -p --databases Tutorials Articles Comments > content_backup.sql

If you want to back up all the databases in the server at one time you should use the --all-databases option. It tells MySQL to dump all the databases it has in storage.


$ mysqldump -u root -p --all-databases > alldb_backup.sql

The mysqldump command has also some other useful options:


--add-drop-table: Tells MySQL to add a DROP TABLE statement before each CREATE TABLE in the dump.


--no-data: Dumps only the database structure, not the contents.


--add-locks: Adds the LOCK TABLES and UNLOCK TABLES statements you can see in the dump file.


The mysqldump command has advantages and disadvantages. The advantages of using mysqldump are that it is simple to use and it takes care of table locking issues for you. The disadvantage is that the command locks tables. If the size of your tables is very big mysqldump can lock out users for a long period of time.


Back up your MySQL Database with Compress


If your mysql database is very big, you might want to compress the output of mysqldump. Just use the mysql backup command below and pipe the output to gzip, then you will get the output as gzip file.


$ mysqldump -u [uname] -p[pass] [dbname] | gzip -9 > [backupfile.sql.gz]

If you want to extract the .gz file, use the command below:


$ gunzip [backupfile.sql.gz]

Restoring your MySQL Database


Above we backup the Tutorials database into tut_backup.sql file. To re-create the Tutorials database you should follow two steps:



  • Create an appropriately named database on the target machine

  • Load the file using the mysql command:


$ mysql -u [uname] -p[pass] [db_to_restore] < [backupfile.sql]

Have a look how you can restore your tut_backup.sql file to the Tutorials database.


$ mysql -u root -p Tutorials < tut_backup.sql

To restore compressed backup files you can do the following:


gunzip < [backupfile.sql.gz] | mysql -u [uname] -p[pass] [dbname]

If you need to restore a database that already exists, you'll need to use mysqlimport command. The syntax for mysqlimport is as follows:


mysqlimport -u [uname] -p[pass] [dbname] [backupfile.sql]

Disable the Enter key on HTML form


How to disable the Enter key on HTML form



Normally when you have a form with several text input fields, it is undesirable that the form gets submitted when the user hits ENTER in a field. Some people are pressing the enter key instead of the tab key to get to the next field. They often do that by accident or they are accustomed to terminate field input that way. If a browser regards hitting ENTER in a text input field as a request to submit the form immediately, there is no sure way to prevent that.


Add the below script to the <head> section of your page. The following code disables the enter key so that visitors of your web page can only use the tab key to get to the next field.


<script type="text/javascript">



function stopRKey(evt) {

  var evt = (evt) ? evt : ((event) ? event : null);

  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);

  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}

}



document.onkeypress = stopRKey;



</script>

Wednesday, October 7, 2009

Flash image upload with PHP

Flash Code
System.security.allowDomain("www.tshirtsetc.co.uk");  import flash.net.FileReference;    // The listener object listens for FileReference events.  var listener:Object = new Object();    listener.onSelect = function(selectedFile:FileReference):Void {      upWin._x = 200;    selectedFile.upload("./upload.php");  };    // the file is starting to upload.  listener.onOpen = function(selectedFile:FileReference):Void {    _root.upWin.results_txt.text = String("Uploading " + selectedFile.name + "\n");  };    listener.onHTTPError = function(file:FileReference, httpError:Number):Void {      _root.upWin.results_txt.text = String("HTTPError number: "+httpError +"\nFile: "+ file.name);  }    listener.onIOError = function(file:FileReference):Void {   _root.upWin.results_txt.text = String("IOError: "+ file.name);  }    listener.onSecurityError = function(file:FileReference, errorString:String):Void {      _root.upWin.results_txt.text = String("SecurityError: "+SecurityError+"\nFile: "+ file.name);      }    listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void {   upWin.loadBar._width = Number(bytesLoaded)/Number(bytesTotal)*300;  }    // the file has uploaded  listener.onComplete = function(selectedFile:FileReference):Void {    upWin.results_txt.text = String("Upload finished.\nNow downloading " + selectedFile.name + " to player\n");        if(position_txt.text == String("Front")){    attachMovie("trans", "transHolder", -16161, {_x:150, _y:120});     downloadImage1(selectedFile.name);    }else{    if(position_txt.text == String("Back")){     attachMovie("trans2", "transHolder2", -16162, {_x:450, _y:120});       downloadImage2(selectedFile.name);    }else{    if(position_txt.text == String("LSleeve")){     attachMovie("trans3", "transHolder3", -16163, {_x:150, _y:120});       downloadImage3(selectedFile.name);    }else{    if(position_txt.text == String("RSleeve")){     attachMovie("trans4", "transHolder4", -16164, {_x:450, _y:120});       downloadImage4(selectedFile.name);    }    }    }    }    Itotal_txt.text = Number(3.00);    _root.upWin._x = 2000;  };    var imageFile:FileReference = new FileReference();  imageFile.addListener(listener);     imageMovie.uploadBtn.onPress = uploadImage;  imageMovie.uploadBtn2.onPress = uploadImage;  imageMovie2.uploadBtn3.onPress = uploadImage;  imageMovie2.uploadBtn4.onPress = uploadImage;    // Call the uploadImage() function, opens a file browser dialog.  function uploadImage(event:Object):Void {    imageFile.browse([{description: "Image Files", extension: "*.jpg;*.gif;*.png"}]);  }    // If the image does not download, the event object's total property  // will equal -1. In that case, display am error message  function imageDownloaded(event:Object):Void {    if(event.total == -1) {      _root.upWin.results_txt.text = String("error");        }  }    // show uploaded image in scrollPane  function downloadImage1(file:Object):Void {   transHolder.umbongo.loadMovie("./uploaded/" + file);  }    // show uploaded image in scrollPane  function downloadImage2(file:Object):Void {   transHolder2.umbongo2.loadMovie("./uploaded/" + file);  }    // show uploaded image in scrollPane  function downloadImage3(file:Object):Void {   transHolder3.umbongo3.loadMovie("./uploaded/" + file);  }    // show uploaded image in scrollPane  function downloadImage4(file:Object):Void {   var randomNum:Number = Math.round(Math.random()*(10000-0))+0;   transHolder4.umbongo4.loadMovie("./uploaded/" + file);  }


Server Side - PHP Code
<?php    move_uploaded_file($_FILES['Filedata']['tmp_name'], './uploaded/'.$_FILES['Filedata']['name']);  copy('./uploaded/'.$_FILES['Filedata']['name'], './timeStamped/'.time().$_FILES['Filedata']['name']);    ?>


For more information goto http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001054.html

Monday, October 5, 2009

27 Apache Request Methods for rewritecond in htaccess

Introduction

The Request Method, as supplied in the REQUEST_METHOD meta-variable, identifies the processing method to be applied by the script in producing a response.

The script author can choose to implement the methods most appropriate for the particular application.

If the script receives a request with a method it does not support it SHOULD reject it with an error.


List of the 27 Request Methods Recognized by Apache

  1. GET

  2. PUT

  3. POST

  4. DELETE

  5. CONNECT

  6. OPTIONS

  7. TRACE

  8. PATCH

  9. PROPFIND

  10. PROPPATCH

  11. MKCOL

  12. COPY

  13. MOVE

  14. LOCK

  15. UNLOCK

  16. VERSION_CONTROL

  17. CHECKOUT

  18. UNCHECKOUT

  19. CHECKIN

  20. UPDATE

  21. LABEL

  22. REPORT

  23. MKWORKSPACE

  24. MKACTIVITY

  25. BASELINE_CONTROL

  26. MERGE

  27. INVALID


GET

The GET method indicates that the script should produce a document based on the meta-variable values. By convention, the GET method is ’safe’ and ‘idempotent’ and SHOULD NOT have the significance of taking an action other than producing a document.

The meaning of the GET method may be modified and refined by protocol-specific meta-variables.


POST

The POST method is used to request the script perform processing and produce a document based on the data in the request message-body, in addition to meta-variable values. A common use is form submission in HTML [18], intended to initiate processing by the script that has a permanent affect, such a change in a database.

The script MUST check the value of the CONTENT_LENGTH variable before reading the attached message-body, and SHOULD check the CONTENT_TYPE value before processing it.


HEAD

The HEAD method requests the script to do sufficient processing to return the response header fields, without providing a response message-body. The script MUST NOT provide a response message-body for a HEAD request. If it does, then the server MUST discard the message-body when reading the response from the script.


OPTIONS

The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

Responses to this method are not cacheable.

If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or Transfer-Encoding), then the media type MUST be indicated by a Content-Type field. Although this specification does not define any use for such a body, future extensions to HTTP might use the OPTIONS body to make more detailed queries on the server. A server that does not support such an extension MAY discard the request body.


If the Request-URI is an asterisk (“*”), the OPTIONS request is intended to apply to the server in general rather than to a specific resource. Since a server’s communication options typically depend on the resource, the “*” request is only useful as a “ping” or “no-op” type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 compliance (or lack thereof). If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.


A 200 response SHOULD include any header fields that indicate optional features implemented by the server and applicable to that resource (e.g., Allow), possibly including extensions not defined by this specification. The response body, if any, SHOULD also include information about the communication options. The format for such a body is not defined by this specification, but might be defined by future extensions to HTTP. Content negotiation MAY be used to select the appropriate response format. If no response body is included, the response MUST include a Content-Length field with a field-value of “0″.


The Max-Forwards request-header field MAY be used to target a specific proxy in the request chain. When a proxy receives an OPTIONS request on an absoluteURI for which request forwarding is permitted, the proxy MUST check for a Max-Forwards field. If the Max-Forwards field-value is zero (“0″), the proxy MUST NOT forward the message; instead, the proxy SHOULD respond with its own communication options. If the Max-Forwards field-value is an integer greater than zero, the proxy MUST decrement the field-value when it forwards the request. If no Max-Forwards field is present in the request, then the forwarded request MUST NOT include a Max-Forwards field.


PUT

The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request. If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be given that reflects the nature of the problem. The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return a 501 (Not Implemented) response in such cases.


If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.


The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request — the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI, it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.


A single resource MAY be identified by many different URIs. For example, an article might have a URI for identifying “the current version” which is separate from the URI identifying each particular version. In this case, a PUT request on a general URI might result in several other URIs being defined by the origin server.


HTTP/1.1 does not define how a PUT method affects the state of an origin server.

PUT requests MUST obey the message transmission requirements.

Unless otherwise specified for a particular entity-header, the entity-headers in the PUT request SHOULD be applied to the resource created or modified by the PUT.


DELETE

The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.

A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.

If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.


TRACE

The TRACE method is used to invoke a remote, application-layer loop- back of the request message. The final recipient of the request SHOULD reflect the message received back to the client as the entity-body of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive a Max-Forwards value of zero (0) in the request (see section 14.31). A TRACE request MUST NOT include an entity.


TRACE allows the client to see what is being received at the other end of the request chain and use that data for testing or diagnostic information. The value of the Via header field (section 14.45) is of particular interest, since it acts as a trace of the request chain. Use of the Max-Forwards header field allows the client to limit the length of the request chain, which is useful for testing a chain of proxies forwarding messages in an infinite loop.


If the request is valid, the response SHOULD contain the entire request message in the entity-body, with a Content-Type of “message/http”. Responses to this method MUST NOT be cached.


CONNECT

This specification reserves the method name CONNECT for use with a proxy that can dynamically switch to being a tunnel e.g. SSL tunneling.

Wednesday, September 2, 2009

PHP Fatal error : Out of memory Problem

PHP Fatal error: Out of memoryProblem. Let see how to solve this problem using various techniques.


The first thing I could think of was to restart the Apache httpd service. This immediately solved the issue. but I knew this is not a permanent fix for the issue. When I researched further, I got to know that the
error comes when certain PHP scripts require more memory than PHP was allowed by default.


So the solution is to increase the memory allocated for

PHP. How to do that? There are 4 possible ways -


1. Try looking for the php.ini file. You might find some redundant php.ini files, so make sure you have got the one which is actually being read by PHP. o be sure, create a new php file in your root folder, say “check.php” and have phpInfo(); within the php open and close tags. Execute this file to get the information on where the php.ini is residing. Normally it will be in /usr/local/lib/php.ini


Open the php.ini file in a text editor like TextPad (not in Notepad) and change the values for memory_limit. By default you should see memory_limit = 8M. Try changing it to 12M. If it doesn’t work, increase it to 16M or even 24M and so on.


2. In case you can’t find the php.ini file or do not have access to it, then open up the file which was throwing the error (test.php in my case) and add a line below just after ini_set(’memory_limit’, lsquo;12M’);


3. You can even consider adding a line in .htaccess file which will resolve the issue.
php_value memory_limit 32M


4. Or else, Try adding this line to your wp-config.php file:

Increasing memory allocated to PHP
define('WP_MEMORY_LIMIT', '32M');


If none of the above things solve your issue, then talk to you host.


Note: I am now worrying on which PHP script required an increase in memory allocation. The analysis won’t be so easy though.

Wednesday, June 10, 2009

Protecting Script using SQL injection For MySQL with PHP

If you are running a dynamic website coded in PHP, chances are you'll be using
MySQL for storing content or information.


MySQL is very well suited for running anything from small personal websites to large corporate
systems, as it is both simple to use and scalable.  However, it is easy to overlook potential
security problems, especially if you don't have much experience.


Example


For instance, you may have a login script for a secure page of your site:



<?php

    
# Database connection code here



    
$result=mysql_query('select * from users where

    user="'
.$_POST['username'].'" and pass="'.$_POST['password'].'"');



    if(
mysql_num_rows($result)==0):

        
# Username or password incorrect

        
exit;

    endif;



    
# Send user protected page

?>



So for instance, if somebody sent " or ""=" for the username and the password,
the SQL query sent to the database would read: select * from users where user="" or
""="" and pass="" or ""=""
, which would allow access to the protected page without a
valid username or password.  This method is called SQL Injection.


Escaping


To prevent this from happening, the data provided by the user need to be 'escaped' - this means
putting backslashes in front of quotes, backslashes and other special characters.


This means that the MySQL engine will recognise that the quotes are part of the string, which
prevents SQL injection.


PHP has a built in function that is intended for escaping strings, called addslashes().


For instance, passing the form data from our example through addslashes would result in select * from users where user="\" or \"\"=\""
and pass="\" or \"\"=\""
being passed to the database, which can
be correctly interpreted by MySQL.


Magic Quotes


PHP has a feature called 'Magic Quotes', which automatically escapes get, post and cookie data, as if
addslashes had been called on them.  The idea of this is to prevent scripts written by
inexperienced coders being vulnerable to SQL injection.


However, there are several problems with this feature:



  • Addslashes doesn't escape data exactly right for MySQL databases. (The MySQL function
    MySQL_real_escape_string() should really be used instead)

  • Magic quotes can give programmers a false sense of security, and makes scripts completely
    vulnerable if the option is turned off.

  • It has the irritating side effect that form inputs used in other parts of scripts have slashes added to
    them, which can be very puzzling for beginners, and adds extra coding to remove them again.


Because of these reasons, magic quotes are turned off by default in PHP 5, although they are on
by default in PHP 4.


Best Practice

To keep your code portable and protected against vulnerabilities whether Magic Quotes is enabled or not,
it is best to use a function similar to the one below:



<?php

    
function proper_escape($datastring) {

        
# Strip slashes if data has already been escaped by magic quotes

        
if(get_magic_quotes_gpc()):

            
$datastring=stripslashes($datastring);

        endif;



        
# Escape string properly & return

        
return mysql_real_escape_string($datastring);

    }

?>


Call this when sending input data to the MySQL database like: proper_escape($_POST['username']).


Wednesday, November 26, 2008

Date Diffrence In Days

Introduction

This code will give you the diffrence between the two dates in days.Some time it is required in the program to get diff. between two dates.It is so small and very efficient code.

//


// Any source code blocks look like this

//


t1="10/10/2006" ;

t2="15/10/2006";


//Total time for one day

var one_day=1000*60*60*24;

//Here we need to split the inputed dates to convert them into standard format

for furter execution
var x=t1.split("/");
var y=t2.split("/");
//date format(Fullyear,month,date)


var date1=new Date(x[2],(x[1]-1),x[0]);

var date2=new Date(y[2],(y[1]-1),y[0])
var month1=x[1]-1;
var month2=y[1]-1;

//Calculate difference between the two dates, and convert to days



_Diff=Math.ceil((date2.getTime()-date1.getTime())/(one_day));
//_Diff gives the diffrence between the two dates.





Friday, August 22, 2008

Mod Rewrite Tips and Examples

For example, to limit the next 5 RewriteRules to only be applied to .html and .php files, you can use the following code, which tests if the url does not end in .html or .php and if it doesn’t, it will skip the next 5 RewriteRules.



RewriteRule !\.(html|php)$ - [S=5]

RewriteRule ^.*-(vf12|vf13|vf5|vf35|vf1|vf10|vf33|vf8).+$ - [S=1]



.htaccess rewrite examples should begin with:


Options +FollowSymLinks



RewriteEngine On

RewriteBase /


Require the www


Options +FollowSymLinks

RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} !^www\.askapache\.com$ [NC]

RewriteRule ^(.*)$ http://www.askapache.com/$1 [R=301,L]


Loop Stopping Code


Sometimes your rewrites cause infinite loops, stop it with one of these rewrite code snippets.


RewriteCond %{REQUEST_URI} ^/(stats/|missing\.html|failed_auth\.html|error/).* [NC]

RewriteRule .* - [L]



RewriteCond %{ENV:REDIRECT_STATUS} 200

RewriteRule .* - [L]


Cache-Friendly File Names


This is probably my favorite, and I use it on every site I work on. It allows me to update my javascript and css files in my visitors cache’s simply by naming them differently in the html, on the server they stay the same name. This rewrites all files for /zap/j/anything-anynumber.js to /zap/j/anything.js and /zap/c/anything-anynumber.css to /zap/c/anything.css


RewriteRule ^zap/(j|c)/([a-z]+)-([0-9]+)\.(js|css)$ /zap/$1/$2.$4 [L]



SEO friendly link for non-flash browsers


When you use flash on your site and you properly supply a link to download flash that shows up for non-flash aware browsers, it is nice to use a shortcut to keep your code clean and your external links to a minimum. This code allows me to link to site.com/getflash/ for non-flash aware browsers.


RewriteRule ^getflash/?$ http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash [NC,L,R=307]



Removing the Query_String


On many sites, the page will be displayed for both page.html and page.html?anything=anything, which hurts your SEO with duplicate content. An easy way to fix this issue is to redirect external requests containing a query string to the same uri without the query_string.


RewriteCond %{THE_REQUEST} ^GET\ /.*\;.*\ HTTP/

RewriteCond %{QUERY_STRING} !^$

RewriteRule .* http://www.askapache.com%{REQUEST_URI}? [R=301,L]


Sending requests to a php script


This .htaccess rewrite example invisibly rewrites requests for all Adobe pdf files to be handled by /cgi-bin/pdf-script.php


RewriteRule ^(.+)\.pdf$ /cgi-bin/pdf-script.php?file=$1.pdf [L,NC,QSA]


Setting the language variable based on Client


For sites using multiviews or with multiple language capabilities, it is nice to be able to send the correct language automatically based on the clients preferred language.


RewriteCond %{HTTP:Accept-Language} ^.*(de|es|fr|it|ja|ru|en).*$ [NC]

RewriteRule ^(.*)$ - [env=prefer-language:%1]



Deny Access To Everyone Except PHP fopen


This allows access to all files by php fopen, but denies anyone else.


RewriteEngine On

RewriteBase /

RewriteCond %{THE_REQUEST} ^.+$ [NC]

RewriteRule .* - [F,L]


Deny access to anything in a subfolder except php fopen


This can be very handy if you want to serve media files or special downloads but only through a php proxy script.


RewriteEngine On

RewriteBase /

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+)/.*\ HTTP [NC]

RewriteRule .* - [F,L]


Require no www


Options +FollowSymLinks

RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} !^askapache\.com$ [NC]

RewriteRule ^(.*)$ http://askapache.com/$1 [R=301,L]


Check for a key in QUERY_STRING


Uses a RewriteCond Directive to check QUERY_STRING for passkey, if it doesn’t find it it redirects all requests for anything in the /logged-in/ directory to the /login.php script.


RewriteEngine On

RewriteBase /

RewriteCond %{QUERY_STRING} !passkey

RewriteRule ^/logged-in/(.*)$ /login.php [L]


Removes the QUERY_STRING from the URL


If the QUERY_STRING has any value at all besides blank than the?at the end of /login.php? tells mod_rewrite to remove the QUERY_STRING from login.php and redirect.


RewriteEngine On

RewriteBase /

RewriteCond %{QUERY_STRING} .

RewriteRule ^login.php /login.php? [L]


Fix for infinite loops


An error message related to this isRequest exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.or you may seeRequest exceeded the limit,probable configuration error,Use 'LogLevel debug' to get a backtrace, orUse 'LimitInternalRecursion' to increase the limit if necessary


RewriteCond %{ENV:REDIRECT_STATUS} 200

RewriteRule .* - [L]


External Redirect .php files to .html files (SEO friendly)


RewriteRule ^(.*)\.php$ /$1.html [R=301,L]


Internal Redirect .php files to .html files (SEO friendly)


Redirects all files that end in .html to be served from filename.php so it looks like all your pages are .html but really they are .php


RewriteRule ^(.*)\.html$ $1.php [R=301,L]



block access to files during certain hours of the day


Options +FollowSymLinks

RewriteEngine On

RewriteBase /

# If the hour is 16 (4 PM) Then deny all access

RewriteCond %{TIME_HOUR} ^16$

RewriteRule ^.*$ - [F,L]



Rewrite underscores to hyphens for SEO URL


Converts all underscores “_” in urls to hyphens “-” for SEO benefits… See the full article for more info.


Options +FollowSymLinks

RewriteEngine On

RewriteBase /



RewriteRule !\.(html|php)$ - [S=4]

RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5 [E=uscor:Yes]

RewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4 [E=uscor:Yes]

RewriteRule ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3 [E=uscor:Yes]

RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=uscor:Yes]



RewriteCond %{ENV:uscor} ^Yes$

RewriteRule (.*) http://d.com/$1 [R=301,L]



Require the www without hardcoding


Options +FollowSymLinks

RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} !^www\.[a-z-]+\.[a-z]{2,6} [NC]

RewriteCond %{HTTP_HOST} ([a-z-]+\.[a-z]{2,6})$ [NC]

RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]



Require no subdomain


RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} \.([a-z-]+\.[a-z]{2,6})$ [NC]

RewriteRule ^/(.*)$ http://%1/$1 [R=301,L]


Require no subdomain


RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} \.([^\.]+\.[^\.0-9]+)$

RewriteRule ^(.*)$ http://%1/$1 [R=301,L]



Redirecting Wordpress Feeds to Feedburner


Full article:Redirecting Wordpress Feeds to Feedburner


RewriteEngine On

RewriteBase /

RewriteCond %{REQUEST_URI} ^/feed\.gif$

RewriteRule .* - [L]



RewriteCond %{HTTP_USER_AGENT} !^.*(FeedBurner|FeedValidator) [NC]

RewriteRule ^feed/?.*$ http://feeds.feedburner.com/apache/htaccess [L,R=302]



RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . /index.php [L]



Only allow GET and PUT Request Methods


Article: Request Methods


RewriteEngine On

RewriteBase /

RewriteCond %{REQUEST_METHOD} !^(GET|PUT)

RewriteRule .* - [F]


Prevent Files image/file hotlinking and bandwidth stealing


RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_REFERER} !^$

RewriteCond %{HTTP_REFERER} !^http://(www\.)?askapache.com/.*$ [NC]

RewriteRule \.(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]


Stop browser prefetching


RewriteEngine On

SetEnvIfNoCase X-Forwarded-For .+ proxy=yes

SetEnvIfNoCase X-moz prefetch no_access=yes



# block pre-fetch requests with X-moz headers

RewriteCond %{ENV:no_access} yes

RewriteRule .* - [F,L]


Make a prefetching hint for Firefox.


Header append Link "

</index.htm>

; rel=prefetch"


This module uses a rule-based rewriting engine (based on a regular-expression parser) to rewrite requested URLs on the fly. It supports an unlimited number of rules and an unlimited number of attached rule conditions for each rule, to provide a really flexible and powerful URL manipulation mechanism. The URL manipulations can depend on various tests, of server variables, environment variables, HTTP headers, or time stamps. Even external database lookups in various formats can be used to achieve highly granular URL matching.


This module operates on the full URLs (including the path-info part) both in per-server context (httpd.conf) and per-directory context (.htaccess) and can generate query-string parts on result. The rewritten result can lead to internal sub-processing, external request redirection or even to an internal proxy throughput.


Further details, discussion, and examples, are provided in the detailed mod_rewrite documentation.

Friday, June 13, 2008

PDF Protection

Informations


Author: Klemen Vodopivec

License: Freeware

Description


This script allows to protect the PDF, that is to say prevent people from copying its content, print it or modify it.



SetProtection([array permissions [, string user_pass [, string owner_pass]]])



permissions: the set of permissions. Empty by default (only viewing is allowed).

user_pass: user password. Empty by default.

owner_pass: owner password. If not specified, a random value is used.



The permission array is composed of values taken from the following ones:




  • copy: copy text and images to the clipboard

  • print: print the document

  • modify: modify it (except for annotations and forms)

  • annot-forms: add annotations and forms


Remark: the protection against modification is for people who have the full Acrobat product.



If you don't set any password, the document will open as usual. If you set a user password, the PDF viewer will ask for it before displaying the document. The master password, if different from the user one, can be used to get full access.



Note: protecting a document requires to encrypt it, which increases the processing time a lot. This can cause a PHP time-out in some cases, especially if the document contains images or fonts.

Source








<?php

/****************************************************************************

* Software: FPDF_Protection                                                 *

* Version:  1.02                                                            *

* Date:     2005/05/08                                                      *

* Author:   Klemen VODOPIVEC                                                *

* License:  Freeware                                                        *

*                                                                           *

* You may use and modify this software as you wish as stated in original    *

* FPDF package.                                                             *

*                                                                           *

* Thanks: Cpdf (http://www.ros.co.nz/pdf) was my working sample of how to   *

* implement protection in pdf.                                              *

****************************************************************************/



require('fpdf.php');



class FPDF_Protection extends FPDF

{

    var $encrypted;          //whether document is protected

    var $Uvalue;             //U entry in pdf document

    var $Ovalue;             //O entry in pdf document

    var $Pvalue;             //P entry in pdf document

    var $enc_obj_id;         //encryption object id

    var $last_rc4_key;       //last RC4 key encrypted (cached for optimisation)

    var $last_rc4_key_c;     //last RC4 computed key



    function FPDF_Protection($orientation='P',$unit='mm',$format='A4')

    {

        parent::FPDF($orientation,$unit,$format);



        $this->encrypted=false;

        $this->last_rc4_key='';

        $this->padding="\x28\xBF\x4E\x5E\x4E\x75\x8A\x41\x64\x00\x4E\x56\xFF\xFA\x01\x08".

                        "\x2E\x2E\x00\xB6\xD0\x68\x3E\x80\x2F\x0C\xA9\xFE\x64\x53\x69\x7A";

    }



    /**

    * Function to set permissions as well as user and owner passwords

    *

    * - permissions is an array with values taken from the following list:

    *   copy, print, modify, annot-forms

    *   If a value is present it means that the permission is granted

    * - If a user password is set, user will be prompted before document is opened

    * - If an owner password is set, document can be opened in privilege mode with no

    *   restriction if that password is entered

    */

    function SetProtection($permissions=array(),$user_pass='',$owner_pass=null)

    {

        $options = array('print' => 4, 'modify' => 8, 'copy' => 16, 'annot-forms' => 32 );

        $protection = 192;

        foreach($permissions as $permission){

            if (!isset($options[$permission]))

                $this->Error('Incorrect permission: '.$permission);

            $protection += $options[$permission];

        }

        if ($owner_pass === null)

            $owner_pass = uniqid(rand());

        $this->encrypted = true;

        $this->_generateencryptionkey($user_pass, $owner_pass, $protection);

    }



/****************************************************************************

*                                                                           *

*                              Private methods                              *

*                                                                           *

****************************************************************************/



    function _putstream($s)

    {

        if ($this->encrypted) {

            $s = $this->_RC4($this->_objectkey($this->n), $s);

        }

        parent::_putstream($s);

    }



    function _textstring($s)

    {

        if ($this->encrypted) {

            $s = $this->_RC4($this->_objectkey($this->n), $s);

        }

        return parent::_textstring($s);

    }



    /**

    * Compute key depending on object number where the encrypted data is stored

    */

    function _objectkey($n)

    {

        return substr($this->_md5_16($this->encryption_key.pack('VXxx',$n)),0,10);

    }



    /**

    * Escape special characters

    */

    function _escape($s)

    {

        $s=str_replace('\\','\\\\',$s);

        $s=str_replace(')','\\)',$s);

        $s=str_replace('(','\\(',$s);

        $s=str_replace("\r",'\\r',$s);

        return $s;

    }



    function _putresources()

    {

        parent::_putresources();

        if ($this->encrypted) {

            $this->_newobj();

            $this->enc_obj_id = $this->n;

            $this->_out('<<');

            $this->_putencryption();

            $this->_out('>>');

            $this->_out('endobj');

        }

    }



    function _putencryption()

    {

        $this->_out('/Filter /Standard');

        $this->_out('/V 1');

        $this->_out('/R 2');

        $this->_out('/O ('.$this->_escape($this->Ovalue).')');

        $this->_out('/U ('.$this->_escape($this->Uvalue).')');

        $this->_out('/P '.$this->Pvalue);

    }



    function _puttrailer()

    {

        parent::_puttrailer();

        if ($this->encrypted) {

            $this->_out('/Encrypt '.$this->enc_obj_id.' 0 R');

            $this->_out('/ID [()()]');

        }

    }



    /**

    * RC4 is the standard encryption algorithm used in PDF format

    */

    function _RC4($key, $text)

    {

        if ($this->last_rc4_key != $key) {

            $k = str_repeat($key, 256/strlen($key)+1);

            $rc4 = range(0,255);

            $j = 0;

            for ($i=0; $i<256; $i++){

                $t = $rc4[$i];

                $j = ($j + $t + ord($k{$i})) % 256;

                $rc4[$i] = $rc4[$j];

                $rc4[$j] = $t;

            }

            $this->last_rc4_key = $key;

            $this->last_rc4_key_c = $rc4;

        } else {

            $rc4 = $this->last_rc4_key_c;

        }



        $len = strlen($text);

        $a = 0;

        $b = 0;

        $out = '';

        for ($i=0; $i<$len; $i++){

            $a = ($a+1)%256;

            $t= $rc4[$a];

            $b = ($b+$t)%256;

            $rc4[$a] = $rc4[$b];

            $rc4[$b] = $t;

            $k = $rc4[($rc4[$a]+$rc4[$b])%256];

            $out.=chr(ord($text{$i}) ^ $k);

        }



        return $out;

    }



    /**

    * Get MD5 as binary string

    */

    function _md5_16($string)

    {

        return pack('H*',md5($string));

    }



    /**

    * Compute O value

    */

    function _Ovalue($user_pass, $owner_pass)

    {

        $tmp = $this->_md5_16($owner_pass);

        $owner_RC4_key = substr($tmp,0,5);

        return $this->_RC4($owner_RC4_key, $user_pass);

    }



    /**

    * Compute U value

    */

    function _Uvalue()

    {

        return $this->_RC4($this->encryption_key, $this->padding);

    }



    /**

    * Compute encryption key

    */

    function _generateencryptionkey($user_pass, $owner_pass, $protection)

    {

        // Pad passwords

        $user_pass = substr($user_pass.$this->padding,0,32);

        $owner_pass = substr($owner_pass.$this->padding,0,32);

        // Compute O value

        $this->Ovalue = $this->_Ovalue($user_pass,$owner_pass);

        // Compute encyption key

        $tmp = $this->_md5_16($user_pass.$this->Ovalue.chr($protection)."\xFF\xFF\xFF");

        $this->encryption_key = substr($tmp,0,5);

        // Compute U value

        $this->Uvalue = $this->_Uvalue();

        // Compute P value

        $this->Pvalue = -(($protection^255)+1);

    }

}



?>

Example


This example shows how to allow only printing.









<?php

define('FPDF_FONTPATH','font/');

require('fpdf_protection.php');



$pdf=new FPDF_Protection();

$pdf->SetProtection(array('print'));

$pdf->Open();

$pdf->AddPage();

$pdf->SetFont('Arial');

$pdf->Write(10,'You can print me but not copy my text.');

$pdf->Output();

?>



View the result here.

Download


ZIP | TGZ

Tuesday, June 10, 2008

Get metadata on MySQL databases

Getting information about databases if essential if you want to write generic and scalable applications. This code shows you how to get information such as all databases on the server, all tables in each database and all field and field info for each table. Even if you do not need to build on this code, you might want to copy the code which prints out all databases, tables and field information plus examples. Its a great way to get an overview of the tables you are working on for a project.

<?

//getting metadata on MySQL databases



//output the structure of a table

$connection_1 = mysql_connect("localhost");

$fields = mysql_list_fields("cmphp","rights");

for($i=0;$i<mysql_num_fields($fields);$i++) {

   echo mysql_field_name($fields,$i)." (".mysql_field_len($fields,$i).") - ".mysql_field_type($fields,$i)."<br>";

}

mysql_close;



//show the structure of ALL tables in ALL databases on the server

$server_connection_1 = mysql_connect("localhost");

$databases = mysql_query("SHOW DATABASES");

while($database = mysql_fetch_row($databases)) {

   echo '<h2>DATABASE: '.$database[0].'</h2>';

   $database_connection_1 = mysql_select_db($database[0]);

   $tables = mysql_query("SHOW TABLES");

   while($table = mysql_fetch_row($tables)){

       echo '<table border="1" cellpadding="5" width="500">';

       echo '<tr><td colspan="3" bgcolor="silver">TABLE: '.$table[0].'</td></tr>';

       $fields = mysql_list_fields($database[0],$table[0]);

       for($i=0;$i<mysql_num_fields($fields);$i++) {

           echo '<tr>';

           echo '<td>'.mysql_field_name($fields,$i)."</td>";

           echo '<td>'.mysql_field_len($fields,$i)."</td>";

           echo '<td>'.mysql_field_type($fields,$i)."</td>";

           echo '</tr>';

       }

       echo '</table><br>';

   }

}

mysql_close;



//show the nice structure of a particular database

$server_connection_1 = mysql_connect("localhost");

$the_database = "cmphp";

echo '<h2>DATABASE: '.$the_database.'</h2>';

$database_connection_1 = mysql_select_db($the_database);

$tables = mysql_query("SHOW TABLES");

while($table = mysql_fetch_row($tables)){

   echo '<table border="1" cellpadding="5" width="600">';

   echo '<tr><td colspan="4" bgcolor="silver"><b>TABLE: '.$table[0].'</b></td></tr>';

   echo '<tr><td bgcolor="silver">NAME</td><td bgcolor="silver">SIZE</td><td bgcolor="silver">TYPE</td><td bgcolor="silver">EXAMPLE</td></tr>';

   $fields = mysql_list_fields($the_database,$table[0]);

   for($i=0;$i<mysql_num_fields($fields);$i++) {

       echo '<tr>';

       echo '<td>'.mysql_field_name($fields,$i)."</td>";

       echo '<td>'.mysql_field_len($fields,$i)."</td>";

       echo '<td>'.mysql_field_type($fields,$i)."</td>";

       $rows = mysql_query("SELECT ".mysql_field_name($fields,$i)." FROM ".$table[0]." LIMIT 1");

       $row = mysql_fetch_array($rows);

       echo '<td bgcolor="eeeeee">'.$row[0].' </td>';

       echo '</tr>';

   }

   echo '</table><br>';

}

mysql_close;

?>

This Article is taken from http://www.developerfusion.co.uk/show/3945/

Thursday, December 6, 2007

imap.class.php

imap.class.php is used to retrieve email from given mailbox in secure way.

You need to provide hostname,username , password, port
It retrieve email from your mailbox. You are flexible to use this class as you wish.


<?php
/*
+----------------------------------------------------------------------+
| BasiliX - Copyright (C) 2000-2002 Murat Arslan <arslanm@basilix.org> |
| Contributions from: |
| Mike Peters <mike@ice2o.com> |
+----------------------------------------------------------------------+
*/


// IMAP package, this is used to handle imap related functions easier
// -----------------------------------------------------------------------
class IMAP {
var $imapstr = 0;
var $user = "";
var $pass = "";
var $host = "";
var $port = "";

function IMAP() {
// do nothing
}

// create an imap connection
function open($username, $password, $host, $port, $notls = 0) {
if($notls>0)$notls_str="/notls";
$i = @imap_open("{" . $host . ":" . $port . $notls_str . "}INBOX", $username, $password);
if(!$i) return false;
$this->imapstr = $i;
$this->user = $username;
$this->pass = $password;
$this->host = $host;
$this->port = $port;
return true;
}

// close the imap connection

function close() {
if($this->imapstr) imap_close($this->imapstr);
$this->imapstr = 0;
return true;
}

// are we connected?
function ifok() {
if(!$this->imapstr) return false;
return true;
}

// create a mbox
function crtmbox($mbox) {
if(!$this->ifok()) return false;
return imap_createmailbox($this->imapstr, "{" . $this->host . ":" . $this->port . "}" . $mbox);
}

// delete a mbox

function delmbox($mbox) {
if(!$this->ifok()) return false;
return imap_deletemailbox($this->imapstr, "{" . $this->host . ":" . $this->port . "}" . $mbox);
}

// rename a mbox

function renmbox($old, $new) {
if(!$this->ifok()) return false;
return imap_renamemailbox($this->imapstr,
"{" . $this->host . ":" . $this->port . "}" . $old,
"{" . $this->host . ":" . $this->port . "}" . $new);
}

// list the subscribed mboxes in a dir (cyrus/courier)

function lstscrbed($dir) {
if(!$this->ifok()) return false;
return imap_listsubscribed($this->imapstr, "{" . $this->host . ":" . $this->port . "}", $dir);
}

// list the mboxes in a dir
function lstmbox($dir) {
if(!$this->ifok()) return false;
return imap_listmailbox($this->imapstr, "{" . $this->host . ":" . $this->port . "}", $dir);
}

function getmailboxes($dir) {
if(!$this->ifok()) return false;
return imap_getmailboxes($this->imapstr, "{" . $this->host . ":" . $this->port . "}", $dir);
}
function getmboxes($dir) {
$mboxes = $this->getmailboxes($dir);
$i = 0;
$ret = array();
if(empty($mboxes)) return $ret;
while(list($key, $val) = each($mboxes)) {
$delim = $val->delimiter;
$name = imap_utf7_decode($val->name);
$name_arr = explode($delim, $name);
$j = count($name_arr) - 1;
$mbox_name = $name_arr[$j];
if($mbox_name == "") continue; // the DIRECTORY itself

$ret[$i++] = $mbox_name;
}
sort($ret);
return $ret;
}

// reopen the desired mbox (just the name of the mbox)
function reopbox($mbox) {
if(!$this->ifok()) return false;
return imap_reopen($this->imapstr, "{" . $this->host . ":" . $this->port . "}" . $mbox);
}

// reopen the desired mbox (full mbox name should be given as $mbox)

function reopbox2($mbox) {
if(!$this->ifok()) return false;
return imap_reopen($this->imapstr, $mbox);
}

// mailbox info
function mboxinfo() {
if(!$this->ifok()) return false;
return imap_mailboxmsginfo($this->imapstr);
}

// sort the mbox
function mboxsrt($criteria, $reverse) {
if(!$this->ifok()) return false;
return imap_sort($this->imapstr, $criteria, $reverse, SE_NOPREFETCH);
}

// retrieve the header of the message

function msghdr($msgnum) {
if(!$this->ifok()) return false;
return imap_header($this->imapstr, $msgnum);
}

// get the UID of the message
function msguid($msgnum) {
if(!$this->ifok()) return false;
return imap_uid($this->imapstr, $msgnum);
}

// get the NO of the message
function msgno($msguid) {
if(!$this->ifok()) return false;
return imap_msgno($this->imapstr, $msguid);
}

// fetch the structure

function ftchstr($msgnum) {
if(!$this->ifok()) return false;
return imap_fetchstructure($this->imapstr, $msgnum);
}

// fetch the header of the message
function ftchhdr($msgnum) {
if(!$this->ifok()) return false;
return imap_fetchheader($this->imapstr, $msgnum);
}


// delete the specified message
function rmmail($uid) {
if(!$this->ifok()) return false;
$msgno = $this->msgno($uid);
return imap_delete($this->imapstr, $msgno);
}

// move the specifed msg to mbox B

function mvmail($uid, $tombox) {
if(!$this->ifok()) return false;
return imap_mail_move($this->imapstr, $uid, $tombox, CP_UID);
}

// expunge the mailbox
function expng() {
if(!$this->ifok()) return false;
return imap_expunge($this->imapstr);
}

// fetch the body of the message
function ftchbody($msgno, $part) {
if(!$this->ifok()) return false;
return imap_fetchbody($this->imapstr, $msgno, $part, NONE);
}

// set the flags

function setflg($seq, $flg) {
if(!$this->ifok()) return false;
return imap_setflag_full($this->imapstr, $seq, $flg);
}

// search messages
function srch($q) {
if(!$this->ifok()) return false;
return imap_search($this->imapstr, $q, SE_UID);
}

// append to sent mail
function apnd($m, $b) {
if(!$this->ifok()) return false;
return @imap_append($this->imapstr, "{" . $this->host . ":" . $this->port . "}" . $m, $b);
}
}

$imap = new IMAP;

?>


imap2.inc.php

/*
+----------------------------------------------------------------------+
| BasiliX - Copyright (C) 2000-2002 Murat Arslan |
| Contributions from: |
| Mike Peters |
+----------------------------------------------------------------------+
*/
if(empty($_POST['password']) && $_COOKIE['BSX_User'])
{
$username = $_COOKIE['BSX_User'];
$sql = new MySQL;
$sql->open();
$password = $sql->session_getpassword($_COOKIE['BSX_User'], $_COOKIE['BSX_SESSID']);
}
else {
$password = $_POST['password'];
$username = $_POST['username'];
}

$IMAP_DOMAIN = $bsx_domains["$domain"]["domain"];
$IMAP_ISVIRTUAL = $bsx_domains["$domain"]["isvirtual"];
$IMAP_HOST = $bsx_domains["$domain"]["imap_host"];
$IMAP_PORT = $bsx_domains["$domain"]["imap_port"];
$SMTP_HOST = $bsx_domains["$domain"]["smtp_host"];
$IMAP_STYPE = $bsx_domains["$domain"]["imap_stype"];
$IMAP_NOTLS = $bsx_domains["$domain"]["notls"];

// here decide what to do
if($IMAP_STYPE == 3) $BSX_MDIR = "Inbox.";

// virtual or non-virtual connection
if($IMAP_ISVIRTUAL) {
$virtual_username = $username . "@" . $IMAP_DOMAIN;
$imap_ok = imap_connect($virtual_username, $password, $IMAP_HOST, $IMAP_PORT, $IMAP_NOTLS);
} else {
$imap_ok = imap_connect($username, $password, $IMAP_HOST, $IMAP_PORT, $IMAP_NOTLS);
}
if($imap_ok == false) {
if($relogin) {
$incfile = "login-relogin.htx.php";
} else {
$incfile = "login-new.htx.php";
}
$LOGIN_ERR = $lng->p(61);
$BODY_ONLOAD = "onLoad='document.loginForm.password.focus();'";
include("$BSX_HTXDIR/header.htx.php");
include("$BSX_HTXDIR/$incfile");
include("$BSX_HTXDIR/footer.htx.php");
my_exit();
}
?>

compose.inc.php

/*
+----------------------------------------------------------------------+
| BasiliX - Copyright (C) 2000-2002 Murat Arslan |
| Contributions from: |
| Mike Peters |
| Cristofer Algotsson |
| Ch. Thielecke |
+----------------------------------------------------------------------+

*/

// Compose message functions
// -----------------------------------------------------------------------


function push_compose_abook() {
global $RequestID, $lng;
global $BSX_HTXDIR, $BSX_THEMEDIR, $BSX_VERSION;
global $BSX_BASEHREF, $BSX_LAUNCHER;

include("$BSX_HTXDIR/header.htx.php");
include("$BSX_HTXDIR/compose-abook.htx.php");
include("$BSX_HTXDIR/footer.htx.php");
}

function push_compose() {
global $customerID, $RequestID, $sql, $lng;
global $BSX_HTXDIR, $BSX_THEMEDIR, $BSX_VERSION;
global $BSX_BASEHREF, $BSX_LAUNCHER;
global $BSX_SENTMAIL_NAME, $BSX_TRASH_NAME;
global $SESSID, $BODY_ONLOAD;
global $abook_items, $abook_items_cnt;
global $abook_grpitems, $abook_grpitems_cnt;
global $err_msg, $info_msg;
$conf = get_conf();
$is_ssl = $conf['is_ssl'];
$is_js = $conf['is_js'];

// --
global $premail, $cmps_atchs;


global $cmps_from, $cmps_to, $cmps_cc, $cmps_bcc;
global $cmps_subject, $cmps_body, $cmps_atchlist;

global $cmps_f0, $cmps_f1, $cmps_f2; global $cmps_s0, $cmps_s1, $cmps_s2;
global $cmps_c0, $cmps_c1, $cmps_c2;

$user_set = $_COOKIE['user_set'];

$cmps_sign = $user_set["sign"];
if(empty($cmps_from)) $cmps_from = $user_set["name"];

if(empty($cmps_to))
$BODY_ONLOAD="onLoad='document.composeMail.cmps_to.focus();'";

$BODY_ONUNLOAD="onUnLoad='closeWins();'";

$cwurl = $BSX_BASEHREF . "/" . $BSX_LAUNCHER . "?RequestID=CMPSCLNUP" . "&is_js=" . $is_js . "&is_ssl=" . $is_ssl;
if($SESSID) $cwurl .= "&SESSID=" . $SESSID;

if(empty($cmps_atchlist)) $cmps_atchlist = $lng->p(411);

include("$BSX_HTXDIR/header.htx.php");
include("$BSX_HTXDIR/menu.htx.php");
include("$BSX_HTXDIR/compose-new.htx.php");
include("$BSX_HTXDIR/footer.htx.php");
}

function abook_fetch_field($abook_items, $id, $what) {
global $abook_items_cnt;

for($i = 0 ; $i < $abook_items_cnt ; $i++) {
if($abook_items[$i]["id"] == $id) {
return $abook_items[$i]["$what"];
}
}
}

function js_getmembers($memberlist, $abook_items) {
global $abook_items_cnt;

$rstr = "";
$glue = "";
$tmp_arr = explode(",", $memberlist);
for($i = 0 ; $i < count($tmp_arr) ; $i++) {
$idx = $tmp_arr[$i];
$tmp_name = abook_fetch_field($abook_items, $idx, "name");
$tmp_email = abook_fetch_field($abook_items, $idx, "email");
if(empty($tmp_name)) $rstr .= $glue . $tmp_email;
else $rstr .= $glue . "\"" . $tmp_name . "\" <" . $tmp_email . ">";
$glue = ",";
}
return $rstr;
}

function js_getitems($tmp) {
if(empty($tmp["name"])) return $tmp["email"];
else return "\"" . $tmp["name"] . "\" <" . $tmp["email"] . ">";
}

function push_jsaddrs() {
global $abook_items_cnt, $abook_grpitems_cnt;
global $abook_items, $abook_grpitems;

echo "\n";
}

function compose_rmatchs($total_atchs) {
global $atch_dir;

$tmp_atchs = explode(chr(2), $total_atchs);
for($j = 0 ; $j < count($tmp_atchs) ; $j++) {
$tmp_atchstr = $tmp_atchs[$j];
$tmp_arr = explode(chr(3), $tmp_atchstr);
$tmp_file = $tmp_arr[0];
$tmp_filepath = $atch_dir . "/" . $tmp_file;
if(empty($tmp_file) || !file_exists($tmp_filepath)) continue;
$tmp_remove = "/bin/rm -f $tmp_filepath";
@sexec($tmp_remove);
}
}

function compose_rmpremail() {
global $sql;
global $premail;
global $customerID;

$sql->sendmsgs_del_premail($customerID, $premail);
}

function prepare_data($d) {
$nd = ereg_replace("\r", "", $d);
$nd = ereg_replace("\n", "\r\n", $nd);
return $nd;
}

function generate_rcpt_header($myarr, $str, &$cmps_rcpts, &$msg_header, &$farr) {
global $tmp_glue;

for($j = 0 ; $j < count($myarr) ; $j++) {
$tmp_rcpt_arr = $myarr[$j];
$tmp_mbox = $tmp_rcpt_arr->mailbox;
$tmp_host = $tmp_rcpt_arr->host;
$tmp_name = $tmp_rcpt_arr->personal;
if(empty($tmp_mbox) && empty($tmp_host)) continue;
$tmp_email = $tmp_mbox . "@" . $tmp_host;
$cmps_rcpts .= $tmp_glue . $tmp_email;
$tmp_glue = " ";

if(!empty($tmp_name)) {
$tmp_rcpt = "\"" . $tmp_name . "\" <" . $tmp_email . ">";
} else {
$tmp_rcpt = $tmp_email;
}

$msg_header .= $str . ": " . $tmp_rcpt . "\r\n";
$farr[] = $tmp_rcpt;
}
}


function compose_sendmail() {
global $BSX_ATTACH_DIR, $BSX_VERSION;
global $BSX_BASEHREF, $BSX_LAUNCHER, $BSX_LIBDIR;
global $BSX_HTXDIR, $BSX_THEMEDIR, $BSX_SENTMAIL;
global $BSX_SENTMAIL_NAME, $BSX_TRASH_NAME, $BSX_MDIR;
global $SESSID, $BODY_ONLOAD;
global $BSX_USE_SENDMAIL, $BSX_SENDMAIL_PATH;
global $customerID, $RequestID, $sql, $imap, $lng;
global $bsx_domains, $domain_name, $domain, $username, $password;

global $info_msg, $err_msg;
global $atch_dir;
// --
global $premail;

global $cmps_from, $cmps_to, $cmps_cc, $cmps_bcc;
global $cmps_subject, $cmps_body, $cmps_sign, $cmps_atchlist;

// TODO: Function for this
$user_set = $_COOKIE['user_set'];

include("$BSX_HTXDIR/header.htx.php");

echo $total_atchs = load_atchs($customerID, $_POST['premail']);

// generate header
$atch_dir = $BSX_ATTACH_DIR . "/" . "$domain_name" . "/" . "$username";
$msg_header = "";

// in replyto
if(!empty($cmps_fromMsgID)) {
$msg_header .= "In-Reply-To: $cmps_fromMsgID\r\n";
}

// replyto
if(!empty($user_set["replyto"])) {
if(!empty($user_set["name"])) {
$repto = "\"" . $user_set["name"] . "\" <" . $user_set["replyto"] . ">";
} else {
$repto = $user_set["replyto"];
}
} else {
if(!empty($user_set["name"])) {
$repto = "\"" . $user_set["name"] . "\" <" . $username . "@" . $domain_name . ">";
} else {
$repto = $username . "@" . $domain_name;
}
}

// from subject etc
$cmps_from_email = $username . "@" . $domain_name;
$msg_header .= "Message-ID: \r\n";
$msg_header .= "X-Mailer: BasiliX " . $BSX_VERSION . " -- http://www.basilix.org\r\n";
$msg_header .= "X-SenderIP: " . $GLOBALS["REMOTE_ADDR"] . "\r\n";
$msg_header .= "Date: " . date("D, d M Y H:i:s T", time()) . "\r\n";
$msg_header .= "From: " . $cmps_from . " <" . $cmps_from_email . ">\r\n";
$msg_header .= "Reply-To: " . $repto . "\r\n";
$cmps_subject = empty($cmps_subject) ? "(no subject)" : $cmps_subject;
$msg_header .= "Subject: " . $cmps_subject . "\r\n";


// all recipients
$cmps_rcpts = "";
$tmp_glue = "";
if(!empty($cmps_to)) {
$cmps_to_arr = imap_rfc822_parse_adrlist($cmps_to, $domain_name);
generate_rcpt_header($cmps_to_arr, "To", &$cmps_rcpts, &$msg_header, &$farr);
}
if(!empty($cmps_cc)) {
$cmps_cc_arr = imap_rfc822_parse_adrlist($cmps_cc, $domain_name);
generate_rcpt_header($cmps_cc_arr, "Cc", &$cmps_rcpts, &$msg_header, &$farr);
}
if(!empty($cmps_bcc)) {
$cmps_bcc_arr = imap_rfc822_parse_adrlist($cmps_bcc, $domain_name);
generate_rcpt_header($cmps_bcc_arr, "Bcc", &$cmps_rcpts, &$msg_header, &$farr);
}

$cmps_finalinfo = $farr;

// include signature
if($cmps_sign) $cmps_body .= "\r\n-- \r\n" . $user_set["sign"];

// generate attachments
$msg_boundary = md5(uniqid(time())) . "-" . time();
$msg_body = "";

if(!empty($total_atchs)) {
$msg_header .= "MIME-Version: 1.0\r\n";
$msg_header .= "Content-Type: multipart/mixed; boundary=\"" . $msg_boundary . "\"\r\n\r\n";
$msg_header .= "--" . $msg_boundary . "\r\n";
$msg_header .= "Content-Type: text/plain\r\n\r\n";
$msg_header .= $cmps_body . "\r\n\r\n";

$tmp_atchs = explode(chr(2), $total_atchs);
$atched = 0;
for($j = 0 ; $j < count($tmp_atchs) ; $j++) {
$tmp_arr = explode(chr(3), $tmp_atchs[$j]);
$tmp_file = $tmp_arr[0];
$tmp_content = $tmp_arr[1];
$tmp_size = $tmp_arr[2];
$tmp_filepath = $atch_dir . "/" . $tmp_file;
if(empty($tmp_file) || !file_exists($tmp_filepath)) continue;
$tmp_fp = fopen($tmp_filepath, "r");
$tmp_filein = fread($tmp_fp, filesize($tmp_filepath));
fclose($tmp_fp);
$msg_header .= "--" . $msg_boundary . "\r\n";
if(empty($tmp_content)) $tmp_content = "application/octet-stream";
else $tmp_content = strtolower($tmp_content);
$msg_header .= "Content-Type: " . $tmp_content . "\r\n";

// New attachment code adapted from egroupware
$handle = fopen($tmp_filepath, 'rb');
$tmp_data = '';
while ( $chunk = fread ( $handle, 57)) {
$tmp_data .= base64_encode ( $chunk) . "\r\n";
}
fclose ( $handle);

$msg_header .= "Content-Transfer-Encoding: base64\r\n";
$msg_header .= "Content-Description: $tmp_file\r\n";
$tmp_type = strtok($tmp_content, "/");
if($tmp_type == "image") $tmp_disp = "inline";
else $tmp_disp = "attachment";
$msg_header .= "Content-Disposition: " . $tmp_disp . "; filename=\"" . $tmp_file . "\"\r\n\r\n";
$msg_header .= $tmp_data;
$atched = 1;
}
}
if($atched) {
$msg_header .= "--" . $msg_boundary . "--\r\n";
} else {
$msg_body = "\r\n" . $cmps_body . "\r\n";
}


// prepare the datas
$msg_header = prepare_data($msg_header);
$msg_body = prepare_data($msg_body);
$msg_body = trans_tr($msg_body);

// log the sent mails to find the abusers or harassment e-mail senders quickly (just in case)
// we log these:
// 1 - date time
// 2 - the IP address of the user
// 3 - the name of the sender (e.g; Murat Arslan)
// 4 - the email address of the sender (e.g; arslanm@basilix.org)
// 5 - the subject of the email
// 6 - the To part
// 7 - the Cc part
// 8 - the Bcc part
// --
$logfile = "/var/log/webmail/BASILIX_" . $domain_name;
$fplog = @fopen($logfile, "a+");
if($fplog) {
$logbuf = date("d/m/Y H:i:s", time()) . "|" . $GLOBALS["REMOTE_ADDR"] . "|";
$logbuf .= $cmps_from . "|";
$logbuf .= $username . "@" . $domain_name . "|";
$logbuf .= $cmps_subject . "|" . $cmps_to . "|" . $cmps_cc . "|" . $cmps_bcc;
$logbuf .= "\n";
fwrite($fplog, $logbuf);
fclose($fplog);
}
// -- end of log

// send the mail
$ok_sent = false;
// echo "CMPS_FROM: [$cmps_from_email]
\n";
// echo "CMPS_RCPTS: [$cmps_rcpts]
\n";
// echo "MSG_HEADER: [$msg_header]
\n";
// echo "MSG_BODY: [$msg_header]
\n";
// echo $cmps_finalinfo;
// $zzz = count($cmps_finalinfo);
// echo "($zzz)
\n";
// for($i = 0 ; $i < count($cmps_finalinfo) ; $i++) {
// echo "RCPT: [" . $cmps_finalinfo[$i] . "]
\n";
// }
// exit();
if($BSX_USE_SENDMAIL && @is_executable($BSX_SENDMAIL_PATH)) {
// use sendmail to send the mail
$pmail = popen("$BSX_SENDMAIL_PATH -i -f$cmps_from_email -- $cmps_rcpts", "w");
$prc = fputs($pmail, $msg_header . "\r\n");
$prc += fputs($pmail, $msg_body);
if(pclose($pmail) != 0) $prc = 0;
else $ok_sent = true;
} else {
// send it via SMTP
require("$BSX_LIBDIR/smtp.class.php");

$SMTP_HOST = $bsx_domains["$domain"]["smtp_host"];
$smtp = new SMTP($SMTP_HOST);

// debug
// $smtp->togdebug();

$rc = $smtp->connect();
if(!rc) {
switch($rc) {
case -4:
err_exit($lng->p(455));
case -5:
err_exit($lng->p(456));
default:
err_exit($lng->p(457));
}
}
$msg_rcpt = explode(" ", $cmps_rcpts);
if(!($smtp->mailfrom("<" . $username . "@" . $domain_name . ">")
&& $smtp->rcptall($msg_rcpt)
&& $smtp->startdata()
&& $smtp->senddata($msg_header)
&& $smtp->senddata($msg_body)
&& $smtp->stopdata()
&& $smtp->disconnect())) {
$msg_errno = $smtp->geterr(&$msg_error, &$msg_srverror);
$err_msg = "SMTP Error $msg_errno:
";
$err_msg .= "Error Message is: " . htmlspecialchars($msg_error) . "
";
$err_msg .= "Server $SMTP_HOST replied: " . $msg_srverror . "
\n";
} else {
$ok_sent = true;
}
}

// successfuly sent
if($ok_sent == true) {
compose_rmatchs($total_atchs);
compose_rmpremail();
$info_msg = $lng->p(444);

if($user_set["savesent"]) {
// append to sent mail
require("$BSX_LIBDIR/imap2.inc.php");
$imap->reopbox($BSX_MDIR.BSX_SENTMAIL_NAME);
$imap->apnd($BSX_MDIR.$BSX_SENTMAIL_NAME, $msg_header . "\r\n\r\n" . $msg_body);
}
}

include("$BSX_HTXDIR/menu.htx.php");
include("$BSX_HTXDIR/compose-finalinfo.htx.php");
include("$BSX_HTXDIR/footer.htx.php");
}

function reply_data($d) {
$d = "> " . $d; // put a leading "> "
$nd = ereg_replace("\r", "", $d);
$nd = ereg_replace("\n", "\r\n> ", $nd);
$nd = substr($nd, 0, strlen($nd) - 2); // get rid of trailing "> "
return $nd;
}

require("$BSX_LIBDIR/readmsg.inc.php");
function get_reply($ID, $what = 0) { // 0 (default) = reply, 1 = reply all, 2 = forward
global $BSX_MDIR, $BSX_ATTACH_DIR, $BODY_ONLOAD, $mbox;
global $cmps_to, $cmps_cc, $cmps_subject, $cmps_body;
global $err_msg, $info_msg, $body_type;
global $lng, $imap, $username, $domain_name;

global $cmps_atchs;

$ID = (int)$ID;
// --
if(strtoupper($mbox) != "INBOX")
if(!$imap->reopbox($BSX_MDIR . $mbox)) return;
// -

$mbox_info = $imap->mboxinfo();
$msg_no = $imap->msgno($ID);
if(!$msg_no) {
$err_msg = $lng->p(445);
return;
}

$msg_header = $imap->msghdr($msg_no);
$msg_str = $imap->ftchstr($msg_no);

$reply_obj = $msg_header->reply_to[0];

if(is_object($reply_obj)) {
$reply_addr = $reply_obj->mailbox . "@" . strtolower($reply_obj->host);
if(empty($reply_obj->personal))
$msg_from = $reply_addr;
else
$msg_from = decode_mime($reply_obj->personal) . " <$reply_addr>";
} else {
$msg_from = "";
}

// clean the "," for possible mistakes
$cmps_to = ereg_replace(",", "", $msg_from);
$my_addr = $username . "@" . strtolower($domain_name);
$glue = ",";


if($what == 1) { // replying to all
// generate "to"
for($i = 0 ; $i < count($msg_header->to) ; $i++) {
$to_obj = $msg_header->to[$i];
if(is_object($to_obj)) {
$to_addr = $to_obj->mailbox . "@" . strtolower($to_obj->host);
if($to_addr == $my_addr) continue;
if(empty($to_obj->personal))
$msg_to = $to_addr;
else
$msg_to = ereg_replace(",", "", decode_mime($to_obj->personal)) . " <$to_addr>";
$cmps_to .= $glue . $to_addr;
}
}
$cmps_cc = "";
$glue = "";
// and "cc"
for($i = 0 ; $i < count($msg_header->cc) ; $i++) {
$cc_obj = $msg_header->cc[$i];
if(is_object($cc_obj)) {
$cc_addr = $cc_obj->mailbox . "@" . strtolower($cc_obj->host);
if($cc_addr == $my_addr) continue;
if(empty($cc_obj->personal))
$msg_cc = $cc_addr;
else
$msg_cc = ereg_replace(",", "", decode_mime($cc_obj->personal)) . " <$cc_addr>";
$cmps_cc .= $glue . $cc_addr;
$glue = ",";
}
}
}

if($what == 2 && check_atch($msg_no) == true) { // get the attachments
$atch_dir = $BSX_ATTACH_DIR . "/" . "$domain_name" . "/" . "$username";
$cmd = "/bin/mkdir -m 0700 -p $atch_dir";
@sexec($cmd);

$cmps_atchs = "";
$glue = "";
for($i = 0 ; $i <= count($msg_str->parts) ; $i++) {
$tmp_type="";$tmp_subtype="";$tmp_file="";$tmp_filepath="";

// attachment part
if(!$i) {
$atch_part = $msg_str->parts[0];
if(!is_object($atch_part))
$atch_part = $msg_str;
} else {
$atch_part = $msg_str->parts[$i];
}

if(!is_object($atch_part)) continue;

// content type
$tmp_type = $body_type[$atch_part->type];
$tmp_subtype = strtolower($atch_part->subtype);
if(empty($tmp_subtype)) $tmp_subtype = "x-unknown";
$tmp_content = $tmp_type . "/" . $tmp_subtype;

if(empty($tmp_type)) {
switch($tmp_subtype) {
case "html":
case "plain":
case "enriched":
$tmp_type = "text";
break;
case "rfc822":
case "delivery-status":
$tmp_type = "message";
break;
default:
$tmp_type = "application";
break;
}
}
// filename
if($atch_part->ifparameters) {
while(list(, $atch_param) = each($atch_part->parameters)) {
switch(strtolower($atch_param->attribute)) {
case "filename":
case "name":
$tmp_file = $atch_param->value;
break;
}
}
}
if($atch_part->ifdparameters && empty($tmp_file)) {
while(list(, $atch_param) = each($atch_part->dparameters)) {
switch(strtolower($atch_param->attribute)) {
case "filename":
case "name":
$tmp_file = $atch_param->value;
break;
}
}
}
if(empty($tmp_file)) {
switch($tmp_subtype) {
case "html":
$tmp_file = "message.html";
break;
case "rfc822":
$tmp_file = "message.txt";
break;
case "delivery-status":
$tmp_file = "message.txt";
break;
case "plain":
$tmp_file = "message.txt";
break;
case "enriched":
$tmp_file = "message.rtf";
break;
case "pgp-signature":
$tmp_file = "pgp-signature.txt";
break;
}
}

if(empty($tmp_file)) {
if(!$i) {
$tmp_file = "msg$ID.txt";
$tmp_content = "text/plain";
} else {
$tt = time();
$tmp_file = "unknown_file_$tt.dat";
$tmp_content = "application/x-unknown";
}
}

$tmp_filepath = $atch_dir . "/" . $tmp_file;

// the file itself
$tmp_encoding = $atch_part->encoding;
$tmp_encfunc = "enc_func" . $tmp_encoding;
$atch_body = $imap->ftchbody($msg_no, $i + 1);
$tmp_filein = $tmp_encfunc($atch_body);

// ok copy and ready the file there
$fp = fopen($tmp_filepath, "wb");
if(!$fp) continue; // wtf?
fwrite($fp, $tmp_filein);
fclose($fp);
$tmp_size = filesize($tmp_filepath);

// finally set variables
$cmps_atchs = $cmps_atchs . $glue . $tmp_file . chr(3) . $tmp_content . chr(3) . $tmp_size;
$glue = chr(2);
}
}

$msg_body = check_body($msg_no, $ID, $imap->ftchbody($msg_no, 1));
$msg_date = date("d M Y H:i T", $msg_header->udate);
$msg_subject = $msg_header->subject;
$cmps_subject = decode_mime($msg_subject);

if($what == 0 || $what == 1) {
$lng->sb(446); $lng->sr("%d", $msg_date); $wrote_str = $lng->sp();
if(strtolower(substr($cmps_subject, 0, 3)) != "re:")
$cmps_subject = "Re: " . $cmps_subject;
$cmps_body = $wrote_str . "\r\n\r\n" . reply_data($msg_body);

$BODY_ONLOAD="onLoad='document.composeMail.cmps_body.focus();'";
} else {
$fwd_str = $lng->p(447);
$lng->sb(448); $lng->sr("%d", $msg_date); $date_str = $lng->sp();
$lng->sb(449); $lng->sr("%f", $msg_from); $from_str = $lng->sp();
$lng->sb(450); $lng->sr("%s", $msg_subject); $subj_str = $lng->sp();
if(strtolower(substr($cmps_subject, 0, 4)) != "fwd:")
$cmps_subject = "Fwd: " . $cmps_subject;
$cmps_body = $fwd_str . "\r\n" . $date_str . "\r\n" . $from_str . "\r\n" . $subj_str . "\r\n\r\n" . prepare_data($msg_body);

// since we'll forward, empty the "To" part and focus
$cmps_to = "";
$BODY_ONLOAD="onLoad='document.composeMail.cmps_to.focus();'";
}
}

function load_drafts($cid) {
global $sql;
return $sql->sendmsgs_load_drafts($cid);
}

function cmps_newmsg($cid) {
global $sql;
return $sql->sendmsgs_init($cid);
}

function load_details($cid, $pm) {
global $sql;
return $sql->sendmsgs_load_premail($cid, $pm);
}
function del_draft($cid, $pm) {
global $sql, $atch_dir;

$total_atchs = load_atchs($cid, $pm);
compose_rmatchs($total_atchs);
return $sql->sendmsgs_del_draft($cid, $pm);
}
function del_empty_drafts($cid) {
global $sql;
return $sql->sendmsgs_del_empty_drafts($cid);
}

function load_atchs($cid, $pm) {
global $sql;
return $sql->sendmsgs_load_atchs($cid, $pm);
}

function check_premail($cid, $pm) {
global $sql;
return $sql->sendmsgs_check_premail($cid, $pm);
}

function update_atchs($cid, $pm, $atchs) {
global $sql;
return $sql->sendmsgs_update_premail_atchs($cid, $pm, $atchs);
}

function update_premail($cid, $pm, $from, $to, $cc, $bcc, $subject, $body) {
global $sql;
return $sql->sendmsgs_update_premail($cid, $pm, $from, $to, $cc, $bcc, $subject, $body);
}

function is_already_attached($file, $filelist) {
$tmp_arr = explode(chr(2), $filelist);
for($i = 0 ; $i < count($tmp_arr) ; $i++) {
$tmp_arr2 = explode(chr(3), $tmp_arr[$i]);
if($tmp_arr2[0] == $file) return true;
}
return false;
}
function remove_atchfile($before, $rmfile) {
$after = "";
$tmp_arr = explode(chr(2), $before);
$glue = "";
for($i = 0 ; $i < count($tmp_arr) ; $i++) {
if(empty($tmp_arr[$i])) continue;
$tmp_arr2 = explode(chr(3), $tmp_arr[$i]);
$file = $tmp_arr2[0];
$type = $tmp_arr2[1];
$size = $tmp_arr2[2];
if($file == $rmfile) continue;
$after .= $glue . $file . chr(3) . $type . chr(3) . $size;
$glue = chr(2);
}
return $after;
}

?>
Your Ad Here