Shabat Closer

Monday, December 30, 2013

TECH - Exchange 2010 : No existing ‘PublicFolder’ matches the following Identity. ‘\’.

TECH - Exchange 2010 :  No existing ‘PublicFolder’ matches the following Identity. ‘\’.

Error:
No existing ‘PublicFolder’ matches the following Identity. ‘\’.  Make sure that you specified the correct ‘PublicFolder’ Identity and that you have the necessary permissions to view ‘PublicFolder’.  It was running the command ‘get-publicfolder -getchildren -identity ‘\’ -server ExchangeServer

Solution:
  1. I try to fix the homeMDB  homeMTA  in ADSI Edit but it's not fix my problem
  2. I remove my admin mailbox and create it again. <- that's fix my problem.

Sunday, December 29, 2013

Mysql - Function : Count Occurence of Character in a String / Word

Mysql : Count Occurrence of Character in a String / Word  Function

CREATE FUNCTION `getCount`(`myStr` VARCHAR(4096), `myword` VARCHAR(100)) RETURNS int(11)
    READS SQL DATA
    DETERMINISTIC
RETURN 
    ROUND (   
        (
            LENGTH(myStr)
            - LENGTH( REPLACE ( myStr, myword, "") ) 
        ) / LENGTH(myword)        
    )




Usage :



Select  getCount('Moshe Test My Code','M')
#Returns : 2

Thursday, August 1, 2013

C# : Disable Alert box javascript in c# webbrower control

if you want to disable all alerts in a website in your webbrower.

the following code disable :

  • Alert window.
  • Print window
  • confirm window.


/************Disable alert/print function()**********************/
HtmlElement head = WebBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = WebBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
string alertBlocker = @"window.alert = function () { }; 
                        window.print=function () { };
                        window.confirm=function () { };
                    ";
element.text = alertBlocker;
head.AppendChild(scriptEl);
WebBrowser1.ScriptErrorsSuppressed = true;
/****************************************************************/


Enjoy!

Tuesday, July 30, 2013

TECH - MySQL 5.5 / 5.6 : disable MySQL slave replication

if you want to disable the slave replication.

run the query :
  • RESET SLAVE ALL;
to verify run the query
  • SHOW SLAVE STATUS
enjoy!

Tuesday, April 23, 2013

TECH: auto load many sitemaps to google webmaster

upload multiple sitemaps to google, by automation javascript script.

auto load many sitemaps to google webmaster

  1. Login to google webmaster
  2. go to Sitemap TAB.
  3. Press F12 on keyboard.
  4. go to Console TAB.
  5. click on Multi Line Mode
  6. paste the following 

/****************************************************
* Variables :                                       *
* the following variables will upload               *
* the sitemap files                                 *
*   from : xmlmap.php?index=0                       *
*   to   : xmlmap.php?index=10                      *
*                                                   *
*  Upload FILE: baseSiteMapName + (jump * index)    *
*****************************************************/
var jump = 1;                               //Jump index count(Only if you need it...).
var index = 0;                              //Start index position.
var end = 10;                               //End index position.
var baseSiteMapName = "xmlmap.php?index=";  //sitemap file.
var UploadDelay = 1000;                     //Delay between uploads.
/**************
* the code   *
**************/
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js';
head.appendChild(script);
function upload_smap() {
    document.getElementById("gwt-uid-58").click();
    document.getElementById("gwt-uid-77").click();
    $("input[type='text']").val(baseSiteMapName + (jump * index));
    document.getElementById("gwt-uid-67").click();
    console.log(index);
    index++;
    if (index > end)
        clearInterval(uploadInt);
}
var uploadInt = setInterval(upload_smap, UploadDelay);

  1. change the variables to your site configuration.
  2. Click "Run Script"

Enjoy!

Wednesday, April 17, 2013

PHP: GODADDY Class - Change Godaddy DNS record Script

