Could not open local file, but the file is there - php

I have a php artisan command that I created, and executed as bheng user
php /home/forge/site.com/artisan products:exportdiff --env=production
that export the file into my /files/product-exports/ directory
Also, I've already did
chmod -R 777 files/product-exports/
Result
The export part is working fine, I got the file exported as you can see in the image below
But I kept getting this
What is the different between white and green color code ?
Why does it place under the dot . ? Does it mean anything at all ?
Is this something that have to do with the permission ?
Update
As requested from #Tensibai
cd /home/forge/site.com/ && pwd && php /home/forge/site.com/artisan products:exportdiff --env=production
/home/forge/site.com
.
Export created successfully. Export ID is 1085
Source: /home/forge/site/files/product-exports/export1085_2016-11-23.csv
Destination: /Site/inbound/products/productexport1085_2016-11-23.csv
$source NOT exist !
[Exception]
Could not open local file: /home/forge/site/files/product-exports/export1085_2016-11-23.csv.
products:exportdiff
Update2
$source = /home/forge/site/files/product-exports/export1088_2016-11-23.csv
I've tried dd(file_exists($source));
It kept return bool(false)
Is it because of the way I check for file_exists ?
Update3
Here is my whole PHP code for ExportProductsDiff.php
<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class ExportProductsDiff extends Command {
/**
* The console command name.
*
* #var string
*/
protected $name = 'products:exportdiff';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Export all products to Diff.';
/**
* The system export message.
*
* #var string
*/
protected $system_message = '[System Diff Export]';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function fire()
{
// Export the products by calling the ExportProducts Command
$options = [
'--format' => "distributor",
'--encoding' => "standard csv",
'--categories' => "all categories",
'--conjugate' => 1,
'--include_disabled'=> 1,
'--export_notes' => $this->system_message
];
// Run the export
$this->call('products:export', $options);
$last_run_export = ProductExport::where('notes', '=', $this->system_message)
->where('status', '=', 'finished')
->where('format', '=', 'distributor')
->orderBy('id', 'desc')
->firstOrFail();
$this->info('Export created successfully. Export ID is ' . $last_run_export->id);
$env = $this->option('env');
if ($env == 'production'){
$localdomain = '*******';
}else{
$env = 'development';
$localdomain = '*******';
}
$sftp_server = '*******';
$sftp_user_name = '*******';
$sftp_user_pass = '*******';
// Open the SFTP connection
$connection = #ssh2_connect($sftp_server);
if (!$connection)
{
throw new Exception("Could not connect to $sftp_server.");
}
// Login to the SFTP server
if (! #ssh2_auth_password($connection, $sftp_user_name, $sftp_user_pass))
{
throw new Exception("Could not authenticate with username $sftp_user_name " .
"and password $sftp_user_pass.");
}
$sftp = #ssh2_sftp($connection);
if (!$sftp)
{
throw new Exception("Could not initialize SFTP subsystem.");
}
// Prepare the files
$source = '/home/forge/site/files/product-exports/' . $last_run_export->file_name;
/////////////////////////////////////
//The bug is here
// update site to site.com
/////////////////////////////////////
$destination = '/Site/inbound/products/product' . $last_run_export->file_name;
$this->info('Source: ' . $source);
$this->info('Destination: ' . $destination);
if (!file_exists('/Site/inbound/products/')) {
ssh2_sftp_mkdir($sftp, '/Site/inbound/products/', 0775, true);
}
dd(file_exists($source));
if (file_exists($source)) {
chmod($source, 0775);
}else{
$this->info('$source NOT exist !');
}
// Upload the file
$stream = #fopen("ssh2.sftp://$sftp$destination", 'w');
if (!$stream)
{
throw new Exception("Could not open file: $destination");
}
$data_to_send = #file_get_contents($source);
if ($data_to_send === false)
{
throw new Exception("Could not open local file: $source.");
}
if (#fwrite($stream, $data_to_send) === false)
{
throw new Exception("Could not send data from file: $source.");
}
#fclose($stream);
// Delete the export when finished
if (file_exists(base_path() . ProductExport::path . $last_run_export->file_name))
{
unlink(base_path() . ProductExport::path . $last_run_export->file_name);
}
$last_run_export->delete();
}
/**
* Get the console command arguments.
*
* #return array
*/
protected function getArguments()
{
return array();
}
/**
* Get the console command options.
*
* #return array
*/
protected function getOptions()
{
return array();
}
}

What is the different between white and green color code ?
green is for files executable (+x), due to your previous chmod 777
Why does it place under the dot . ?
I assume you did a ls -altr wich sort the entries by modification time in ascending order, each time a file is created, the directory inode is modified, so it's listed just before your file (directory modified at file creation, file modified when all text has been written)
Does it mean anything at all ?
Well, generally speaking yes, for your error in particular, we have no clue from wich directory you're starting from, if it writes relative to where you are, it's normal you don't find the files.
Try ls /home/forge/biossantibodies.com/files/product-exports/and if you get an error, cd /home/forge/biossantibodies.com/ and rerun your php command.

Executable files: Green
Directory: Blue
Image files(jpg, gif, bmp, png, tif): Magenta
Symbolic links: Cyan
Pipe: Yellow
Socket: Magenta
Orphaned symbolic links: Blinking Bold white with red
background
Block device driver: Bold yellow foreground, with black
background
Missing links along with files they point to: Blinking Bold white
with red background
Archives or compressed files(like tar,gz,zip,rpm): Red
The directory has a link to itself in the . entry
Each of its sub-directories has a link back via ..
So it doesn't seem anything special with the file permission please check the way you are accessing the file or share code.

Related

How to use adminer without password basing on login-password-less plugins

I want to use adminer without password.
I uploaded adminer-4.7.7-en.php file and finding login-password-less plugin
I create file plugins/login-password-less.php with content :
<?php
/** Enable login for password-less database
* #link https://www.adminer.org/plugins/#use
* #author Jakub Vrana, https://www.vrana.cz/
* #license https://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* #license https://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2 (one or other)
*/
class AdminerLoginPasswordLess {
/** #access protected */
var $password_hash;
/** Set allowed password
* #param string result of password_hash
*/
function __construct($password_hash) {
$this->password_hash = $password_hash;
}
function credentials() {
$password = get_password();
return array(SERVER, $_GET["username"], (password_verify($password, $this->password_hash) ? "" : $password));
}
function login($login, $password) {
if ($password != "") {
return true;
}
}
}
and reading https://www.adminer.org/plugins/#use I created file adminer.php, which is
located in one dir with adminer-4.7.7-en.php and I created new apache host pointed at this file.
This file has :
<?php
function adminer_object() {
// required to run any plugin
include_once "./plugins/login-password-less.php"; // Plugin I want to use
// autoloader
foreach (glob("plugins/*.php") as $filename) {
include_once "./$filename";
}
$plugins = array(
// specify enabled plugins here
new AdminerLoginPasswordLess, // Plugin I want to use
/* new AdminerTinymce,
new AdminerFileUpload("data/"),
new AdminerSlugify,
new AdminerTranslation,
new AdminerForeignSystem,*/
);
/* It is possible to combine customization and plugins:
class AdminerCustomization extends AdminerPlugin {
}
return new AdminerCustomization($plugins);
*/
return new AdminerPlugin($plugins); // I am not sure which class is it and where it is defined ?
}
// include original Adminer or Adminer Editor
include "./adminer-4.7.7-en.php"; // encoded file I uploaded
?>
and I got error:
Fatal error: Uncaught ArgumentCountError: Too few arguments to function AdminerLoginPasswordLess::__construct(), 0 passed in /mnt/_work_sdb8/wwwroot/lar/local_adminer/adminer.php on line 13 and exactly 1 expected in /mnt/_work_sdb8/wwwroot/lar/local_adminer/plugins/login-password-less.php:16 Stack trace: #0 /mnt/_work_sdb8/wwwroot/lar/local_adminer/adminer.php(13): AdminerLoginPasswordLess->__construct() #1 /mnt/_work_sdb8/wwwroot/lar/local_adminer/adminer-4.7.7-en.php(1654): adminer_object() #2 /mnt/_work_sdb8/wwwroot/lar/local_adminer/adminer.php(31): include('/mnt/_work_sdb8...') #3 {main} thrown in /mnt/_work_sdb8/wwwroot/lar/local_adminer/plugins/login-password-less.php on line 16
Which is the valid way to use adminer without password ?
MODIFIED:
I made :
new AdminerLoginPasswordLess(hash("md5", 'my_sql_user_password')),
Is the selected "md5" method valid ?
But I got error :
Fatal error: Uncaught Error: Class 'AdminerPlugin' not found in /mnt/_work_sdb8/wwwroot/lar/local_adminer/adminer.php:32 Stack trace: #0 /mnt/_work_sdb8/wwwroot/lar/local_adminer/adminer-4.7.7-en.php(1654): adminer_object() #1 /mnt/_work_sdb8/wwwroot/lar/local_adminer/adminer.php(36): include('/mnt/_work_sdb8...') #2 {main} thrown in /mnt/_work_sdb8/wwwroot/lar/local_adminer/adminer.php on line 32
MODIFIED:
In source version of the site I foun file plugin.php with AdminerPlugin class implementation.
I moved this file under plugins directory.
In plugins/login-password-less.php I added reference to plugins/plugin.php file and added debugging info :
<?php
/** Enable login for password-less database
* #link https://www.adminer.org/plugins/#use
* #author Jakub Vrana, https://www.vrana.cz/
* #license https://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
* #license https://www.gnu.org/licenses/gpl-2.0.html GNU General Public License, version 2 (one or other)
*/
include_once "./plugins/plugin.php";
class AdminerLoginPasswordLess {
/** #access protected */
var $password_hash;
/** Set allowed password
* #param string result of password_hash
*/
function __construct($password_hash) {
$this->password_hash = $password_hash;
debToFile('-2 AdminerLoginPasswordLess->__construct:$this->password_hash::'.$this->password_hash);
// That is debugging method appending string into text file
}
function credentials() {
$password = get_password();
debToFile('-3 AdminerLoginPasswordLess->credentials:$password::'.$password);
// That is debugging method appending string into text file
return array(SERVER, $_GET["username"], (password_verify($password, $this->password_hash) ? "" : $password));
}
function login($login, $password) {
debToFile('-4 AdminerLoginPasswordLess->login:$login::'.$login);
if ($password != "") {
debToFile('-5 TRUE AdminerLoginPasswordLess->login:$login::'.$login);
// That is debugging method appending string into text file
return true;
}
debToFile('-5 false AdminerLoginPasswordLess->login:$login::'.$login);
}
}
and in adminer.php I added debugging line:
$plugins = array(
new AdminerLoginPasswordLess(hash("md5", 'm8y2s8q&L')),
);
debToFile('-1After:AdminerLoginPasswordLess');
I loggin file I see:
<pre>::-2 AdminerLoginPasswordLess->__construct:$this->password_hash::c61d49aaab35ca428e60d764ff05159d</pre>
<pre>::-1After:AdminerLoginPasswordLess</pre>
It means that methods credentials and login of AdminerLoginPasswordLess class are not triggered.
I run in browser as :
http://local-adminer.com/?username=mysql_login_user
or
http://local-adminer.com // host in apache config
and I have no errors, but I still have to enter password for mysql_login_user.
Did I miss some options/plugins?
Thanks!
first do
mkdir -p plugins;
wget -O plugins/plugin.php https://raw.githubusercontent.com/vrana/adminer/master/plugins/plugin.php;
nano plugins/passwordless_login.php
then write
<?php
class AdminerLoginPasswordLess {
public function credentials() {
return array("mysql_hostname", "mysql_username", "mysql_password");
}
function login($login, $password) {
return true;
}
}
then save and exit, then run nano adminer_with_plugins.php and write:
<?php
function adminer_object() {
// required to run any plugin
include_once "./plugins/plugin.php";
// "autoloader"
foreach (glob("plugins/*.php") as $filename) {
include_once "./$filename";
}
$plugins = array(
// specify enabled plugins here
new AdminerLoginPasswordLess,
//new AdminerDumpXml,
//new AdminerTinymce,
//new AdminerFileUpload("data/"),
//new AdminerSlugify,
//new AdminerTranslation,
//new AdminerForeignSystem,
);
return new AdminerPlugin($plugins);
}
// include original Adminer or Adminer Editor
include "./adminer.php";
then save & exit;
then point your web-browser to adminer_with_plugins.php instead of adminer.php, now you have effectively disabled adminer's ability to login with different usernames/passwords/hosts, no matter what credentials you try to login with, it will always login with the mysql_hostname/mysql_username/mysql_password written in the source code, ignoring the user input credentials.
needless to say, this is quite a security-sensitive operation.
It often saves time if you can bypass small time consuming tasks. I tried above methods but did not work for me so I did the following which works in 2021 for Adminer 4.7.9.
WARNING: Please note that its only for your local machine & not advised for online databases.:
Step-1: Download Adminer source from Github, this link.
Step-2: Open adminer-master\adminer\include\auth.inc.php
Step-3: Edit the following at lines 55 to 57 & replace my_username & my_password with your MySQL credentials:
$server = "localhost"; //$auth["server"];
$username = "my_username"; //$auth["username"];
$password = "my_password"; //(string) $auth["password"];
Step-4: Save & now open Adminer by pointing your browser to "adminer-master\adminer"
Step-5: Just click Login button & you will login without entering anything.
Hope it will work for you.

PHP Warning: ftp_get(): Could not open data connection to port 39997: Connection timed out

I hope i will explain my problem clearly because i feel lost and don't know what is real problem.
Using Symfony 2.8 and https://github.com/iJanki/FtpBundle i'm trying to connect to ftp server and download files. Whole proccess will be launched only through symfony's app/console.
Here's my service which contain whole logic:
<?php
namespace xxx\Services\Import;
use Doctrine\ORM\EntityManager;
use Ijanki\Bundle\FtpBundle\Ftp;
use Ijanki\Bundle\FtpBundle\Exception\FtpException;
use xxx\Entity\Product;
use xxx\Entity\ProductImage;
class ImageImport
{
const FTP_HOST = 'xxx';
const FTP_USER = 'xxx';
const FTP_PASSWORD = 'xxx';
const FTP_PNG_DIR = 'xxx';
const FTP_FILES_EXT = 'png';
/**
*
* #var EntityManager
*/
private $em;
/**
*
* #var string
*/
private $rootDir;
/**
*
* #var Ftp
*/
private $ftp;
/**
*
* #param EntityManager $em
* #param string $rootDir
* #param Ftp $ftp
*/
public function __construct(EntityManager $em, $rootDir, Ftp $ftp)
{
$this->em = $em;
$this->rootDir = $rootDir;
$this->ftp = $ftp;
}
public function import()
{
set_time_limit(10000);
ini_set('max_input_time', 10000);
$this->connectToFtp();
$this->copyAndMatch();
$this->disconnectFtp();
}
/**
*
* #return boolean
*/
public function connectToFtp()
{
try {
$this->ftp->connect(self::FTP_HOST, 21, 10000);
$this->ftp->login(self::FTP_USER, self::FTP_PASSWORD);
$this->ftp->chdir(self::FTP_PNG_DIR);
$this->ftp->pasv(false);
return true;
} catch (FtpException $e) {
echo 'Error: ', $e->getMessage();
return false;
}
}
public function copyAndMatch()
{
$matches = $this->getCsvMatches();
$this->matchWithProducts($matches);
}
public function disconnectFtp()
{
$this->ftp->close();
}
public function __destruct()
{
try {
if (false !== $this->ftp->pwd()) {
$this->ftp->close();
}
} catch (FtpException $ex) {
}
}
/**
*
* #return array|null
*/
private function getCsvMatches()
{
//...
}
/**
*
* #param array $matches
* #return true|null
*/
private function matchWithProducts(array $matches)
{
if (empty($matches) || !is_array($matches)) {
return;
}
foreach ($matches as $pair) {
//...
$filename = $pair['image'] . '.' . self::FTP_FILES_EXT;
if (false === $this->fileAlreadyAdded($product, $filename) and null !== $this->downloadFile($filename)) {
//...
}
}
}
$this->em->flush();
return true;
}
/**
*
* #param Product $product
* #param string $filename
* #return boolean
*/
private function fileAlreadyAdded(Product $product, $filename)
{
//...
}
/**
*
* #param string $filename
* #return string|null
*/
private function downloadFile($filename)
{
try {
$localFile = $this->rootDir . '/../' . ImportHelper::UPLOAD_DIR . '/' . $filename;
if ($this->remoteFileExists($filename)) {
if (false === $this->ftp->pwd()) {
$this->connectToFtp();
}
$this->ftp->get($localFile, $filename, FTP_BINARY);
}
return file_exists($localFile) ? $filename : null;
} catch (FtpException $ex) {
echo $ex->getMessage();
return null;
}
}
/**
*
* #param string $filename
* #return boolean
*/
private function remoteFileExists($filename)
{
return $this->ftp->size($filename) !== -1;
}
}
Commented out or removed code includes Doctrine operations and are not relevant as they don't cause any problems.
As local enviroment I use Xampp with Apache2 server on Windows 7. Also i test FTP connection with Filezilla and i discovered that it works only when using ftp active mode.
Also I discovered that my Windows firewall was reason for warnings and I could connect but do nothing more when it was enabled. So I added exceptions for php.exe and apache httpd.exe so everything works perfectly when php script is launched on my local server.
With Windows firewall enabled, ftp_nlist returned false when using passive mode, and returned warnings when using active mode.
But my goal is to launch that script on production web server which is on VPS which has Ubuntu 14.04.3 LTS installed. My knowledge about Unix is very poor but I was assured by VPS provider that there's no firewall enabled on this server but i get all the time warnings:
PHP Warning: ftp_get(): Could not open data connection to port 39997: Connection timed out
Same warnings that i got when my windows firewall was enabled.
I also called person who's administrating server with FTP (with files i want to dl) and asked him to add exceptions in firewall for ftp connection on port 21 but it didn't help at all.
I'm sure i don't get dicsonnected from ftp server, i never get FtpException. As I can see, download proccess starts because file appears in destination folder but it's empty.
And my problem is that i don't know which side of connection is causing this issues. And what can i do to fix my code to work properly.
Chain INPUT (policy DROP)
target prot opt source destination
ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED
ACCEPT tcp -- anywhere anywhere multiport dports 7727,http
ACCEPT icmp -- anywhere anywhere icmp echo-request
ACCEPT all -- anywhere anywhere
that is output from sudo iptables -L
output from sudo ufw status was Status: inactive
You know what fixed my problem? sudo ufw enable
I still dont know why it's a fix and what was the problem. But it works now.
"In active mode FTP the client connects from a random unprivileged port (N > 1023) to the FTP server's command port, port 21. Then, the client starts listening to port N+1 and sends the FTP command PORT N+1 to the FTP server. The server will then connect back to the client's specified data port from its local data port, which is port 20."
Looks like you have to add this 39997 port to firewall exceptions.
sudo ufw allow out 39997/tcp
sudo ufw allow in 39997/tcp
sudo ufw reload
I'm not sure if this bundle could start to use some other than "39997" port. But looks like it is constant in this case.

Owncloud 8.1 "myapp" sample, add a function to write to a file

On Owncloud 8.1 using the owncloud command line, I create a new test app:
ocdev startapp MyApp --email mail#example.com --author "Your Name" --description "My first app" --owncloud 8
The app is working, I can add it in the owncloud control panel.
Now I'd like to write to a file, so I use one example from the owncloud documentation:
https://doc.owncloud.org/server/8.1/developer_manual/app/filesystem.html
[Edit] I started over and now, I don't know if I omitted something, but "myapp" comes with no "application.php" file.
So I create it at /var/www/core/apps/myapp/appinfo/application.php :
<?php
namespace OCA\MyApp\AppInfo;
use \OCP\AppFramework\App;
use \OCA\MyApp\Storage\AuthorStorage;
class Application extends App {
public function __construct(array $urlParams=array()){
parent::__construct('myapp', $urlParams);
$container = $this->getContainer();
/**
* Storage Layer
*/
$container->registerService('AuthorStorage', function($c) {
return new AuthorStorage($c->query('RootStorage'));
});
$container->registerService('RootStorage', function($c) {
return $c->query('ServerContainer')->getRootFolder();
});
}
}
Then I create a file called /var/www/core/apps/myapp/storage/AuthorStorage.php with:
<?php
namespace OCA\MyApp\Storage;
class AuthorStorage {
private $storage;
public function __construct($storage){
$this->storage = $storage;
}
public function writeTxt($content) {
// check if file exists and write to it if possible
try {
try {
$file = $this->storage->get('/myfile.txt');
} catch(\OCP\Files\NotFoundException $e) {
$this->storage->touch('/myfile.txt');
$file = $this->storage->get('/myfile.txt');
}
// the id can be accessed by $file->getId();
$file->putContent($content);
} catch(\OCP\Files\NotPermittedException $e) {
// you have to create this exception by yourself ;)
throw new StorageException('Cant write to file');
}
}
}
The sample app already gives me a route to the index function in the pagecontroller.php
['name' => 'page#index', 'url' => '/', 'verb' => 'GET']
How do I call the function "writeTxt" from there?
Based on http://php.net/manual/en/language.oop5.basic.php
I tried:
use \OCA\MyApp\Storage\AuthorStorage;
and
public function index() {
//added part
$a = new AuthorStorage();
$a->writeTxt('test');
//original part
$params = ['user' => $this->userId];
return new TemplateResponse('myapp', 'main', $params); //templates/main.php
}
After running I get a "Class 'OCA\MyApp\Storage\AuthorStorage' not found at /var/www/core/apps/myapp/controller/pagecontroller.php#44"
Even with the help of use \OCA\MyApp\Storage\AuthorStorage; ( ClassNotFoundException: Attempted to load class... Symfony ) it doesn't seem to help.
Thanks
Time has gone by, so I'm posting an answer to my question for owncloud 9.
Here are the steps to a basic script with read, write, copy file ability.
"application.php" has definitively been removed from the example. It was not a bug.
Following:
https://doc.owncloud.org/server/9.0/developer_manual/app/startapp.html
Generate the demo "MyApp" app:
ocdev startapp MyApp --email mail#example.com --author "Your Name" --description "My first app" --owncloud 9
Edit the file myapp/controller/pagecontroller.php
<?php
/**
* ownCloud - myapp
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* #author Your Name <mail#example.com>
* #copyright Your Name 2016
*/
namespace OCA\MyApp\Controller;
use OCP\IRequest;
use OCP\AppFramework\Http\TemplateResponse;
use OCP\AppFramework\Http\DataResponse;
use OCP\AppFramework\Controller;
use OCP\Files\IRootFolder;
use OC\Files\Storage\Temporary;
class PageController extends Controller {
private $userId;
private $storage;
private $userstorage;
public function __construct($AppName, IRequest $request, IRootFolder $storage, $UserId){
parent::__construct($AppName, $request);
$this->storage = $storage;
$this->userId = $UserId;
$this->userstorage = $this->storage->get($this->userId.'/files/');
}
/**
* CAUTION: the #Stuff turns off security checks; for this page no admin is
* required and no CSRF check. If you don't know what CSRF is, read
* it up in the docs or you might create a security hole. This is
* basically the only required method to add this exemption, don't
* add it to any other method if you don't exactly know what it does
*
* #NoAdminRequired
* #NoCSRFRequired
*/
public function index() {
$listedudossier = $this->userstorage->getDirectoryListing();
//list all items in the root directory
//and copies the files in an directory called old
//the directory "old" is not script created
foreach ($listedudossier as $value) {
if ( $value->getType() == 'file' ){
$value->copy($this->userId.'/files/old/'.$value->getName());
//also works
//$value->copy($this->userstorage->getPath().'/old/'.$value->getName());
}
}
$params = ['listedudossier' => $listedudossier ];
return new TemplateResponse('myapp', 'main', $params); // templates/main.php
}
/**
* Simply method that posts back the payload of the request
* #NoAdminRequired
*/
public function doEcho($echo) {
//creates a file
$this->userstorage->newFile('myfile2.txt');
//opens a file, adds inputbox content and saves the file
$file = $this->userstorage->get('myfile.txt');
$contenu = $file->getContent();
$file->putContent($contenu.$echo);
return new DataResponse(['echo' => $echo]);
}
}
You also need to edit the myapp/templates/part.content.php
<p>Hello World <?php p($_['user']) ?></p>
<p><button id="hello">click me</button></p>
<p><textarea id="echo-content">
Send this as ajax
</textarea></p>
<p><button id="echo">Send ajax request</button></p>
Ajax response: <div id="echo-result"></div>
<p>listedudossier:<p> <?php
foreach ($_['listedudossier'] as $file) {
echo "type:".$file->getType();
echo "<p>";
echo "nom:".$file->getName();
echo "<p>";
echo "modif:".$file->getMTime();
echo "<p>";
}
From here you can test the code in a development environment:
https://github.com/owncloud/ocdev/blob/master/README.rst#installation

php zip include only new files

I've run into an issue with the php zip library causing an error 500 if the file is growing to larger than 500MB, probably memory related...
But I tried to cmd line the zip creation, which works well on my server.
<?php
set_time_limit(10000);
// Make Zip name
$zipname = "main_backup.zip";
// Make a zip file
$cmd = `zip -r $zipname * -x filelist.php -x $zipname`;
if($cmd){
echo 'zip created';
}
else{
echo 'failed';
}
unlink(__FILE__);
?>
I know how to exclude files and folders, but is there a way to zip only files based on the modified time using this approach?
I've googled for hours and came up empty.
for the sake of it, here's the code that was creating the error 500. My site is about 1.8GB, it always errors at 500MB~. I should note the error log is blank, so the cause of the error I'm just assuming to be RAM limit problems.
<?php
$zip = new ZipArchive;
$zip_name = "test.zip";
$res = $zip->open($zip_name, ZipArchive::CREATE);
/**
* Real Recursive Directory Iterator
*/
class RRDI extends RecursiveIteratorIterator {
/**
* Creates Real Recursive Directory Iterator
* #param string $path
* #param int $flags
* #return DirectoryIterator
*/
public function __construct($path, $flags = 0) {
parent::__construct(new RecursiveDirectoryIterator($path, $flags));
}
}
/**
* Real RecursiveDirectoryIterator Filtered Class
* Returns only those items which filenames match given regex
*/
class AdvancedDirectoryIterator extends FilterIterator {
/**
* Regex storage
* #var string
*/
private $regex;
/**
* Creates new AdvancedDirectoryIterator
* #param string $path, prefix with '-R ' for recursive, postfix with /[wildcards] for matching
* #param int $flags
* #return DirectoryIterator
*/
public function __construct($path, $flags = 0) {
if (strpos($path, '-R ') === 0) { $recursive = true; $path = substr($path, 3); }
if (preg_match('~/?([^/]*\*[^/]*)$~', $path, $matches)) { // matched wildcards in filename
$path = substr($path, 0, -strlen($matches[1]) - 1); // strip wildcards part from path
$this->regex = '~^' . str_replace('*', '.*', str_replace('.', '\.', $matches[1])) . '$~'; // convert wildcards to regex
if (!$path) $path = '.'; // if no path given, we assume CWD
}
parent::__construct($recursive ? new RRDI($path, $flags) : new DirectoryIterator($path));
}
/**
* Checks for regex in current filename, or matches all if no regex specified
* #return bool
*/
public function accept() { // FilterIterator method
return $this->regex === null ? true : preg_match($this->regex, $this->getInnerIterator()->getFilename());
}
}
foreach (new AdvancedDirectoryIterator('-R *') as $i){
//$fullpath = str_replace(',','',$i->getPath()).'/'.$i->getFilename();
//echo $fullpath.'<br />';
if ($i->isFile() && $i->getFilename()!='filelist.php') {
//echo $i->getFilename() . " " . $i->getMTime() . "<br />";
if($i->getMTime()>='0'){
$array[] = substr($i->getPathname(), 2);
}
}
};
// will output all php files in CWD and all subdirectories
foreach($array as $files) {
$zip_array[] = files;
$zip->addFile($files);
}
$zip->close();
echo 'done';
?>
You can use the -t or -tt option for the zip command and have your modifed date stored as a variable or just pass one in.
-t with the format mmddyyyy for from-date
-tt with the format mmddyyyy for before-date
//Zips up all files in current directory that were dated 08152013 or later
zip -r -t 08152013 $zipname * -x filelist.php -x $zipname

php shell_exec: how to copy a directory from one user to another (VPS on CentOs5)

In Running on CentOS5 + DirectAdmin.
I own a VPS, but for security reasons I just want to give all managenent only to 'reseller' user.
With a resseler user I have script, which connects to ressellers DA and creates an user.
My problem is - how to copy a directory tree with ~10000 of files, which is located in 'resellers user' ftp, ex. /domains/hoster.dom.com/public_html/dir_to_be_copied
to a new created user, which password and user name I know.
As i understand, it should be possible to do this as internal server action via 'shell_exec()' command.
Also, what is the command to login another user FTP and work with his files. And is it possible to be connected at the same time to the two FTP users, and make copies from one to another.
I know that it may be suggested to do this logging as 'root' user, but maybe it is possible without accessing a 'root' user.
Thanks.
<?php
/**
* Copy file or folder from source to destination, it can do
* recursive copy as well and is very smart
* It recursively creates the dest file or directory path if there weren't exists
* Situtaions :
* - Src:/home/test/file.txt ,Dst:/home/test/b ,Result:/home/test/b -> If source was file copy file.txt name with b as name to destination
* - Src:/home/test/file.txt ,Dst:/home/test/b/ ,Result:/home/test/b/file.txt -> If source was file Creates b directory if does not exsits and copy file.txt into it
* - Src:/home/test ,Dst:/home/ ,Result:/home/test/** -> If source was directory copy test directory and all of its content into dest
* - Src:/home/test/ ,Dst:/home/ ,Result:/home/**-> if source was direcotry copy its content to dest
* - Src:/home/test ,Dst:/home/test2 ,Result:/home/test2/** -> if source was directoy copy it and its content to dest with test2 as name
* - Src:/home/test/ ,Dst:/home/test2 ,Result:->/home/test2/** if source was directoy copy it and its content to dest with test2 as name
* #todo
* - Should have rollback technique so it can undo the copy when it wasn't successful
* - Auto destination technique should be possible to turn off
* - Supporting callback function
* - May prevent some issues on shared enviroments : http://us3.php.net/umask
* #param $source //file or folder
* #param $dest ///file or folder
* #param $options //folderPermission,filePermission
* #return boolean
*/
function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
{
$result=false;
if (is_file($source)) {
if ($dest[strlen($dest)-1]=='/') {
if (!file_exists($dest)) {
cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
}
$__dest=$dest."/".basename($source);
} else {
$__dest=$dest;
}
$result=copy($source, $__dest);
chmod($__dest,$options['filePermission']);
} elseif(is_dir($source)) {
if ($dest[strlen($dest)-1]=='/') {
if ($source[strlen($source)-1]=='/') {
//Copy only contents
} else {
//Change parent itself and its contents
$dest=$dest.basename($source);
#mkdir($dest);
chmod($dest,$options['filePermission']);
}
} else {
if ($source[strlen($source)-1]=='/') {
//Copy parent directory with new name and all its content
#mkdir($dest,$options['folderPermission']);
chmod($dest,$options['filePermission']);
} else {
//Copy parent directory with new name and all its content
#mkdir($dest,$options['folderPermission']);
chmod($dest,$options['filePermission']);
}
}
$dirHandle=opendir($source);
while($file=readdir($dirHandle))
{
if($file!="." && $file!="..")
{
if(!is_dir($source."/".$file)) {
$__dest=$dest."/".$file;
} else {
$__dest=$dest."/".$file;
}
//echo "$source/$file ||| $__dest<br />";
$result=smartCopy($source."/".$file, $__dest, $options);
}
}
closedir($dirHandle);
} else {
$result=false;
}
return $result;
}
?>
http://www.php.net/manual/en/function.copy.php#91256

Categories