Code snippets

Find all our code examples below in the Snippets Library.

MS Security Essentials End-of-Life Warning Popup Fix (Win XP) (VBScript)



      

' MS SE End-of-Life Warning Popup Fix (Win XP)
' REQUIRES: javaControl (http://www.javitesoft.com/projects.php?javacontrol)

Dim objCtrl
Dim objWnd
Dim objBtn

Set objCtrl = CreateObject("javaControl.clsWindowController")

Do

    Set objWnd = objCtrl.InitByWindow("#32770", "Microsoft Security Essentials")
    If objWnd.IsWindow Then

        Set objBtn = objWnd.GetChild("Button", "&Close")
        If objBtn.IsWindow Then

            objBtn.ClickButton 0
            Exit Do

        End If
        Set objBtn = Nothing

    End If
    Set objWnd = Nothing

    WScript.Sleep 1000

Loop

Set objBtn = Nothing
Set objWnd = Nothing
Set objCtrl = Nothing

      
    

Back to top

Disable Internet Explorer Proxy (VB.NET)



      

Option Explicit On

Imports Microsoft.Win32

Module modDisableProxy

    Private Declare Function SendMessageTimeout Lib "user32" Alias "SendMessageTimeoutA" (ByVal hWnd As Integer, ByVal msg As Integer, ByVal wParam As Integer, ByVal lParam As String, ByVal fuFlags As Integer, ByVal uTimeout As Integer, ByRef lpdwResult As Integer) As Integer

    Private Const HWND_BROADCAST As Integer = &HFFFF
    Private Const WM_SETTINGCHANGE As Integer = &H1A

    Private Enum SendMessageTimeoutFlags
        SMTO_NORMAL = &H0
        SMTO_BLOCK = &H1
        SMTO_ABORTIFHUNG = &H2
        SMTO_NOTIMEOUTIFNOTHUNG = &H0
    End Enum

    Private Declare Function InternetSetOption Lib "wininet" Alias "InternetSetOptionA" (ByVal hInternet As Integer, ByVal lOption As Integer, ByVal sBuffer As Integer, ByVal lBufferLength As Integer) As Integer

    Private Const INTERNET_OPTION_REFRESH As Integer = 37
    Private Const INTERNET_OPTION_SETTINGS_CHANGED As Integer = 39

    Sub DisableProxy()

        Dim regParent As RegistryKey = Registry.CurrentUser
        Dim regSubKey As RegistryKey = regParent.OpenSubKey("Software\Microsoft\Windows\CurrentVersion\Internet Settings\", True)

        regSubKey.SetValue("ProxyEnable", 0)

        Dim result As UIntPtr = UIntPtr.Zero
        SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, UIntPtr.Zero, UIntPtr.Zero, SendMessageTimeoutFlags.SMTO_NORMAL, 1000, result)

        InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0)
        InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0)

    End Sub

End Module

      
    

Back to top

Send URL To Samsung Smart TV (PHP Script)



      

