/**
  * Return Transport. example: TransportFactory::GetTransport('SSH', $ssh_host, $ssh_port, $ssh_user, $ssh_pass);
  *
  * @static 
  * @param string $transportname
  * @return Object
  */
 public static function GetTransport($transportname)
 {
     $path_to_transports = dirname(__FILE__) . "/Transports";
     if (file_exists("{$path_to_transports}/class.{$transportname}Transport.php")) {
         Core::Load("class.{$transportname}Transport.php", $path_to_transports);
         if (class_exists("{$transportname}Transport") && self::IsTransport("{$transportname}Transport")) {
             // Get Constructor Reflection
             if (is_callable(array("{$transportname}Transport", "__construct"))) {
                 $reflect = new ReflectionMethod("{$transportname}Transport", "__construct");
             }
             // Delete $objectname from arguments
             $num_args = func_num_args() - 1;
             $args = func_get_args();
             array_shift($args);
             if ($reflect) {
                 $required_params = $reflect->getNumberOfRequiredParameters();
                 if ($required_params > $num_args) {
                     $params = $reflect->getParameters();
                     //TODO: Show what params are missing in error
                     Core::RaiseError(sprintf(_("Missing some required arguments for %s Transport constructor. Passed: %s, expected: %s."), $transportname, $num_args, $required_params));
                 }
             }
             $reflect = new ReflectionClass("{$transportname}Transport");
             if (count($args) > 0) {
                 return $reflect->newInstanceArgs($args);
             } else {
                 return $reflect->newInstance(true);
             }
         } else {
             Core::RaiseError(sprintf(_("Class '%s' not found or doesn't implements ITransport interface"), "{$transportname}Transport"));
         }
     }
 }
示例#2
0
 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 "";
     }
 }
示例#3
0
        function __construct($process_classes_folder)
        {
            $processes = @glob("{$process_classes_folder}/class.*Process.php");
            
           $jobs = array();
            if (count($processes) > 0)
            {
                foreach ($processes as $process)
                {
                    $filename = basename($process);
                    $directory = dirname($process);
                    Core::Load($filename, $directory);
                    preg_match("/class.(.*)Process.php/s", $filename, $tmp);
                    $process_name = $tmp[1];
                    if (class_exists("{$process_name}Process"))
                    {
                        $reflect = new ReflectionClass("{$process_name}Process");
                        if ($reflect)
                        {
                            if ($reflect->implementsInterface("IProcess"))
                            {
                                $job = array(
                                                "name"          => $process_name,
                                                "description"   => $reflect->getProperty("ProcessDescription")->getValue($reflect->newInstance())
                                            );
                                array_push($jobs, $job);    
                            }
                            else 
                                Core::RaiseError("Class '{$process_name}Process' doesn't implement 'IProcess' interface.", E_ERROR);
                        }
                        else 
                            Core::RaiseError("Cannot use ReflectionAPI for class '{$process_name}Process'", E_ERROR);
                    }
                    else
                        Core::RaiseError("'{$process}' does not contain definition for '{$process_name}Process'", E_ERROR);
                }
            }
            else 
                Core::RaiseError(_("No job classes found in {$ProcessClassesFolder}"), E_ERROR);
             
            $options = array();
            foreach($jobs as $job)
                $options[$job["name"]] = $job["description"];

            $options["help"] = "Print this help";
                           
            $Getopt = new Getopt($options);
            $opts = $Getopt->getOptions();
            
            if (in_array("help", $opts) || count($opts) == 0 || !$options[$opts[0]])
            {
                print $Getopt->getUsageMessage();    
                exit();
            }
            else
            {                               
                $this->ProcessName = $opts[0];
            }
        }
