Upload files to Owncloud - owncloud

I wonder, can i upload files to OwnCloud by some post or put request?
My goal - user uploads files to one server1, after submitting form his data
handles and sends to another server2 with Owncloud installed on, then returns
path to file in owncloud back. So record in server1 will have some filename
property points to owncloud storage.
(Note: I am not talking about WebDAV).
Any other capabilities?

The Own Cloud API exposes an endpoint which makes this possible (both for POST and PUT):
post(string $uri, array $options = array()) : \OCP\Http\Client\IResponse
and
put(string $uri, array $options = array()) : \OCP\Http\Client\IResponse
Parameters
string $uri array $options Array such as
'body' => [ 'field' =>
'abc', 'other_field' => '123', 'file_name' => fopen('/path/to/file',
'r'), ], 'headers' => [ 'foo' => 'bar', ], 'cookies' => [' 'foo' =>
'bar', ], 'allow_redirects' => [ 'max' => 10, // allow at most 10
redirects. 'strict' => true, // use "strict" RFC compliant redirects.
'referer' => true, // add a Referer header 'protocols' => ['https'] //
only allow https URLs ], 'save_to' => '/path/to/file', // save to a
file or a stream 'verify' => true, // bool or string to CA file
'debug' => true,
see https://doc.owncloud.org/api/classes/OCP.Http.Client.IClient.html for the relevant section in the API docs

Related

Aura Router AJAX Route Failure - Route Not Found