<?php

    function get_url_contents($url)
    {
        $response_input = "";

        $hdrs = array('http' => array(
            'method' => "GET",
            'header' => "Host: ".parse_url($url, PHP_URL_HOST)."\r\n".
            "User-Agent: Mozilla/5.0\r\n\r\n",
            'content' => ''
            )
        );

        $context = stream_context_create($hdrs);

        if(($fp = @fopen($url, "r", false, $context)))
        {
            while(!feof($fp) && ($data = @fread($fp, 4096)))
                $response_input .= $data;

            fclose($fp);
        }

        return $response_input;
    }

    // send url to samsung smart tv

    $service_url = "http://[samsung tv ip]:7676/smp_4_";
    $response_input = "";
    $not_recv = true;
    $retry = 3;
    $retries = 0;

    if (isset($stop) && !empty($stop))
    {
        $post_data = "<?xml version='1.0' encoding='utf-8'?>\r\n".
            "<s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>\r\n".
            "   <s:Body>\r\n".
            "      <u:StopBrowser xmlns:u='urn:samsung.com:service:MainTVAgent2:1'></u:StopBrowser>\r\n".
            "   </s:Body>\r\n".
            "</s:Envelope>";

        $hdrs = array('http' => array(
            'method' => "POST",
            'header' => "HOST: " . parse_url($service_url, PHP_URL_HOST) . ":" . parse_url($service_url, PHP_URL_PORT) . "\r\n".
            "SOAPACTION: 'urn:samsung.com:service:MainTVAgent2:1#StopBrowser'\r\n".
            "CONTENT-TYPE: text/xml; charset='utf-8'\r\n".
            "Content-Length: " . strlen($post_data) . "\r\n\r\n",
            'content' => $post_data
            )
        );
    }
    else if (isset($url) && !empty($url))
    {
        $url_to_post = str_replace("<", "&lt;", str_replace(">", "&gt;", trim($url)));

        if (stripos(parse_url($url_to_post, PHP_URL_HOST), 'youtube.com') !== false)
        {
            // add youtube hacks
            $url_to_post = preg_replace("/\\/watch\\?v\\=/i", "/v/", $url_to_post) . "?";
            $sep = "";
            if (substr($url_to_post, -1) != "?") $sep = "&";
            $url_to_post .= $sep . "HD=1&autoplay=1";
        }

        $post_data = "<?xml version='1.0' encoding='utf-8'?>\r\n".
            "<s:Envelope s:encodingStyle='http://schemas.xmlsoap.org/soap/encoding/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>\r\n".
            "   <s:Body>\r\n".
            "      <u:RunBrowser xmlns:u='urn:samsung.com:service:MainTVAgent2:1'>\r\n".
            "         <BrowserURL>" . $url_to_post . "</BrowserURL>\r\n".
            "      </u:RunBrowser>\r\n".
            "   </s:Body>\r\n".
            "</s:Envelope>";

        $hdrs = array('http' => array(
            'method' => "POST",
            'header' => "HOST: " . parse_url($service_url, PHP_URL_HOST) . ":" . parse_url($service_url, PHP_URL_PORT) . "\r\n".
            "SOAPACTION: 'urn:samsung.com:service:MainTVAgent2:1#RunBrowser'\r\n".
            "CONTENT-TYPE: text/xml; charset='utf-8'\r\n".
            "Content-Length: " . strlen($post_data) . "\r\n\r\n",
            'content' => $post_data
            )
        );
    }

    if (isset($hdrs))
    {
        $context = stream_context_create($hdrs);

        while($not_recv && $retries < $retry)
        {
            if(($fp = @fopen($service_url, "r", false, $context)))
            {
                //$meta_data = stream_get_meta_data($fp);
                $response_input = "";

                while(!feof($fp) && ($data = @fread($fp, 4096)))
                    $response_input .= $data;

                fclose($fp);
            }

            $not_recv = empty($response_input);
            $retries++;

            if ($not_recv && $retries < $retry) sleep(1);
        }
    }

    if (isset($min) && !empty($min))
    {
        echo $response_input;
    }
    else
    {
        echo '<html>
<head>
  <title>Samy Send URL</title>
</head>
<body onload="document.url_form.url.focus(); document.url_form.url.select();">
  <form name="url_form" method="post">
    <input type="hidden" name="stop" value="" />
    <input type="text" name="url" size="60" maxlength="2048" value="' . ((isset($url) && !empty($url)) ? $url : '') . '" autocomplete="off" />
    <input type="submit" value="Send To TV" /> <input type="submit" value="Stop Browser" onclick="this.form.stop.value=\'1\';" />
  </form>
  ' . ((!empty($response_input)) ? '<b>Response: ' . $response_input . '</b>' : '') . '
</body>
</html>
';
    }

?>

      
    

Back to top