示例#4
0
 public static function GetPublicKeyFromPrivateKey($private_key)
 {
     try {
         $key_resource = openssl_pkey_get_private($private_key);
         $info = openssl_pkey_get_details($key_resource);
         return $info["key"];
     } catch (Exception $e) {
         Core::RaiseError($e->getMessage(), E_ERROR);
     }
 }
		/**
		 * Constructor
		 * 
		 * @param string path to vbulletin config
		 */
    	function __construct($config_path)
    	{
	    	if (!file_exists($config_path)) 
	    		return false;
	    	
	    	// version checking
	    	$includes = dirname($config_path);
	    	if (file_exists("$includes/class_core.php"))
	    	{
	    		require_once("$includes/class_core.php");
	    		preg_match("/^(\d)\.(\d)/", FILE_VERSION, $m);
	    		$ver = intval($m[1] . $m[2]);
	    	}
	    	
	    	if (!$ver || $ver < self::MIN_VERSION)
	    		Core::RaiseError(sprintf(_("vBulletin forum version '%s' installed. %s or higher required."), $ver, self::MIN_VERSION));
	    	
	    	$config = array();
	    	require($config_path);

	    	$this->TablePrefix = $config['Database']['tableprefix'];
	    	$this->CookiePrefix = $config['Misc']['cookieprefix'];
    		
    		$conf = array(
    			'host'	=> $config['MasterServer']['servername'],
    			'user'	=> $config['MasterServer']['username'],
    			'pass'	=> $config['MasterServer']['password'],
    			'name'	=> $config['Database']['dbname']
    		);
    		
			$this->DB = Core::GetDBInstance($conf, true, $config['Database']['dbtype']);
			$this->Crypto = Core::GetInstance('Crypto', CF_CRYPTOKEY);
			
			// user groups 
			$groups = $this->DB->GetAll("SELECT * FROM {$this->TablePrefix}usergroup");
			foreach($groups as $group)
			{
				$this->Groups[$group['title']] = $group['usergroupid']; 
			}
    	}
		/**
		 * Execute script
		 *
		 * @param string $script
		 * @return string
		 */
	    public function SendLine($command)
	    {
	        Core::RaiseError("SendLine not supported in MySQLScriptingAdapter");
		}
示例#7
0
 /**
  * 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);
     }
 }
示例#8
0
 /**
  * Adds WHERE filter to SQL, depending on SESSION and POST filters.
  * @access private
  * @return string Usable SQL string
  */
 public function ApplyFilter($filter, $fields)
 {
     if ($this->PagingApplied) {
         Core::RaiseError(_("Cannot call ApplyFilter after ApplySQLPaging has been called"));
     }
     $filter = stripslashes($filter);
     // Same filter - unchecking button
     if ($filter == $_SESSION["filter"]) {
         $filter = NULL;
         $_SESSION["filter"] = NULL;
         $this->Display["filter"] = false;
     } else {
         if (!$_GET["pf"]) {
             $this->PageNo = 1;
         }
         $filter = $filter ? $filter : $_GET["pf"];
         $filter = stripslashes($filter);
         // Add template vars
         $this->Display["filter_q"] = $filter;
         $this->Display["filter"] = true;
         $_SESSION["filter"] = $filter;
     }
     if ($filter) {
         $this->URLFormat = "?pn=%d&pt=%d&pf=" . urlencode($filter);
         $this->Filter = $filter;
         //SQL
         $filter = mysql_escape_string($filter);
         foreach ($fields as $f) {
             $likes[] = "{$f} LIKE '%{$filter}%'";
         }
         $like = implode(" OR ", $likes);
         if (!stristr($this->SQL, "WHERE")) {
             $this->SQL .= " WHERE {$like}";
         } else {
             $this->SQL .= " AND ({$like})";
         }
         // Additional SQL
         if (!stristr($this->SQL, $this->AdditionalSQL)) {
             $this->SQL .= " " . $this->AdditionalSQL . " ";
         }
         // Downgrade total records count
         if ((int) $_GET["pt"] > 0) {
             $this->Total = (int) $_GET["pt"];
         } else {
             $this->ExecuteSQL();
         }
     }
     return $this->SQL;
 }
示例#9
0
		/**
		 * Update data in RRD
		 *
		 * @param array $data
		 * @param integer $timestamp UNIX TimeStamp
		 * @return bool
		 */
		function Update($data, $timestamp = "N")
		{
			$arg = "{$timestamp}";
			foreach ($data as $val)
				$arg .= ":{$val}";
			
			if(rrd_update($this->DBPath, $arg))
				return true;
			else 
				Core::RaiseError(_("Cannot update RRD: ".rrd_error()));
		}
示例#10
0
 /**
  * Get password hash
  * @access public
  * @return string Password hash, $this->PwdHash
  */
 public final function GetPwdHash()
 {
     if (!is_readable($this->PassFilePath)) {
         Core::RaiseError(_("{$this->PassFilePath} not readable"));
     }
     $res = $this->Shell->QueryRaw("cat {$this->PassFilePath} | grep ^{$this->Username}:");
     $rowarr = explode(":", $res);
     $this->PwdHash = $rowarr[1];
     return $this->PwdHash;
 }
