xref: /plugin/gitbacked/action/editcommit.php (revision 985a1bc73e150d3a2ae5422461a36a9cd13ad152)
1<?php
2/**
3 * DokuWiki Plugin gitbacked (Action Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Wolfgang Gassler <wolfgang@gassler.org>
7 */
8
9// must be run within Dokuwiki
10if (!defined('DOKU_INC')) die();
11
12if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
13if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");
14if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
15
16require_once DOKU_PLUGIN.'action.php';
17require_once dirname(__FILE__).'/../lib/Git.php';
18
19class action_plugin_gitbacked_editcommit extends DokuWiki_Action_Plugin {
20
21    function __construct() {
22        global $conf;
23        $this->temp_dir = $conf['tmpdir'].'/gitbacked';
24        io_mkdir_p($this->temp_dir);
25    }
26
27    public function register(Doku_Event_Handler &$controller) {
28
29        $controller->register_hook('IO_WIKIPAGE_WRITE', 'AFTER', $this, 'handle_io_wikipage_write');
30        $controller->register_hook('MEDIA_UPLOAD_FINISH', 'AFTER', $this, 'handle_media_upload');
31        $controller->register_hook('MEDIA_DELETE_FILE', 'AFTER', $this, 'handle_media_deletion');
32        $controller->register_hook('DOKUWIKI_DONE', 'AFTER', $this, 'handle_periodic_pull');
33    }
34
35    private function initRepo() {
36        //get path to the repo root (by default DokuWiki's savedir)
37        if(defined('DOKU_FARM')) {
38            $repoPath = $this->getConf('repoPath');
39        } else {
40            $repoPath = DOKU_INC.$this->getConf('repoPath');
41        }
42        //init the repo and create a new one if it is not present
43        io_mkdir_p($repoPath);
44        $repo = new GitRepo($repoPath, true, true);
45        //set git working directory (by default DokuWiki's savedir)
46        $repoWorkDir = DOKU_INC.$this->getConf('repoWorkDir');
47        Git::set_bin(Git::get_bin().' --work-tree '.escapeshellarg($repoWorkDir));
48
49        $params = str_replace(
50            array('%mail%','%user%'),
51            array($this->getAuthorMail(),$this->getAuthor()),
52            $this->getConf('addParams'));
53        if ($params) {
54            Git::set_bin(Git::get_bin().' '.$params);
55        }
56        return $repo;
57    }
58
59	private function isIgnored($filePath) {
60		$ignore = false;
61		$ignorePaths = trim($this->getConf('ignorePaths'));
62		if ($ignorePaths !== '') {
63			$paths = explode(',',$ignorePaths);
64			foreach($paths as $path) {
65				if (strstr($filePath,$path)) {
66					$ignore = true;
67				}
68			}
69		}
70		return $ignore;
71	}
72
73    private function commitFile($filePath,$message) {
74
75		if (!$this->isIgnored($filePath)) {
76			$repo = $this->initRepo();
77
78			//add the changed file and set the commit message
79			$repo->add($filePath);
80			$repo->commit($message);
81
82			//if the push after Commit option is set we push the active branch to origin
83			if ($this->getConf('pushAfterCommit')) {
84				$repo->push('origin',$repo->active_branch());
85			}
86		}
87
88    }
89
90    private function getAuthor() {
91        return $GLOBALS['USERINFO']['name'];
92    }
93
94    private function getAuthorMail() {
95        return $GLOBALS['USERINFO']['mail'];
96    }
97
98    public function handle_periodic_pull(Doku_Event &$event, $param) {
99        if ($this->getConf('periodicPull')) {
100            $lastPullFile = $this->temp_dir.'/lastpull.txt';
101            //check if the lastPullFile exists
102            if (is_file($lastPullFile)) {
103                $lastPull = unserialize(file_get_contents($lastPullFile));
104            } else {
105                $lastPull = 0;
106            }
107            //calculate time between pulls in seconds
108            $timeToWait = $this->getConf('periodicMinutes')*60;
109            $now = time();
110
111            //if it is time to run a pull request
112            if ($lastPull+$timeToWait < $now) {
113                $repo = $this->initRepo();
114
115                //execute the pull request
116                $repo->pull('origin',$repo->active_branch());
117
118                //save the current time to the file to track the last pull execution
119                file_put_contents($lastPullFile,serialize(time()));
120            }
121        }
122    }
123
124    public function handle_media_deletion(Doku_Event &$event, $param) {
125        $mediaPath = $event->data['path'];
126        $mediaName = $event->data['name'];
127
128        $message = str_replace(
129            array('%media%','%user%'),
130            array($mediaName,$this->getAuthor()),
131            $this->getConf('commitMediaMsgDel')
132        );
133
134        $this->commitFile($mediaPath,$message);
135
136    }
137
138    public function handle_media_upload(Doku_Event &$event, $param) {
139
140        $mediaPath = $event->data[1];
141        $mediaName = $event->data[2];
142
143        $message = str_replace(
144            array('%media%','%user%'),
145            array($mediaName,$this->getAuthor()),
146            $this->getConf('commitMediaMsg')
147        );
148
149        $this->commitFile($mediaPath,$message);
150
151    }
152
153    public function handle_io_wikipage_write(Doku_Event &$event, $param) {
154
155        $rev = $event->data[3];
156
157        /* On update to an existing page this event is called twice,
158         * once for the transfer of the old version to the attic (rev will have a value)
159         * and once to write the new version of the page into the wiki (rev is false)
160         */
161        if (!$rev) {
162
163            $pagePath = $event->data[0][0];
164            $pageName = $event->data[2];
165            $pageContent = $event->data[0][1];
166
167            // get the summary directly from the form input
168            // as the metadata hasn't updated yet
169            $editSummary = $GLOBALS['INPUT']->str('summary');
170
171            // empty content indicates a page deletion
172            if ($pageContent == '') {
173                // get the commit text for deletions
174                $msgTemplate = $this->getConf('commitPageMsgDel');
175
176                // bad hack as DokuWiki deletes the file after this event
177                // thus, let's delete the file by ourselves, so git can recognize the deletion
178                // DokuWiki uses @unlink as well, so no error should be thrown if we delete it twice
179                @unlink($pagePath);
180
181            } else {
182                //get the commit text for edits
183                $msgTemplate = $this->getConf('commitPageMsg');
184            }
185
186            $message = str_replace(
187                array('%page%','%summary%','%user%'),
188                array($pageName,$editSummary,$this->getAuthor()),
189                $msgTemplate
190            );
191
192            $this->commitFile($pagePath,$message);
193
194        }
195
196    }
197
198}
199
200// vim:ts=4:sw=4:et:
201