System Stats (PHP Script)



      

    // PHP System Stats Script
    // REQUIRES: wmi (http://www.javitesoft.com/snippets.php#wmi)

    define("SYS_PATH", "c:\\");
    
    clearstatcache();

    echo "<ul>\nStorage Statistics<br /><br />\n".
        "<li>" . format_bytes(disk_free_space(SYS_PATH)) . " :: Free space</li>\n" .
        "<li>" . format_bytes(disk_total_space(SYS_PATH) - disk_free_space(SYS_PATH)) . " :: Used space</li>\n" .
        "<li>" . format_bytes(disk_total_space(SYS_PATH)) . " :: Total space</li>\n" .
        "</ul>\n";

    // instantiate the wmi interface class
    $winmgmts = new wmi;

    // get network information
    $netinfo = $winmgmts->GetValues(Array("BytesReceivedPerSec", "BytesSentPerSec", "PacketsReceivedPerSec", "PacketsSentPerSec"), "Win32_PerfRawData_Tcpip_NetworkInterface");

    // convert signed integers to unsigned
    if ($netinfo['BytesReceivedPerSec'] < 0) $netinfo['BytesReceivedPerSec'] = ((float)$netinfo['BytesReceivedPerSec']) + ((float)4294967296);
    if ($netinfo['BytesSentPerSec'] < 0) $netinfo['BytesSentPerSec'] = ((float)$netinfo['BytesSentPerSec']) + ((float)4294967296);
    if ($netinfo['PacketsReceivedPerSec'] < 0) $netinfo['PacketsReceivedPerSec'] = ((float)$netinfo['PacketsReceivedPerSec']) + ((float)4294967296);
    if ($netinfo['PacketsSentPerSec'] < 0) $netinfo['PacketsSentPerSec'] = ((float)$netinfo['PacketsSentPerSec']) + ((float)4294967296);

    // get operating system information
    $sysinfo = $winmgmts->GetValues(Array("LastBootUpTime", "FreePhysicalMemory", "FreeVirtualMemory", "TotalVisibleMemorySize", "TotalVirtualMemorySize"), "Win32_OperatingSystem");

    // get processes and threads
    $sysinfo2 = $winmgmts->GetValues(Array("Processes", "Threads"), "Win32_PerfRawData_PerfOS_System");

    // get processor information
    $procinfo1 = $winmgmts->GetValues(Array("PercentProcessorTime", "Timestamp_Sys100NS"), "Win32_PerfRawData_PerfOS_Processor");

    // wait 2 secs for data calculations
    sleep(2);

    // get network information again
    $netinfo2 = $winmgmts->GetValues(Array("BytesReceivedPerSec", "BytesSentPerSec", "PacketsReceivedPerSec", "PacketsSentPerSec"), "Win32_PerfRawData_Tcpip_NetworkInterface");

    // convert signed integers to unsigned
    if ($netinfo2['BytesReceivedPerSec'] < 0) $netinfo2['BytesReceivedPerSec'] = ((float)$netinfo2['BytesReceivedPerSec']) + ((float)4294967296);
    if ($netinfo2['BytesSentPerSec'] < 0) $netinfo2['BytesSentPerSec'] = ((float)$netinfo2['BytesSentPerSec']) + ((float)4294967296);
    if ($netinfo2['PacketsReceivedPerSec'] < 0) $netinfo2['PacketsReceivedPerSec'] = ((float)$netinfo2['PacketsReceivedPerSec']) + ((float)4294967296);
    if ($netinfo2['PacketsSentPerSec'] < 0) $netinfo2['PacketsSentPerSec'] = ((float)$netinfo2['PacketsSentPerSec']) + ((float)4294967296);

    // perform bytes/packets/sec calculations
    $netinfo['BytesRecvLastSec'] = $netinfo2['BytesReceivedPerSec'] - $netinfo['BytesReceivedPerSec'];
    $netinfo['BytesSentLastSec'] = $netinfo2['BytesSentPerSec'] - $netinfo['BytesSentPerSec'];
    $netinfo['PacketsRecvLastSec'] = $netinfo2['PacketsReceivedPerSec'] - $netinfo['PacketsReceivedPerSec'];
    $netinfo['PacketsSentLastSec'] = $netinfo2['PacketsSentPerSec'] - $netinfo['PacketsSentPerSec'];

    // get processor information again
    $procinfo2 = $winmgmts->GetValues(Array("PercentProcessorTime", "Timestamp_Sys100NS"), "Win32_PerfRawData_PerfOS_Processor");

    // perform proc usage calculation
    $n = $procinfo2['PercentProcessorTime'] - $procinfo1['PercentProcessorTime'];
    $d = $procinfo2['Timestamp_Sys100NS'] - $procinfo1['Timestamp_Sys100NS'];

    $winmgmts->dispose();
    $winmgmts = null;

    // get the boot date/time
    $bootdatetime = $sysinfo['LastBootUpTime'];
    $bootdatetime = $bootdatetime{0} . $bootdatetime{1} . $bootdatetime{2} . $bootdatetime{3} .
        "/" . $bootdatetime{4} . $bootdatetime{5} . "/" . $bootdatetime{6} . $bootdatetime{7} .
        " " . $bootdatetime{8} . $bootdatetime{9} . ":" . $bootdatetime{10} . $bootdatetime{11} .
        ":" . $bootdatetime{12} . $bootdatetime{13};

    $bootsecs = (time() - strtotime($bootdatetime));
    $bootdays = intval($bootsecs / 60 / 60 / 24);
    $boothours = intval(($bootsecs / 60 / 60) - ($bootdays * 24));
    $bootmins = intval(($bootsecs / 60) - (($bootdays * 24) * 60) - ($boothours * 60));

    $bootstr = (($bootdays > 0) ? "$bootdays day(s) " : "").
        (($boothours > 0) ? "$boothours hour(s) " : "")."$bootmins min(s)";

    echo "<ul>\nNetwork Statistics<br /><br />\n" .
        "<li>" . format_bytes($netinfo['BytesRecvLastSec']) . " :: Data Received / sec</li>\n" .
        "<li>" . format_bytes($netinfo['BytesSentLastSec']) . " :: Data Sent / sec</li>\n" .
        "<li>" . number_format($netinfo['PacketsRecvLastSec']) . " :: Packets Received / sec</li>\n" .
        "<li>" . number_format($netinfo['PacketsSentLastSec']) . " :: Packets Sent / sec</li>\n" .
        "<li>" . format_bytes($netinfo['BytesReceivedPerSec']) . " :: Total Data Received</li>\n" .
        "<li>" . format_bytes($netinfo['BytesSentPerSec']) . " :: Total Data Sent</li>\n" .
        "<li>" . number_format($netinfo['PacketsReceivedPerSec']) . " :: Total Packets Received</li>\n" .
        "<li>" . number_format($netinfo['PacketsSentPerSec']) . " :: Total Packets Sent</li>\n" .
        "</ul>\n";

    echo "<ul>\nComputer Statistics<br /><br />\n" .
        "<li>$bootstr :: Computer Uptime</li>\n" .
        "<li>" . number_format(abs(100 - (100 * $n / $d)), 2) . "% :: Current Processor Usage</li>\n" .
        "<li>" . number_format($sysinfo2['Processes']) . " :: Total Processes</li>\n" .
        "<li>" . number_format($sysinfo2['Threads']) . " :: Total Threads</li>\n" .
        "<li>" . format_bytes($sysinfo['FreePhysicalMemory'] * 1024) . " :: Free Physical Memory</li>\n" .
        "<li>" . format_bytes($sysinfo['FreeVirtualMemory'] * 1024)  ." :: Free Virtual Memory</li>\n" .
        "<li>" . format_bytes($sysinfo['TotalVisibleMemorySize'] * 1024) . " :: Total Physical Memory</li>\n" .
        "<li>" . format_bytes($sysinfo['TotalVirtualMemorySize'] * 1024) . " :: Total Virtual Memory</li>\n" .
        "</ul>\n";

      
    