PHP Godaddy Class  - script to add/delete record from godaddy dns.

<?php
/**
 * The main class for sending and parsing server requests to the
 * GoDaddy?® TotalDNS management system. Eventually this class
 * could split into multiple classes representing the various
 * components such as the Service, Account, Zone, and Record(s).
 */
class GoDaddyDNS{
 /**
  * Class variables
  */
 private $_config;
 private $_curlHandle;
 private $_lastResponse;
 
 /**
  * Initialize the configuration array with configuration defaults.
  */
 public function __construct($config = array()) {
  // Apply default configuration settings
  $this->_config = array_merge(array(
   'username'       =>'',
   'password'       =>'',
   'domain'       =>'',
   'cookie_file'                 => tempnam(sys_get_temp_dir(), 'Curl'),
   'auto_remove_cookie_file'     => true,
   'auto_logout'                 => true,
   'godaddy_dns_zonefile_url'    => 'https://dns.godaddy.com/ZoneFile.aspx?zoneType=0&sa=&zone=',
   'godaddy_dns_zonefile_ws_url' => 'https://dns.godaddy.com/ZoneFile_WS.asmx'
   ), $config);
  
  $this->_authenticate($this->_config["username"],$this->_config["password"],$this->_config["domain"]);
 }

 /**
  * Destroy the curl handle and unlink the cookies file.
  */
 public function __destruct() {
  if ($this->_config['auto_logout']) {
   $this->logout();
  }
  if ($this->_curlHandle) {
   curl_close($this->_curlHandle);
  }
  if ($this->_config['auto_remove_cookie_file'] && file_exists($this->_config['cookie_file'])) {
   unlink($this->_config['cookie_file']);
  }
 }


 /**
  * Login to the user's account, returning an error if the credentials are
  * invalid or the login fails.
  */
 private function _authenticate($username, $password,$domain) {
  $this->_lastResponse = $this->_fetchURL($this->_config['godaddy_dns_zonefile_url'].$domain);
  if (!$this->isLoggedIn($username)) {
   // User is not already logged in, build and submit a login request
   $postUrl = curl_getinfo($this->_curlHandle, CURLINFO_EFFECTIVE_URL);

   $post = array(
    'Login$userEntryPanel2$LoginImageButton.x' => 0,
    'Login$userEntryPanel2$LoginImageButton.y' => 0,
    'Login$userEntryPanel2$UsernameTextBox' => $username,
    'Login$userEntryPanel2$PasswordTextBox' => $password,
    '__EVENTARGUMENT' => $this->_getField('__EVENTARGUMENT'),
    '__EVENTTARGET' => $this->_getField('__EVENTTARGET'),
    '__VIEWSTATE' => $this->_getField('__VIEWSTATE'),
    );
   $this->_lastResponse = $this->_fetchURL($postUrl, $post);

   if (!$this->isLoggedIn($username, $this->_lastResponse)) {
    // Invalid username/password or unknown response received
    return false;
   }
  }
  return true;
 }

 /**
  * Check to see if the expected user is logged in.
  */
 public function isLoggedIn($username) {
  if (preg_match('#Welcome:&nbsp;<span id="ctl00_lblUser" .*?\>(.*)</span>#', $this->_lastResponse, $match)) {
   if (strtolower($match[1]) == strtolower($username) || $match[2] == $username) {
    return true;
   } else {
    // An unexpected user was logged in
    $this->logout();
   }
  }
  return false;
 }

 /**
  * Log the user out.
  */
 public function logout() {
  if (preg_match('#<a [^>]+href="(.*?)"[^>]*>Log Out</a>#', $this->_lastResponse, $match)) {
   $this->_lastResponse = $this->_fetchURL($match[1]);
   if (preg_match('#<img src="([^"]+)" height="1" width="1" />#', $this->_lastResponse, $match)) {
    $this->_lastResponse = $this->_fetchURL($match[1]);
    return true;
   }
  }
  return false;
 }
 