示例#11
0
 public function Handle($request = false, $defaultNS = "")
 {
     if (!$request) {
         $request = $_REQUEST;
     } else {
         if (!is_array($request)) {
             @parse_str($request, $request);
         }
     }
     if (!$request["method"]) {
         Core::RaiseError("Malformed request", E_USER_ERROR);
     }
     $this->Request = $request;
     // Determine namespace & method
     if ($this->Methods[$request["method"]] instanceof ReflectionMethodEx) {
         $reflection_method = $this->Methods[$request["method"]];
         $req_args = $reflection_method->getParameters();
         foreach ($req_args as $arg) {
             if ($request[$arg->getName()] || $arg->isOptional()) {
                 $given_args++;
                 $args[$arg->getName()] = $request[$arg->getName()];
             } else {
                 $missing_args = $arg->getName();
             }
         }
         if (count($req_args) != $given_args) {
             Core::RaiseError("Invalid Method Call to '{$this->Request['method']}'. Requires '" . count($req_args) . "' arguments, '" . count($given_args) . "' given.", E_USER_ERROR);
         }
         try {
             if ($req_args == 0) {
                 $result = $reflection_method->invoke();
             } else {
                 $result = $reflection_method->invokeArgs($args);
             }
         } catch (Exception $e) {
             Core::RaiseError($e->getMessage(), E_ERROR);
         }
     } elseif ($this->Methods[$request["method"]] instanceof ReflectionFunction) {
         $req_args = $this->Methods[$request["method"]]->getParameters();
         foreach ($req_args as $arg) {
             if ($request[$arg->getName()] || $arg->isOptional()) {
                 $given_args++;
                 $args[$arg->getName()] = $request[$arg->getName()];
             } else {
                 $missing_args = $arg->getName();
             }
         }
         if (count($req_args) != $given_args) {
             Core::RaiseError("Invalid Method Call to '{$this->Request['method']}'. Requires '" . count($req_args) . "' arguments, '" . count($given_args) . "' given.", E_USER_ERROR);
         }
         try {
             if ($req_args == 0) {
                 $result = $this->Methods[$request["method"]]->invoke();
             } else {
                 $result = $this->Methods[$request["method"]]->invokeArgs($args);
             }
         } catch (Exception $e) {
             Core::RaiseError($e->getMessage(), E_ERROR);
         }
     } else {
         Core::RaiseError("Method not implemented", E_USER_ERROR);
     }
     if ($result instanceof SimpleXMLElement) {
         $response = $result->asXML();
     } elseif ($result instanceof DOMDocument) {
         $response = $result->saveXML();
     } elseif ($result instanceof DOMNode) {
         $response = $result->ownerDocument->saveXML($result);
     } elseif (is_array($result) || is_object($result)) {
         $response = $this->HandleStruct($result);
     } else {
         $response = $this->HandleScalar($result);
     }
     @header("Content-type: text/xml");
     @header("Content-length: " . strlen($response));
     print $response;
 }
示例#12
0
		function __doRequest($request, $location, $saction, $version) 
		{		    
		    $doc = new DOMDocument('1.0');
			$doc->loadXML($request);
			
			$objWSSE = new WSSESoap($doc);
			#echo "<pre>"; var_dump($request); #die();
			/* add Timestamp with no expiration timestamp */
		 	$objWSSE->addTimestamp();
		
			/* create new XMLSec Key using RSA SHA-1 and type is private key */
			$objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type'=>'private'));
		
			/* load the private key from file - last arg is bool if key in file (TRUE) or is string (FALSE) */
			$objKey->loadKey($this->KeyPath, TRUE);
		
			try
			{
                /* Sign the message - also signs appropraite WS-Security items */
                $objWSSE->signSoapDoc($objKey);
			}
			catch (Exception $e)
			{
			    Core::RaiseError("[".__METHOD__."] ".$e->getMessage(), E_ERROR);
			}
		
			/* Add certificate (BinarySecurityToken) to the message and attach pointer to Signature */
			$token = $objWSSE->addBinaryToken(file_get_contents($this->CertPath));
			$objWSSE->attachTokentoSig($token);
					
			try
			{
				return parent::__doRequest($objWSSE->saveXML(), $location, $saction, $version);
			}
			catch (Exception $e)
			{
				Core::RaiseError("[".__METHOD__."] ".$e->__toString(), E_ERROR);
			}
		}