Back to top

javaProxy (PHP Proxy Script)



      

    // javaProxy ---> http pass-thru via query string

    $url = urldecode($QUERY_STRING);

    if (strlen($url) == 0) die("Please enter the url as the query string.");

    $base_host = parse_url_component($url, "host");
    $headers = request_headers();
    $buff = "";
    $is_text = false;

    if (!isset($SCRIPT_URI)) $SCRIPT_URI = "http://".$HTTP_HOST.$PHP_SELF;

    if (!array_key_exists("User-Agent", $headers))
        $headers['User-Agent'] = "Mozilla/5.0";

    foreach ($headers as $header => $value)
    {
        if (strtolower($header) == "host") $value = $base_host;
        if (strpos(strtolower($header), "accept") === false) $buff .= "$header: $value\r\n";
    }

    if (strpos(strtolower($buff), "connection:") === false)
        $buff .= "Connection: close\r\n";

    if ($REQUEST_METHOD == "GET")
    {
        $hdrs = array('http' => array(
            'method' => "GET",
            'header'=> "$buff\r\n"
            )
        );
    }
    else if ($REQUEST_METHOD == "POST")
    {
        $request_content = "";
        if (strpos(strtolower($buff), "content-length") !== false)
            $buff = str_replace("Content-Length:", "Filler-Arg:", $buff);

        foreach ($_POST as $k => $v)
        {
            $request_content .= (($request_content != "") ? "&" : "")."$k=$v";
        }

        $hdrs = array('http' => array(
            'method' => "POST",
            'header' => "$buff".
            "Content-Length: ".strlen($request_content)."\r\n\r\n",
            'content' => $request_content
            )
        );
    }

    clearstatcache();
    $context = stream_context_create($hdrs);

    if(!($fp = fopen($url, "r", false, $context)))
        die("Error: Cannot open url: $url");

    $meta_data = stream_get_meta_data($fp);

    foreach ($meta_data['wrapper_data'] as $response)
    {
        if (strpos($response, "text") !== false) $is_text = true;
        header($response);
    }

    $buff = "";

    while($data = fread($fp, 4096))
        $buff .= $data;

    fclose($fp);

    if ($is_text) echo fix_links($buff);
    else echo $buff;

    // FUNCTIONS ------------------------------------------------------

    function fix_links($data)
    {
        global $SCRIPT_URI, $base_host;

        $data = preg_replace("/href\\=\\\"http\\:\\/\\/([^\\\"]*)/e", "'href=\"$SCRIPT_URI?http://'.urlencode('$1')", $data);
        $data = preg_replace("/href\\=\\\"\\/([^\\\"]*)/e", "'href=\"$SCRIPT_URI?http://$base_host/'.urlencode('$1')", $data);
        $data = preg_replace("/href\\='http\\:\\/\\/([^']*)/e", "'href=\'$SCRIPT_URI?http://'.urlencode('$1')", $data);
        $data = preg_replace("/href\\='\\/([^']*)/e", "'href=\'$SCRIPT_URI?http://$base_host/'.urlencode('$1')", $data);
        $data = preg_replace("/href\\=http\\:\\/\\/([^\\>\\s\\/]*)/e", "'href=$SCRIPT_URI?http://'.urlencode('$1')", $data);
        $data = preg_replace("/href\\=\\/([^\\>\\s\\/]*)/e", "'href=$SCRIPT_URI?http://$base_host/'.urlencode('$1')", $data);
        $data = preg_replace("/src\\=\\\"http\\:\\/\\/([^\\\"]*)/e", "'src=\"$SCRIPT_URI?http://'.urlencode('$1')", $data);
        $data = preg_replace("/src\\=\\\"\\/([^\\\"]*)/e", "'src=\"$SCRIPT_URI?http://$base_host/'.urlencode('$1')", $data);
        $data = preg_replace("/src\\='http\\:\\/\\/([^']*)/e", "'src=\'$SCRIPT_URI?http://'.urlencode('$1')", $data);
        $data = preg_replace("/src\\='\\/([^']*)/e", "'src=\'$SCRIPT_URI?http://$base_host/'.urlencode('$1')", $data);
        $data = preg_replace("/src\\=http\\:\\/\\/([^\\>\\s\\/]*)/e", "'src=$SCRIPT_URI?http://'.urlencode('$1')", $data);
        $data = preg_replace("/src\\=\\/([^\\>\\s\\/]*)/e", "'src=$SCRIPT_URI?http://$base_host/'.urlencode('$1')", $data);
        $data = preg_replace("/action\\=\\\"http\\:\\/\\/([^\\\"]*)/e", "'action=\"$SCRIPT_URI?http://'.urlencode('$1')", $data);
        $data = preg_replace("/action\\=\\\"\\/([^\\\"]*)/e", "'action=\"$SCRIPT_URI?http://$base_host/'.urlencode('$1')", $data);
        $data = preg_replace("/action\\='http\\:\\/\\/([^']*)/e", "'action=\'$SCRIPT_URI?http://'.urlencode('$1')", $data);
        $data = preg_replace("/action\\='\\/([^']*)/e", "'action=\'$SCRIPT_URI?http://$base_host/'.urlencode('$1')", $data);
        $data = preg_replace("/action\\=http\\:\\/\\/([^\\>\\s\\/]*)/e", "'action=$SCRIPT_URI?http://'.urlencode('$1')", $data);
        $data = preg_replace("/action\\=\\/([^\\>\\s\\/]*)/e", "'action=$SCRIPT_URI?http://$base_host/'.urlencode('$1')", $data);

        return str_replace("\\\"", "\"", $data);
    }

    function request_headers()
    {
        global $_SERVER;

        if(function_exists("apache_request_headers")) // If apache_request_headers() exists...
        {
            if($headers = apache_request_headers()) // And works...
            {
                return $headers; // Use it
            }
        }

        $headers = array();

        foreach(array_keys($_SERVER) as $skey)
        {
            if(substr($skey, 0, 5) == "HTTP_")
            {
                $headername = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($skey, 5)))));
                $headers[$headername] = $_SERVER[$skey];
            }
        }

        return $headers;
    }

    function parse_url_component($url, $component)
    {
        $contents = parse_url($url);
        return $contents[$component];
    }

      
    

