fixed branch view
[GITManagedWebpage.git] / GITManagedWebpage.class.php
1 <?php
2 /*************************** GITManagedWebpage **************************
3  * Copyright (C) 2013       Philipp Kreil (pk910)                       *
4  *                                                                      *
5  * This program is free software: you can redistribute it and/or modify *
6  * it under the terms of the GNU General Public License as published by *
7  * the Free Software Foundation, either version 3 of the License, or    *
8  * (at your option) any later version.                                  *
9  *                                                                      *
10  * This program is distributed in the hope that it will be useful,      *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
13  * GNU General Public License for more details.                         *
14  *                                                                      *
15  * You should have received a copy of the GNU General Public License    *
16  * along with this program. If not, see <http://www.gnu.org/licenses/>. *
17  *                                                                      *
18  ************************************************************************
19  *
20  *  GITManagedWebpage.class.php
21  *
22  * Functions to manage a Website using GIT Version Control
23  *
24  */
25
26 class GITManagedWebpage {
27     const ERROR_CRITICAL = 1;
28     const SESSION_PREFIX = "GITManagedWebpage_";
29
30     private $giturl;
31     private $workdir, $localdir;
32     private $ready = false;
33     private $loopedcall = false;
34     private $config = null;
35     private $config_changed = true;
36     private $activeSession = null;
37     
38     public function __construct($giturl, $workdir = null, $localdir = null) {
39         if(session_status() != PHP_SESSION_ACTIVE) {
40             session_start();
41         }
42         
43         if(defined("GITMANAGED_EXECUTED")) {
44             $this->loopedcall = true;
45             return;
46         }
47         
48         if($workdir === null) {
49             $workdir = dirname(__FILE__);
50             if(substr($workdir, -1) != "/")
51                 $workdir .= "/";
52             $workdir .= ".gitmanaged/";
53         }
54         else if(substr($workdir, -1) != "/")
55             $workdir .= "/";
56         
57         if($localdir === null) {
58             $localdir = dirname(__FILE__);
59             if(substr($localdir, -1) != "/")
60                 $localdir .= "/";
61         }
62         else if(substr($localdir, -1) != "/")
63             $localdir .= "/";
64         
65         $this->giturl = $giturl;
66         $this->workdir = $workdir;
67         $this->localdir = $localdir;
68         
69         if(!file_exists($this->workdir) || !is_dir($this->workdir)) {
70             if(file_exists($this->workdir) && !is_dir($this->workdir)) {
71                 $this->error(self::ERROR_CRITICAL, "local workdir (".htmlspecialchars($this->workdir).") is not a directory.");
72                 return;
73             }
74             $this->setupWorkdir();
75         }
76         $this->ready = true;
77     }
78     
79     /* private function gitcmd(...)
80     * Execute a git command and return output
81     */
82     private function gitcmd() {
83         $args = func_get_args();
84         $argstr = "";
85         foreach($args as $arg) {
86             if(is_array($arg)) {
87                 foreach($arg as $subarg) {
88                     $argstr .= " ".escapeshellarg($subarg);
89                 }
90             } else
91                 $argstr .= " ".escapeshellarg($arg);
92         }
93         $gitcmd = 'git '.escapeshellarg('--git-dir='.$this->workdir.'repository/.git').' '.escapeshellarg('--work-tree='.$this->workdir.'repository').$argstr;
94         $output = shell_exec($gitcmd);
95         return $output;
96     }
97     
98     /* private function setConfig($name, $value)
99     * store a option in the configuration
100     */
101     private function setConfig($name, $value) {
102         $this->config[strtolower($name)] = $value;
103         $this->config_changed = true;
104     }
105     
106     private function checkConfigIntegrity() {
107         foreach($this->config as $key => $value) {
108             if(substr($key, 0, strlen('branch_')) == 'branch_') {
109                 if(!file_exists($this->workdir.$key)) {
110                     unset($this->config['key']);
111                 }
112             }
113         }
114     }
115     
116     /* private function getConfig($name)
117     * get an option from the configuration
118     */
119     private function getConfig($name) {
120         if($this->config == null) {
121             if(!$this->ready)
122                 return null;
123             if(file_exists($this->workdir."config.txt")) {
124                 $config_txt = @file_get_contents($this->workdir."config.txt");
125                 $this->config = unserialize($config_txt);
126                 $this->checkConfigIntegrity();
127             } else {
128                 $this->config = array();
129                 return null;
130             }
131         }
132         if(array_key_exists(strtolower($name), $this->config))
133             return $this->config[strtolower($name)];
134         else
135             return null;
136     }
137     
138     private function saveConfig() {
139         if($this->config_changed && $this->ready) {
140             $fp = fopen($this->workdir."config.txt", "w");
141             fwrite($fp, serialize($this->config));
142             fclose($fp);
143         }
144     }
145     
146     /* private function setupWorkdir()
147     * Setup local GITManagedWebpage Work directory with git repository
148     */
149     private function setupWorkdir() {
150         // check requirements
151         $git_exec = shell_exec('which git');
152         if(!preg_match('#git#', $git_exec)) {
153             $this->error(self::ERROR_CRITICAL, "git not installed locally.");
154             return;
155         }
156         
157         mkdir($this->workdir);
158         mkdir($this->workdir.'repository');
159         shell_exec('git clone '.escapeshellarg($this->giturl).' '.escapeshellarg($this->workdir.'repository'));
160         $gitok = $this->gitcmd("status");
161         if(preg_match("#Not a git repository#", $gitok)) {
162             rmdir($this->workdir.'repository');
163             rmdir($this->workdir);
164             $this->error(self::ERROR_CRITICAL, "error cloning git repository.");
165             return;
166         }
167         $this->ready = true;
168         
169         $default_branch = str_replace(array("\r", "\n"), array("", ""), $this->gitcmd("rev-parse", "--abbrev-ref", "HEAD"));
170         $this->setConfig("defaultbranch", $default_branch);
171         $this->saveConfig();
172     }
173     
174     private function getActiveBranch() {
175         if($this->activeSession)
176             return $this->activeSession;
177         else if(isset($_SESSION[self::SESSION_PREFIX.'branch']))
178             return $_SESSION[self::SESSION_PREFIX.'branch'];
179         else
180             return $this->getConfig("defaultbranch");
181     }
182     
183     private function setActiveBranch($branch, $remember) {
184         $this->activeSession = $branch;
185         if($remember)
186             $_SESSION[self::SESSION_PREFIX.'branch'] = $branch;
187     }
188     
189     private function getLocalUntrackedFiles() {
190         $default_branch = $this->getConfig("defaultbranch");
191         $tracked_files = $this->gitcmd("ls-tree", $default_branch, "--full-name", "--name-only");
192         $local_files = shell_exec("find ".escapeshellarg($this->localdir));
193         $untracked_files = array();
194         
195         $tracked_files = explode("\n", str_replace(array("\r"), array(""), $tracked_files));
196         $local_files = explode("\n", str_replace(array("\r"), array(""), $local_files));
197         
198         foreach($local_files as $local_file) {
199             if(!$local_file)
200                 continue;
201             if($strip_local || (($strip_local = strlen($this->localdir)) && substr($local_file, 0, $strip_local) == $this->localdir)) {
202                 $local_file = substr($local_file, $strip_local);
203             }
204             $tracked = false;
205             foreach($tracked_files as $tracked_file) {
206                 if($tracked_file == $local_file) {
207                     $tracked = true;
208                     break;
209                 }
210             }
211             if(!$tracked) {
212                 $untracked_files[] = $local_file;
213             }
214         }
215         return $untracked_files;
216     }
217     
218     private function branchExists($branch) {
219         //check if branch exists
220         $gitret = $this->gitcmd("rev-list", "--max-count=1", $branch);
221         if(!preg_match("#([a-z0-9]{40})#", $gitret, $match))
222             return false;
223         else
224             return $match[1];
225     }
226     
227     private function localBranchPath($branch, $create = false) {
228         $default_branch = $this->getConfig("defaultbranch");
229         if($branch == $default_branch)
230             $dir = $this->localdir;
231         else
232             $dir = $this->workdir.'branch_'.str_replace(array('/'), array('_'), $branch).'/';
233         if(file_exists($dir))
234             return $dir;
235         else if($create) {
236             mkdir($dir);
237             return $dir;
238         } else 
239             return false;
240     }
241     
242     private function updateBranch($branch, $path, $force = false) {
243         if(substr($path, -1) != '/')
244             $path .= '/';
245         $current_branch = str_replace(array("\r", "\n"), array("", ""), $this->gitcmd("rev-parse", "--abbrev-ref", "HEAD"));
246         if($current_branch != $branch)
247             $this->gitcmd("checkout", $branch);
248         $this->gitcmd("pull");
249         $gitret = $this->gitcmd("rev-list", "--max-count=1", $branch);
250         preg_match("#([a-z0-9]{40})#", $gitret, $match);
251         $newest_version = $match[1];
252         
253         $deleted_files = array();
254         if(($current_version = $this->getConfig('version_'.$branch))) {
255             if($current_version == $newest_version && !$force)
256                 return;
257             else {
258                 $override_all = true;
259                 $delfiles = $this->gitcmd("diff", "--diff-filter=D", "--name-only", $current_version, $newest_version);
260                 $delfiles = explode("\n", str_replace(array("\r"), array(""), $delfiles));
261                 foreach($delfiles as $file) {
262                     if(!$file)
263                         continue;
264                     $deleted_files[] = $file;
265                 }
266             }
267         } else
268             $override_all = true;
269         if($override_all) {
270             $rsync_present = preg_match("#rsync#", `which rsync`);
271             if($rsync_present)
272                 shell_exec('rsync -avz --exclude ".git" '.escapeshellarg($this->workdir."repository/").' '.escapeshellarg($path));
273             else
274                 shell_exec('tar -c --exclude ".git" -C '.escapeshellarg($this->workdir."repository").' . | tar -x -C '.escapeshellarg($path));
275             
276             // remove deleted files
277             foreach($deleted_files as $file) {
278                 unlink($path.$file);
279             }
280         }
281         $this->setConfig('version_'.$branch, $newest_version);
282         $this->saveConfig();
283     }
284     
285     /* public function update()
286     * Pulls latest commit of active branch and overwrites files in branch folder
287     */
288     public function update() {
289         if($this->loopedcall)
290             return;
291         
292         $active_branch = $this->getActiveBranch();
293         
294         if(!$this->branchExists($active_branch))
295             return false;
296         $dir = $this->localBranchPath($active_branch, true);
297         $this->updateBranch($active_branch, $dir);
298     }
299     
300     public function setBranch($branch, $remember = false) {
301         if($this->loopedcall)
302             return;
303         
304         if(!$this->branchExists($branch)) {
305             if(!$this->branchExists('origin/'.$branch))
306                 return false;
307         }
308         $this->setActiveBranch($branch, $remember);
309         
310         if(!$this->localBranchPath($branch)) {
311             $dir = $this->localBranchPath($branch, true);
312             $this->updateBranch($branch, $dir, true);
313         }
314     }
315     
316     public function execute($file = null) {
317         if($this->loopedcall)
318             return;
319         define("GITMANAGED_EXECUTED", true);
320         
321         if(!$file)
322             $file = $_SERVER['PHP_SELF'];
323         if($file[0] == '/')
324             $file = substr($file, 1);
325         
326         $default_branch = $this->getConfig("defaultbranch");
327         $active_branch = $this->getActiveBranch();
328         if($active_branch != $default_branch) {
329             if(!($dir = $this->localBranchPath($branch))) {
330                 $dir = $this->localBranchPath($active_branch, true);
331                 $this->updateBranch($active_branch, $dir, true);
332             }
333             chdir($dir);
334             include_once($dir.$file);
335         } else {
336             include($file); //possible loop!
337         }
338         die();
339     }
340     
341 }
342
343 ?>