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 PHP. Show all posts
Showing posts with label PHP. Show all posts

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'




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

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']).


Tuesday, January 20, 2009

MySQL Regular Expressions - Part 2


Regular Expressions in MySQL


Introduction



A very interesting and useful capability of MySQL is to incorporate Regular Expressions (regex) in SQL queries. The regular expression support in MySQL is extensive. Let's take a look at using Regular Expressions in queries and the supported metacharacters.



Using Regular Expressions in queries



A simple example of using Regular Expressions in a SQL query would be to select all names from a table that start with 'A'.



Code: SQL

SELECT name FROM employees WHERE name REGEXP '^A'




Your Ad Here


A slight modification in the above example to look for names starting with 'A' or 'D' or 'F' will look like this.


Code: SQL

SELECT name FROM employees WHERE name REGEXP '^(A|D|F)'



If we want to select all names ending with 'P', then the SQL query goes like this


Code: SQL

SELECT name FROM employees WHERE name REGEXP 'P$'



We can use much complex patterns in our SQL queries, but first let's have a look at various MySQL Regular Expression metacharacters.



Regular Expression Metacharacters



*
Matches zero or more instances of the string preceding it

+
Matches one or more instances of the string preceding it

?
Matches zero or one instances of the string preceding it

.
Matches any single character, except a newline

[xyz]
Matches any of x, y, or z (match one of enclosed characters)

[^xyz]
Matches any character not enclosed

[A-Z]
Matches any uppercase letter

[a-z]
Matches any lowercase letter

[0-9]
Matches any digit

^
Anchors the match from the beginning

$
Anchors the match to the end

|
Separates alternatives

{n,m}
String must occur at least n times, but not more than m times

{n}
String must occur exactly n times

{n,}
String must occur at least n times

[[:<:]]
Matches beginning of words

[[:>:]]
Matches ending of words

[:class:]
match a character class i.e.,



[:alpha:] for letters

[:space:] for whitespace

[:punct:] for punctuation

[:upper:] for upper case letters


Extras



MySQL interprets a backslash (\) character as an escape character. To use a backslash in a regular expression, you must escape it with another backslash (\\).



Your Ad Here



Whether the Regular Expression match is case sensitive or otherwise is decided by the collation method of the table. If your collation method name ends with ci then the comparison/match is case-insensitive, else if it end in cs then the match is case sensitive.



Examples



Checking only for numbers


Code: SQL

SELECT age FROM employees WHERE age REGEXP '^[0-9]+$'

/* starts, ends and contains numbers */



Contains a specific word, for example the skill PHP in skill sets


Code: SQL

SELECT name FROM employees WHERE skill_sets REGEXP '[[:<:]]php[[:>:]]'



Fetching records where employees have entered their 10-digit mobile number as the contact number.


Code: SQL

SELECT name FROM employees WHERE contact_no REGEXP '^[0-9]{10}$'





For more information refer http://dev.mysql.com/doc/refman/5.1/en/regexp.html

MySQL Regular Expressions - Part 1


A regular expression (regex) is a powerful way of specifying a complex search.



MySQL uses Henry Spencer's implementation of regular
expressions, which is aimed at conformance with POSIX
1003.2. MySQL uses the extended version.



This is a simplistic reference that skips the details. To get more exact
information, see Henry Spencer's regex(7) manual page that is
included in the source distribution. See section C Credits.



A regular expression describes a set of strings. The simplest regexp is
one that has no special characters in it. For example, the regexp
hello matches hello and nothing else.



Non-trivial regular expressions use certain special constructs so that
they can match more than one string. For example, the regexp
hello|word matches either the string hello or the string
word.



As a more complex example, the regexp B[an]*s matches any of the
strings Bananas, Baaaaas, Bs, and any other string
starting with a B, ending with an s, and containing any
number of a or n characters in between.




Your Ad Here


A regular expression may use any of the following special
characters/constructs:



^

Match the beginning of a string.

 
mysql> SELECT "fo\nfo" REGEXP "^fo$"; -> 0
mysql> SELECT "fofo" REGEXP "^fo"; -> 1


$

Match the end of a string.

 
mysql> SELECT "fo\no" REGEXP "^fo\no$"; -> 1
mysql> SELECT "fo\no" REGEXP "^fo$"; -> 0


.

Match any character (including newline).

 
mysql> SELECT "fofo" REGEXP "^f.*"; -> 1
mysql> SELECT "fo\nfo" REGEXP "^f.*"; -> 1


a*

Match any sequence of zero or more a characters.

 
mysql> SELECT "Ban" REGEXP "^Ba*n"; -> 1
mysql> SELECT "Baaan" REGEXP "^Ba*n"; -> 1
mysql> SELECT "Bn" REGEXP "^Ba*n"; -> 1


a+

Match any sequence of one or more a characters.

 
mysql> SELECT "Ban" REGEXP "^Ba+n"; -> 1
mysql> SELECT "Bn" REGEXP "^Ba+n"; -> 0


a?