Back to top

Remote Windows Management Instrumentation class (PHP Script)



      

    // rwmi: Remote Windows Management Instrumentation class

    define("RWMI_PROGID", "WbemScripting.SWbemLocator");

    class rwmi
    {

        // class object references
        var $winmgmts;

        function rwmi($host, $username, $password)
        {
            $this->__construct($host, $username, $password);
        }

        function __construct($host, $username, $password)
        {
            // connect to the windows management console
            $this->winmgmts = new COM(RWMI_PROGID);
            $this->winmgmts = $this->winmgmts->ConnectServer($host, "root/CIMV2", $username, $password);
        }

        function GetValue($prop_name, $class_name, $conditions="")
        {
            if (!empty($conditions)) $conditions = " where $conditions";

            // query prop_name from class_name
            $wmi_query = $this->winmgmts->ExecQuery("Select $prop_name from $class_name$conditions");
            $ret = null;
            foreach ($wmi_query as $wmi_call)
            {
                eval('$ret = $wmi_call->'.$prop_name.';');
                break;
            }

            return $ret;
        }

        function GetValues($prop_names, $class_name, $conditions="")
        {
            if (!empty($conditions)) $conditions = " where $conditions";

            // query prop_names from class_name
            $wmi_query = $this->winmgmts->ExecQuery("Select ".implode(", ", $prop_names)." from $class_name$conditions");
            $ret = array();
            foreach ($wmi_query as $wmi_call)
            {
                foreach ($prop_names as $prop_name)
                {
                    eval('$ret[$prop_name] = $wmi_call->'.$prop_name.';');
                }
                break;
            }
            return $ret;
        }

        function GetAllValues($prop_names, $class_name, $conditions="")
        {
            if (!empty($conditions)) $conditions = " where $conditions";

            // query prop_names from class_name
            $wmi_query = $this->winmgmts->ExecQuery("Select ".implode(", ", $prop_names)." from $class_name$conditions");
            $ret = array();
            $i = 0;

            foreach ($wmi_query as $wmi_call)
            {
                foreach ($prop_names as $prop_name)
                {
                    eval('$ret[$i][$prop_name] = $wmi_call->'.$prop_name.';');
                }

                $i++;
            }
            return $ret;
        }

        function dispose()
        {
            $this->winmgmts = null;
        }
    }

