📜 ⬆️ ⬇️

System scripts in php for linux, we write a screenshot

Many people believe that php is only suitable for developing websites, and can not be used in any other areas of programming languages, for creating programs ... In this article I would like to highlight the use of php scripts in a “non-targeted” way, namely, we will write the script that will make the screen, upload it to the yandex disk and output the screenshot address to the console ...

Consider the structure of the project, it is very simple and consists of 3 files:

1. screen.php - entry point to the application.
2. classes / autoload.php - project autoloader.
3. classes / Request.php - a class that implements requests to Yandex api.

Next, consider the screen.php code:
')
Code screen.php
#!/usr/bin/php <?php require_once('classis/autoload.php'); $request = new Request(); if(isset($argv[1]) && $argv[1] == '--getToken') { echo $request->getOauthLink();die; } $home = $_SERVER['HOME']; $config = include($home . '/.config/scrphp/config.php'); $nameScreenshot = date('Y_m_d_G_i_s_') . 'screen.png'; system('scrot -s /tmp/'.$nameScreenshot); $result = $request ->setToken($config['token']) ->setFileNameOnDisk($nameScreenshot) ->setPathToFile('/tmp/'.$nameScreenshot) ->upload() ->publicateFile(); $url = $result['public_url']; echo $url.PHP_EOL; 


As you can see this is the entry point into the application, the logic is simple:
1. Formation of the screenshot name
2. Calling the scrot system program
3. Request api yandex.disk and upload a screenshot

The autoload.php file is also very simple and consists of only three lines of code, I will give it only for your reference, and we will not consider it in detail.

 spl_autoload_register(function($name){ require_once __DIR__.'/'.$name.'.php'; }); 

Working with yandex api is quite simple. I wrote a small class Request.php, with a set of some methods that help me in working with it ...

Listing Request.php
 <?php class Request { private $_token = null; private $_href = null; private $_method = null; private $_filePath = null; private $_fileName = null; /** * get oauth link */ public function getOauthLink() { /** * https://oauth.yandex.ru/authorize? * response_type=token * & client_id=< > * [& device_id=< >] * [& device_name=< >] * [& display=popup] * [& login_hint=<    >] * [& force_confirm=yes] * [& state=< >] */ $link = 'https://oauth.yandex.ru/authorize' .'?response_type=token' . '&client_id=8fc231e60575439fafcdb3b9281778a3'; echo $link; } /** * set file path on disk * @param $filePath * @return $this */ public function setFileNameOnDisk($name) { /** * https://cloud-api.yandex.net/v1/disk/resources/upload ? * path=<,     > */ $link = 'https://cloud-api.yandex.net/v1/disk/resources/upload?path='.urlencode('/'.trim($name,'/')); $response = file_get_contents($link,false,$this->_context('GET')); $responseAsArray = json_decode($response,true); $this->_href = $responseAsArray['href']; $this->_method = $responseAsArray['method']; $this->_fileName = $name; return $this; } /** * get path to file on local disk * @param $path * @return $this */ public function setPathToFile($path) { $this->_filePath = $path; return $this; } /** * upload file to disk */ public function upload() { $ch = curl_init($this->_href); curl_setopt($ch,CURLOPT_HTTPHEADER, array( 'Authorization', 'OAuth '.$this->_token ) ); curl_setopt($ch,CURLOPT_INFILE,fopen($this->_filePath,"r")); curl_setopt($ch,CURLOPT_INFILESIZE,filesize($this->_filePath)); curl_setopt($ch,CURLOPT_PUT,true); curl_exec($ch); curl_close($ch); return $this; } /** * public file and get public url for screenshot * @return mixed */ public function publicateFile() { /** * https://cloud-api.yandex.net/v1/disk/resources/publish ? * path=<   > */ $link = 'https://cloud-api.yandex.net/v1/disk/resources/publish?path='.urlencode('/'.trim($this->_fileName,'/')); $response = file_get_contents($link,false,$this->_context('PUT')); $responseAsArray = json_decode($response,true); $publicateFile = file_get_contents($responseAsArray['href'],false,$this->_context($responseAsArray['method'])); $publicateFileAsArray = json_decode($publicateFile,true); return $publicateFileAsArray; } /** * set oauth token * @param $key * @return $this */ public function setToken($token) { $this->_token = $token; return $this; } /** * get context for request by file_get_contents * @param $method * @return resource */ private function _context($method) { /** * Authorization: OAuth <key> */ $opts = array( 'http'=>array( 'method'=>$method, 'header'=>"Authorization: OAuth ".$this->_token."\r\n" ) ); $context = stream_context_create($opts); return $context; } } 