示例#13
0
		public function AddAddon($domain, $foldername = "", $pass = "")
		{
			Core::RaiseError("Fixme: Add \$crypto instance here.");
			if (!$foldername) $foldername = preg_replace("/[\-\_]/i", "", $domain);
			if (!$pass) $pass = $crypto->Sault(13);

			$this->Fetch("addon/doadddomain.html?domain=".$domain."&user="******"&pass="******"user" => $foldername, "pass" => $pass);
		}
示例#14
0
		/**
		 * Constructor
		 *
		 * @param string $host
		 * @param string $port
		 * @param array $authinfo
		 * @param string $rndc_path
		 * @param string $namedconf_path
		 * @param string $nameddb_path
		 * @param string $zonetemplate
		 */
		function __construct($host, $port, $authinfo, $rndc_path, $namedconf_path, $nameddb_path, $zonetemplate, $inittransport= true)
		{
			// Call Bind class construct
			parent::__construct($namedconf_path, $nameddb_path, $zonetemplate, $rndc_path, false);	

			$this->Host = $host;
			$this->Port = $port;
			$this->Authinfo = $authinfo;
					
			$this->Transport = self::DEFAULT_TRANSPORT;
			
			if ($inittransport)
				if (!$this->InitTransport())
					Core::RaiseError("Cannot init transport");
			
			$this->DoMakeBackup = false;
			$this->HaveNewZones = 0;
		}
示例#15
0
 /**
  * Execute script
  *
  * @param string $script
  * @return bool
  * @static 
  */
 static public function Execute($script, $params)
 {
     if (!self::$Adapter)
         Core::RaiseError("Please define Adapter using ScriptingClient::SetAdapter() method");
     
     return self::$Adapter->Execute($script, $params);
 }
示例#16
0
 /**
  * Connect to SSH Server
  *
  * @access private
  * @return bool
  * @return bool
  */
 private function Connect()
 {
     if (!$this->SSHConnection->Connect($this->SSHHost, $this->SSHPort))
         Core::RaiseError(sprintf(_("Transports/SSHTransport: Cannot connect to %s:%s."), $this->SSHHost, $this->SSHPort));
     else 
         return true;
 }
示例#17
0
 /**
  * Execute commands chain.
  * @access public
  * @var mixed $stdin Optional STDIN string to write to a 1st proccess in chain
  * @var string $in_file_path Optional input file path that input for the last proccess will be read from
  * @var string $out_file_path Optional output file path that output of the last proccess will be written to
  * @return int The return value of the command (0 on success) or strict false on failure.
  * @todo may be it worths rewriting interptoccess piping from | binary usage to posix_mkfifo()
  */
 function Execute($stdin = null, $out_file_path = null, $in_file_path = null)
 {
     if (count($this->Links) == 0) {
         Core::RaiseError("Cannot call PipedChain->Execute() - no links in chain");
     }
     // Build a piped string
     $cmd = implode(" | ", $this->Links);
     $MProcess = new ManagedProcess($cmd, $stdin);
     $retval = $MProcess->Execute($cmd, $stdin, $out_file_path, $in_file_path);
     $this->StdOut = $MProcess->StdOut;
     $this->StdErr = $MProcess->StdErr;
     return $retval;
 }
示例#18
0
 /**
  * 
  * @return string Resulting image binary string.
  */
 public function Process()
 {
     $result = $this->PChain->Execute($this->StdIn, $this->OutFilePath, $this->InFilePath);
     if (!empty($this->PChain->StdErr)) {
         Core::RaiseError(trim($this->PChain->StdErr), E_ERROR);
     } elseif (!$this->OutFilePath) {
         $retval = $this->PChain->StdOut;
     } else {
         $retval = $result;
     }
     // Reset some stuff for a fresh new chain
     $this->Init();
     return $retval;
 }
