1<?php
2/**
3 * Plugin GitLab: Gets commit message by project name and commit id.
4 *
5 * @license     GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author      Karsten Kosmala <kosmalakarsten@gmail.com>
7 */
8
9if(!defined('DOKU_INC')) die();
10
11class syntax_plugin_gitlab extends DokuWiki_Syntax_Plugin {
12    public function getType() { return 'substition'; }
13    public function getSort() { return 32; }
14
15    public function connectTo($mode) {
16        $this->Lexer->addSpecialPattern('\[\[gitlabapi>[a-zA-Z0-9.-]+>[a-z0-9]+\]\]', $mode, 'plugin_gitlab');
17    }
18
19    public function handle($match, $state, $pos, Doku_Handler &$handler) {
20        list($name, $repository_name, $commit_id) = explode('>', $match);
21        $commit_id_short = substr($commit_id, 0, -2);
22        list($repository_id, $web_url)= $this->getInfoByName($repository_name);
23        list($commit_msg, $commit_id_long) = $this->getInfoByHash($repository_id, $commit_id_short);
24
25        return array($web_url, $commit_id_long, $commit_msg);
26    }
27
28    public function render($mode, Doku_Renderer &$renderer, $data) {
29    // $data is what the function handle return'ed.
30        if($mode == 'xhtml'){
31            /** @var Doku_Renderer_xhtml $renderer */
32            $renderer->doc .= '<a target="_blank" href="' . htmlspecialchars($data[0]) . '/commit/' . htmlspecialchars($data[1]) . '">' . htmlspecialchars($data[2]) . '</a>';
33            return true;
34        }
35        return false;
36    }
37
38    public function getInfoByName($name) {
39        $gitlabServer = $this->getConf('server');
40        $apiToken = $this->getConf('api_token');
41        $http = new DokuHTTPClient();
42        $reqUrl = $gitlabServer . '/api/v3/projects/search/' . $name . '/?private_token=' . $apiToken;
43        $repositories = json_decode($http->get($reqUrl), true);
44
45        foreach ($repositories as &$repository) {
46            if ($repository['name'] == $name) {
47                $data = $repository;
48            }
49        }
50
51        return array($data['id'], $data['web_url']);
52    }
53
54    public function getInfoByHash($repository_id, $commit_id) {
55        $gitlabServer = $this->getConf('server');
56        $apiToken = $this->getConf('api_token');
57        $http = new DokuHTTPClient();
58        $reqUrl = $gitlabServer . '/api/v3/projects/' . $repository_id . '/repository/commits/' . $commit_id . '/?private_token=' .$apiToken;
59        $data = json_decode($http->get($reqUrl), true);
60
61        return array($data['message'], $data['id']);
62    }
63}
64