/* EXAMPLE:

    // instantiate the rwmi interface class
    $winmgmts = new rwmi("remotemachine", "user", "pass");

    // get computer name
    $compname = $winmgmts->GetValue("Name", "Win32_ComputerSystem");

    print_r($compname);

    $winmgmts = null;

*/

      
    

Back to top

Windows Management Instrumentation class (PHP Script)



      

    // wmi: Windows Management Instrumentation class

    define("WMI_PROGID", "winmgmts://%s/root/CIMV2");
    define("DEFAULT_HOST", "localhost");

    class wmi
    {

        // class object references
        var $winmgmts;

        function wmi($host = DEFAULT_HOST)
        {
            $this->__construct($host);
        }

        function __construct($host = DEFAULT_HOST)
        {
            // connect to the windows management console
            $this->winmgmts = new COM(sprintf(WMI_PROGID, $host));
        }

        function GetValue($prop_name, $class_name, $conditions="")
        {
            if (!empty($conditions)) $conditions = " where $conditions";

            // query prop_name from class_name
            $wmi_query = $this->winmgmts->ExecQuery("Select $prop_name from $class_name$conditions");

            return eval('$wmi_query->'.$prop_name);
        }

        function GetValues($prop_names, $class_name, $conditions="")
        {
            if (!empty($conditions)) $conditions = " where $conditions";

            // query prop_names from class_name
            $wmi_query = $this->winmgmts->ExecQuery("Select ".implode(", ", $prop_names)." from $class_name$conditions");
            $ret = array();

            foreach ($wmi_query as $wmi_call)
            {
                foreach ($prop_names as $prop_name)
                {
                    eval('$ret[$prop_name] = $wmi_call->'.$prop_name.';');
                }
                break;
            }
            return $ret;
        }

        function GetAllValues($prop_names, $class_name, $conditions="")
        {
            if (!empty($conditions)) $conditions = " where $conditions";

            // query prop_names from class_name
            $wmi_query = $this->winmgmts->ExecQuery("Select ".implode(", ", $prop_names)." from $class_name$conditions");
            $ret = array();
            $i = 0;

            foreach ($wmi_query as $wmi_call)
            {
                foreach ($prop_names as $prop_name)
                {
                    eval('$ret[$i][$prop_name] = $wmi_call->'.$prop_name.';');
                }

                $i++;
            }
            return $ret;
        }

        function dispose()
        {
            $this->winmgmts = null;
        }
    }