示例#19
0
		/**
		* Transfer file over SFTP
		* @access public
		* @param string $remote_path Remote file path
		* @param string $local_path Local file path
		* @param string $write_type Write path
		* @param bool $read_content_from_file If True we read content from '$source' else content = $source
		* @return bool
		*/
		public function SendFile($remote_path, $source, $write_type = "w+", $read_content_from_file = true)
		{
			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, $write_type);
						if ($stream)
						{
						    if ($read_content_from_file)
							 $content = @file_get_contents($source);
							else 
							 $content = $source;
							 
							if (fwrite($stream, $content) === FALSE) 
							{
								Core::RaiseError(sprintf(_("SFTP: Cannot write to file '%s'"), $remote_path));
								return false;
							}
							@fclose($stream);
							return true;
						}
						else
						{
							Core::RaiseWarning(sprintf(_("SFTP: Cannot open remote file '%s'"), $remote_path));
							return false;
						}
					}
					else
						return false;
				}
				else
					return false;
			}
			catch (Exception $e) 
			{
				return false;
			}
		}
示例#20
0
 /**
  * Sets a specific value in the SOA field.
  *
  * This function updates the list of SOA data we have.
  * List of accepted key => value pairs:
  * <pre>
  * Array
  *   (
  *       [name] => example.com.
  *       [ttl] => 345600
  *       [class] => IN
  *       [origin] => ns1.example.com.
  *       [person] => hostmaster.example.com.
  *       [serial] => 204041514
  *       [refresh] => 14400
  *       [retry] => 1800
  *       [expire] => 86400
  *       [minimum] => 10800
  *   )
  * </pre>
  *
  * @param array  $values A list of key -> value pairs
  * @return bool  true on success, false failure.
  * @see SOA
  */
 public function SetSOAValue($values)
 {
     Core::ClearWarnings();
     $soa = array();
     if (!is_array($values)) {
         Core::RaiseError(_("Unable to set SOA value"));
     }
     $validKeys = array('name', 'ttl', 'class', 'origin', 'person', 'serial', 'refresh', 'retry', 'expire', 'minimum');
     foreach ((array) $values as $key => $value) {
         if (array_search($key, $validKeys) === false) {
             Core::RaiseWarning(sprintf(_("Unable to set SOA value. %s not recognized"), $key));
         }
         switch (strtolower($key)) {
             case 'person':
                 $value = str_replace('@', '.', $value);
                 $value = trim($value, '.') . '.';
             case 'name':
             case 'origin':
                 $valid = '/^[A-Za-z0-9\\-\\_\\.]*\\.$/';
                 $value = $this->Dottify($value);
                 if (preg_match($valid, $value)) {
                     $soa[$key] = $value;
                 } else {
                     Core::RaiseWarning(sprintf(_("Unable to set SOA value. %s not valid"), $key));
                 }
                 break;
             case 'class':
                 $soa[$key] = $value;
                 break;
             case 'ttl':
                 $soa[$key] = $value;
                 break;
             case 'serial':
                 $value = $this->RaiseSerial($value);
                 $soa[$key] = $value;
             case 'refresh':
             case 'retry':
             case 'expire':
             case 'minimum':
                 // Normalize time
                 $value = $this->ParseTimeToSeconds($value);
                 if (is_numeric($value)) {
                     $soa[$key] = $value;
                 } else {
                     Core::RaiseWarning(sprintf(_("Unable to set SOA value. %s not recognized"), $key));
                 }
                 break;
         }
         // Set zone name
         if (strtolower($key) == "name") {
             $this->Name = $this->UnDottify($value);
         }
     }
     // Default serial
     if (!$soa["serial"]) {
         $soa["serial"] = $this->RaiseSerial();
     }
     //If all got parsed, save values.
     $this->SOA = array_merge($this->SOA, $soa);
     return !self::HasWarnings();
 }
示例#21
0
		/**
		 * The CreateBucket operation creates a bucket. Not every string is an acceptable bucket name.
		 *
		 * @param string $bucket_name
		 * @return string 
		 */
		public function CreateBucket($bucket_name)
		{
		    $timestamp = $this->GetTimestamp();
		    
		    try 
		    {
    		    $res = $this->S3SoapClient->CreateBucket(
            		                                      array(  
            		                                              "Bucket" => $bucket_name,
            		                                              "AWSAccessKeyId" => $this->AWSAccessKeyId,
            		                                              "Timestamp"      => $timestamp,
            		                                              "Signature"      => $this->GetSOAPSignature("CreateBucket", $timestamp)
            		                                           )
            		                                     );
            		                                     
                if (!($res instanceof SoapFault))
                    return true;
                else 
                    Core::RaiseError($res->faultString, E_ERROR);
		    }
		    catch (SoapFault $e)
		    {
		        Core::RaiseError($e->faultString, E_ERROR);
		    }
		}