Consider the key methods of this class for requesting api methods, I mainly used file_get_contents, and since I had to use it, I used a method for generating context when requesting many methods:

  /** * get context for request by file_get_contents * @param $method * @return resource */ private function _context($method) { /** * Authorization: OAuth <key> */ $opts = array( 'http'=>array( 'method'=>$method, 'header'=>"Authorization: OAuth ".$this->_token."\r\n" ) ); $context = stream_context_create($opts); return $context; } 

It is also quite simple. We create a context with a specific request method and authentication information ...

Next, we need to “create a file on yandex.disk” we perform this action using the following method:

  /** * set file path on disk * @param $filePath * @return $this */ public function setFileNameOnDisk($name) { /** * https://cloud-api.yandex.net/v1/disk/resources/upload ? * path=<,     > */ $link = 'https://cloud-api.yandex.net/v1/disk/resources/upload?path='.urlencode('/'.trim($name,'/')); $response = file_get_contents($link,false,$this->_context('GET')); $responseAsArray = json_decode($response,true); $this->_href = $responseAsArray['href']; $this->_method = $responseAsArray['method']; $this->_fileName = $name; return $this; } 

As I said earlier, we request api using the file_get_contents function. After this method completes and all information is requested, the upload method starts:

  /** * upload file to disk */ public function upload() { $ch = curl_init($this->_href); curl_setopt($ch,CURLOPT_HTTPHEADER, array( 'Authorization', 'OAuth '.$this->_token ) ); curl_setopt($ch,CURLOPT_INFILE,fopen($this->_filePath,"r")); curl_setopt($ch,CURLOPT_INFILESIZE,filesize($this->_filePath)); curl_setopt($ch,CURLOPT_PUT,true); curl_exec($ch); curl_close($ch); return $this; } 

In this case, it would be possible to use one of the functions `file_get_contents` or` file_put_contents` to send the file, but this is not advisable, because it would have to, in the context of these functions, manually imitate the headers and other problems resulting from this, so it's easier to just use curl for this purpose.

And so the file is loaded, it remains only to publish it and get a direct link to view, this is performed by the function publicateFile ():

  /** * public file and get public url for screenshot * @return mixed */ public function publicateFile() { /** * https://cloud-api.yandex.net/v1/disk/resources/publish ? * path=<   > */ $link = 'https://cloud-api.yandex.net/v1/disk/resources/publish?path='.urlencode('/'.trim($this->_fileName,'/')); $response = file_get_contents($link,false,$this->_context('PUT')); $responseAsArray = json_decode($response,true); $publicateFile = file_get_contents($responseAsArray['href'],false,$this->_context($responseAsArray['method'])); $publicateFileAsArray = json_decode($publicateFile,true); return $publicateFileAsArray; } 

In this method, too, everything is quite simple, we request the publication of the file by the PUT method from the api, Yandex returns a link to which we must execute the request to confirm the publication, and the method of the request in the disk. And in the end, after the second request, we get an array that maintains a link to the public file.

Install script


Well, we’ve finished, now we’ll have to figure out, but how will this script work from the console? How to run it in the "global area"? The answer to these questions will be a phar archive containing php files and able to run as a separate application, similar to the same jar.

we will build phar using the box.phar utility for this we write a simple configuration file box.json:

 { "files": [ "classis/autoload.php", "classis/Request.php", "screen.php" ], "main": "screen.php", "output": "srcphp.phar", "stub": true } 

To build run:

 $ php box.phar build 

And our project is now ready to install the rights to execute the file, and copy it to the / usr / bin / srcphp directory:

 $ chmod +x srcphp.phar $ cp srcphp.phar /usr/bin/srcphp 

Do not forget about the configuration of the file /home/myname/.config/srcphp/config.php:

 <?php // copy this file to /home/user/.config/srcphp/config.php return array( 'token' => 'your token' ); 

in the token, you need to enter the token received from oAuth from Yandex, when going through the script generated by launching the script with the --getToken key:

 $ srcphp --getToken 

findings


The main idea of ​​the article is to consider how to create a console application using php, using the screenshots program as an example. In the following I will raise the topic of using php in various fields of application, and the next article will be devoted to developing a simple usb device driver for linux. Thank you for your attention and have a nice day.

ps application source code

Source: https://habr.com/ru/post/310694/


All Articles