public static function GetFileMimeType($path) { if (file_exists($path)) { try { if (class_exists("finfo")) { // Probe magick database file $magic_db_path = dirname(__FILE__) . "/magic"; if (!file_exists($magic_db_path)) { $magic_db_path = "/usr/share/file/magic"; } // Create fifo instance $finfo = new finfo(FILEINFO_MIME, $magic_db_path); if ($finfo) { $retval = @$finfo->file($path); } else { Core::RaiseError("Cannot open FIFO database. Tried {$magic_db_path}", E_ERROR); } return $retval; } elseif (function_exists("mime_content_type")) { return mime_content_type($path); } else { Core::RaiseError("Cannot determine file mime type.", E_ERROR); return ""; } } catch (Exception $e) { Core::RaiseError($e->getMessage(), E_ERROR); } } else { Core::RaiseWarning("File not found."); return ""; } }
function libwebta_error_handler($errno, $errstr, $errfile, $errline) { $message = "Error {$errno} {$errstr}, in {$errfile}:{$errline}"; switch ($errno) { case E_CORE_ERROR: case E_ERROR: case E_USER_ERROR: Core::ThrowException($message, $errno); break; case E_USER_WARNING: Core::ThrowException($message, E_USER_WARNING); break; case E_USER_NOTICE: break; default: if (error_reporting() & $errno) Core::RaiseWarning($message); break; } }
/** * Get filesystem block size * @access public * @param string $device Device * @return int block size in bytes */ public function GetFSBlockSize($device) { $retval = $this->Shell->QueryRaw("/sbin/dumpe2fs {$device} 2>/dev/null | grep \"Block size\" | awk '{print \$3}'"); if (!is_int($retval)) { Core::RaiseWarning(_("Cannot determine filesystem block size")); $retval = false; } return $retval; }
/** * Upload file from URL * * @param string $url * @return bool * @todo Pass custom headers, like User-Agent */ public function UploadFromURL($url, $headers = array()) { $urlinfo = parse_url($url); $file = array("name" => $this->NormalizeFileName(basename($url))); // Open socket connection $sock = @fsockopen($urlinfo['host'], $urlinfo["port"] ? $urlinfo["port"] : 80, $errno, $errstr, 10); @stream_set_blocking($sock, 1); // If cannot open socket connection raise warning and return false if (!$sock) { $this->RaiseWarning(_("Failed to copy a file. Cannot connect to " . $urlinfo['host'] . "."), false); return false; } else { if (substr($urlinfo['path'], 0, 1) != '/') { $urlinfo['path'] = "/{$urlinfo['path']}"; } // Define request $request = "GET " . $urlinfo['path'] . ($urlinfo['query'] ? "?{$urlinfo['query']}" : "") . " HTTP/1.1\r\n"; if (count($headers) > 0 && is_array($headers)) { $request .= implode("\r\n", $headers) . "\r\n"; } $request .= "Host: {$urlinfo['host']}\r\n"; $request .= "Connection: Close\r\n\r\n"; // Send request @fwrite($sock, $request); $headers = ""; while ($str != "\r\n") { $str = @fgets($sock, 2048); $headers .= $str; } if (stristr($headers, "200 OK")) { while (!feof($sock) && !$meta['eof']) { @file_put_contents($this->Destination, @fgets($sock, 2048), FILE_APPEND); $meta = stream_get_meta_data($sock); } // Generate real file info $this->File = array("name" => basename($url), "type" => IOTool::GetFileMimeType($this->Destination), "size" => @filesize($this->Destination)); // Validate real file info if ($this->Validate()) { if (file_exists($this->Destination)) { return true; } else { Core::RaiseError(_("Cannot write file."), E_ERROR); } } @unlink($this->Destination); return false; } else { $tmp = split("\n", $headers); $error = trim($tmp[0]); Core::RaiseWarning($error); return false; } @fclose($sock); } }
/** * Convert a BIND-style time(1D, 2H, 15M) to seconds. * * @param string $time Time to convert. * @return int time in seconds on success, PEAR error on failure. */ function ParseTimeToSeconds($time) { if (is_numeric($time)) { //Already a number. Return. return $time; } else { // TODO: Add support for multiple \d\s $split = preg_split("/([0-9]+)([a-zA-Z]+)/", $time, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); if (count($split) != 2) Core::RaiseWarning(sprintf(_("Unable to parse time. %d"), $time)); list($num, $what) = $split; switch (strtoupper($what)) { case 'S': //Seconds $times = 1; break; case 'M': //Minute $times = 1 * 60; break; case 'H': //Hour $times = 1 * 60 * 60; break; case 'D': //Day $times = 1 * 60 * 60 * 24; break; case 'W': //Week $times = 1 * 60 * 60 * 24 * 7; break; default: Core::RaiseWarning(sprintf(_("Unable to parse time %s"), $time)); break; } $time = $num * $times; return $time; } }
case "MX": $record = new MXDNSRecord($record["rkey"], $record["rvalue"], $record["ttl"], $record["rpriority"]); $Zone->AddRecord($record); break; } } } foreach ($Zone->Records as $record) { if (!($record instanceof CNAMEDNSRecord)) { if (in_array($record->Name, $CNAMERecords)) { Core::RaiseWarning(sprintf(_("CNAME RRs '%s' cannot have any other RRs with the same name."), $record->Name)); $error = true; } } } $zonecontent = $Zone->__toString(); if (Core::HasWarnings()) $error = true; } if ($error) { $db->RollbackTrans(); Log::Log(sprintf(_("Failed to generate DNS zone for '%s'"), $post_zonename), E_ERROR);
/** * Create new object on S3 Bucket * * @param string $object_path * @param string $bucket_name * @param string $filename * @param string $object_content_type * @param string $object_permissions * @return bool */ public function CreateObject($object_path, $bucket_name, $filename, $object_content_type, $object_permissions = "public-read") { if (!file_exists($filename)) { Core::RaiseWarning("{$filename} - no such file."); return false; } $HttpRequest = new HttpRequest(); $HttpRequest->setOptions(array( "redirect" => 10, "useragent" => "LibWebta AWS Client (http://webta.net)" ) ); $timestamp = $this->GetTimestamp(true); $data_to_sign = array("PUT", "", $object_content_type, $timestamp, "x-amz-acl:{$object_permissions}","/{$bucket_name}/{$object_path}"); $signature = $this->GetRESTSignature($data_to_sign); $HttpRequest->setUrl("http://{$bucket_name}.s3.amazonaws.com/{$object_path}"); $HttpRequest->setMethod(constant("HTTP_METH_PUT")); $headers["Content-type"] = $object_content_type; $headers["x-amz-acl"] = $object_permissions; $headers["Date"] = $timestamp; $headers["Authorization"] = "AWS {$this->AWSAccessKeyId}:{$signature}"; $HttpRequest->addHeaders($headers); $HttpRequest->setPutFile($filename); try { $HttpRequest->send(); $info = $HttpRequest->getResponseInfo(); if ($info['response_code'] == 200) return true; else { $xml = @simplexml_load_string($HttpRequest->getResponseBody()); return $xml->Message; } } catch (HttpException $e) { Core::RaiseWarning($e->__toString(), E_ERROR); return false; } }
/** * Converts a BIND-style timeout(1D, 2H, 15M) to seconds. * * @param string $time Time to convert. * @return int time in seconds on success, PEAR error on failure. */ function ParseTimeToSeconds($time) { if (is_numeric($time)) { //Already a number. Return. return $time; } else { $pattern = '/([0-9]+)([a-zA-Z]+)/'; $split = preg_split($pattern, $time, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); if (count($split) != 2) { Core::RaiseWarning(sprintf(_("Unable to parse time. %d"), $time)); } list($num, $what) = $split; switch (strtoupper($what)) { case 'S': $times = 1; //Seconds break; case 'M': $times = 1 * 60; //Minute break; case 'H': $times = 1 * 60 * 60; //Hour break; case 'D': $times = 1 * 60 * 60 * 24; //Day break; case 'W': $times = 1 * 60 * 60 * 24 * 7; //Week break; default: Core::RaiseWarning(sprintf(_("Unable to parse time. %d"), $time)); break; } $time = $num * $times; return $time; } }
/** * Add Class to REST * * @param string $classname * @param string $namespace * @return bool */ public function AddClass($classname, $args = array()) { $namespace = ""; if (class_exists($classname)) { $reflectionClass = new ReflectionClassEx($classname); $methods = $reflectionClass->getPublicMethods(); foreach ($methods as $method) { if ($namespace == "") { $this->Methods[$method->getName()] = $method; } else { $this->Methods[$namespace][$method->getName()] = $method; } } } else { Core::RaiseWarning("Class '{$classname}' not found"); return false; } }
public function Fetch($file, $notheme=false) { $this->HTMLResult = false; try { $this->ExecRetry++; $ch = curl_init(); if (!$notheme) curl_setopt($ch, CURLOPT_URL, "https://{$this->Host}:2083/frontend/".$this->Theme."/{$file}"); else curl_setopt($ch, CURLOPT_URL, "https://{$this->Host}:2083/{$file}"); curl_setopt($ch, CURLOPT_USERPWD, $this->User.":".$this->Password); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->ConnectTimeout); curl_setopt($ch, CURLOPT_TIMEOUT, $this->ExecTimeout); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0); $res = curl_exec($ch); $e = curl_error($ch); // Try to Fetch again or raise warning. if ($e) { if ($this->ExecRetry >= $this->ExecRetries) Core::RaiseWarning($e); else { @curl_close($ch); $this->Fetch($file, $notheme); } } @curl_close($ch); } catch(Exception $e) { Core::RaiseWarning("Failed to fetch CPanel page. ".$e->__toString()); return false; } if (!$res) { Core::RaiseWarning("Failed to fetch CPanel page. Make sure that theme name is correct."); return false; } // Return $this->HTMLResult = $res; // Reset retries counter $this->ExecRetry = 0; return true; }
/** * Send request to payment server * @param float $amount * @param integer $invoiceid * @param string $description * @param string $type 'single or subscription' * @param array $extra * * @return bool */ public final function ProceedToPayment($amount, $invoiceid, $description, $type = 'single', $extra = array()) { $merchant_reference = "REF ".implode("", explode(" ", microtime())); $amount = $amount*100; $request = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <JProxyPayLink> <Message> <Type>PreAuth</Type> <Authentication> <MerchantID>".CF_PAYMENTS_PROXYPAY3_MERCHANTID."</MerchantID> <Password>".CF_PAYMENTS_PROXYPAY3_PASSWORD."</Password> </Authentication> <OrderInfo> <Amount>{$amount}</Amount> <MerchantRef>{$merchant_reference}</MerchantRef> <MerchantDesc>".htmlspecialchars($description)."</MerchantDesc> <Currency>{$this->CurrencySymbol}</Currency> <CustomerEmail>{$extra["email"]}</CustomerEmail> <Var1>InvoiceID: {$invoiceid}</Var1> <Var2 /> <Var3 /> <Var4 /> <Var5 /> <Var6 /> <Var7 /> <Var8 /> <Var9 /> </OrderInfo> <PaymentInfo> <CCN>{$extra["ccn"]}</CCN> <Expdate>{$extra["Expdate_m"]}{$extra["Expdate_Y"]}</Expdate> <CVCCVV>{$extra["cvv"]}</CVCCVV> <InstallmentOffset>0</InstallmentOffset> <InstallmentPeriod>0</InstallmentPeriod> </PaymentInfo> </Message> </JProxyPayLink> "; $response = $this->SendRequest($request); if(!$response) return false; $response = @simplexml_load_string($response); if (intval($response->ERRORCODE) != 0) { Core::RaiseWarning(sprintf(_("Cannot proceed request. Error code: %s. Please contact Administrator."), $response->ERRORCODE)); return false; } else return true; }
/** * Generate a text zone file * @access public * @return string Zone file content */ function __toString() { $this->Content = $this->Template; if (count($this->Records) == 0) { Core::RaiseWarning(_("No records found")); return ""; } foreach ($this->RecordsSortMap as $RecordType) { foreach((array)$this->Records as $Record) { $classname = "{$RecordType}DNSRecord"; if ($Record instanceof $classname) { // Set TTL if ($this->TTL && !$Record->TTL) $Record->TTL = ""; elseif (!$Record->TTL && $RecordType != "SOA") $Record->TTL = $Record->DefaultTTL; // Raise Preference for MX record if ($RecordType == "MX") $Record->Pref = $this->RaiseMXPref($Record->Pref); if ($RecordType == "SOA") $soa = $Record; $this->Content .= $Record->__toString()."\n"; } } } $tags = array("{name}" => $soa->Name); if ($this->TTL) $tags["{ttl}"] = '$TTL '.$this->TTL; else $tags["{ttl}"] = ""; $this->Content = str_replace( array_keys($tags), array_values($tags), $this->Content ); return $this->Content; }
/** * Return array with all zones * @access public * @return array $zones */ public function ListZones($ptr_zones = false) { // Delete multiline comments from named.conf $this->Conf = preg_replace("/\\/\\*(.*?)\\*\\//ism", "", $this->Conf); $lines = explode("\n", $this->Conf); $retval = array(); foreach ($lines as $line) { preg_match_all("/^[^\\/;#]*zone(.*?)['\"]+(.*?)['\"]+(.*?)\\{(.*?)\$/si", $line, $matches); // filter local zones if ($matches[2][0] != '' && $matches[2][0] != '.' && $matches[2][0] != 'localhost' && $matches[2][0] != 'localdomain' && !stristr($matches[2][0], "in-addr.arpa") && !stristr($matches[2][0], "ip6.arpa") && !$ptr_zones || (stristr($matches[2][0], "in-addr.arpa") || stristr($matches[2][0], "ip6.arpa")) && $ptr_zones) { $in_zone = $matches[2][0]; } if (preg_match("/^[^\\/;#]*}/", $line, $matches)) { $in_zone = false; } if ($in_zone) { preg_match_all("/^[^\\/;#]*file(.*?)['\"]+(.*?)['\"]+(.*?)\$/si", $line, $matches); if ($matches[2][0]) { $content = $this->GetZoneFileContent($matches[2][0]); if ($content) { $retval[$in_zone] = $content; } else { Core::RaiseWarning("Cannot get '{$matches[2][0]}'"); } } } } return $retval; }
/** * Start virtualhost * * @return bool */ public function Start() { $res = $this->SSH2->Exec("{$this->VentriloPath}/vent.sh start {$this->Port}", "\004"); if ($res) { if (stristr($res, "Cannot find")) { Core::RaiseWarning(_("Cannot find virtualhost")); return false; } elseif (stristr($res, "Cannot start server on")) { $lines = explode("\n", $res); $error = $lines[count($lines)-5]."\n".$lines[count($lines)-4]; Core::RaiseWarning($error); return false; } elseif (stristr($res, "Done.")) return true; else { Core::RaiseWarning(_("Unknown error")); return false; } } else return false; }
/** * Whois request * * @param string $host * @return string */ public function FetchRecord($host) { // Cut off www if(substr($host, 0, 4) == 'www.') $host = substr($host, 4); // Extract TLD and find a suitable whois server $pi = pathinfo($host); $whoisinfo = $this->Servers[$pi["extension"]]; if (!$whoisinfo[0]) { Core::RaiseWarning(sprintf(_("No custom whois server defined for %s. Using default one."), $host)); $hostparam = ""; } else $hostparam = " -h {$whoisinfo[0]}"; // Sanitize $host = escapeshellcmd($host); // Execute Shell command and Get result $retval = $this->Shell->QueryRaw("{$this->WhoisBinPath} {$hostparam} {$host}"); // Check domain name existense and return false if domain NOT exists or Raw whois data about domain if (stristr($retval, $whoisinfo[1]) || stristr($retval, "hostname nor servname provided") || preg_match("/((No entries found)|(No match)|(No Data Found)|(No match for)|(No data found))/si", $retval) ) return false; else return $retval; }
/** * Ventrilo Constructor * * @param string $host * @param integer $port * @param array $authinfo * @param string $ventrilo_path * @param string $config_template * @return bool */ function __construct ($host, $port, $login, $password, $ventrilo_path, $config_template) { parent::__construct(); $this->VentriloPath = $ventrilo_path; $this->ConfigTemplate = $config_template; $this->SSH2 = new SSH2(); if (!$this->SSH2->TestConnection($host, $port)) { Core::RaiseWarning(_("Cannot connect to remote server")); die(_("Cannot connect to remote server")); return false; } if (!$this->SSH2->Connect($host, $port, $login, trim($password))) { Core::RaiseWarning(_("Cannot connect to remote server")); die(_("Cannot connect to remote server")); return false; } $this->SSHHost = $host; $this->SSHPort = $port; $this->SSHLogin = $login; $this->SSHPassword = trim($password); return true; }
/** * Connect to memcached server * @return bool * @access protected */ protected function Connect() { if (!is_object($this->MemCache)) $this->MemCache = new Memcache; try { $this->IsConnected = @$this->MemCache->connect($this->Options["host"], $this->Options["port"]); return $this->IsConnected; } catch (Exception $e) { Core::RaiseWarning("Cannot connect to memcached server on ".$this->Options["host"] .":". $this->Options["port"]); return false; } // Would need it anyway if (!$retval) Core::RaiseWarning("Cannot connect to memcached server on ".$this->Options["host"] .":". $this->Options["port"]); return false; }
/** * Return Number of zones if BIND worked else false * * @return integer */ public function RndcStatus() { if ($this->Transport == "ssh") { $retval = $this->SSH2->Exec("{$this->Rndc} status"); $this->Logger->info("Execute rndc status"); $this->Logger->info("Result: {$retval}"); preg_match_all("/number of zones:[^0-9]([0-9]+)/", $retval, $matches); if ($matches[1][0] > 0) { return $matches[1][0]; } else { return false; } } elseif ($this->Transport == "ftp") { Core::RaiseWarning(_("FTP transport not support RNDC status command")); } }
function __construct($host, $port, $login, $password, $sc_path, $accounts_dir, $skeleton_dir) { parent::__construct(); $this->ShoutcastDir = $sc_path; $this->AccountsDir = $accounts_dir; $this->SkeletonDir = $skeleton_dir; $this->SSH2 = new SSH2(); if (!$this->SSH2->Connect($host, $port, $login, trim($password))) { Core::RaiseWarning(_("Cannot connect to remote server")); return false; } $this->SSHHost = $host; $this->SSHPort = $port; $this->SSHLogin = $login; $this->SSHPassword = trim($password); }
public function AddRecord($type, $record, $ttl = 14440) { Core::ClearWarnings(); $ttl = $this->ParseTimeToSeconds($ttl); if ($ttl && $ttl != $this->SOA["ttl"]) { $record["ttl"] = $ttl; } // Add $z = $record; // Moron if (!$z["ttl"]) { $z["ttl"] = $ttl; } /// NS if ($type == "NS") { if (!$this->IsDomain($z[1])) { Core::RaiseWarning(sprintf(_("Unable to add NS record. %s is not a valid subdomain."), $z[1])); } else { if (empty($z[0])) { $z[0] = $this->SOA["name"]; } $z[1] = $this->Dottify($z[1]); $this->tpl .= "{$z[0]}\t{$z['ttl']}\tIN NS\t{$z[1]}\n"; $this->records["{$type}"][] = array("left" => $z[0], "right" => $z[1], "ttl" => $z['ttl']); } } elseif ($type == "A") { if (empty($z[0])) { $z[0] = $this->Dottify($this->SOA["name"]); } else { if (!$this->IsDomain($z[0])) { Core::RaiseWarning(sprintf(_("Unable to add A record. %s is not valid subdomain."), $z[0])); } } if (!$this->IsIP($z[1])) { Core::RaiseWarning(sprintf(_("Unable to add A record. %s is not an IP address."), $z[1])); } elseif (!$this->IsValidIP($z[1]) && !ALLOWINTIPS) { Core::RaiseWarning(sprintf(_("Unable to add A record. %s is not valid IP address."), $z[1])); } else { $this->tpl .= "{$z[0]}\t{$z['ttl']}\tIN A\t{$z[1]}\n"; $this->records["{$type}"][] = array("left" => $z[0], "right" => $z[1], "ttl" => $z['ttl']); } } elseif ($type == "PTR") { $z[0] = (int) $z[0]; if (empty($z[0])) { Core::RaiseWarning(_("Invalid IP address")); } else { if (!is_integer($z[0]) && $z[0] < 255 && $z[0] > 0) { Core::RaiseWarning(sprintf(_("Unable to add PTR record. %s is not an integer."), $z[0])); } } if (!$this->IsDomain($z[1])) { Core::RaiseWarning(sprintf(_("Unable to add PTR record. %s is not an valid domain."), $z[1])); } else { $z[1] = $this->Dottify($z[1]); $this->tpl .= "{$z[0]}\t{$z['ttl']}\tIN PTR\t{$z[1]}\n"; $this->records["{$type}"][] = array("left" => $z[0], "right" => $z[1], "ttl" => $z['ttl']); } } elseif ($type == "MX") { if ($this->isIP($z[1])) { Core::RaiseWarning(sprintf(_("Unable to add MX record. %s cannot be IP address."), $z[1])); } else { $d = $z[0] ? $z[0] : $this->SOA["name"]; $pref = $this->RaiseMXPref($z[2]); $z[1] = $this->Dottify($z[1]); $this->tpl .= "{$d}\t{$z['ttl']}\tIN MX\t{$pref}\t{$z[1]}\n"; $this->records["{$type}"][] = array("left" => $d, "right" => $z[1], "ttl" => $z['ttl'], "pref" => $pref); } } elseif ($type == "CNAME") { if (!empty($z[1])) { $d = $this->Dottify($z[1]); } else { $d = $this->SOA["name"]; } $z[0] = $this->undottify($z[0]); if (!$this->IsDomain($z[0]) || !$this->IsDomain($z[1])) { Core::RaiseWarning(sprintf(_("Unable to add CNAME record. %s or %s are not valid domains."), $z[1], $z[0])); } elseif (empty($z[0])) { Core::RaiseWarning(sprintf(_("Unable to add CNAME record. %s is not valid subdomain name."), $z[1])); } else { $this->tpl .= "{$z[0]}\t{$z['ttl']}\tIN CNAME\t{$d}\n"; $this->records["{$type}"][] = array("left" => $z[0], "right" => $d, "ttl" => $z['ttl']); } } return !self::HasWarnings(); }
/** * Get file contents over SFTP * @access public * @param string $remote_path Remote file path * @return strung */ public function GetFile($remote_path) { $retval = false; try { if ($this->Connection) { if (!$this->SFTP || !is_resource($this->SFTP)) $this->SFTP = @ssh2_sftp($this->Connection); if ($this->SFTP && is_resource($this->SFTP)) { $stream = @fopen("ssh2.sftp://{$this->SFTP}".$remote_path, "r"); if ($stream) { $string = true; while($string != false) { $string = @fread($stream, 1024); $retval .= $string; } @fclose($stream); return $retval; } else { Core::RaiseWarning(sprintf(_("SFTP: Cannot open remote file '%s'"), $remote_path)); return false; } } else { Core::RaiseWarning(_("SFTP: Connection broken")); return false; } } else { Core::RaiseWarning(_("No established SSH connection")); return false; } } catch (Exception $e) { Core::RaiseWarning($e->__toString()); return false; } }
private function ApiRequest($method, $params) { $this->HttpRequest->setUrl(self::FLICKR_API_URL); $this->HttpRequest->setMethod(HTTP_METH_GET); $params["format"] = self::FLICKR_RESP_FORMAT; $params["method"] = $method; $query_data = http_build_query($params); $this->HttpRequest->setQueryData($query_data); try { $this->HttpRequest->send(); if ($this->HttpRequest->getResponseCode() == 200) { return unserialize($this->HttpRequest->getResponseBody()); } else { Core::RaiseWarning($this->HttpRequest->getResponseStatus()." (".$this->HttpRequest->getResponseCode().")"); return false; } } catch (HttpException $e) { Core::RaiseWarning($e->__toString()); return false; } }
/** * Connecting to server by given URL with given parameters and fetching * content * * @param string $url URL to the server * @param array $params Params to send in the query * @param bool $post If variable value is true then query method will * be POST. Otherwise uses GET method * @return string Result content if success * @access public */ public function Fetch($url, $params = array(), $post = false) { if (!$this->Curl) return false; $chunks = parse_url($url); if ($this->Params && is_array($params)) $this->Params = array_merge($this->Params, $params); else $this->SetParams($params); if ($chunks['scheme'] == 'https') { curl_setopt($this->Curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($this->Curl, CURLOPT_SSL_VERIFYHOST,1); } curl_setopt($this->Curl, CURLOPT_RETURNTRANSFER,1); curl_setopt($this->Curl, CURLOPT_URL, $url); if ($this->Headers) curl_setopt($this->Curl, CURLOPT_HTTPHEADER, $this->Headers); if ($this->Credentials) curl_setopt($this->Curl, CURLOPT_USERPWD, $this->Credentials); if ($post) { curl_setopt($this->Curl, CURLOPT_POST,1); if (count($this->Params) > 0) curl_setopt($this->Curl, CURLOPT_POSTFIELDS, http_build_query($this->Params)); } if ($this->Cookies) curl_setopt($this->Curl, CURLOPT_COOKIE, $this->Cookies); if ($this->UseCookies) curl_setopt($this->Curl, CURLOPT_COOKIEFILE, $this->CookiePath); if ($this->ConnectTimeout) curl_setopt($this->Curl, CURLOPT_CONNECTTIMEOUT, $this->ConnectTimeout); if ($this->CurlTimeout) curl_setopt($this->Curl, CURLOPT_TIMEOUT, $this->CurlTimeout); if ($this->UseRedirects) { curl_setopt($this->Curl, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($this->Curl, CURLOPT_MAXREDIRS, $this->MaxRedirects); } else curl_setopt($this->Curl, CURLOPT_FOLLOWLOCATION, 0); if ($this->NeedHeaders) curl_setopt($this->Curl, CURLOPT_HEADER, 1); if ($this->Debug) { curl_setopt($this->Curl, CURLOPT_VERBOSE, 1); curl_setopt($this->Curl, CURLOPT_STDERR, $this->DebugHandler); } $this->Result = trim(curl_exec($this->Curl)); if (curl_error($this->Curl) && !$this->IgnoreErrors) { Core::RaiseWarning(curl_error($this->Curl)); $this->Result = ''; return false; } return $this->Result; }
/** * Converts CIDR range to IPS array * @access public * @param string $ip IP range in CIDR notation * @return array */ public final function CIDR2List($ip) { // validate IP address $num = "([0-9]|1?\\d\\d|2[0-4]\\d|25[0-5])"; $range = "([1-9]|1\\d|2\\d|3[0-2])"; if (!preg_match("/^{$num}\\.{$num}\\.{$num}\\.{$num}\\/{$range}\$/", $ip)) { return false; } // Separate CIDR structure into network-IP and netmask $ip_arr = explode("/", $ip); // Calculate number of hosts in the subnet $mask_bits = $ip_arr[1]; if ($mask_bits > 31 || $mask_bits < 0) { Core::RaiseError(_("Nonsense mask")); } $host_bits = 32 - $mask_bits; $num_hosts = pow(2, $host_bits) - 1; // Netmask in decimal for use later: (hack around PHP always using signed ints) $netmask = ip2long("255.255.255.255") - $num_hosts; // Calculate start and end // Store IP-addresses internally as longs, to ease compare of two // addresses in a sorted structure. $ip_start = ip2long($ip_arr[0]); if ($ip_start != ($ip_start & $netmask)) { Core::RaiseWarning(_("Address {$ip} not on network boundary")); } $ip_end = $ip_start + $num_hosts; for ($i = 0; $i <= $num_hosts; $i++) { $ip_range[] = long2ip($ip_start + $i); } return $ip_range; }
/** * Validate all data in array * * @param array $array * @return bool or array of errors */ public function ValidateAll($array) { $this->Errors = array(); foreach ($array as $var => $method) { if (method_exists($this, $method)) { eval("\$this->{$method}('{$var}');"); } else { Core::RaiseWarning("{$method} is not valid method of Validator class."); } } if ($this->HasErrors()) { return $this->Errors; } else { return true; } }
private function GetUserFeed($access = "all") { if (!$this->UserFeed) { $params = array("kind" => "album", "alt" => "rss", "hl" => "en", "access" => $access); $req = $this->Request( "http://picasaweb.google.com/data/feed/api/user/{$this->Username}", http_build_query($params), array(), "GET" ); if (!$req) return false; elseif ($req == 200) { $data = $this->HttpRequest->getResponseBody(); $this->UserFeed = new SimpleXMLElement($data); } else { Core::RaiseWarning($this->HttpRequest->getResponseBody()); return false; } } return $this->UserFeed; }
/** * Stop virtual host * @access public * @param string $name Host name * @return bool True on success, False on failure */ public function StopVHost($name) { $retval = $this->SSH2->Exec($this->InstallPath."/webadmin/bin/stopserver.sh $name"); $retval = (bool)strstr($retval, "Ok"); if (!$retval) Core::RaiseWarning("Cannot stop zeus vhost {$retval}"); return ($retval); }
/** * Add network to rwhois database * * @param string $network_address * @param integer $CIDR * @param array $netinfo * @param bool $reindex * @return bool */ public function AddNetwork($network_address, $CIDR, $netinfo, $reindex = true) { Log::Log("RWhoisManager::AddNetwork Adding/Update network {$network_address}/{$CIDR}", LOG_LEVEL_INFO); $network_conf_path = "{$this->RWHoisConfDir}/net-{$network_address}-{$CIDR}"; // Remove Old config if exists $this->DeleteNetwork($network_address, $CIDR, false, true); //Create network directory $this->Transport->MkDir($network_conf_path); //Copy templates if(!$this->Transport->Copy("{$this->RWHoisConfDir}/net-10.0.0.0-8/*", "{$network_conf_path}", true)) { Core::RaiseWarning("Cannot copy NET template"); return false; } // // Edit auth_area file for rwhoisd // $auth_area = $this->Transport->Read("{$this->RWHoisConfDir}/rwhoisd.auth_area"); // Add new network to auth_area $auth_area .= "---\n"; $auth_area .= "name: {$network_address}/{$CIDR}\n"; $auth_area .= "data-dir: net-{$network_address}-{$CIDR}/data\n"; $auth_area .= "schema-file: net-{$network_address}-{$CIDR}/schema\n"; $auth_area .= "soa-file: net-{$network_address}-{$CIDR}/soa\n"; $auth_area = $this->NormalizeAuthArea($auth_area); // Save auth_area file $this->Transport->Write("{$this->RWHoisConfDir}/rwhoisd.auth_area", $auth_area, true); // // Edit SOA For network // $soa = $this->Transport->Read("{$network_conf_path}/soa"); // Change serial $serial = date("Ymd")."000000000"; $soa = preg_replace("/Serial-Number:([0-9]+)/", "Serial-Number:{$serial}", $soa); // Change Primary server $soa = preg_replace("/Primary-Server:(.*)\n/", "Primary-Server:{$this->Host}:{$this->Port}\n", $soa); //Change Hostmaster $soa = preg_replace("/Hostmaster:(.*)\n/", "Hostmaster:{$this->Hostmaster}\n", $soa); // Save soa $this->Transport->Write("{$network_conf_path}/soa", $soa, true); // // Edit Schema For network // //$schema = $this->Transport->Read("{$network_conf_path}/schema"); // Create schema content $schema = "name:network\n"; $schema .= "attributedef:net-{$network_address}-{$CIDR}/attribute_defs/network.tmpl\n"; $schema .= "dbdir:net-{$network_address}-{$CIDR}/data/network\n"; $schema .= "Schema-Version: {$serial}\n"; // Write schema $this->Transport->Write("{$network_conf_path}/schema", $schema, true); // // Edit network information // $network = "ID: {$netinfo["id"]}\n"; $network .= "Auth-Area: {$network_address}/{$CIDR}\n"; $network .= "Network-Name: {$netinfo["name"]}\n"; $network .= "IP-Network: {$network_address}/{$CIDR}\n"; $network .= "Organization: {$netinfo["org"]}\n"; $network .= "Tech-Contact: {$netinfo["tech"]}\n"; $network .= "Admin-Contact: {$netinfo["admin"]}\n"; $network .= "Created: {$netinfo["dtcreated"]}\n"; $network .= "Updated: {$netinfo["dtupdated"]}\n"; $network .= "Updated-By: {$this->Hostmaster}\n"; $this->Transport->Write("{$network_conf_path}/data/network/network.txt", $network, true); if ($reindex) { $this->Reindex(); return $this->Restart(); } else return true; }
/** * Reastart apache * * @return bool */ public function RestartApache() { $retval = $this->SSH2->Exec(CF_HTTPD_APACHECTL." restart 2>&1"); $retval = !(bool)strstr($retval, "error") && !(bool)strstr($retval, "Usage"); if (!$retval) Core::RaiseWarning("Cannot restart apache: {$retval}"); return $retval; }
/** * Request to google service * * @param string $url * @param string $data * @param array $headers * @param string $method (POST or GET) * @param int $followlocation (Handle redirect) * @return string */ protected function Request($url, $data, $headers = array(), $method = "POST", $isretry = false) { $this->HttpRequest->setUrl($url); $this->HttpRequest->setMethod(constant("HTTP_METH_{$method}")); // Add auth token if ($this->AuthToken) $headers = array_merge($headers, array("Authorization" => "GoogleLogin auth={$this->AuthToken}")); $this->HttpRequest->addHeaders($headers); if ($method == "POST" || $method == "GET") $this->HttpRequest->setQueryData($data); elseif ($method == "PUT") $this->HttpRequest->setPutData($data); try { $this->HttpRequest->send(); if (($this->HttpRequest->getResponseCode() == 500 && stristr($this->HttpRequest->getResponseBody(), "Token expired")) && !$isretry) { if($this->Authenticate(false, false, $this->Service)) { return $this->Request($url, $data, $headers, $method, true); } else { Core::RaiseWarning("Session expired"); return false; } } else return $this->HttpRequest->getResponseCode(); } catch (HttpException $e) { Core::RaiseWarning($e->__toString()); return false; } }