Author: Kevin Hutchinson (kevin@guanoo.com)
Inheritance: extends Relating_model, implements Modelled, implements Persisted, implements Validated
Exemple #1
10
function file_write($path, $data, $simple = false, $skip_purge = false)
{
    global $config, $debug;
    if (preg_match('/^remote:\\/\\/(.+)\\:(.+)$/', $path, $m)) {
        if (isset($config['remote'][$m[1]])) {
            require_once 'inc/remote.php';
            $remote = new Remote($config['remote'][$m[1]]);
            $remote->write($data, $m[2]);
            return;
        } else {
            error('Invalid remote server: ' . $m[1]);
        }
    }
    if (!function_exists("dio_truncate")) {
        if (!($fp = fopen($path, $simple ? 'w' : 'c'))) {
            error('Unable to open file for writing: ' . $path);
        }
        // File locking
        if (!$simple && !flock($fp, LOCK_EX)) {
            error('Unable to lock file: ' . $path);
        }
        // Truncate file
        if (!$simple && !ftruncate($fp, 0)) {
            error('Unable to truncate file: ' . $path);
        }
        // Write data
        if (($bytes = fwrite($fp, $data)) === false) {
            error('Unable to write to file: ' . $path);
        }
        // Unlock
        if (!$simple) {
            flock($fp, LOCK_UN);
        }
        // Close
        if (!fclose($fp)) {
            error('Unable to close file: ' . $path);
        }
    } else {
        if (!($fp = dio_open($path, O_WRONLY | O_CREAT, 0644))) {
            error('Unable to open file for writing: ' . $path);
        }
        // File locking
        if (dio_fcntl($fp, F_SETLKW, array('type' => F_WRLCK)) === -1) {
            error('Unable to lock file: ' . $path);
        }
        // Truncate file
        if (!dio_truncate($fp, 0)) {
            error('Unable to truncate file: ' . $path);
        }
        // Write data
        if (($bytes = dio_write($fp, $data)) === false) {
            error('Unable to write to file: ' . $path);
        }
        // Unlock
        dio_fcntl($fp, F_SETLK, array('type' => F_UNLCK));
        // Close
        dio_close($fp);
    }
    /**
     * Create gzipped file.
     *
     * When writing into a file foo.bar and the size is larger or equal to 1
     * KiB, this also produces the gzipped version foo.bar.gz
     *
     * This is useful with nginx with gzip_static on.
     */
    if ($config['gzip_static']) {
        $gzpath = "{$path}.gz";
        if ($bytes & ~0x3ff) {
            // if ($bytes >= 1024)
            if (file_put_contents($gzpath, gzencode($data), $simple ? 0 : LOCK_EX) === false) {
                error("Unable to write to file: {$gzpath}");
            }
            if (!touch($gzpath, filemtime($path), fileatime($path))) {
                error("Unable to touch file: {$gzpath}");
            }
        } else {
            @unlink($gzpath);
        }
    }
    if (!$skip_purge && isset($config['purge'])) {
        // Purge cache
        if (basename($path) == $config['file_index']) {
            // Index file (/index.html); purge "/" as well
            $uri = dirname($path);
            // root
            if ($uri == '.') {
                $uri = '';
            } else {
                $uri .= '/';
            }
            purge($uri);
        }
        purge($path);
    }
    if ($config['debug']) {
        $debug['write'][] = $path . ': ' . $bytes . ' bytes';
    }
    event('write', $path);
}
Exemple #2
0
 public function action_do()
 {
     $params = Oauth2::parse_query();
     try {
         if (empty($params['code']) or isset($params['error'])) {
             throw new Oauth2_Exception($params['error']);
         }
         $token = Remote::get($this->_configs['token_uri'], array(CURLOPT_POST => TRUE, CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded;charset=utf-8'), CURLOPT_POSTFIELDS => Oauth2::build_query(array('grant_type' => $this->_configs['grant_type'], 'code' => $params['code'], 'client_id' => $this->_configs['client_id'], 'redirect_uri' => $this->_configs['redirect_uri'], 'client_secret' => $this->_configs['client_secret']))));
         $token = json_decode($token);
         if (isset($token->error)) {
             throw new Oauth2_Exception($token->error);
         }
         // Resource in json format
         $resource = Remote::get($this->_configs['access_uri'], array(CURLOPT_POST => TRUE, CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded;charset=utf-8'), CURLOPT_POSTFIELDS => Oauth2::build_query(array('oauth_token' => $token->access_token, 'timestamp' => $_SERVER['REQUEST_TIME'], 'refresh_token' => $token->refresh_token, 'expires_in' => $token->expires_in, 'client_id' => $this->_configs['client_id']))));
         $this->request->response = $resource;
     } catch (Exception $e) {
         $error = $e->getMessage();
     }
     if (isset($error)) {
         switch ($error) {
             case 'access_denied':
                 $this->request->response = 'You have denied this request.';
                 break;
             default:
                 $this->request->response = 'There must be some errors happen in this connection, please contact our web master.' . "[{$error}]";
                 break;
         }
     }
 }
Exemple #3
0
	/**
	 * Tests Remote::status
	 *
	 * @test
	 * @dataProvider provider_status
	 * @param boolean $input  Input for File::mime
	 * @param boolean $expected Output for File::mime
	 */
	public function test_status($input, $expected)
	{
		if ( ! $this->hasInternet())
			$this->markTestSkipped('An internet connection is required for this test');
		
		$this->assertSame($expected, Remote::status($input));
	}
Exemple #4
0
 /**
  * Test we can set and get default values
  */
 public function get_and_set_defaults_test()
 {
     Remote::set_default('pickle', 'gherkin');
     $this->should('set a default value', Remote::get_default('pickle') == 'gherkin');
     Remote::set_default(array('one' => 1, 'two' => 2));
     $this->should('set an array of default values', Remote::get_default('one') == 1 && Remote::get_default('two') == 2);
 }
 /**
  * Sets up this unittest
  *
  */
 public function setUp()
 {
     try {
         $this->remote = Remote::forName('xp://' . self::$bindAddress[0] . ':' . self::$bindAddress[1]);
     } catch (RemoteException $e) {
         throw new PrerequisitesNotMetError('Cannot setup client/server communication', $e);
     }
 }
Exemple #6
0
 public function action_test()
 {
     try {
         $resource = Remote::get('http://docs/api', array(CURLOPT_POST => TRUE, CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded;charset=UTF-8'), CURLOPT_POSTFIELDS => Oauth::build_query(array())));
     } catch (Exception $e) {
         $resource = $e->getMessage();
     }
     echo '<pre>' . print_r($resource, TRUE) . '</pre>';
 }
Exemple #7
0
 public function action_get_xml($xml_uri = '')
 {
     $this->auto_render = false;
     //        $this->request->headers['Content-Type'] = 'text/xml';
     // header('Content-type: text/xml');
     Request::instance()->headers = array('Content-type: text/xml');
     Request::instance()->send_headers();
     echo Remote::get(urldecode($_GET['id']));
     //        $data = file_get_contents(urldecode($_GET['id']));
     //        $this->request->response = $data;
     //        print $data;
 }
Exemple #8
0
 /**
  * @return  DOMDocument
  */
 public function execute()
 {
     // Set the API access URL
     $url = ($this->sandbox ? gCheckout::URL_SANDBOX : gCheckout::URL_PRODUCTION) . $this->merchant_id;
     // Build the XML for the request
     $xml = $this->build();
     // Get the server response
     $response = Remote::get($url, array(CURLOPT_USERPWD => $this->merchant_id . ':' . $this->merchant_key, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $xml));
     // Create a new DOMDocument for the response
     $xml = new DOMDocument();
     $xml->formatOutput = TRUE;
     $xml->loadXML($response);
     return $xml;
 }
Exemple #9
0
 /**
  *  Get data from remote service
  *  Method : pull(String $action [, Array $parameters])
  *  Return : a JSON object, same structure as returned by Web Service
  **/
 public function get($action, $parameters = false)
 {
     $url = $this->baseURL . '/' . (!!$this->version ? $this->version . '/' : '') . $action . '?';
     $url = $this->attach($url, $parameters);
     $response = Remote::pull($url);
     if (!!$response) {
         $ob = json_decode($response);
         if (!!$ob && is_object($ob)) {
             if (!isset($ob->error) || !$ob->error) {
                 return $ob;
             }
         }
     }
     return false;
 }
 /**
  * Constructor
  *
  * @param   util.cmd.ParamString args
  */
 public function __construct(ParamString $args)
 {
     $url = new URL($args->value(0));
     // If protocol string does not contain port number, set default.
     if (self::ESDL_PORT === $url->getPort(self::ESDL_PORT)) {
         $url->setPort(self::ESDL_PORT);
     }
     // Check given URL to inform user if invalid port used.
     if (self::ESDL_PORT !== $url->getPort()) {
         Console::$err->writeLine('Notice: using non-standard port ' . $url->getPort() . ', ESDL services are usually available at port 6449.');
     }
     $this->remote = Remote::forName($url->getURL());
     $this->jndi = $args->value(1);
     $this->processor = new DomXSLProcessor();
     $this->processor->setXSLBuf($this->getClass()->getPackage()->getResource($args->value('lang', 'l', 'xp5') . '.xsl'));
 }
Exemple #11
0
 public function action_tigia()
 {
     $this->auto_render = false;
     $eximbank = 'http://www.eximbank.com.vn/WebsiteExrate1/exchange.aspx';
     $data = Remote::get($eximbank);
     $pattern = '/<table[ ]class="width_tb".*>(.*)<\\/table>.*/ismxU';
     preg_match($pattern, $data, $matches);
     if (count($matches) > 0) {
         echo $matches[1];
     } else {
         echo "Không có dữ liệu";
     }
     //print_r($matches);
     //echo "<hr/>";
     //echo $data;
 }
 /**
  * @return array
  */
 private function getModifiedRemoteFiles()
 {
     $this->currentRemoteState = $this->remote->remoteScan();
     $currentArray = $this->utils->tabSepStringToArray($this->currentRemoteState, 0, 3);
     $saved = $this->utils->readSavedState(BASEPATH . '/deployhelper/remotestate');
     $savedArray = $this->utils->tabSepStringToArray($saved, 0, 3);
     $changeSet = array();
     foreach ($savedArray as $file => $sum) {
         if (isset($currentArray[$file])) {
             if ($currentArray[$file] != $sum) {
                 $changeSet[$file] = array('state' => 'REMOTEMOD', 'file' => $file);
             }
         } else {
             $changeSet[$file] = array('state' => 'REMOTEDEL', 'file' => $file);
         }
     }
     return $changeSet;
 }
Exemple #13
0
 /**
  * Funkcja odpowiedzialna za pobranie informacji o filmie.
  * @param string $path 
  * @return array
  */
 public static function getMovie($path)
 {
     // Trzymamy ciasteczka (czasami wyskakują reklamy)
     Remote::$default_options += array(CURLOPT_COOKIEFILE => dirname(__FILE__) . DIRECTORY_SEPARATOR . Filmweb_Parser::COOKIES . DIRECTORY_SEPARATOR . 'filmweb', CURLOPT_COOKIEJAR => dirname(__FILE__) . DIRECTORY_SEPARATOR . Filmweb_Parser::COOKIES . DIRECTORY_SEPARATOR . 'filmweb');
     // Wywowałmy filmweba.pl - dla usunięcia reklamy.
     Remote::get(Filmweb_Parser::URL);
     $request = Filmweb_Parser::URL;
     $response = Remote::get($request . $path);
     $data = new stdClass();
     foreach (Filmweb_Parser::$regexps as $k => $r) {
         if ($r['all']) {
             preg_match_all($r['reg'], $response, $found);
         } else {
             preg_match($r['reg'], $response, $found);
         }
         if (isset($found[$r['data']])) {
             if ($r['all']) {
                 if ($r['references']) {
                     $a = array();
                     foreach ($found[$r['data']] as $key => $v) {
                         $ref = $r['references'][0]::${$r}['references'][1];
                         $a[] = array('key' => $v, 'value' => $ref[$v]);
                     }
                 }
                 $data->{$k} = $a;
             } else {
                 if (isset($r['filter'])) {
                     if (is_array($r['filter'])) {
                         if (isset($r['filter'][2])) {
                             $data->{$k} = call_user_func($r['filter'][0], $r['filter'][1], $r['filter'][2], $found[$r['data']]);
                         } else {
                             $data->{$k} = call_user_func($r['filter'][0], $r['filter'][1], $found[$r['data']]);
                         }
                     } else {
                         $data->{$k} = call_user_func($r['filter'], $found[$r['data']]);
                     }
                 } else {
                     $data->{$k} = $found[$r['data']];
                 }
             }
         }
     }
     return $data;
 }
Exemple #14
0
 /**
  * Download a file to a new location. If no filename is provided,
  * the original filename will be used, with a unique prefix added.
  *
  * @param   string   remote url
  * @param   string   new filename
  * @param   string   new directory
  * @param   integer  chmod mask
  * @return  array    on success, upload style file array
  * @return  false    on failure
  */
 public static function download($url, $filename = NULL, $directory = NULL, $chmod = 0644)
 {
     if (!Valid::url($url)) {
         return false;
     }
     // If no filename given, use remote filename with uniqid
     $original_filename = basename(parse_url($url, PHP_URL_PATH));
     if ($filename === null) {
         $filename = uniqid() . $original_filename;
     }
     // Remove spaces from the filename
     if (Upload::$remove_spaces === true) {
         $filename = preg_replace('/\\s+/', '_', $filename);
     }
     // Use the pre-configured upload directory if not given
     if ($directory === null) {
         $directory = Upload::$default_directory;
     }
     if (!is_dir($directory) || !is_writable(realpath($directory))) {
         throw new Kohana_Exception('Directory :dir must be writable', array(':dir' => Kohana::debug_path($directory)));
     }
     // Make the filename into a complete path
     $filename = realpath($directory) . DIRECTORY_SEPARATOR . $filename;
     // Download file
     try {
         // Dummy escape to get rid of spaces to awoid 400 Bad Request
         $url = str_replace(' ', '%20', $url);
         $fh = fopen($filename, 'w');
         Remote::get($url, null, array(CURLOPT_RETURNTRANSFER => true, CURLOPT_FILE => $fh));
         $size = Arr::get(fstat($fh), 'size', 0);
         fclose($fh);
         // Set permissions
         if ($chmod !== false) {
             chmod($filename, $chmod);
         }
         // Build file array
         $finfo = finfo_open(FILEINFO_MIME_TYPE);
         $mime = finfo_file($finfo, $filename);
         finfo_close($finfo);
         return array('error' => UPLOAD_ERR_OK, 'name' => $original_filename, 'type' => $mime, 'tmp_name' => $filename, 'size' => $size);
     } catch (Kohana_Exception $e) {
         return false;
     }
 }
 private function _get_status()
 {
     $data = array('pos_id' => Arr::get($_POST, 'pos_id'), 'session_id' => Arr::get($_POST, 'session_id'), 'ts' => time(), 'key' => $this->_pos_data['key']);
     $data['sig'] = $this->_get_sig($data);
     unset($data['key']);
     $url = self::PAYMENT_URL . $this->_codepage . '/' . self::PAYMENT_GET . '/' . $this->_format;
     $response = Remote::get($url, array(CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => http_build_query($data)));
     if ($this->_format == self::PAYMENT_FORMAT_XML) {
         $xml = new SimpleXMLElement($response);
         $pending = array(1, 4, 5);
         $success = array(99);
         $fail = array(2, 3, 7, 888);
         if (in_array((int) $xml->trans->status, $pending)) {
             return Payment::STATUS_PENDING;
         }
         if (in_array((int) $xml->trans->status, $success)) {
             return Payment::STATUS_SUCCESS;
         }
         if (in_array((int) $xml->trans->status, $fail)) {
             return Payment::STATUS_FAILED;
         }
         return FALSE;
     }
 }
 public function lookupNonExistantName()
 {
     Remote::forName(REMOTE_SPEC_ONE)->lookup('does/not/Exist');
 }
Exemple #17
0
 /**
  * 功能描述:获取数据
  * @auther   王晨
  * @datetime 2015年09月29日14:03:46
  * @param $code
  * @param $params
  */
 public static function getData(array $code, array $params)
 {
     $request = [];
     $localResult = [];
     $remoteResult = [];
     foreach ($code as $k => $c) {
         $codeArr = explode('_', $c);
         if (count($codeArr) != 2) {
             return false;
         }
         list($prefix, $event) = $codeArr;
         $request[$prefix][] = $event;
     }
     if (isset($request[self::EVENT_LOCAL_PREFIX])) {
         $localResult = Local::getData($request[self::EVENT_LOCAL_PREFIX], $params);
     }
     if (isset($request[self::EVENT_REMOTE_PREFIX])) {
         $remoteResult = Remote::getData($request[self::EVENT_REMOTE_PREFIX], $params);
         //$remoteResult = Remote::getDataByRedis($request[self::EVENT_REMOTE_PREFIX], $params);
         //$remoteResult = Remote::getDataByProcess($request[self::EVENT_REMOTE_PREFIX], $params);
     }
     return array_merge($localResult, $remoteResult);
 }
Exemple #18
0
 private function generate_cluster_map($project_id, $chid, $chart_file)
 {
     $api_url = $this->chart_api_url . "?chid={$chid}";
     // Open chart file and extract data
     $file_handle = fopen($chart_file, "r");
     $chart_params = array();
     while (!feof($file_handle)) {
         $line = rtrim(fgets($file_handle));
         $param_ex = explode("=", $line);
         $param_name = $param_ex[0];
         $param_vals = $param_ex[1];
         if ($param_name == "mpids") {
             // List of cluster_ids in order displayed on chart
             $cluster_ids = explode(",", $param_vals);
         } else {
             if ($param_name == "mps") {
                 // List of cluster sizes (number of documents) in order displayed on chart
                 $cluster_sizes = explode(",", $param_vals);
             } else {
                 // Parameter is chart param
                 $chart_params[$param_name] = $param_vals;
                 if ($param_name == "chd") {
                     $chd_ex = explode("|", substr($param_vals, 2));
                     $cluster_scores = explode(",", $chd_ex[1]);
                 }
             }
         }
     }
     fclose($file_handle);
     $chart_params['chof'] = 'json';
     // tell API to return image map HTML
     // Send the POST request, parse json data, & compile image map HTML
     $response = Remote::get($api_url, array(CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => http_build_query($chart_params)));
     $image_map_html = '';
     $json = json_decode($response, true);
     $num_results = count($json['chartshape']);
     if ($num_results > 0) {
         $i = 0;
         foreach ($json['chartshape'] as $map_item) {
             if ($map_item['type'] == "CIRCLE") {
                 $coords_str = implode(",", $map_item['coords']);
                 $title = $cluster_sizes[$i] . " documents (score: " . $cluster_scores[$i] . ")";
                 $href = "javascript:startLyteframe('" . $title . "', '" . Url::base() . "index.php/results/cluster_summary/{$project_id}?cluster_id=" . $cluster_ids[$i] . "')";
                 $image_map_html .= '<area name="' . $map_item['name'] . '" shape="' . $map_item['type'] . '" class="noborder icolorff0000" coords="' . $coords_str . '" href="' . $href . '" title="' . $title . '">';
                 $i++;
             }
         }
     }
     return $image_map_html;
 }
Exemple #19
0
function file_write($path, $data, $simple = false, $skip_purge = false)
{
    global $config, $debug;
    if (preg_match('/^remote:\\/\\/(.+)\\:(.+)$/', $path, $m)) {
        if (isset($config['remote'][$m[1]])) {
            require_once 'inc/remote.php';
            $remote = new Remote($config['remote'][$m[1]]);
            $remote->write($data, $m[2]);
            return;
        } else {
            error('Invalid remote server: ' . $m[1]);
        }
    }
    if (!($fp = fopen($path, $simple ? 'w' : 'c'))) {
        error('Unable to open file for writing: ' . $path);
    }
    // File locking
    if (!$simple && !flock($fp, LOCK_EX)) {
        error('Unable to lock file: ' . $path);
    }
    // Truncate file
    if (!$simple && !ftruncate($fp, 0)) {
        error('Unable to truncate file: ' . $path);
    }
    // Write data
    if (($bytes = fwrite($fp, $data)) === false) {
        error('Unable to write to file: ' . $path);
    }
    // Unlock
    if (!$simple) {
        flock($fp, LOCK_UN);
    }
    // Close
    if (!fclose($fp)) {
        error('Unable to close file: ' . $path);
    }
    if (!$skip_purge && isset($config['purge'])) {
        // Purge cache
        if (basename($path) == $config['file_index']) {
            // Index file (/index.html); purge "/" as well
            $uri = dirname($path);
            // root
            if ($uri == '.') {
                $uri = '';
            } else {
                $uri .= '/';
            }
            purge($uri);
        }
        purge($path);
    }
    if ($config['debug']) {
        $debug['write'][] = $path . ': ' . $bytes . ' bytes';
    }
    event('write', $path);
}
Exemple #20
0
 /**
  * @return string
  */
 public static function getFilesPath()
 {
     return Remote::getApplicationPath() . "files/";
 }
 public function test_forge()
 {
     $test_subject = \Remote::forge('http://google.com', 'curl', 'get');
     $this->assertInternalType('object', $test_subject);
     $this->assertSame('GET', $test_subject->get_method());
 }
Exemple #22
0
 function handler_admin($page, $id = null, $action = null)
 {
     $page->assign('title', "Administration de l'authentification externe");
     $page->assign('remoterights_available', implode(',', Remote::availableRights()));
     // Find remote
     $remote = null;
     if ($id == 'new') {
         $remote = new Remote();
         $remote->insert();
     } elseif (Remote::isId($id)) {
         $remote = new Remote($id);
         // Delete a remote
         if ($action == 'delete') {
             $remote->delete();
             $remote = null;
         }
     }
     if (!empty($remote)) {
         $remote->select(RemoteSelect::groups());
         if (Env::has('change_remote')) {
             $remote->site(Env::t('site'));
             $remote->label(Env::t('label'));
             $remote->privkey(Env::t('privkey'));
             $rights = explode(',', Env::t('rights'));
             foreach ($rights as $k => $v) {
                 $rights[$k] = strtolower(trim($v));
             }
             $rights = array_intersect($rights, Remote::availableRights());
             $remote->rights(new PlFlagSet(implode(',', $rights)));
             $groups = new Collection('Group');
             $groups_fields = array('binets', 'frees');
             foreach ($groups_fields as $field) {
                 foreach (explode(';', Env::t($field)) as $gid) {
                     $gid = trim($gid);
                     if ($gid) {
                         $groups->add(new Group($gid));
                     }
                 }
             }
             $groups->select(GroupSelect::base());
             $remote->groups($groups);
         }
         $page->assign('remote', $remote);
         $page->changeTpl('remote/admin.tpl');
     } else {
         $remotes = Remote::selectAll(RemoteSelect::groups());
         $page->assign('remotes', $remotes);
         $page->changeTpl('remote/list.tpl');
     }
 }
Exemple #23
0
 /**
  * Makes an API request and returns the response.
  *
  * @param   string  method to call
  * @param   array   query parameters
  * @return  array
  */
 protected function _request($method, array $params = NULL)
 {
     // Add the token to the parameters
     $params['token'] = $this->_token;
     try {
         // Make an API request
         $response = Remote::get(Todoist::API_URL . $method . '?' . http_build_query($params, NULL, '&'));
     } catch (Kohana_Exception $e) {
         throw new Todoist_Exception('API :method request failed, API may be offline', array(':method' => $method));
     }
     // Return the decode response
     return json_decode($response, TRUE);
 }
Exemple #24
0
 *  Foundation, Inc.,                                                      *
 *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
 ***************************************************************************/
/**
 * This script saves database information into outputed SQL lines
 */
require_once dirname(__FILE__) . '/connect.db.inc.php';
// DELETE confidential data
echo XDB::format('UPDATE account SET password={?};', '') . PHP_EOL;
echo 'DELETE FROM remote;' . PHP_EOL;
echo 'DELETE FROM remote_groups;' . PHP_EOL;
// Get this data from bdd
$iter = XDB::iterRow('SELECT  hruid, password
                        FROM  account
                       WHERE  password != {?}', '');
while (list($hruid, $password) = $iter->next()) {
    echo XDB::format('UPDATE account SET password = {?} WHERE hruid = {?};', $password, $hruid) . PHP_EOL;
}
// Save dev's remote sites
$remote_cols = array('site', 'privkey', 'label', 'rights');
$remotes = Remote::selectAll(RemoteSelect::groups());
foreach ($remotes as $r) {
    $query = XDB::format('INSERT INTO remote SET remid = {?}', $r->id());
    foreach ($remote_cols as $c) {
        $query .= XDB::format(', ' . $c . ' = {?}', $r->{$c}());
    }
    echo $query . ';' . PHP_EOL;
    foreach ($r->groups() as $g) {
        echo XDB::format('INSERT INTO remote_groups SET remid = {?}, gid = {?};', $r->id(), $g->id()) . PHP_EOL;
    }
}
Exemple #25
0
 /**
  * Execute the request and return a response.
  *
  * @param   string   request type: GET, POST, etc (NULL for header)
  * @param   array    additional cURL options
  * @return  string   request response body
  * @uses    OAuth_Request::check
  * @uses    Arr::get
  * @uses    Remote::get
  */
 public function execute(array $options = NULL)
 {
     // Check that all required fields are set
     $this->check();
     // Get the URL of the request
     $url = $this->url;
     if (!isset($options[CURLOPT_CONNECTTIMEOUT])) {
         // Use the request default timeout
         $options[CURLOPT_CONNECTTIMEOUT] = $this->timeout;
     }
     if ($this->send_header) {
         // Get the the current headers
         $headers = Arr::get($options, CURLOPT_HTTPHEADER, array());
         // Add the Authorization header
         $headers[] = 'Authorization: ' . $this->as_header();
         // Store the new headers
         $options[CURLOPT_HTTPHEADER] = $headers;
     }
     if ($this->method === 'POST') {
         // Send the request as a POST
         $options[CURLOPT_POST] = TRUE;
         if ($post = $this->as_query()) {
             // Attach the post fields to the request
             $options[CURLOPT_POSTFIELDS] = $post;
         }
     } elseif ($query = $this->as_query()) {
         // Append the parameters to the query string
         $url = "{$url}?{$query}";
     }
     return Remote::get($url, $options);
 }
 /**
  * Run the request
  * 
  * @param \Raml\SecurityScheme $securityscheme_obj The security scheme to process the call data for
  * @param \V1\APICall $apicall_obj					The APICall object
  * 
  * @return mixed The object we just completed or an array describing the next step in the security process
  */
 public function run(\Raml\SecurityScheme $securityscheme_obj, \V1\APICall $apicall_obj)
 {
     $settings = $securityscheme_obj->getSettings();
     $credentials = $apicall_obj->get_credentials();
     // Save the credentials
     \V1\Keyring::set_credentials($credentials);
     /**
      * By default we'll return the response from the authentication request so that it's meaningful.
      * However, in doing so, we'll need to block the main request, so developers may set this flag
      * to ignore the authentication, signifying that they've already got the information they needed
      * from it.
      * 
      * NOTE: This security method is meant as a basic way to catch security methods we otherwise
      * haven't implemented in our system. Take it for what it's worth. 
      * 
      * @TODO When using this security method, skip processing the APICall object for a speedup.
      */
     if (!empty($credentials['CUSTOM_IGNORE_AUTH'])) {
         return true;
     }
     // Remove unused credentials so as not to replace bad variables in the template.
     foreach ($credentials as $variable => $entry) {
         if (strpos($variable, 'CUSTOM_') !== 0) {
             unset($credentials[$variable]);
         }
     }
     // We need the method or we'll fail the call.
     if (empty($settings['method'])) {
         $this->error = true;
         return $this;
     }
     // Normalize the data into arrays.
     $described_by = $securityscheme_obj->getDescribedBy();
     $headers = $this->get_param_array($described_by->getHeaders());
     $query_params = $this->get_param_array($described_by->getQueryParameters());
     $bodies = $described_by->getBodies();
     $method = \Str::upper($settings['method']);
     $url = $settings['url'];
     // Grab the body if we have one, and the method supports one.
     $body = null;
     $body_type = null;
     if (count($bodies) > 0 && !in_array($method, array('GET', 'HEAD'))) {
         reset($bodies);
         $body_type = key($bodies);
         $body = $bodies[$body_type]->getExamples()[0];
     }
     /**
      * NOTE: These replacements may ruin the formatting or allow for people to inject data into them.
      * API Providers should be aware of that possibility.
      * 
      * @TODO In the future, we can consider implementing checking to verify that people aren't sending
      * crap data through the system.
      */
     $headers = $this->remove_cr_and_lf($this->replace_variables($headers, $credentials));
     $query_params = $this->remove_cr_and_lf($this->replace_variables($query_params, $credentials));
     $body = $this->replace_variables($body, $credentials);
     if (!empty($query_params)) {
         $query_string = http_build_query($query_params, null, '&');
         if (strpos($url, '?') === false) {
             $url .= '?' . $query_string;
         } else {
             $url .= '&' . $query_string;
         }
     }
     /**
      * RUNCLE RICK'S RAD RUN CALLS (The second coming!)
      */
     $curl = \Remote::forge($url, 'curl', $method);
     // Set the headers
     $headers = \V1\RunCall::get_headers($headers);
     foreach ($headers as $header_name => $header_value) {
         $curl->set_header($header_name, $header_value);
     }
     // Return the headers
     $curl->set_option(CURLOPT_HEADER, true);
     // If we need a body, set that.
     if (!empty($body) && !in_array($method, array('GET', 'HEAD'))) {
         $curl->set_header('Content-Type', $body_type);
         $curl->set_params($body);
     }
     // Run the request
     try {
         $response = $curl->execute()->response();
     } catch (\RequestStatusException $e) {
         $response = \Remote::get_response($curl);
     } catch (\RequestException $e) {
         $this->error = true;
         return $this;
     }
     // Set the usage stats, and format the response
     return \V1\Socket::prepare_response(array('status' => $response->status, 'headers' => $response->headers, 'body' => $response->body));
 }
Exemple #27
0
 private static function remoteToLocalImage($url, $path, $lim = false, $saveas = '', $quality = 75)
 {
     $im = @getimagesize($url);
     if (!!$im) {
         require_once 'Master/base/libraries/Images/SimpleImage.php';
         $type = $im['mime'];
         $width = $im[0];
         $height = $im[1];
         $minWidth = static::MIN_WIDTH;
         $minHeight = static::MIN_HEIGHT;
         $maxWidth = static::MAX_WIDTH;
         $maxHeight = static::MAX_HEIGHT;
         if (!!$lim) {
             $lim = (object) $lim;
             if (isset($lim->minWidth)) {
                 $minWidth = $lim->minWidth;
             }
             if (isset($lim->minHeight)) {
                 $minHeight = $lim->minHeight;
             }
             if (isset($lim->maxWidth)) {
                 $maxWidth = $lim->maxWidth;
             }
             if (isset($lim->maxHeight)) {
                 $maxHeight = $lim->maxHeight;
             }
         }
         if ($width > $minWidth && $height > $minHeight && strpos($type, 'image') === 0) {
             $ext = static::getExt($type);
             if (!!$ext) {
                 $content = Remote::pull($url);
                 if (!!$content) {
                     $name = !!$saveas ? $saveas : Bella::createId(32);
                     $name .= $ext;
                     $file = $path . $name;
                     $save = @file_put_contents($file, $content);
                     if (!!$save) {
                         if ($width > $maxWidth || $height > $maxHeight) {
                             $sm = new SimpleImage();
                             $sm->load($file);
                             $sm->fillTo($maxWidth, $maxHeight);
                             $sm->save($file, false, $quality);
                         }
                         return $name;
                     }
                 }
             }
         }
     }
     return false;
 }
Exemple #28
0
 protected function createRemote($name = 'name', $url = 'url')
 {
     $remote = new Remote();
     return $remote->setName($name)->setUrl($url);
 }
Exemple #29
0
 public function api_connect($request_url, $method, array $post_data = array())
 {
     $method = strtolower($method);
     if ($method != 'get' and $method != 'post') {
         throw new Exception("api_connect: method supplied must be either 'post' or 'get'");
     }
     $num_requests_sent = 0;
     $response = "";
     while (TRUE) {
         if ($num_requests_sent > $this->connection_retries) {
             print "Could not connect to API with request: {$request_url}\n";
             // Add ERROR entry to gather log
             $this->model_gather->insert_gather_log(array('project_id' => $this->project_id, 'search_query' => $error, 'date' => time(), 'results_gathered' => 0, 'error' => 1));
             $this->api_connect_error = 1;
             break;
         } else {
             if ($num_requests_sent > 0) {
                 print "Re-trying ({$num_requests_sent})...\n";
             }
             // Try connecting to API
             $error = "";
             try {
                 if ($method == "get") {
                     $response = Remote::get($request_url, array(CURLOPT_RETURNTRANSFER => TRUE));
                 } else {
                     if ($method == "post") {
                         $response = Remote::get($request_url, array(CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => http_build_query($post_data)));
                     }
                 }
             } catch (Exception $e) {
                 $error = $e->getMessage();
                 $num_requests_sent++;
                 sleep($this->wait_before_retry);
                 // Wait before trying to reconnect
             }
             if (!$error) {
                 print "Successfully connected to API!\n";
                 break;
             }
         }
     }
     return $response;
 }
 /**
  * Request the WWW-Authentication header from the remote server, and parse it.
  * 
  * @param string $url The URL to contact and beg for a nonce
  * @return bool True on success, or false on fail
  */
 private function parse_www_auth_remote($url)
 {
     // We tried to pull the data, so if we can't get an array later, we'll know what happened.
     $this->www_data = true;
     $curl = \Remote::forge($url, 'curl', 'head');
     try {
         $headers = $curl->execute()->headers;
     } catch (\RequestStatusException $e) {
         $headers = \Remote::get_response($curl)->headers;
     } catch (\RequestException $e) {
         return false;
     }
     if (is_array($parsed = $this->parse_www_auth($headers))) {
         $this->www_data = $parsed;
         return true;
     } else {
         return false;
     }
 }