 /**
 * Add new record
 */
 public function AddRecord($host,$type = 'A',$pointsTo,$ttl=3600){
  $domain=$this->_config["domain"];
  $next_record_id=$this->_nextRecordIndex();
  switch (strtoupper($type)) {
   case 'A':
    $post = array(
     'sInput' => '<PARAMS>
         <PARAM name="host" value="'.$host.'" />
         <PARAM name="pointsTo" value="'.$pointsTo.'" />
         <PARAM name="lstIndex" value="'.$next_record_id.'" />
         <PARAM name="ttl" value="'.$ttl.'" />
        </PARAMS>',
     );
    $calloutResponse = $this->_fetchURL($this->_config['godaddy_dns_zonefile_ws_url'] . '/AddNewARecord', http_build_query($post, '', '&'));
    if (strpos($calloutResponse, 'SUCCESS') === false) {
     return false;
    }
    
    // Commit the updates
    $post = array(
     'sInput' => '<PARAMS>
         <PARAM name="domainName" value="' . $domain . '" />
         <PARAM name="zoneType" value="0" />
         <PARAM name="aRecEditCount" value="1" />
         <PARAM name="aRecEdit0Index" value="'.$next_record_id.'" />
         <PARAM name="aRecDeleteCount" value="0" />
         <PARAM name="cnameRecEditCount" value="0" />
         <PARAM name="cnameRecDeleteCount" value="0" />
         <PARAM name="mxRecEditCount" value="0" />
         <PARAM name="mxRecDeleteCount" value="0" />
         <PARAM name="txtRecEditCount" value="0" />
         <PARAM name="txtRecDeleteCount" value="0" />
         <PARAM name="srvRecEditCount" value="0" />
         <PARAM name="srvRecDeleteCount" value="0" />
         <PARAM name="aaaaRecEditCount" value="0" />
         <PARAM name="aaaaRecDeleteCount" value="0" />
         <PARAM name="soaRecEditCount" value="0" />
         <PARAM name="soaRecDeleteCount" value="0" />
         <PARAM name="nsRecEditCount" value="0" />
         <PARAM name="nsRecDeleteCount" value="0" />
        </PARAMS>',
     );
    $calloutResponse = $this->_fetchURL($this->_config['godaddy_dns_zonefile_ws_url'] . '/SaveRecords', http_build_query($post, '', '&'));
    if (strpos($calloutResponse, 'SUCCESS') === false) {
     return false;
    }
    return true;
   
   
   default:
    // Other record types are currently unsupported
    throw new Exception('Unknown record type encountered: ' . $type);
  }
 }

 /**
 * Delete record
 */
 public function deleteRecord($record){
  $host=$record["host"];
  $domain=$this->_config["domain"];
  switch (strtoupper($record["type"])) {
   case 'A':
    $post = array(
     'sInput' => $record['index'].'|true',
     );
    $calloutResponse = $this->_fetchURL($this->_config['godaddy_dns_zonefile_ws_url'] . '/FlagARecForDeletion', http_build_query($post, '', '&'));
    if (strpos($calloutResponse, 'SUCCESS') === false) {
     return false;
    }
    
    // Commit the updates
    $post = array(
     'sInput' => '<PARAMS>
         <PARAM name="domainName" value="' . $domain . '" />
         <PARAM name="zoneType" value="0" />
         <PARAM name="aRecEditCount" value="0" />
         <PARAM name="aRecDeleteCount" value="1" />
         <PARAM name="aRecDelete0Index" value="' . $record['index'] . '" />
         <PARAM name="cnameRecEditCount" value="0" />
         <PARAM name="cnameRecDeleteCount" value="0" />
         <PARAM name="mxRecEditCount" value="0" />
         <PARAM name="mxRecDeleteCount" value="0" />
         <PARAM name="txtRecEditCount" value="0" />
         <PARAM name="txtRecDeleteCount" value="0" />
         <PARAM name="srvRecEditCount" value="0" />
         <PARAM name="srvRecDeleteCount" value="0" />
         <PARAM name="aaaaRecEditCount" value="0" />
         <PARAM name="aaaaRecDeleteCount" value="0" />
         <PARAM name="soaRecEditCount" value="0" />
         <PARAM name="soaRecDeleteCount" value="0" />
         <PARAM name="nsRecEditCount" value="0" />
         <PARAM name="nsRecDeleteCount" value="0" />
        </PARAMS>',
     );
    $calloutResponse = $this->_fetchURL($this->_config['godaddy_dns_zonefile_ws_url'] . '/SaveRecords', http_build_query($post, '', '&'));
    if (strpos($calloutResponse, 'SUCCESS') === false) {
     return false;
    }
    return true;
   case 'CNAME':
   case 'MX':
   case 'TXT':
   case 'SRV':
   case 'AAAA':
   case 'NS':
   default:
    // Other record types are currently unsupported
    throw new Exception('Unknown record type encountered: ' . $type);
  }
 }
 