Match either zero or one a character.

 
mysql> SELECT "Bn" REGEXP "^Ba?n"; -> 1
mysql> SELECT "Ban" REGEXP "^Ba?n"; -> 1
mysql> SELECT "Baan" REGEXP "^Ba?n"; -> 0


de|abc

Match either of the sequences de or abc.

 
mysql> SELECT "pi" REGEXP "pi|apa"; -> 1
mysql> SELECT "axe" REGEXP "pi|apa"; -> 0
mysql> SELECT "apa" REGEXP "pi|apa"; -> 1
mysql> SELECT "apa" REGEXP "^(pi|apa)$"; -> 1
mysql> SELECT "pi" REGEXP "^(pi|apa)$"; -> 1
mysql> SELECT "pix" REGEXP "^(pi|apa)$"; -> 0



Your Ad Here

(abc)*

Match zero or more instances of the sequence abc.

 
mysql> SELECT "pi" REGEXP "^(pi)*$"; -> 1
mysql> SELECT "pip" REGEXP "^(pi)*$"; -> 0
mysql> SELECT "pipi" REGEXP "^(pi)*$"; -> 1


{1}

{2,3}

The is a more general way of writing regexps that match many
occurrences of the previous atom.


a*

Can be written as a{0,}.
a+

Can be written as a{1,}.
a?

Can be written as a{0,1}.

To be more precise, an atom followed by a bound containing one integer
i and no comma matches a sequence of exactly i matches of
the atom. An atom followed by a bound containing one integer i
and a comma matches a sequence of i or more matches of the atom.
An atom followed by a bound containing two integers i and
j matches a sequence of i through j (inclusive)
matches of the atom.

Both arguments must be in the range from 0 to RE_DUP_MAX
(default 255), inclusive. If there are two arguments, the second must be
greater than or equal to the first.
[a-dX]

[^a-dX]

Matches
any character which is (or is not, if ^ is used) either a, b,
c, d or X. To include a literal ] character,
it must immediately follow the opening bracket [. To include a
literal - character, it must be written first or last. So
[0-9] matches any decimal digit. Any character that does not have
a defined meaning inside a [] pair has no special meaning and
matches only itself.


Your Ad Here

 
mysql> SELECT "aXbc" REGEXP "[a-dXYZ]"; -> 1
mysql> SELECT "aXbc" REGEXP "^[a-dXYZ]$"; -> 0
mysql> SELECT "aXbc" REGEXP "^[a-dXYZ]+$"; -> 1
mysql> SELECT "aXbc" REGEXP "^[^a-dXYZ]+$"; -> 0
mysql> SELECT "gheis" REGEXP "^[^a-dXYZ]+$"; -> 1
mysql> SELECT "gheisa" REGEXP "^[^a-dXYZ]+$"; -> 0


[[.characters.]]

The sequence of characters of that collating element. The sequence is a
single element of the bracket expression's list. A bracket expression
containing a multi-character collating element can thus match more than
one character, for example, if the collating sequence includes a ch
collating element, then the regular expression [[.ch.]]*c matches the
first five characters of chchcc.

[=character_class=]

An equivalence class, standing for the sequences of characters of all
collating elements equivalent to that one, including itself.

For example, if o and (+) are the members of an
equivalence class, then [[=o=]], [[=(+)=]], and
[o(+)] are all synonymous. An equivalence class may not be an
endpoint of a range.

[:character_class:]

Within a bracket expression, the name of a character class enclosed in
[: and :] stands for the list of all characters belonging
to that class. Standard character class names are:







Name Name Name
alnum digit punct
alpha graph space
blank lower upper
cntrl print xdigit


These stand for the character classes defined in the ctype(3) manual
page. A locale may provide others. A character class may not be used as an
endpoint of a range.


Your Ad Here

 
mysql> SELECT "justalnums" REGEXP "[[:alnum:]]+"; -> 1
mysql> SELECT "!!" REGEXP "[[:alnum:]]+"; -> 0


[[:<:]]

[[:>:]]

These match the null string at the beginning and end of a word
respectively. A word is defined as a sequence of word characters which
is neither preceded nor followed by word characters. A word character is
an alnum character (as defined by ctype(3)) or an underscore
(_).

 
mysql> SELECT "a word a" REGEXP "[[:<:]]word[[:>:]]"; -> 1
mysql> SELECT "a xword a" REGEXP "[[:<:]]word[[:>:]]"; -> 0





 
mysql> SELECT "weeknights" REGEXP "^(wee|week)(knights|nights)$"; -> 1


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.

Thursday, August 14, 2008

Ebook Of Open Source CMS

Apress.Building.Online.Communities.With.Drupal.phpBB.and.WordPress.Dec.2005


Free Ebook for Apress Building Online Communities With Drupal phpBB and WordPress Dec 2005 Please Download this ebook freely and learn.

Dowanload Link :- Click here




Free e-book Pro Drupal Development (John K. VanDyk and Matt Westgate)


Download Link :- Click Here

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