示例#22
0
		/**
		 * Fetching post from server
		 *
		 * @param string $group
		 * @return object
		 */
        function FetchPosting($group)
        {
            if ($this->GroupName !== $group->GetName())
            {
                $res = $this->NNTP->SelectGroup($group->GetName());

                if ($res !== FALSE)
                {
                    $group->SetFirst($res['first']);
                    $group->SetLast($res['last']);
                }
                else
                    Core::RaiseError('Fetch Posting: select group error');
            }



            if ($group->GetUnreadPostingsNumber() > 0)
            {
                if ($group->GetUnreadPostingsNumber() > $this->PostsLimit && $this->PostsLimit)
                    $current = $group->GetLast() - $this->PostsLimit;
                else
                    $current = $group->GetLastRead() >= $group->GetFirst() ? $group->GetLastRead() + 1 : $group->GetFirst();
				
                if ($current)
                	$overview = $this->NNTP->GetOverview($current);
               	
                while (($overview === FALSE || $overview["Bytes"] == 0) && ($current <= $group->GetLast()))
                {
                	Log::Log("NNTP: Skipping Article #{$current}. Empty overwiew.", 1, "NNTPLog");
                	
					$group->SetLastRead($current);
					$this->SetGroupStatus($group);
					
					$current++;
					$overview = $this->NNTP->GetOverview($current);
                }
				
                
                
                if (isset($overview["Bytes"]) && $overview["Bytes"] > 0)
                {
                    $header = $this->NNTP->GetArticleHead($current);
                    $body   = $this->NNTP->GetArticleBody($current, true);
					
                    if ($this->FilterPosting($header->fields, $body))
                    {
                        $posting = new UsenetPosting($header, $body, $group->getId(), $group->getName(), $current, $group->GetEncoding());
						
						if ($posting->GetEnc())
							$group->SetDetectedEncoding = $posting->GetEnc();
						
                        $this->Status = 0;

            			Log::Log("NNTP: Fetching Article #{$current}", 1, "NNTPLog");

                        $this->Report[$group->GetName()]++;
                    }
                    else
                    {
           				Log::Log("NNTP: Skipping Article #{$current}. Filtered", 1, "NNTPLog");
					
                        $this->Status = 2;     // skipped posting
                        $posting = false;
                    }

                    $group->SetLastRead($current);
                    $this->SetGroupStatus($group);

                    return $posting;

                }
                else
                {
                    $this->Status = 1;
                    return false;
                }
            }
            else
            {
                $this->Status = 1;       // end of group
                return false;
            }
        }
		/**
		* Find user by username
		* @access public
		* @param string $username username
		* @return SystemUser SystemUser object
		*/

		public function GetUserByUID($uid) 
		{
			if (!is_readable("/etc/passwd"))
				Core::RaiseError(_("/etc/passwd not readable"));
			
			$res = $this->Shell->QueryRaw("cat /etc/passwd | grep ':[\*x]:$uid:'");
			$rowarr = explode(":", $res);
			$retval = new SystemUser($rowarr[2]);
			return $retval;
		}