 /**
  * Find and return the details about a host record, return false if nothing is found.
 *
 * Note: The only type of records currently supported are "A" records.
  */
 public function findRecords($host,$type = 'A') {
  $domain=strtolower($this->_config["domain"]);
  $currentZone = $this->_getField('ctl00$cphMain$hdnCurrentZone');
  if (strtolower($currentZone) != strtolower($domain)) {
   // Request zone details if not already loaded - 
   // could keep a separate cache of each zone's records in the future
   $this->_lastResponse = $this->_fetchUrl($this->_config['godaddy_dns_zonefile_url'] . $domain);
  }
  
  $records=array();
  $offset=0;
  while(preg_match("#Undo{$type}Edit\('tbl{$type}Records_([0-9]+)?', '({$host})', '([^']+)?', '([^']+)?', '([^']+)?', '([^']+)?', '([^']+)?'\);#is", $this->_lastResponse, $match,0,$offset)) {
   array_push($records,array_combine(array('match', 'index', 'host', 'data', 'ttl', 'host_td', 'points_to', 'rec_modified','type'), array_merge($match,array($type))));
   $offset=strpos($this->_lastResponse,$match[0],$offset)+strlen($match[0]);
  }
  return $records;
 }

 private function _nextRecordIndex($type = 'A'){
  return preg_match_all("#Undo{$type}Edit\('tbl{$type}Records_([0-9]+)?', '([^']+)', '([^']+)?', '([^']+)?', '([^']+)?', '([^']+)?', '([^']+)?'\);#is", $this->_lastResponse, $match,0,$offset);
 }
 /**
  * Connect to the remote server using CURL.
  */
 private function _fetchURL($url, $post = null, $referer = '', $agent = 'Mozilla/5.0 (compatible; PHP; cURL)', $language = 'en', $timeout = 30) {
  // Initialize CURL
  if (!$this->_curlHandle) {
   if (!function_exists('curl_init')) {
    die('CURL is not loaded or compiled into this version of PHP.');
   }
   if (!is_writable($this->_config['cookie_file'])) {
    die('Cookie jar file is not writable: ' . $this->_config['cookie_file']);
   }

   $this->_curlHandle = curl_init();

   curl_setopt_array($this->_curlHandle, array(
    CURLOPT_CONNECTTIMEOUT => $timeout,
    CURLOPT_TIMEOUT        => $timeout,
    CURLOPT_HEADER         => false,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_AUTOREFERER    => true,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_COOKIEJAR      => $this->_config['cookie_file'],
    CURLOPT_COOKIEFILE     => $this->_config['cookie_file'],
    ));
  }

  // Set the options
  curl_setopt($this->_curlHandle, CURLOPT_URL, $url);
  curl_setopt($this->_curlHandle, CURLOPT_REFERER, $referer);
  curl_setopt($this->_curlHandle, CURLOPT_USERAGENT, $agent);
  $extraHeaders = array(
   'Accept-Language: ' . $language,
   );
  curl_setopt($this->_curlHandle, CURLOPT_HTTPHEADER, $extraHeaders);
  if ($post) {
   curl_setopt($this->_curlHandle, CURLOPT_POST, true);
   curl_setopt($this->_curlHandle, CURLOPT_POSTFIELDS, $post);
  } else {
   curl_setopt($this->_curlHandle, CURLOPT_HTTPGET, true);
  }

  // Execute the request, returning the results
  return curl_exec($this->_curlHandle);
 }

