xref: /plugin/gitbacked/action/editcommit.php (revision 477c7cb4e85002ab4cbe9a9f555cfe6115d5ce25)
1fa53f2a3SWolfgang Gassler<?php
22762023dSMarkus Hoffrogge
3fa53f2a3SWolfgang Gassler/**
4fa53f2a3SWolfgang Gassler * DokuWiki Plugin gitbacked (Action Component)
5fa53f2a3SWolfgang Gassler *
6fa53f2a3SWolfgang Gassler * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
7fa53f2a3SWolfgang Gassler * @author  Wolfgang Gassler <wolfgang@gassler.org>
8fa53f2a3SWolfgang Gassler */
9fa53f2a3SWolfgang Gassler
102762023dSMarkus Hoffrogge// phpcs:disable PSR1.Files.SideEffects.FoundWithSymbols
11fa53f2a3SWolfgang Gassler// must be run within Dokuwiki
12fa53f2a3SWolfgang Gasslerif (!defined('DOKU_INC')) die();
13fa53f2a3SWolfgang Gassler
14fa53f2a3SWolfgang Gasslerif (!defined('DOKU_LF')) define('DOKU_LF', "\n");
15fa53f2a3SWolfgang Gasslerif (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
16fa53f2a3SWolfgang Gasslerif (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
17fa53f2a3SWolfgang Gassler
182762023dSMarkus Hoffroggerequire_once __DIR__ . '/../loader.php';
19fa53f2a3SWolfgang Gassler
202762023dSMarkus Hoffroggeuse dokuwiki\Extension\ActionPlugin;
212762023dSMarkus Hoffroggeuse dokuwiki\Extension\EventHandler;
222762023dSMarkus Hoffroggeuse dokuwiki\Extension\Event;
23aeb41f7dSMarkus Hoffroggeuse dokuwiki\Search\Indexer;
24fa53f2a3SWolfgang Gassler
252762023dSMarkus Hoffroggeuse woolfg\dokuwiki\plugin\gitbacked\Git;
262762023dSMarkus Hoffroggeuse woolfg\dokuwiki\plugin\gitbacked\GitRepo;
272762023dSMarkus Hoffroggeuse woolfg\dokuwiki\plugin\gitbacked\GitBackedUtil;
282762023dSMarkus Hoffrogge
292762023dSMarkus Hoffrogge// phpcs:disable PSR1.Classes.ClassDeclaration.MissingNamespace
302762023dSMarkus Hoffrogge// phpcs:disable Squiz.Classes.ValidClassName.NotCamelCaps
312762023dSMarkus Hoffroggeclass action_plugin_gitbacked_editcommit extends ActionPlugin
322762023dSMarkus Hoffrogge{
332762023dSMarkus Hoffrogge    /**
342762023dSMarkus Hoffrogge     * Temporary directory for this gitbacked plugin.
352762023dSMarkus Hoffrogge     *
362762023dSMarkus Hoffrogge     * @var string
372762023dSMarkus Hoffrogge     */
382762023dSMarkus Hoffrogge    private $temp_dir;
392762023dSMarkus Hoffrogge
402762023dSMarkus Hoffrogge    public function __construct()
412762023dSMarkus Hoffrogge    {
42eeb1a599SMarkus Hoffrogge        $this->temp_dir = GitBackedUtil::getTempDir();
4300ce3f12SDanny Lin    }
4400ce3f12SDanny Lin
452762023dSMarkus Hoffrogge    public function register(EventHandler $controller)
462762023dSMarkus Hoffrogge    {
472762023dSMarkus Hoffrogge        $controller->register_hook('IO_WIKIPAGE_WRITE', 'AFTER', $this, 'handleIOWikiPageWrite');
482762023dSMarkus Hoffrogge        $controller->register_hook('MEDIA_UPLOAD_FINISH', 'AFTER', $this, 'handleMediaUpload');
492762023dSMarkus Hoffrogge        $controller->register_hook('MEDIA_DELETE_FILE', 'AFTER', $this, 'handleMediaDeletion');
502762023dSMarkus Hoffrogge        $controller->register_hook('DOKUWIKI_DONE', 'AFTER', $this, 'handlePeriodicPull');
51442c3981SWolfgang Gassler    }
52442c3981SWolfgang Gassler
532762023dSMarkus Hoffrogge    private function initRepo()
542762023dSMarkus Hoffrogge    {
55442c3981SWolfgang Gassler        //get path to the repo root (by default DokuWiki's savedir)
56dee8dca1SMarkus Hoffrogge        $repoPath = GitBackedUtil::getEffectivePath($this->getConf('repoPath'));
57635161d0SCarsten Teibes        $gitPath = trim($this->getConf('gitPath'));
58635161d0SCarsten Teibes        if ($gitPath !== '') {
592762023dSMarkus Hoffrogge            Git::setBin($gitPath);
60635161d0SCarsten Teibes        }
61442c3981SWolfgang Gassler        //init the repo and create a new one if it is not present
624eba9b44SDanny Lin        io_mkdir_p($repoPath);
63e8224fc2SMarkus Hoffrogge        $repo = new GitRepo($repoPath, $this, true, true);
644eba9b44SDanny Lin        //set git working directory (by default DokuWiki's savedir)
65dee8dca1SMarkus Hoffrogge        $repoWorkDir = $this->getConf('repoWorkDir');
66dee8dca1SMarkus Hoffrogge        if (!empty($repoWorkDir)) {
67dee8dca1SMarkus Hoffrogge            $repoWorkDir = GitBackedUtil::getEffectivePath($repoWorkDir);
68dee8dca1SMarkus Hoffrogge        }
692762023dSMarkus Hoffrogge        Git::setBin(empty($repoWorkDir) ? Git::getBin()
702762023dSMarkus Hoffrogge            : Git::getBin() . ' --work-tree ' . escapeshellarg($repoWorkDir));
710d7cb616SBirkir A. Barkarson        $params = str_replace(
72c365e7dbSmhoffrog            ['%mail%', '%user%'],
73c365e7dbSmhoffrog            [$this->getAuthorMail(), $this->getAuthor()],
742762023dSMarkus Hoffrogge            $this->getConf('addParams')
752762023dSMarkus Hoffrogge        );
76442c3981SWolfgang Gassler        if ($params) {
772762023dSMarkus Hoffrogge            Git::setBin(Git::getBin() . ' ' . $params);
78442c3981SWolfgang Gassler        }
79b92b117aSWolfgang Gassler        return $repo;
80b92b117aSWolfgang Gassler    }
81b92b117aSWolfgang Gassler
822762023dSMarkus Hoffrogge    private function isIgnored($filePath)
832762023dSMarkus Hoffrogge    {
8466f21a70SWolfgang Gassler        $ignore = false;
8566f21a70SWolfgang Gassler        $ignorePaths = trim($this->getConf('ignorePaths'));
8666f21a70SWolfgang Gassler        if ($ignorePaths !== '') {
8766f21a70SWolfgang Gassler            $paths = explode(',', $ignorePaths);
8866f21a70SWolfgang Gassler            foreach ($paths as $path) {
8966f21a70SWolfgang Gassler                if (strstr($filePath, $path)) {
9066f21a70SWolfgang Gassler                    $ignore = true;
9166f21a70SWolfgang Gassler                }
9266f21a70SWolfgang Gassler            }
9366f21a70SWolfgang Gassler        }
9466f21a70SWolfgang Gassler        return $ignore;
9566f21a70SWolfgang Gassler    }
9666f21a70SWolfgang Gassler
972762023dSMarkus Hoffrogge    private function commitFile($filePath, $message)
982762023dSMarkus Hoffrogge    {
9966f21a70SWolfgang Gassler        if (!$this->isIgnored($filePath)) {
100*477c7cb4SSam Edwards            $message = str_replace(
101*477c7cb4SSam Edwards                ['%user%', '%mail%', '\n'],
102*477c7cb4SSam Edwards                [$this->getAuthor(), $this->getAuthorMail(), "\n"],
103*477c7cb4SSam Edwards                $message
104*477c7cb4SSam Edwards            );
105*477c7cb4SSam Edwards
106e8224fc2SMarkus Hoffrogge            try {
107b92b117aSWolfgang Gassler                $repo = $this->initRepo();
108442c3981SWolfgang Gassler
109442c3981SWolfgang Gassler                //add the changed file and set the commit message
110442c3981SWolfgang Gassler                $repo->add($filePath);
111442c3981SWolfgang Gassler                $repo->commit($message);
112442c3981SWolfgang Gassler
113442c3981SWolfgang Gassler                //if the push after Commit option is set we push the active branch to origin
114442c3981SWolfgang Gassler                if ($this->getConf('pushAfterCommit')) {
1152762023dSMarkus Hoffrogge                    $repo->push('origin', $repo->activeBranch());
116442c3981SWolfgang Gassler                }
117e8224fc2SMarkus Hoffrogge            } catch (Exception $e) {
118e8224fc2SMarkus Hoffrogge                if (!$this->isNotifyByEmailOnGitCommandError()) {
119e8224fc2SMarkus Hoffrogge                    throw new Exception('Git committing or pushing failed: ' . $e->getMessage(), 1, $e);
12066f21a70SWolfgang Gassler                }
121e8224fc2SMarkus Hoffrogge                return;
122e8224fc2SMarkus Hoffrogge            }
123e8224fc2SMarkus Hoffrogge        }
124442c3981SWolfgang Gassler    }
125442c3981SWolfgang Gassler
12641fa3ce7Smhoffrog    private function getUserInfo($key)
12741fa3ce7Smhoffrog    {
12841fa3ce7Smhoffrog        return $GLOBALS['USERINFO'][$key] ?? '';
129442c3981SWolfgang Gassler    }
130442c3981SWolfgang Gassler
13141fa3ce7Smhoffrog    private function getAuthor()
13241fa3ce7Smhoffrog    {
13319993fa1Sribsey        return $this->getUserInfo('name');
13419993fa1Sribsey    }
13519993fa1Sribsey
13641fa3ce7Smhoffrog    private function getAuthorMail()
13741fa3ce7Smhoffrog    {
13819993fa1Sribsey        return $this->getUserInfo('mail');
1390d7cb616SBirkir A. Barkarson    }
1400d7cb616SBirkir A. Barkarson
1412762023dSMarkus Hoffrogge    private function computeLocalPath()
1422762023dSMarkus Hoffrogge    {
143a2effbcbSmsx80        global $conf;
144a2effbcbSmsx80        $repoPath = str_replace('\\', '/', realpath(GitBackedUtil::getEffectivePath($this->getConf('repoPath'))));
145a2effbcbSmsx80        $datadir = $conf['datadir']; // already normalized
146c365e7dbSmhoffrog        if (substr($datadir, 0, strlen($repoPath)) !== $repoPath) {
147a2effbcbSmsx80            throw new Exception('Datadir not inside repoPath ??');
148a2effbcbSmsx80        }
149a2effbcbSmsx80        return substr($datadir, strlen($repoPath) + 1);
150a2effbcbSmsx80    }
151a2effbcbSmsx80
1522762023dSMarkus Hoffrogge    private function updatePage($page)
1532762023dSMarkus Hoffrogge    {
154a2effbcbSmsx80
155c365e7dbSmhoffrog        if (is_callable(Indexer::class . '::getInstance')) {
156c365e7dbSmhoffrog            $Indexer = Indexer::getInstance();
157a2effbcbSmsx80            $success = $Indexer->addPage($page, false, false);
158a2effbcbSmsx80        } elseif (class_exists('Doku_Indexer')) {
159a2effbcbSmsx80            $success = idx_addPage($page, false, false);
160a2effbcbSmsx80        } else {
161a2effbcbSmsx80            // Failed to index the page. Your DokuWiki is older than release 2011-05-25 "Rincewind"
162a2effbcbSmsx80            $success = false;
163a2effbcbSmsx80        }
164a2effbcbSmsx80
165a2effbcbSmsx80        echo "Update $page: $success <br/>";
166a2effbcbSmsx80    }
167a2effbcbSmsx80
1682762023dSMarkus Hoffrogge    public function handlePeriodicPull(Event &$event, $param)
1692762023dSMarkus Hoffrogge    {
1702377428fSDanny Lin        if ($this->getConf('periodicPull')) {
171a2effbcbSmsx80            $enableIndexUpdate = $this->getConf('updateIndexOnPull');
1722377428fSDanny Lin            $lastPullFile = $this->temp_dir . '/lastpull.txt';
1732377428fSDanny Lin            //check if the lastPullFile exists
1742377428fSDanny Lin            if (is_file($lastPullFile)) {
1752377428fSDanny Lin                $lastPull = unserialize(file_get_contents($lastPullFile));
1762377428fSDanny Lin            } else {
1772377428fSDanny Lin                $lastPull = 0;
1782377428fSDanny Lin            }
1792377428fSDanny Lin            //calculate time between pulls in seconds
1802377428fSDanny Lin            $timeToWait = $this->getConf('periodicMinutes') * 60;
1812377428fSDanny Lin            $now = time();
1822377428fSDanny Lin
1832377428fSDanny Lin            //if it is time to run a pull request
1842377428fSDanny Lin            if ($lastPull + $timeToWait < $now) {
185e8224fc2SMarkus Hoffrogge                try {
1862377428fSDanny Lin                    $repo = $this->initRepo();
1872762023dSMarkus Hoffrogge                    if ($enableIndexUpdate) {
188a2effbcbSmsx80                        $localPath = $this->computeLocalPath();
189a2effbcbSmsx80
190a2effbcbSmsx80                        // store current revision id
191a2effbcbSmsx80                        $revBefore = $repo->run('rev-parse HEAD');
192a2effbcbSmsx80                    }
1932377428fSDanny Lin
1942377428fSDanny Lin                    //execute the pull request
1952762023dSMarkus Hoffrogge                    $repo->pull('origin', $repo->activeBranch());
196a2effbcbSmsx80
1972762023dSMarkus Hoffrogge                    if ($enableIndexUpdate) {
198a2effbcbSmsx80                        // store new revision id
199a2effbcbSmsx80                        $revAfter = $repo->run('rev-parse HEAD');
200a2effbcbSmsx80
2012762023dSMarkus Hoffrogge                        if (strcmp($revBefore, $revAfter) != 0) {
202a2effbcbSmsx80                            // if there were some changes, get the list of all changed files
203a2effbcbSmsx80                            $changedFilesPage = $repo->run('diff --name-only ' . $revBefore . ' ' . $revAfter);
204a2effbcbSmsx80                            $changedFiles = preg_split("/\r\n|\n|\r/", $changedFilesPage);
205a2effbcbSmsx80
2062762023dSMarkus Hoffrogge                            foreach ($changedFiles as $cf) {
207a2effbcbSmsx80                                // check if the file is inside localPath, that is, it's a page
2082762023dSMarkus Hoffrogge                                if (substr($cf, 0, strlen($localPath)) === $localPath) {
209a2effbcbSmsx80                                    // convert from relative filename to page name
210a2effbcbSmsx80                                    // for example: local/path/dir/subdir/test.txt -> dir:subdir:test
2112762023dSMarkus Hoffrogge                                    // -4 removes .txt
2122762023dSMarkus Hoffrogge                                    $page = str_replace('/', ':', substr($cf, strlen($localPath) + 1, -4));
213a2effbcbSmsx80
214a2effbcbSmsx80                                    // update the page
215a2effbcbSmsx80                                    $this->updatePage($page);
2162762023dSMarkus Hoffrogge                                } else {
217a2effbcbSmsx80                                    echo "Page NOT to update: $cf <br/>";
218a2effbcbSmsx80                                }
219a2effbcbSmsx80                            }
220a2effbcbSmsx80                        }
221a2effbcbSmsx80                    }
222e8224fc2SMarkus Hoffrogge                } catch (Exception $e) {
223e8224fc2SMarkus Hoffrogge                    if (!$this->isNotifyByEmailOnGitCommandError()) {
224e8224fc2SMarkus Hoffrogge                        throw new Exception('Git command failed to perform periodic pull: ' . $e->getMessage(), 2, $e);
225e8224fc2SMarkus Hoffrogge                    }
226e8224fc2SMarkus Hoffrogge                    return;
227e8224fc2SMarkus Hoffrogge                }
2282377428fSDanny Lin
2292377428fSDanny Lin                //save the current time to the file to track the last pull execution
2302377428fSDanny Lin                file_put_contents($lastPullFile, serialize(time()));
2312377428fSDanny Lin            }
2322377428fSDanny Lin        }
2332377428fSDanny Lin    }
2342377428fSDanny Lin
2352762023dSMarkus Hoffrogge    public function handleMediaDeletion(Event &$event, $param)
2362762023dSMarkus Hoffrogge    {
237442c3981SWolfgang Gassler        $mediaPath = $event->data['path'];
238442c3981SWolfgang Gassler        $mediaName = $event->data['name'];
239442c3981SWolfgang Gassler
240442c3981SWolfgang Gassler        $message = str_replace(
241*477c7cb4SSam Edwards            ['%media%'],
242*477c7cb4SSam Edwards            [$mediaName],
243442c3981SWolfgang Gassler            $this->getConf('commitMediaMsgDel')
244442c3981SWolfgang Gassler        );
245442c3981SWolfgang Gassler
246442c3981SWolfgang Gassler        $this->commitFile($mediaPath, $message);
247442c3981SWolfgang Gassler    }
248442c3981SWolfgang Gassler
2492762023dSMarkus Hoffrogge    public function handleMediaUpload(Event &$event, $param)
2502762023dSMarkus Hoffrogge    {
251442c3981SWolfgang Gassler
252442c3981SWolfgang Gassler        $mediaPath = $event->data[1];
253442c3981SWolfgang Gassler        $mediaName = $event->data[2];
254442c3981SWolfgang Gassler
255442c3981SWolfgang Gassler        $message = str_replace(
256*477c7cb4SSam Edwards            ['%media%'],
257*477c7cb4SSam Edwards            [$mediaName],
258442c3981SWolfgang Gassler            $this->getConf('commitMediaMsg')
259442c3981SWolfgang Gassler        );
260442c3981SWolfgang Gassler
261442c3981SWolfgang Gassler        $this->commitFile($mediaPath, $message);
262fa53f2a3SWolfgang Gassler    }
263fa53f2a3SWolfgang Gassler
2642762023dSMarkus Hoffrogge    public function handleIOWikiPageWrite(Event &$event, $param)
2652762023dSMarkus Hoffrogge    {
266fa53f2a3SWolfgang Gassler
267fa53f2a3SWolfgang Gassler        $rev = $event->data[3];
268fa53f2a3SWolfgang Gassler
269fa53f2a3SWolfgang Gassler        /* On update to an existing page this event is called twice,
270fa53f2a3SWolfgang Gassler         * once for the transfer of the old version to the attic (rev will have a value)
271fa53f2a3SWolfgang Gassler         * and once to write the new version of the page into the wiki (rev is false)
272fa53f2a3SWolfgang Gassler         */
273fa53f2a3SWolfgang Gassler        if (!$rev) {
274fa53f2a3SWolfgang Gassler            $pagePath = $event->data[0][0];
275fa53f2a3SWolfgang Gassler            $pageName = $event->data[2];
276*477c7cb4SSam Edwards            $pageNs = $event->data[1];
277442c3981SWolfgang Gassler            $pageContent = $event->data[0][1];
278fa53f2a3SWolfgang Gassler
2797af27dc9SWolfgang Gassler            // get the summary directly from the form input
280e7471cfaSDanny Lin            // as the metadata hasn't updated yet
2817af27dc9SWolfgang Gassler            $editSummary = $GLOBALS['INPUT']->str('summary');
282442c3981SWolfgang Gassler
283442c3981SWolfgang Gassler            // empty content indicates a page deletion
284442c3981SWolfgang Gassler            if ($pageContent == '') {
285442c3981SWolfgang Gassler                // get the commit text for deletions
286d4e1c54bSWolfgang Gassler                $msgTemplate = $this->getConf('commitPageMsgDel');
287442c3981SWolfgang Gassler
288442c3981SWolfgang Gassler                // bad hack as DokuWiki deletes the file after this event
289442c3981SWolfgang Gassler                // thus, let's delete the file by ourselves, so git can recognize the deletion
290442c3981SWolfgang Gassler                // DokuWiki uses @unlink as well, so no error should be thrown if we delete it twice
291442c3981SWolfgang Gassler                @unlink($pagePath);
292442c3981SWolfgang Gassler            } else {
293442c3981SWolfgang Gassler                //get the commit text for edits
294d4e1c54bSWolfgang Gassler                $msgTemplate = $this->getConf('commitPageMsg');
295442c3981SWolfgang Gassler            }
296442c3981SWolfgang Gassler
297fa53f2a3SWolfgang Gassler            $message = str_replace(
298*477c7cb4SSam Edwards                ['%page%', '%summary%', '%ns%'],
299*477c7cb4SSam Edwards                [$pageName, $editSummary, $pageNs],
300442c3981SWolfgang Gassler                $msgTemplate
301fa53f2a3SWolfgang Gassler            );
302fa53f2a3SWolfgang Gassler
303442c3981SWolfgang Gassler            $this->commitFile($pagePath, $message);
304fa53f2a3SWolfgang Gassler        }
305e8224fc2SMarkus Hoffrogge    }
306fa53f2a3SWolfgang Gassler
307e8224fc2SMarkus Hoffrogge    // ====== Error notification helpers ======
308e8224fc2SMarkus Hoffrogge    /**
309e8224fc2SMarkus Hoffrogge     * Notifies error on create_new
310e8224fc2SMarkus Hoffrogge     *
311e8224fc2SMarkus Hoffrogge     * @access  public
312e8224fc2SMarkus Hoffrogge     * @param   string  repository path
313e8224fc2SMarkus Hoffrogge     * @param   string  reference path / remote reference
314e8224fc2SMarkus Hoffrogge     * @param   string  error message
315e8224fc2SMarkus Hoffrogge     * @return  bool
316e8224fc2SMarkus Hoffrogge     */
3172762023dSMarkus Hoffrogge    public function notifyCreateNewError($repo_path, $reference, $error_message)
3182762023dSMarkus Hoffrogge    {
319aeb41f7dSMarkus Hoffrogge        $template_replacements = [
320aeb41f7dSMarkus Hoffrogge            'GIT_REPO_PATH' => $repo_path,
321aeb41f7dSMarkus Hoffrogge            'GIT_REFERENCE' => (empty($reference) ? 'n/a' : $reference),
322aeb41f7dSMarkus Hoffrogge            'GIT_ERROR_MESSAGE' => $error_message
323aeb41f7dSMarkus Hoffrogge        ];
324e8224fc2SMarkus Hoffrogge        return $this->notifyByMail('mail_create_new_error_subject', 'mail_create_new_error', $template_replacements);
325e8224fc2SMarkus Hoffrogge    }
326e8224fc2SMarkus Hoffrogge
327e8224fc2SMarkus Hoffrogge    /**
328e8224fc2SMarkus Hoffrogge     * Notifies error on setting repo path
329e8224fc2SMarkus Hoffrogge     *
330e8224fc2SMarkus Hoffrogge     * @access  public
331e8224fc2SMarkus Hoffrogge     * @param   string  repository path
332e8224fc2SMarkus Hoffrogge     * @param   string  error message
333e8224fc2SMarkus Hoffrogge     * @return  bool
334e8224fc2SMarkus Hoffrogge     */
3352762023dSMarkus Hoffrogge    public function notifyRepoPathError($repo_path, $error_message)
3362762023dSMarkus Hoffrogge    {
337aeb41f7dSMarkus Hoffrogge        $template_replacements = [
338aeb41f7dSMarkus Hoffrogge            'GIT_REPO_PATH' => $repo_path,
339aeb41f7dSMarkus Hoffrogge            'GIT_ERROR_MESSAGE' => $error_message
340aeb41f7dSMarkus Hoffrogge        ];
341e8224fc2SMarkus Hoffrogge        return $this->notifyByMail('mail_repo_path_error_subject', 'mail_repo_path_error', $template_replacements);
342e8224fc2SMarkus Hoffrogge    }
343e8224fc2SMarkus Hoffrogge
344e8224fc2SMarkus Hoffrogge    /**
345e8224fc2SMarkus Hoffrogge     * Notifies error on git command
346e8224fc2SMarkus Hoffrogge     *
347e8224fc2SMarkus Hoffrogge     * @access  public
348e8224fc2SMarkus Hoffrogge     * @param   string  repository path
349e8224fc2SMarkus Hoffrogge     * @param   string  current working dir
350e8224fc2SMarkus Hoffrogge     * @param   string  command line
351e8224fc2SMarkus Hoffrogge     * @param   int     exit code of command (status)
352e8224fc2SMarkus Hoffrogge     * @param   string  error message
353e8224fc2SMarkus Hoffrogge     * @return  bool
354e8224fc2SMarkus Hoffrogge     */
3552762023dSMarkus Hoffrogge    public function notifyCommandError($repo_path, $cwd, $command, $status, $error_message)
3562762023dSMarkus Hoffrogge    {
357aeb41f7dSMarkus Hoffrogge        $template_replacements = [
358aeb41f7dSMarkus Hoffrogge            'GIT_REPO_PATH' => $repo_path,
359aeb41f7dSMarkus Hoffrogge            'GIT_CWD' => $cwd,
360aeb41f7dSMarkus Hoffrogge            'GIT_COMMAND' => $command,
361aeb41f7dSMarkus Hoffrogge            'GIT_COMMAND_EXITCODE' => $status,
362aeb41f7dSMarkus Hoffrogge            'GIT_ERROR_MESSAGE' => $error_message
363aeb41f7dSMarkus Hoffrogge        ];
364e8224fc2SMarkus Hoffrogge        return $this->notifyByMail('mail_command_error_subject', 'mail_command_error', $template_replacements);
365e8224fc2SMarkus Hoffrogge    }
366e8224fc2SMarkus Hoffrogge
367e8224fc2SMarkus Hoffrogge    /**
368e8224fc2SMarkus Hoffrogge     * Notifies success on git command
369e8224fc2SMarkus Hoffrogge     *
370e8224fc2SMarkus Hoffrogge     * @access  public
371e8224fc2SMarkus Hoffrogge     * @param   string  repository path
372e8224fc2SMarkus Hoffrogge     * @param   string  current working dir
373e8224fc2SMarkus Hoffrogge     * @param   string  command line
374e8224fc2SMarkus Hoffrogge     * @return  bool
375e8224fc2SMarkus Hoffrogge     */
3762762023dSMarkus Hoffrogge    public function notifyCommandSuccess($repo_path, $cwd, $command)
3772762023dSMarkus Hoffrogge    {
378e8224fc2SMarkus Hoffrogge        if (!$this->getConf('notifyByMailOnSuccess')) {
379e8224fc2SMarkus Hoffrogge            return false;
380e8224fc2SMarkus Hoffrogge        }
381aeb41f7dSMarkus Hoffrogge        $template_replacements = [
382aeb41f7dSMarkus Hoffrogge            'GIT_REPO_PATH' => $repo_path,
383aeb41f7dSMarkus Hoffrogge            'GIT_CWD' => $cwd,
384aeb41f7dSMarkus Hoffrogge            'GIT_COMMAND' => $command
385aeb41f7dSMarkus Hoffrogge        ];
386e8224fc2SMarkus Hoffrogge        return $this->notifyByMail('mail_command_success_subject', 'mail_command_success', $template_replacements);
387e8224fc2SMarkus Hoffrogge    }
388e8224fc2SMarkus Hoffrogge
389e8224fc2SMarkus Hoffrogge    /**
390e8224fc2SMarkus Hoffrogge     * Send an eMail, if eMail address is configured
391e8224fc2SMarkus Hoffrogge     *
392e8224fc2SMarkus Hoffrogge     * @access  public
393e8224fc2SMarkus Hoffrogge     * @param   string  lang id for the subject
394e8224fc2SMarkus Hoffrogge     * @param   string  lang id for the template(.txt)
395e8224fc2SMarkus Hoffrogge     * @param   array   array of replacements
396e8224fc2SMarkus Hoffrogge     * @return  bool
397e8224fc2SMarkus Hoffrogge     */
3982762023dSMarkus Hoffrogge    public function notifyByMail($subject_id, $template_id, $template_replacements)
3992762023dSMarkus Hoffrogge    {
400e8224fc2SMarkus Hoffrogge        $ret = false;
4012762023dSMarkus Hoffrogge        //dbglog("GitBacked - notifyByMail: [subject_id=" . $subject_id
4022762023dSMarkus Hoffrogge        //    . ", template_id=" . $template_id
4032762023dSMarkus Hoffrogge        //    . ", template_replacements=" . $template_replacements . "]");
404e8224fc2SMarkus Hoffrogge        if (!$this->isNotifyByEmailOnGitCommandError()) {
405e8224fc2SMarkus Hoffrogge            return $ret;
406e8224fc2SMarkus Hoffrogge        }
407e8224fc2SMarkus Hoffrogge        //$template_text = rawLocale($template_id); // this works for core artifacts only - not for plugins
408e8224fc2SMarkus Hoffrogge        $template_filename = $this->localFN($template_id);
409e8224fc2SMarkus Hoffrogge        $template_text = file_get_contents($template_filename);
410e8224fc2SMarkus Hoffrogge        $template_html = $this->render_text($template_text);
411e8224fc2SMarkus Hoffrogge
412e8224fc2SMarkus Hoffrogge        $mailer = new \Mailer();
413e8224fc2SMarkus Hoffrogge        $mailer->to($this->getEmailAddressOnErrorConfigured());
414dd477e30SMarkus Hoffrogge        //dbglog("GitBacked - lang check['".$subject_id."']: ".$this->getLang($subject_id));
415dd477e30SMarkus Hoffrogge        //dbglog("GitBacked - template text['".$template_id."']: ".$template_text);
416dd477e30SMarkus Hoffrogge        //dbglog("GitBacked - template html['".$template_id."']: ".$template_html);
417e8224fc2SMarkus Hoffrogge        $mailer->subject($this->getLang($subject_id));
418e8224fc2SMarkus Hoffrogge        $mailer->setBody($template_text, $template_replacements, null, $template_html);
419c365e7dbSmhoffrog
420e8224fc2SMarkus Hoffrogge        $ret = $mailer->send();
421e8224fc2SMarkus Hoffrogge
422e8224fc2SMarkus Hoffrogge        return $ret;
423e8224fc2SMarkus Hoffrogge    }
424e8224fc2SMarkus Hoffrogge
425e8224fc2SMarkus Hoffrogge    /**
426e8224fc2SMarkus Hoffrogge     * Check, if eMail is to be sent on a Git command error.
427e8224fc2SMarkus Hoffrogge     *
428e8224fc2SMarkus Hoffrogge     * @access  public
429e8224fc2SMarkus Hoffrogge     * @return  bool
430e8224fc2SMarkus Hoffrogge     */
4312762023dSMarkus Hoffrogge    public function isNotifyByEmailOnGitCommandError()
4322762023dSMarkus Hoffrogge    {
433e8224fc2SMarkus Hoffrogge        $emailAddressOnError = $this->getEmailAddressOnErrorConfigured();
434e8224fc2SMarkus Hoffrogge        return !empty($emailAddressOnError);
435e8224fc2SMarkus Hoffrogge    }
436e8224fc2SMarkus Hoffrogge
437e8224fc2SMarkus Hoffrogge    /**
438e8224fc2SMarkus Hoffrogge     * Get the eMail address configured for notifications.
439e8224fc2SMarkus Hoffrogge     *
440e8224fc2SMarkus Hoffrogge     * @access  public
441e8224fc2SMarkus Hoffrogge     * @return  string
442e8224fc2SMarkus Hoffrogge     */
4432762023dSMarkus Hoffrogge    public function getEmailAddressOnErrorConfigured()
4442762023dSMarkus Hoffrogge    {
445e8224fc2SMarkus Hoffrogge        $emailAddressOnError = trim($this->getConf('emailAddressOnError'));
446e8224fc2SMarkus Hoffrogge        return $emailAddressOnError;
447fa53f2a3SWolfgang Gassler    }
448fa53f2a3SWolfgang Gassler}
4492762023dSMarkus Hoffrogge// phpcs:enable Squiz.Classes.ValidClassName.NotCamelCaps
4502762023dSMarkus Hoffrogge// phpcs:enable PSR1.Classes.ClassDeclaration.MissingNamespace
451fa53f2a3SWolfgang Gassler
452fa53f2a3SWolfgang Gassler// vim:ts=4:sw=4:et:
453