/* EXAMPLE:

    // instantiate the wmi interface class
    $winmgmts = new wmi;

    // get operating system information
    $sysinfo = $winmgmts->GetValues(Array("LastBootUpTime", "FreePhysicalMemory", "FreeVirtualMemory", "TotalVisibleMemorySize", "TotalVirtualMemorySize"), "Win32_OperatingSystem");

    // get processes and threads
    $sysinfo2 = $winmgmts->GetValues(Array("Processes", "Threads"), "Win32_PerfRawData_PerfOS_System");

    print_r($sysinfo);
    print_r($sysinfo2);

    $winmgmts = null;

*/

      
    

Back to top

Read System Tray Tooltips (PHP Script)



      

    // SAMPLE SYSTEM TRAY ENUMERATION
    // REQUIRES: javaControl (http://www.javitesoft.com/projects.php?javacontrol)

    define("SYSTRAYCONTROLLER_PROGID", "javaControl.clsSysToolbar");

    // instantiate the system tray controller
    $sysTray = new COM(SYSTRAYCONTROLLER_PROGID);
    if (!is_null($sysTray)) $sysTray = $sysTray->Init();

    $stats = "";

    if (!is_null($sysTray))
    {
        for ($i = 0; $i < $sysTray->Count; $i++)
        {
            $btn = $sysTray->GetButtonByIndex($i);

            if (!is_null($btn))
            {
                $stats .= "<li>".$btn->Text."</li>\n";
            }

            $btn = null;
        }
    }

    echo $stats;

    $sysTray = null;

      
    

Back to top

Download All Links From A Specified URL (VB.NET)



      

Option Explicit On

Imports System.IO
Imports System.Net
Imports System.Text.RegularExpressions