 /**
  * Parse and return a named field's value from the last response.
  */
 private function _getField($name) {
  if (preg_match_all('#<input[^>]+>#is', $this->_lastResponse, $matches, PREG_SET_ORDER)) {
   foreach ($matches as $match) {
    $fieldHtml = $match[0];
    if ($this->_getFieldAttribute('name', $fieldHtml) == $name) {
     return $this->_getFieldAttribute('value', $fieldHtml);
    }
   }
  }
  return false;
 }

 /**
  * Get the attribute from a field's html.
  */
 private function _getFieldAttribute($attribute, $fieldHtml) {
  if (preg_match('#' . $attribute . '=["\']([^"\']+)?["\']#is', $fieldHtml, $match)) {
   return $match[1];
  }
  return false;
 }
}
?>


Usage: Add record

<?
$dns = new GoDaddyDNS(array(
 "username"=>'username',
 "password"=>'password',
 'domain'  =>'domain.com'
));
$dns->AddRecord("@","A","123.123.123.123",3600);
?>

Usage: Delete record

<?php
$dns = new GoDaddyDNS(array(
 "username"=>'username',
 "password"=>'password',
 'domain'  =>'domain.com'
));
$records = $dns->findRecords("@");
foreach ($records as $record){
 if ($record["data"]=="123.123.123.123"){
  $dns->deleteRecord($record);
 }
}
$dns->deleteRecord($record);
?>


Sunday, March 31, 2013

c#: save and open hashtable to file.

Save Hashtable object in file:


static void SaveHashtableFile(Hashtable ht,string path){
            BinaryFormatter bfw = new BinaryFormatter();
            FileStream file = File.OpenWrite(path);
            StreamWriter ws = new StreamWriter(file);
            bfw.Serialize(ws.BaseStream, ht);
            file.Close();
        }


Open the save Hashtable file



static Hashtable OpenHashtableFile(string path) {
            FileStream filer = File.OpenRead(path);
            StreamReader readMap = new StreamReader(filer);
            BinaryFormatter bf = new BinaryFormatter();
            Hashtable ret = (Hashtable)bf.Deserialize(readMap.BaseStream);
            file.Close();
            return ret;
        }
usage:

//Open Hash table file
Hashtable ht=OpenHashtableFile("ha.dat");

//Save Hash table into file


SaveHashtableFile(ht,"ha.dat");


Thursday, February 21, 2013

TECH:postfix mail server: filter email by php script

Howto: create simple scrip using PHP to filter incoming email on POSTFIX MAIL SERVER

read article :  http://www.postfix.org/FILTER_README.html ("Simple content filter example")

for the sample we use /etc/postfix to save the script files.

Step 1: create script file  "/etc/postfix/content-filter.sh"


#!/bin/sh

# Localize these. The -G option does nothing before Postfix 2.3.
INSPECT_DIR=/var/spool/filter
SENDMAIL="/usr/sbin/sendmail -G -i" # NEVER NEVER NEVER use "-t" here.

# Exit codes from <sysexits.h>
EX_TEMPFAIL=75
EX_UNAVAILABLE=69

# Clean up when done or when aborting.
trap "rm -f in.$$" 0 1 2 3 15