To preface this question, I'm converting a demo application to utilize RESTful, SEO-friendly URLs; EVERY route with the exception of one of two routes used for AJAX requests works when being used in the application on the web, and ALL the routes have been completely tested using Postman - using a vanilla Nginx configuration.
That being said, here is the offending route definition(s) - the login being the defined route that's failing:
$routing_map->post('login.read', '/services/authentication/login', [
'params' => [
'values' => [
'controller' => '\Infraweb\Toolkit\Services\Authentication',
'action' => 'login',
]
]
])->accepts([
'application/json',
]);
$routing_map->get('logout.read', '/services/authentication/logout', [
'params' => [
'values' => [
'controller' => '\Infraweb\Toolkit\Services\Authentication',
'action' => 'logout',
]
]
])->accepts([
'application/json',
]);
With Postman & xdebug tracing I think I'm seeing that it's (obviously) failing what I believe to be a REGEX check in the Path rule, but I can't quite make it out. It's frustrating to say the least. I looked everywhere I could using web searches before posting here - the Google group for Auraphp doesn't seem to get much traffic these days. It's probable I've done something incorrectly, so I figured it was time to ask the collective user community for some direction. Any and all constructive criticism is greatly welcomed and appreciated.
Thanx in advance, and apologies for wasting anyone's bandwidth on this question...
Let me make something clear. Aura.Router doesn't do the dispatching. It only matches the route. It doesn't handle how your routes are handled.
See the full working example ( In that example the handler is assumed as callable )
$callable = $route->handler;
$response = $callable($request);
In your case if you matched the request ( See matching request )
$matcher = $routerContainer->getMatcher();
$route = $matcher->match($request);
you will get the route, now you need to write appropriate ways how to handle the values from the $route->handler.
This is what I did after var_dump the $route->handler for the /signin route .
array (size=1)
'params' =>
array (size=1)
'values' =>
array (size=2)
'controller' => string '\Infraweb\LoginUI' (length=17)
'action' => string 'read' (length=4)
Full code tried below. As I mentioned before I don't know your route handling logic. So it is up to you to write things properly.
<?php
require __DIR__ . '/vendor/autoload.php';
use Aura\Router\RouterContainer;
$routerContainer = new RouterContainer();
$map = $routerContainer->getMap();
$request = Zend\Diactoros\ServerRequestFactory::fromGlobals(
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$map->get('application.signin.read', '/signin', [
'params' => [
'values' => [
'controller' => '\Infraweb\LoginUI',
'action' => 'read',
]
]
]);
$map->post('login.read', '/services/authentication/login', [
'params' => [
'values' => [
'controller' => '\Infraweb\Toolkit\Services\Authentication',
'action' => 'login',
]
]
])->accepts([
'application/json',
]);
$matcher = $routerContainer->getMatcher();
// .. and try to match the request to a route.
$route = $matcher->match($request);
if (! $route) {
echo "No route found for the request.";
exit;
}
echo '<pre>';
var_dump($route->handler);
exit;
For the record, this is the composer.json
{
"require": {
"aura/router": "^3.1",
"zendframework/zend-diactoros": "^2.1"
}
}
and running via
php -S localhost:8000 index.php
and browsing http://localhost:8000/signin

How can I do multipart requests mith Mojo::UserAgent?

I'd like to perform a multipart file upload to Google Drive as described here using a Mojo::UserAgent. I currently do it like this:
my $url = Mojo::URL->new('https://www.googleapis.com/upload/drive/v3/files');
$url->query({ fields => 'id,parents',
ocr => 'true',
ocrLanguage => 'de',
uploadType => 'multipart' });
my $tx = $ua->post($url,
json => { parents => [ '0ByFk4UawESNUX1Bwak1Ka1lwVE0' ] },
{
'Content-Type' => 'multipart/related',
'parents' => [ '0ByFk4UawESNUX1Bwak1Ka1lwVE0' ]
},
$content );
but it doesn't work.
I've managed authorization OK (omitted here) and simple file upload works fine. I just can't seem to do the multipart.
I've tried to make sense of the docs here - but to no avail, in the sense that the file gets uploaded OK, but the JSON part gets ignored, and the file gets uploaded in the root folder.

Codeigniter + HAuth, Authentication failed! Facebook returned an invalid user id

I am using HybridAuth Library with Codeigniter Framework, All the other Social login are working properly Except "Facebook Social Login", I am getting the error "Authentication Failed! Facebook returned an invalid user Id."
I Tried all available Answers, Like:
Hybridauth Authentication failed! Facebook returned an invalid user id
Hybridauth - PHP - Facebook returned an invalid user id
https://github.com/hybridauth/hybridauth/issues/188
https://github.com/hybridauth/hybridauth/issues/633
I am struggling from 2 days, and tried all the possible answers, still can't figure it out what is the problem, any help will be really appreciable.
Note: CURL is working properly on my server
Update
Code File
config->hybridauthlib.php
$config =
array(
'base_url' => '/hauth/endpoint/',
"providers" => array (
"Facebook" => array (
"enabled" => true,
"keys" => array ( "id" => "xxxxxxxx", "secret" => "xxxxxxxxxx" ),
),
);
Thirdparty->hybridauth->config.php
return
array(
"base_url" => "/hauth/endpoint/",
"Facebook" => array (
"enabled" => true,
"keys" => array ( "id" => "", "secret" => "" ),
"trustForwarded" => true,
),
I have also do changes in third_party->hybridauth->Hybrid->thirdparty->facebook->base_facebook.php as suggested by other developers
public static $CURL_OPTS = array(
CURLOPT_CONNECTTIMEOUT => 30,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_USERAGENT => 'facebook-php-3.2',
CURLOPT_SSL_VERIFYPEER => false
);
protected $trustForwarded = true;
protected $allowSignedRequest = false;
Facebook Redirect URIs
http://localhost/myproj/index.php/hauth/endpoint?hauth.done=Facebook
I have also found same issue and resolve it. Please go to this URL:
https://github.com/aviansh26dec/hauth

Google cloud storage: How can I reset edge cache?

I updated an image (from PHP) but still the old version of the image is downloaded.
If I download the image on the GCS console, I can download the new version of the image. However, this url below returns the old version.
https://storage.googleapis.com/[bucket name]/sample-image.png
It seems that the old image is on the Google's edge cache.
Some articles say that I should delete the image object then insert the new image object so that the edge cache is cleared.
Does anyone know about this?
Update 1
This is my PHP code which is on GCE.
$obj = new \Google_Service_Storage_StorageObject();
$obj->setName($path . "/" . $name);
$client = new \Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(\Google_Service_Storage::DEVSTORAGE_FULL_CONTROL);
$storage = new \Google_Service_Storage($client);
$bucket = 'sample.com';
$binary = file_get_contents($_FILES['files']['tmp_name']);
$fileInfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $fileInfo->buffer($binary);
$storage->objects->insert($bucket, $obj, [
'name' => $path . "/" . $name,
'data' => $binary,
'uploadType' => 'media',
'mimeType' => $mimeType,
]);
It seems that only these parameters are valid. I don't think I can set any cache settings.
// Valid query parameters that work, but don't appear in discovery.
private $stackParameters = array(
'alt' => array('type' => 'string', 'location' => 'query'),
'fields' => array('type' => 'string', 'location' => 'query'),
'trace' => array('type' => 'string', 'location' => 'query'),
'userIp' => array('type' => 'string', 'location' => 'query'),
'quotaUser' => array('type' => 'string', 'location' => 'query'),
'data' => array('type' => 'string', 'location' => 'body'),
'mimeType' => array('type' => 'string', 'location' => 'header'),
'uploadType' => array('type' => 'string', 'location' => 'query'),
'mediaUpload' => array('type' => 'complex', 'location' => 'query'),
'prettyPrint' => array('type' => 'string', 'location' => 'query'),
);
https://github.com/google/google-api-php-client/blob/master/src/Google/Service/Resource.php
I tried this way but not work so far. This is for only GAE...? (Or mounting may be necessary)
$image = file_get_contents($gs_name);
$options = [ "gs" => [ "Content-Type" => "image/jpeg"]];
$ctx = stream_context_create($options);
file_put_contents("gs://<bucketname>/".$fileName, $gs_name, 0, $ctx);
How do I upload images to the Google Cloud Storage from PHP form?
Update 2
API doc shows cacheControl property of Request body. I guess that using API directly (not via SDK) is a way. I will try it.
https://cloud.google.com/storage/docs/json_api/v1/objects/insert
cacheControl string Cache-Control directive for the object data. writable
I think I found it finally!
$obj->setCacheControl('no-cache');
Update 3
$bucket_name = 'my-bucket';
$file = "xxx.html";
$infotowrite = "999";
$service = new Google_Service_Storage($client);
$obj = new Google_Service_Storage_StorageObject();
$obj->setName($file);
$obj->setCacheControl('public, max-age=6000');
$results = $service->objects->insert(
$bucket_name,
$obj,
['name' => $file, 'mimeType' => 'text/html', 'data' => $infotowrite, 'uploadType' => 'media']
);
Set Cache-Control php client on Google Cloud Storage Object
We can check the result
gsutil ls -L gs://...
By default, if an object is publicly accessible to all anonymous users and you do not otherwise specify a cacheControl setting, GCS will serve a Cache-Control header of 3600 seconds, or 1 hour. If you're getting stale object data and haven't been messing with cache control settings, I assume you're serving publicly accessible objects. I'm not sure if Google itself is caching your object data or if there's some other cache between you and Google, though.
In the future, you can fix this by explicitly setting a shorter Cache-Control header, which can be controlled on a per-object basis with the cacheControl setting.
Right now, you can probably get around this by tacking on some made up extra URL query parameter, like ?ignoreCache=1
More: https://cloud.google.com/storage/docs/xml-api/reference-headers#cachecontrol

Yii2 restful not working

By using this link I tried to have a restful app, but it's not working and always returned this:
Object not found!
The requested URL was not found on this server. If you entered the URL manually please > > check your spelling and try again.
If you think this is a server error, please contact the webmaster.
Error 404
localhost
Apache/2.4.4 (Win32) OpenSSL/1.0.1e PHP/5.5.1
I call it like this: localhost/restful/web/users
Edit:
This kind of call is not working either: localhost/restful/web/?r=users
It returned this:
Not Found (#404)
Page not found.
The above error occurred while the Web server was processing your request.
Please contact us if you think this is a server error. Thank you.
Have the same error (stil getting 404 Not found on each request) have solve it adding .htaccess to (my yii path)/web folder (the same where you have index.php):
# use mod_rewrite for pretty URL support
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php
This is because when you create an clean instance of Yii2 you don't have the .htaccess file (in my opinion probably the security reason).
for me the: (enabling curl and using it in my controller) installed via composer
composer require --prefer-dist linslin/yii2-curl "*"
use in controller
<?php
namespace app\controllers;
use yii\rest\ActiveController;
use linslin\yii2\curl;//this was added
class UserController extends ActiveController
{
Don't work.
Maybe this helps someone :)
This is my config/web.php:
<?php
$params = require(__DIR__ . '/params.php');
$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'components' => [
'urlManager'=>[
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'a',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => require(__DIR__ . '/db.php'),
],
'params' => $params,
];
if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = 'yii\gii\Module';
}
return $config;
And the controller:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController{
public $modelClass = 'app\models\User';
}
Also a created my model by gii.
The problem solved by enabling curl and using it in my controller.