示例#24
0
 /**
  * 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;
 }
示例#25
0
		public function CreateKeyPair($keyName) 
		{
		    try 
		    {
				$response = $this->EC2SoapClient->CreateKeyPair(array('keyName' => $keyName));
				
				if ($response instanceof SoapFault)
					Core::RaiseError($response->faultstring, E_ERROR);
				
			} 
			catch (SoapFault $e) 
			{
			    Core::RaiseError($e->getMessage(), E_ERROR);	
			}
	
			return $response;
		}
示例#26
0
        /**
         * Prepare system command
         *
         * @param integer $command
         * @param integer $option
         */
        private function PrepareCommand($command, $option = false)
        {
            
            if ($command == 253) {
    			# respond to DO commands
    			switch ($option) 
    			{
    				case 31:	# Window size
    				case 32:	# Term speed
    				case 33:	# Remote flow control
    				case 34:	# LINEMODE
    				case 35:	# X Display
    				case 36:	# Old Env.
    				case 39:	# New Env.
    				case 37:	# Authentication
    				default:
    					$this->SendCommand(252, $option);
    					break;
    
    				case 24:	# TERMINAL-TYPE
    					$this->SendCommand(251, $option);
    					break;
    			}
    		} 
    		else if ($command == 251) 
    		{
    			# respond to WILL commands
    			switch ($option) 
    			{
    				case 3:		# Suppress go ahead
    				case 5:		# Give status
    					$this->SendCommand(253, $option);
    					break;
    
    				case 1:		# Echo
    				case 38:	# Encrypt
    				default:
    					$this->SendCommand(254, $option);
    					break;
    			}
    		} 
    		else if ($command == 250) 
    		{
    			$option = $this->ReadCharFromBuffer();
    			$params = array();
    			$next = $this->ReadCharFromBuffer();
    			while ($next !== 255) 
    			{
       				$params[] = $next;
    				$next = $this->ReadCharFromBuffer();
    			}
    			
    			$end = $this->ReadCharFromBuffer();
    			if ($end != 240) 
    			    Core::RaiseError("Telnet::PrepareCommand - error in subnegotiation");
    			
    			if ($option == 24) 
    			{
        			if ($params[0] == 1) 
        			{
        				$prm = array(chr(0),$this->ttype);
        				$this->SendCommand(250, 24);
                		for ($i=0; $i<count($prm); $i++) 
                			$this->Send($prm[$i], false);

                		$this->SendCommand(240);
        			}
        		} 
        		else 
                    Core::RaiseError("Telnet::PrepareCommand - unsupported option");
    		} 
    		else 
                Core::RaiseError("Telnet::PrepareCommand - unsupported command ({$command})");            
        }
示例#27
0
 /**
  * Return true if the parameter is in a valid format for
  * the option $flag.
  * Throw an exception in most other cases.
  *
  * @param string $flag
  * @param string $param
  */
 protected function checkParameterType($flag, $param)
 {
     if (!isset($this->_rules[$flag]['param']) || $this->_rules[$flag]['param'] == 'none') {
         if (isset($param)) {
             Core::RaiseError("Option \"{$flag}\" requires no parameter." . $this->getUsageMessage());
         } else {
             return true;
         }
     } else {
         if (!isset($param) && $this->_rules[$flag]['param'] == 'optional') {
             return true;
         } else {
             if (!isset($param) && $this->_rules[$flag]['param'] == 'required') {
                 $this->PrintError("Option \"{$flag}\" requires a parameter.");
             }
         }
     }
     switch ($this->_rules[$flag]['paramType']) {
         case 'string':
             break;
         case 'word':
             if (preg_match('/\\W/', $param)) {
                 $this->PrintError("Option \"{$flag}\" requires a single-word parameter, but was given \"{$param}\"");
             }
             break;
         case 'integer':
             if (preg_match('/\\D/', $param)) {
                 $this->PrintError("Option \"{$flag}\" requires an integer parameter, but was given \"{$param}\".");
             }
             break;
         default:
             $this->PrintError("Unknown parameter type: \"{$this->_rules[$flag]['paramType']}\".");
     }
     return true;
 }
示例#28
0
		/**
		 * Parse xml/rss into structured array
		 * 
		 * @param string valid xml string
		 */
		public function Parse($xml)
		{ 
			if (!$xml) return;
			
			$this->ResetParser();
			
			$this->XMLParser = xml_parser_create();
			xml_set_object($this->XMLParser, $this);
			xml_parser_set_option($this->XMLParser, XML_OPTION_CASE_FOLDING, true);
			xml_set_element_handler($this->XMLParser, "OpenTag", "CloseTag");
			xml_set_character_data_handler($this->XMLParser, "ParseTag");
			
		    if(!@xml_parse($this->XMLParser, $xml))
		    {
		        $error = xml_error_string(xml_get_error_code($this->XMLParser));
		        Core::RaiseError($error);
		    }
		    
			xml_parser_free($this->XMLParser);
		}
示例#29
0
 public static function SetExceptionClassName($name)
 {
     if (class_exists($name)) {
         self::$ExceptionClassName = $name;
         self::$ReflectionException = new ReflectionClass($name);
     } else {
         Core::RaiseError("Core::SetExceptionClassName failed. Class '{$name}' not found");
     }
 }
		/**
		 * Register Failed Transaction function
		 *
		 * @param string $functionname
		 */
		public function RegisterFailedTransactionFunction($functionname)
		{
			if (function_exists($functionname))
				$this->FailedTransactionFunction = $functionname;
			else 
				Core::RaiseError(_("Failed Transaction Function is not defined!"));
		}