# Start processing.
cd $INSPECT_DIR || {
 echo $INSPECT_DIR does not exist; exit $EX_TEMPFAIL; }

cat >in.$$ || { 
 echo Cannot save mail to file; exit $EX_TEMPFAIL; }

/./etc/postfix/mail-cleaner.php in.$$
$SENDMAIL "$@" <in.$$

exit $?

Step 2: create php content filter file "/etc/postfix/mail-cleaner.php"



#!/usr/bin/php
<?php
//read mail file.
$file=$argv[1];
$data=file_get_contents($file);

$mail_parts=explode("\n\n",$data);
//Get header
$header=$mail_parts[0];

//Get all mail parts.
$mail_parts[0]="";
$content=implode($mail_parts,"\n\n");

//Remove all email address from  mail content
$content=preg_replace("/[^\s]*@[^@\s]*\.[^@\s]*/", "***@***.***", $content);

//Remove all websites from mail contant
$content=preg_replace("/[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+\.+/i", "www.***.***", $content);

//Save the new email.
file_put_contents($file,$header."\n\n".$content);
?>

Step 3: add configuration to "/etc/postfix/master.cf"

add the following lines to "master.cf"




filter    unix  -       n       n       -       10      pipe
    flags=Rq user=filter null_sender=
    argv=/etc/postfix/content-filter.sh -f ${sender} -- ${recipient}









add option "-o content_filter=filter:dummy" to smtp service 


smtp      inet  n       -       -       -       -       smtpd
 -o content_filter=filter:dummy







Step 4: Create user "filter" and add premissions 
simple run commands :


# (for centOS 6) create new user without home directory
useradd -M filter 

#add execute permissions to script files
chmod +rx /etc/postfix/content-filter.sh   
chmod +rx /etc/postfix/mail-cleaner.php

#create directory filter
mkdir /var/spool/filter

#change owner and group to filter
chown filter /var/spool/filter
chgrp filter /var/spool/filter

Step 5: (*) Disable SELinux security
to running the scripts we must to trun off the selinux security
http://www.crypt.gen.nz/selinux/disable_selinux.html

change the in file "/etc/selinux/config"

from :

SELINUX=enforcing

to:
SELINUX=disabled

Step 6: Reboot.

enjoy!

Attention :
(*) if you don't disable the  SELinux you will see in the maillog file ("/var/log/maillog")
the errors:
Sep 9 18:50:22 localhost postfix/pipe[2960]: 9F2349ABB01: to=<em...@domain.com>, relay=postfixfilter, delay=7441, delays=7441/0.08/0/0.65, dsn=4.3.0, status=deferred (temporary failure. Command output: pipe: fatal: pipe_command: execvp /etc/postfix/content-filter.sh: Permission denied )




Monday, February 11, 2013

Mysql: encode / decode IP to HEX

MYSQL Function to encode IP to HEX

CREATE  FUNCTION `ip_encode`(`ip` VARCHAR(25)) RETURNS char(8) CHARSET utf8
    NO SQL
