📜 ⬆️ ⬇️

Comments on the problem in Bitrix24 with commit for Mercurial

image With each semester, the 1C-Bitrix team presents a new functionality of the cloud corporate portals Bitrix24. One of the popular functions of the portal can be called “Tasks”, allowing Bitrix24 to occupy places in the rating of task trackers (for example, Quantity and quality: how do task trackers develop in a competitive environment ). Therefore, many web studios, especially those associated with the development on 1C-Bitrix and Bitrix24, use the functionality of tasks in development.

In each task can be director, and co-performers, and observers, including customers. In most cases, working with a task lasts more than one day and it may turn out that the task (in the comments to it) does not observe the activity of the developer (developers), and it seems to observers that their task is not taken to work and is simply “dynamized.” In addition to the above problem, I want to have complete information about what happened to the task from its inception to its completion.

In this connection, it became necessary to send information about the development process during commits, in order to capture all changes in task comments without being distracted by writing comments to it — just add an informative comment when committing.
')
The paper uses VCS Mercurial, for which the setting of sending information about the commit in the comments of the portal task is described.

To send comments when you commit Mercurial to the Bitrix24 portal, you need to do the following steps:

  1. The site where the application will be located requires an SSL certificate.

  2. Install the following packages using composer:
    • mesilov / bitrix24-php-sdk - php wrapper for working with BX24 REST API
    • defuse / php-encryption - required for generating an access key

    Installation is carried out by the command
    $ composer require "mesilov/bitrix24-php-sdk: ^0.2.0" "defuse/php-encryption: ^2.0" 

  3. Upload application files to site:
    • install.php - application installation file for Bitrix24. Required for an application to get access tokens when installing an application.
      install.php
       <?php /** *  . * *     24     */ error_reporting(E_ALL & ~E_NOTICE); require __DIR__ . '/vendor/autoload.php'; require __DIR__ . '/lib.php'; if (null === $_REQUEST['DOMAIN'] || null === $_REQUEST['member_id'] || null === $_REQUEST['AUTH_ID'] || null === $_REQUEST['REFRESH_ID']) { die('     24'); } $params = AddMessageToBitrix24Task::load(); if (0 === count($params)) { $params = [ //    (    ) 'B24_APPLICATION_ID' => '<CLIENT_ID>', //     (    ) 'B24_APPLICATION_SECRET' => '<CLIENT_SECRET>', //     (    ) 'B24_APPLICATION_SCOPE' => ['task'], //URL    (    ) 'B24_REDIRECT_URI' => 'https://<APP_DOMAIN>/app.php', //  'DOMAIN' => $_REQUEST['DOMAIN'], //   'MEMBER_ID' => $_REQUEST['member_id'], //  'AUTH_ID' => $_REQUEST['AUTH_ID'], //  'REFRESH_ID' => $_REQUEST['REFRESH_ID'], ]; //     AddMessageToBitrix24Task::save($params); } //,     if (AddMessageToBitrix24Task::check()) { //      24   $params = AddMessageToBitrix24Task::load(); $result = ' .<br>'; $result .= '   hook.php  :<br>'; $result .= $params['KEY']; } else { $result = '  c .<br>'; } die($result); 

    • app.php is the main application file, adding comments to the tasks when Mercurial hook is triggered ...
      app.php
       <?php /** *       */ error_reporting(E_ALL & ~E_NOTICE); require __DIR__ . '/vendor/autoload.php'; require __DIR__ . '/lib.php'; //  $params = AddMessageToBitrix24Task::load(); try { //    $key = $params['B24_APPLICATION_ID'] . $params['MEMBER_ID'] . $params['B24_APPLICATION_SECRET']; //       if (AddMessageToBitrix24Task::decrypt($_REQUEST['key']) !== $key) { die('  '); } } catch (Exception $e) { die('   '); } if (!is_numeric($_REQUEST['task'])) { die('   '); } if (null === $_REQUEST['message'] || '' === trim($_REQUEST['message'])) { die('  '); } try { //     Bitrix24 $bx24 = AddMessageToBitrix24Task::getBX24Instance($params); //    $result = AddMessageToBitrix24Task::add($bx24, $_REQUEST['task'], $_REQUEST['message']); die($result); } catch (Exception $e) { die('     '); } 

    • lib.php - a set of functions required for the application
      lib.php
       <?php /** *    */ use Defuse\Crypto\Crypto; use Defuse\Crypto\Key; /** *       24 * * Class AddMessageToBitrix24Task */ class AddMessageToBitrix24Task { /** * @var string    .       . */ private static $config = __DIR__ . '/../bx24.auth'; /** * @var string   */ private static $safeKey; /** *   * * @param string $var    * * @return string   * * @throws \Defuse\Crypto\Exception\BadFormatException * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException */ public static function encrypt($var) { return Crypto::encrypt($var, self::getKey()); } /** *   * * @param string $var    * * @return string   * * @throws \Defuse\Crypto\Exception\BadFormatException * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException */ public static function decrypt($var) { return Crypto::decrypt($var, self::getKey()); } /** *    * * @return Key   * * @throws \Defuse\Crypto\Exception\BadFormatException * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException */ public static function getKey() { if (null === self::$safeKey) { $params = self::load(); //    -  if (null === $params || null === $params['PRIVATE_KEY']) { self::$safeKey = Key::createNewRandomKey()->saveToAsciiSafeString(); } else { self::$safeKey = $params['PRIVATE_KEY']; } } return Key::loadFromAsciiSafeString(self::$safeKey); } /** *      Bitrix24 * * @param array $params     24 * * @return \Bitrix24\Bitrix24     24 * * @throws \Bitrix24\Bitrix24Exception * @throws \Defuse\Crypto\Exception\BadFormatException * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException */ public static function getBX24Instance(array $params) { $bx24 = new \Bitrix24\Bitrix24(false); $bx24->setApplicationScope($params['B24_APPLICATION_SCOPE']); $bx24->setApplicationId($params['B24_APPLICATION_ID']); $bx24->setApplicationSecret($params['B24_APPLICATION_SECRET']); $bx24->setRedirectUri($params['B24_REDIRECT_URI']); $bx24->setDomain($params['DOMAIN']); $bx24->setMemberId($params['MEMBER_ID']); $bx24->setAccessToken($params['AUTH_ID']); $bx24->setRefreshToken($params['REFRESH_ID']); //     if ($bx24->isAccessTokenExpire()) { //    $temp = $bx24->getNewAccessToken(); //    $params['AUTH_ID'] = $temp['access_token']; $params['REFRESH_ID'] = $temp['refresh_token']; $bx24->setAccessToken($params['AUTH_ID']); $bx24->setRefreshToken($params['REFRESH_ID']); //   self::save($params); } return $bx24; } /** *     * * @param \Bitrix24\Bitrix24 $bx24     24 * @param int $task   * @param string $message  * * @return string */ public static function add(\Bitrix24\Bitrix24 $bx24, $task, $message) { $str = ''; try { //       $bx24->call( 'task.item.getdata', [ 'TASKID' => $task ] ); $str .= ' #' . $task . '   ' . $bx24->getDomain() . ' ' . PHP_EOL; //    $bx24->call( 'task.commentitem.add', [ 'TASKID' => $task, 'FIELDS' => [ 'POST_MESSAGE' => $message ] ] ); $str .= '    '; } catch (Exception $e) { $str .= '     '; } return $str; } /** *      * * @param array $params  * * @return bool * * @throws \Defuse\Crypto\Exception\BadFormatException * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException */ public static function save(array $params) { //        $params['KEY'] = AddMessageToBitrix24Task::encrypt($params['B24_APPLICATION_ID'] . $params['MEMBER_ID'] . $params['B24_APPLICATION_SECRET']); //  $params['PRIVATE_KEY'] = self::$safeKey; //     $result = json_encode($params, JSON_UNESCAPED_UNICODE); return file_put_contents(self::$config, $result) > 0; } /** *      * * @return array  */ public static function load() { if (!file_exists(self::$config)) { return []; } //   $params = file_get_contents(self::$config); return json_decode($params, true); } /** * ,       24. * * @return bool */ public static function check() { try { $params = AddMessageToBitrix24Task::load(); $bx24 = self::getBX24Instance($params); $result = $bx24->call('app.info'); return $result['result']['CODE'] === $params['B24_APPLICATION_ID']; } catch (\Exception $e) { return false; } } } 

  4. Upload the hghook-commit-to-bx24.php file to the web server where the VCS Mercurial is used to access the application at commit. File must be placed outside the site root. The script requires the following functions:
    • shell_exec - execute console commands to generate information about the commit
    • curl_exec - to send data to the application
    hghook-commit-to-bx24.php
     <?php /** *      hg commit */ //  24 define('BX24_APP_URL', 'https://<APP_DOMAIN>/app.php'); //    .        define('KEY', '<ACCESS_KEY>'); echo '  Mercurial,        ' . PHP_EOL; if(!function_exists('shell_exec')){ echo ':  «shell_exec» ' . PHP_EOL; echo ' ' . PHP_EOL; exit(0); } if(!function_exists('curl_exec')){ echo ':  «curl_exec» ' . PHP_EOL; echo ' ' . PHP_EOL; exit(0); } //    Mercurial $hg = $_SERVER['HG']; if (!is_file($hg) || !is_executable($hg)) { echo ':     Mercurial' . PHP_EOL; echo ' ' . PHP_EOL; exit(0); } echo '   ' . PHP_EOL; //   ,    Mercurial $hostname = trim(shell_exec('hostname -f')); //     $pwd = $_SERVER['PWD']; //   Mercurial $branch = shell_exec("$hg branch"); //     $log = trim(shell_exec("$hg log -l 1")); //  $matches = null; $user = preg_match('/user:\s+(?<user>\S.*)/ium', $log, $matches) ? $matches['user'] : 'unknown'; //  $summary = preg_match('/summary:\s+(?<summary>\S.*)/ium', $log, $matches) ? $matches['summary'] : ''; //        $files = trim(shell_exec("$hg st -amr")); //    $filesCount = substr_count($files, PHP_EOL); //       Mercurial      echo '       ' . PHP_EOL; $task = 0; if (preg_match('/^task[#\@\$](?<id>\d+)/iu', $branch, $matches)) { $task = (int)$matches['id']; } elseif (preg_match('/^task[#\@\$](?<id>\d+)/iu', $summary, $matches)) { $task = (int)$matches['id']; } //   ,      if ($task <= 0) { echo '   ' . PHP_EOL; echo '       Enter,  : '; $count = fscanf(STDIN, "%d\n", $task); if ($count <= 0) { echo '   .' . PHP_EOL; echo '       ' . PHP_EOL; echo ' ' . PHP_EOL; exit(0); } } echo '     ' . PHP_EOL; $message = <<<EOT      $user  $pwd  $hostname: $summary ======    : $log    ( $filesCount ): $files   . EOT; //   $postData = [ 'message' => $message, 'task' => $task, 'key' => KEY ]; //    $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, BX24_APP_URL); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $result = curl_exec($ch); echo $result . PHP_EOL; echo ' ' . PHP_EOL; 

  5. Add to hgrc the path to the downloaded file hghook-commit-to-bx24.php
     [hooks] commit = php -f /home/bitrix/hghook-commit-to-bx24.php 

  6. Select in the left menu of the portal the item “Add application”, if it is not visible, then expand the item “Applications”

  7. On the page, select the type of application “For personal use”, since we are not going to spread it to the cloudy Marketplace.
    Select the type of application
    image

  8. On the settings page of the new application, specify
    • Application Name
    • The name of the menu item in the desired language
    • Set access rights to "Tasks (task)"
    • Specify the link to the executable file of the application.
    • Specify a link to the application installation file
    Application settings
    image

    After entering all the settings, save the application. Settings can always be edited and supplemented, if necessary, by selecting the appropriate item on the task list in the "My Applications" section

  9. After saving the application, we get to the page with a list of applications. For each application, Bitrix24 assigns two unique parameters “Application code (client_id)” and “Application key (client_secret)”, which must be specified in the file install.php
    Application list
    image

  10. Now you need to go to install the application by clicking on the link to the application in the left menu. If everything is done correctly, a message of the form will be displayed.
      .    hghook-commit-to-bx24.php  : <ACCESS_KEY> 

    Application installation
    image

    If nothing was displayed (white area instead of the application), then most likely you have the title
     Header set X-Frame-Options SAMEORIGIN 

    It prohibits showing your site in frames. To fix this, in the application directory it is enough to create (or edit) the .htaccess file by adding the line
     Header unset X-Frame-Options 

    The resulting access code must be written to the file hghook-commit-to-bx24.php

  11. If everything is correctly configured, then to add information about commit to the task, you will need its number. The task number in Bitrix24 is displayed near its name.
    The task in the portal
    image

    To add information about a commit to a task, you can specify a number in the commit text at the very beginning after “task #”, “task @” or “task $”.
     [bitrix@dhcppc5 www]$ hg st M composer.json [bitrix@dhcppc5 www]$ hg ci -u testuser -m 'task#62   #1 :  -  -'   Mercurial,                            #62   <PORTAL_NAME>.bitrix24.ru         [bitrix@dhcppc5 www]$ 

    Comment on problem # 1
    image

    You can also get the task number from the name of the Mercurial work branch if it has a name starting with “task #”, “task @”, or “task $”.

    If the task number is not found either in the comment or in the name of the branch, you can enter it manually.
     [bitrix@dhcppc5 www]$ hg ci -u testuser -m '  #2 :  -  -'   Mercurial,                                Enter,  : 62        #62   <PORTAL_NAME>.bitrix24.ru         [bitrix@dhcppc5 www]$ 

    Comment on problem # 2
    image

    If the task number entry is omitted, the comment will not be sent.
     [bitrix@dhcppc5 www]$ hg ci -u testuser -m '  #3 :  -  -'   Mercurial,                                Enter,  :               [bitrix@dhcppc5 www]$ 

    If a non-existing task number is indicated, an appropriate error notification will be displayed.
     [bitrix@dhcppc5 www]$ hg ci -u testuser -m 'task$65445642   #3 :  -  -'   Mercurial,                                   [bitrix@dhcppc5 www]$ 

Code from the article .

Used materials:

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


All Articles