<Microsoft.VisualBasic.ComClass()> Public Class clsHttpExtractor

    Public Class clsPullFilesResult
        Public PulledFiles As New Collection
        Public LastErrorException As Exception
        Public LastWebException As System.Net.WebException
    End Class

    Public Class clsPullFilesProgress

        Public FileName As String = ""
        Public FileSize As Integer = 0

        Public Sub New(ByVal strFileName As String, _
            ByVal intFileSize As Integer)
            FileName = strFileName
            FileSize = intFileSize
        End Sub

    End Class

    Public Delegate Sub PullFilesCallback(ByVal e As clsPullFilesResult)
    Public Delegate Sub PullFilesProgressCallback(ByVal e As clsPullFilesProgress)

    Private thisHttp As HttpWebRequest
    Private thisURI As String = ""
    Private thisPutPath As String = ""
    Private thisFinishedCallback As PullFilesCallback
    Private thisProgressCallback As PullFilesProgressCallback
    Private thisResult As clsPullFilesResult
    Private ASCII As New System.Text.ASCIIEncoding()

    Private Const BUFFER_SIZE = 8192

    Public Function PullFiles(ByVal strURI As String, ByVal strPutPath As String, _
        ByVal funcFinishedCallback As PullFilesCallback, _
        Optional ByVal funcProgressCallback As PullFilesProgressCallback = Nothing) As Boolean

        Try
            ' store the request uri
            thisURI = strURI

            ' store the put path
            thisPutPath = strPutPath

            ' store the finished callback method
            thisFinishedCallback = funcFinishedCallback

            ' store the progress callback method
            thisProgressCallback = funcProgressCallback

            ' instantiate the new web request
            thisHttp = HttpWebRequest.Create(strURI)

            ' instantiate the async result object
            thisResult = New clsPullFilesResult

            ' begin the async http request
            thisHttp.BeginGetResponse(AddressOf BeginCallBack, Nothing)

            Return True

        Catch
            Return False
        End Try

    End Function

    Private Sub BeginCallBack(ByVal ar As IAsyncResult)

        ' buffer
        Dim buffer(BUFFER_SIZE - 1) As Byte
        Dim lastRead As Integer = 0
        Dim i As Integer = 0
        Dim strResponse As String = ""

        Try
            ' end async receive and get response
            Dim thisResponse As WebResponse = thisHttp.EndGetResponse(ar)

            ' open request stream
            Dim responseStream As Stream = thisResponse.GetResponseStream()

            ' receive file
            Do While i < thisResponse.ContentLength

                ' read from response stream
                lastRead = responseStream.Read(buffer, 0, buffer.Length)

                i += lastRead

                ' check last recv
                If lastRead < BUFFER_SIZE - 1 Then Array.Resize(buffer, lastRead)

                ' buffer the response
                strResponse += ASCII.GetString(buffer, 0, buffer.Length)

                ' resize buffer
                If buffer.Length < BUFFER_SIZE - 1 Then Array.Resize(buffer, BUFFER_SIZE - 1)

            Loop

            ' get an array of links from the html
            Dim htmlLinks As ArrayList = ParseLinks(strResponse)

            ' cleanup
            thisResponse.Close()
            Array.Clear(buffer, 0, buffer.Length)
            htmlLinks.RemoveAt(0)

            ' download each link
            ProcessList(htmlLinks)

        Catch ex As Exception
            thisResult.LastErrorException = ex
        End Try

        Try
            ' invoke the finished callback method and pass result
            thisFinishedCallback.Invoke(thisResult)
        Catch
        End Try

    End Sub

    Private Sub ProcessList(ByVal htmlLinks As ArrayList)

        For Each thisFile As String In htmlLinks

            ' get the filename from the uri
            thisFile = thisFile.Substring(thisFile.LastIndexOf("/") + 1)

            Try
                ' instantiate the new web request
                thisHttp = HttpWebRequest.Create(thisURI + thisFile)

                ' begin the syncronous http request
                Dim thisResponse As WebResponse = thisHttp.GetResponse()

                ' open response stream
                Dim responseStream As Stream = thisResponse.GetResponseStream()

                ' open destination stream
                Dim destStream As Stream = New StreamWriter(thisPutPath + thisFile, False).BaseStream

                ' buffer
                Dim buffer(BUFFER_SIZE - 1) As Byte
                Dim lastRead As Integer = 0
                Dim i As Integer = 0
                Dim thisSize As Integer = thisResponse.ContentLength

                ' receive file
                Do While i < thisSize

                    ' read from response stream
                    lastRead = responseStream.Read(buffer, 0, buffer.Length)

                    i += lastRead

                    ' check last recv
                    If lastRead < BUFFER_SIZE - 1 Then Array.Resize(buffer, lastRead)

                    ' write to destination stream
                    destStream.Write(buffer, 0, buffer.Length)

                    ' resize buffer
                    If buffer.Length < BUFFER_SIZE - 1 Then Array.Resize(buffer, BUFFER_SIZE - 1)

                Loop

                ' cleanup
                destStream.Close()
                responseStream.Close()
                Array.Clear(buffer, 0, buffer.Length)

                ' store the filename in the files collection
                thisResult.PulledFiles.Add(thisFile)

                If Not (thisProgressCallback Is Nothing) Then

                    Try
                        ' invoke the progress callback method and pass result
                        thisProgressCallback.Invoke( _
                            New clsPullFilesProgress(thisFile, thisSize))
                    Catch
                    End Try

                End If

            Catch exw As WebException
                thisResult.LastWebException = exw
            Catch ex As Exception
                thisResult.LastErrorException = ex
                Exit For
            End Try

        Next

    End Sub

    Private Function ParseLinks(ByVal strHTML As String) As ArrayList

        Dim objRegEx As Regex
        Dim objMatch As Match
        Dim arrLinks As New ArrayList

        ' create regular expression
        objRegEx = New Regex("href=(?:""(?<1>[^""]*)"")", _
            RegexOptions.IgnoreCase Or RegexOptions.Compiled)

        ' match expression to html
        objMatch = objRegEx.Match(strHTML)

        ' loop through matches and add <1> to ArrayList
        While objMatch.Success
            arrLinks.Add(objMatch.Groups(1).ToString)
            objMatch = objMatch.NextMatch()
        End While

        ' return array
        Return arrLinks

    End Function

End Class

      
    

Back to top