return concat(
conv(SUBSTRING_INDEX( ip , '.', 1 ),10,16 ) ,
conv(SUBSTRING_INDEX(SUBSTRING_INDEX( ip , '.', 2 ),'.',-1) ,10,16),
conv(SUBSTRING_INDEX(SUBSTRING_INDEX( ip , '.', -2 ),'.',1) ,10,16),
conv(SUBSTRING_INDEX( ip , '.', -1 ),10,16 )


MYSQL Function to decode ip (HEX to IP)


CREATE FUNCTION `ip_decode`(`session_ip` VARCHAR(25)) RETURNS char(50) CHARSET utf8
    DETERMINISTIC
RETURN concat_ws('.',
CONV(substr(session_ip,1,2),16,10),
CONV(substr(session_ip,3,2),16,10),
CONV(substr(session_ip,5,2),16,10),
CONV(substr(session_ip,7,2),16,10),
CONV(substr(session_ip,9,2),16,10))

Sunday, February 10, 2013

PHP: filezilla ftp server - auto create user

html + php script to create new user in filezilla ftp server


<?php
define("FTP_CONF_FILE",'C:/Program Files/FileZilla Server/FileZilla Server.xml');
define("FTP_EXE_FILE","C:\\Program Files\\FileZilla Server\\FileZilla server.exe");

function create_user($user_name,$password,$ftpUserFolder,$createBackup=true,$reloadFTP=true){ 
 $xmlfile = FTP_CONF_FILE;
 $xmlfolder=dirname($xmlfilename);
 
 $xmlbackupfile = $xmlfolder . @date("Y-m-d-H-i-s") . '_FileZilla_Server.xml';
 
 $xml = simplexml_load_file($xmlfile);
 // Copy Config for backup before each change, too.
 

 $isvalid = isUserID($user_name);
 if (!$isvalid){
  echo  "Username $user_name is invalid\n";
  return false;
 }
 
 
 if(check_user_exists($xml,$user_name)){
  echo "Username $user_name already exists...\n";
  return false;
 }
 if ($createBackup){
  if (!copy($xmlfile,$xmlbackupfile)){
   echo "Problem creating xml backup file";
   return false;
  }
 }


 $user = $xml->Users->addChild('User');
 $user->addAttribute('Name', $user_name);
 
 add_option($user,'Pass',md5($password));
 add_option($user,'Group',null);
 add_option($user,'Bypass server userlimit','0');
 add_option($user,'User Limit','0');
 add_option($user,'IP Limit','0');
 add_option($user,'Enabled','1');
 add_option($user,'Comments','none');
 add_option($user,'ForceSsl','0');

 $filter = $user->addChild('IpFilter');
 $filter->addChild('Disallowed');
 $filter->addChild('Allowed');

 $permissions = $user->addChild('Permissions');
 $permission = $permissions->addChild('Permission');

 $permission->addAttribute('Dir', str_replace("/","\\",$ftpUserFolder));

 add_option($permission,'FileRead','1');
 add_option($permission,'FileWrite','1');
 add_option($permission,'FileDelete','1');
 add_option($permission,'FileAppend','1');
 add_option($permission,'DirCreate','1');
 add_option($permission,'DirDelete','1');
 add_option($permission,'DirList','1');
 add_option($permission,'DirSubdirs','1');
 add_option($permission,'IsHome','1');
 add_option($permission,'AutoCreate','1');

 $speed = $user->addChild('SpeedLimits');
 $speed->addAttribute('DlType', '1');
 $speed->addAttribute('DlLimit', '10');
 $speed->addAttribute('ServerDlLimitBypass', '0');
 $speed->addAttribute('UlType', '1');
 $speed->addAttribute('UlLimit', '10');
 $speed->addAttribute('ServerUlLimitBypass', '0');
 $speed->addChild('Download');
 $speed->addChild('Upload');

 if(!$rv = $xml->asXML($xmlfile)){
  echo ('SimpleXML could not write file');
  return false;
 }


 //Change file encoding from UTF8 to ISO-8859-1
 $dom = new DOMDocument("1.0","ISO-8859-1");
 $dom->preserveWhiteSpace = false;
 $dom->formatOutput = true;
 if(!$dom->load($xmlfile) || !$dom->save($xmlfile)){
  echo ('DOMDocument could not change file enconding from UTF8 to ISO-8859-1');
  return false;
 }
 
 
 if ($reloadFTP){
  $ftpExecutable = '"'.FTP_EXE_FILE.'" /reload-config';
  $command = $ftpExecutable;
  system($command, $retval);
 }
 
 return true;
 
}
function isUserID($username){return preg_match('/^[A-Za-z0-9][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/', $username);}
function isValid($str){return !preg_match('/[^A-Za-z0-9\_\-]/', $str);}
function add_option($xmlobj,$name,$value){
 $option = $xmlobj->addChild('Option', $value);
 $option->addAttribute('Name', $name);
}

function check_user_exists($xml,$username){
 $children=$xml->Users->children();
 foreach($children as $child){
  if ($child->getName()=='User'){
   foreach($child->attributes() as $attributes ){
    if(trim($attributes) == trim($username)){
     echo "Username $username already exits... \n";
     return true;
    }
   }
  }
 }
 return false;
}







if ($_POST){
 create_user($_POST["user_name"],$_POST["password"],$_POST["ftp_folder"]);
}

?><html><body>
Create FTP User in filzilla server.<br/><br/><form method="POST">
 <table>
  <tr>
   <td>User name : </td>
   <td><input typr="text" name="user_name"/></td>
  </tr>
  <tr>
   <td>Password : </td>
   <td><input typr="text" name="password" /></td>
  </tr>
  <tr>
   <td>FTP root folder : </td>
   <td><input typr="text" name="ftp_folder" /></td>
  </tr>
 </table>
 <input type="submit"></form></body></html>

Enjoy!

Friday, February 8, 2013

TECH: windows 7 SP1 multi rdp session(x86/x64)


windows 7 with SP1 multi rdp session (32/64bit)


download the file :
https://docs.google.com/file/d/0BxpqhwvDEFKvaVBwVUpSUERhMjQ/edit?usp=sharing

extract files and run the file Install.cmd("run as administrator")

enjoy!

C#: extract all domains from text

simple function to find all domain in text:

using : System.Text.RegularExpressions (regex)

public void get_all_domains(string text) {
const string MatchEmailPattern =
@"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)";
Regex rx = new Regex(MatchEmailPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Find matches.
MatchCollection matches = rx.Matches(text);
// Report the number of matches found.
int noOfMatches = matches.Count;
// Report on each match.
foreach (Match match in matches) {
string dst_domain=match.Value.ToString();
if (dst_domain == "")
continue;
      //do something with  dst_domain like :
      //DB.Insert(dst_domain);
}
} 

C#: extract all emails from text

simple function to find all email in text.
using :
System.Text.RegularExpression(regex)

public void get_emails(string text) {
const string MatchEmailPattern = @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@" +
@"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."+
@"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"+
@"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";
Regex rx = new Regex(MatchEmailPattern,RegexOptions.Compiled | RegexOptions.IgnoreCase);
// Find matches.MatchCollection matches = rx.Matches(text);
// Report the number of matches found.int noOfMatches = matches.Count;// Report on each match.
foreach (Match match in matches) {
string email = match.Value.ToString();if (email == "")
continue;
    //do somthing with email variable like.
    //db.insert(email);
}
}

usage:
get_emails("<a href='my@emsil.com'>email2@domain.com</a>");
//found : my@emsil.com , email2@domain.com

Thursday, February 7, 2013

TECH: owa 2007/2010 auto login script (JS)

simple javascript(JS) script to make auto login "outlook web access"

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form action="http://owa.domain.com/auth/owaauth.dll" method="POST"
       name="logonForm" ENCTYPE="application/x-www-form-urlencoded" id="logonFormId">
<input type="hidden" name="destination" value="http://owa.domain.com/">
<input type="hidden" name="flags" value="0">
<input type="hidden" name="forcedownlevel" value="0">
<input id="rdoPrvt" type="radio" name="trusted" value="0" class="rdo" checked><br>
<input id="username" name="username" type="text" value="username@domain.com" ><br>
<input id="password" name="password" type="password" value="userpassword">
<input name="isUtf8" type="hidden" value="1">
<script language="JavaScript">

//Autosubmit the form. Yeah.

document.getElementById('logonFormId').submit();
</script>
</form>
</body>

</html>



Enjoy!