Example #1
0
 /**
  * Rebuild caches, indexes, etc.
  */
 static function rebuild($forceFullRebuild = false)
 {
     gb::log(LOG_NOTICE, 'rebuilding cache' . ($forceFullRebuild ? ' (forcing full rebuild)' : ''));
     $time_started = microtime(1);
     $failures = array();
     # Load rebuild plugins
     gb::load_plugins('rebuild');
     # Load rebuilders if needed
     if (empty(self::$rebuilders)) {
         self::loadRebuilders();
     }
     # Create rebuilder instances
     $rebuilders = array();
     foreach (self::$rebuilders as $cls) {
         $rebuilders[] = new $cls($forceFullRebuild);
     }
     # Load rebuild plugins (2nd offer)
     gb::load_plugins('rebuild');
     # Query ls-tree
     $ls = rtrim(git::exec('ls-files --stage'));
     if ($ls) {
         # Iterate objects
         $ls = explode("\n", $ls);
         foreach ($ls as $line) {
             try {
                 # <mode> SP <object> SP <stage no> TAB <name>
                 if (!$line) {
                     continue;
                 }
                 $line = explode(' ', $line, 3);
                 $id = $line[1];
                 $name = gb_normalize_git_name(substr($line[2], strpos($line[2], "\t") + 1));
                 foreach ($rebuilders as $rebuilder) {
                     $rebuilder->onObject($name, $id);
                 }
             } catch (RuntimeException $e) {
                 gb::log(LOG_ERR, 'failed to rebuild object %s %s: %s', var_export($name, 1), $e->getMessage(), $e->getTraceAsString());
                 $failures[] = array($rebuilder, $name);
             }
         }
     }
     # Let rebuilders finalize
     foreach ($rebuilders as $rebuilder) {
         try {
             $rebuilder->finalize();
         } catch (RuntimeException $e) {
             gb::log(LOG_ERR, 'rebuilder %s (0x%x) failed to finalize: %s', get_class($rebuilder), spl_object_hash($rebuilder), GBException::format($e, true, false, null, 0));
             $failures[] = array($rebuilder, null);
         }
     }
     gb::log(LOG_NOTICE, 'cache updated -- time spent: %s', gb_format_duration(microtime(1) - $time_started));
     return $failures;
 }
<?php

require_once "../../classes/git.class.php";
$git = new git();
$git->download();
?>

Example #3
0
File: git.php Project: rsms/gitblog
 /** Retrieve ids for $pathspec (string or array of strings) at the current branch head */
 static function id_for_pathspec($pathspec)
 {
     if (is_string($pathspec)) {
         return trim(git::exec('rev-parse ' . escapeshellarg(':' . $pathspec)));
     }
     if (!is_array($pathspec)) {
         throw new InvalidArgumentException('$pathspec is ' . gettype($pathspec));
     }
     # array
     $pathspec_to_id = array();
     foreach ($pathspec as $k => $s) {
         $pathspec[$k] = escapeshellarg(':' . $s);
     }
     $lines = explode("\n", trim(git::exec('rev-parse ' . implode(' ', $pathspec))));
     $i = 0;
     foreach ($pathspec as $s) {
         $pathspec_to_id[$s] = $lines[$i++];
     }
     return $pathspec_to_id;
 }
<?php

require_once "../../classes/git.class.php";
$git = new git();
$git->commit();
?>

<?php

require_once "../../classes/git.class.php";
$git = new git();
$git->checkoutDownload();
<?php

require_once "../../classes/git.class.php";
$git = new git();
$git->checkout();
<?php

require_once "../../classes/git.class.php";
$git = new git();
$git->upload();
Example #8
0
# prepare for rendering
gb::$title[] = 'Setup';
$is_writable = is_writable(gb::$site_dir);
if (!$is_writable) {
    gb::$errors[] = '<b>Ooops.</b> The directory <code>' . h(gb::$site_dir) . '</code> is not writable.
		Gitblog need to create a few files in this directory.
		<br/><br/>
		Please make this directory (highlighted above) writable and then reload this page.';
    # todo: check if the web server user and/or is the same as user and/or group
    #       on directory. If so, suggest a chmod, otherwise suggest a chown.
}
if (!isset($_POST['email'])) {
    $_POST['email'] = git::config('user.email');
}
if (!isset($_POST['name'])) {
    $_POST['name'] = git::config('user.name');
}
include '_header.php';
?>
<script type="text/javascript" charset="utf-8">
	$(function(){
		$('input[name=email]').focus();
	});
</script>
<div id="content" class="setup margins">
	<h2>Setup your gitblog</h2>
	<p>
		It's time to setup your new gitblog.
	</p>
	<form action="setup.php" method="post">
	
Example #9
0
 /** Batch-reload objects */
 function reloadObjects($objects)
 {
     $names = array();
     $ids = array();
     # Demux
     foreach ($objects as $id => $obj) {
         $names[] = $obj->name;
         $ids[] = $id;
     }
     # Load commits
     $commits = GitCommit::find(array('names' => $names, 'mapnamestoc' => true));
     $commitsbyname = $commits[2];
     # Load blobs
     $out = git::exec("cat-file --batch", implode("\n", $ids));
     $p = 0;
     $numobjects = count($objects);
     # Parse object blobs
     for ($i = 0; $i < $numobjects; $i++) {
         # <id> SP <type> SP <size> LF
         # <contents> LF
         $hend = strpos($out, "\n", $p);
         $h = explode(' ', substr($out, $p, $hend - $p));
         $size = 0;
         $data = null;
         $dstart = $hend + 1;
         if ($h[1] === 'missing') {
             throw new UnexpectedValueException('missing blob ' . $obj->id . ' ' . var_export($obj->name, 1) . ' in repo stage');
         }
         $obj = $objects[$h[0]];
         $size = intval($h[2]);
         $data = substr($out, $dstart, $size);
         $obj->reload($data, isset($commitsbyname[$obj->name]) ? $commitsbyname[$obj->name] : array());
         $p = $dstart + $size + 1;
     }
 }
Example #10
0
 function rawBody($data = null)
 {
     if ($this->_rawBody === null) {
         if ($data === null) {
             if ($this->isWorkVersion()) {
                 $data = file_get_contents(gb::$site_dir . '/' . $this->name);
             } else {
                 $data = git::cat_file($this->id);
             }
         }
         $p = self::findHeaderTerminatorOffset($data);
         if ($p === false) {
             return '';
         }
         $this->_rawBody = substr($data, $p);
     }
     return $this->_rawBody;
 }
<?php

require_once "../../classes/git.class.php";
$git = new git();
$git->branch();
header("location:/controllers/mail.php?flag=branch");
Example #12
0
gb::$title[] = 'Posts';
include '../_header.php';
$muxed_posts = array();
class st
{
    const STAGED = 't';
    const UNSTAGED = 'c';
    const UNTRACKED = 'u';
    const DRAFT = 'd';
    const SCHEDULED = 's';
    const MODIFIED = 'm';
    const REMOVED = 'r';
    const RENAMED = 'e';
    const ADDED = 'a';
}
$st = git::status();
function _mkflags($post, $status = '')
{
    $flags = '';
    if ($post->draft) {
        $flags .= st::DRAFT;
    }
    switch ($status) {
        # added'|'modified'|'deleted renamed
        case 'added':
            $flags .= st::ADDED;
            break;
        case 'modified':
            $flags .= st::MODIFIED;
            break;
        case 'deleted':
Example #13
0
 function rollback($strict = true)
 {
     if ($this->txFp === false) {
         if ($strict) {
             throw new LogicException('transaction is not active');
         }
         return false;
     }
     if ($this->autocommitToRepo) {
         try {
             git::reset($this->file);
         } catch (Exception $y) {
         }
     }
     return $this->txEnd();
 }
Example #14
0
    static function _000104($from, $to)
    {
        $datadir = gb::$site_dir . '/data/';
        $added = array();
        # create data/
        if (!file_exists($datadir)) {
            gb::log('creating directory %s', $datadir);
            mkdir($datadir, 0775);
            chmod($datadir, 0775);
        }
        # load old site.json
        gb::log('loading %s', gb::$site_dir . '/site.json');
        gb::$site_state = is_readable(gb::$site_dir . '/site.json') ? json_decode(file_get_contents(gb::$site_dir . '/site.json'), true) : array();
        # move site.json:plugins to data/plugins.json
        $plugins = isset(gb::$site_state['plugins']) ? gb::$site_state['plugins'] : array();
        gb::log('creating data:plugins');
        gb::data('plugins')->storage()->set($plugins);
        unset(gb::$site_state['plugins']);
        # write data/site.json
        gb::log('moving %s -> data:site', gb::$site_dir . '/site.json');
        # gb_maint::sync_site_state() will be called after this method returns
        @unlink(gb::$site_dir . '/site.json');
        # remove /site.json from .gitignore
        if (gb_maint::gitignore_sub('/(?:\\r?\\n)\\/site\\.json([\\t\\s \\r\\n]+|^)/m', '$1')) {
            gb::log('removed "/site.json" from .gitignore');
            $added[] = git::add('.gitignore');
        }
        # load settings.json
        gb::log('loading %s', gb::$site_dir . '/settings.json');
        $settings = is_readable(gb::$site_dir . '/settings.json') ? json_decode(file_get_contents(gb::$site_dir . '/settings.json'), true) : array();
        # move settings.json:* to data/plugins/*
        foreach ($settings as $pluginn => $d) {
            if (!is_array($d)) {
                $d = $d !== null ? array($d) : array();
            }
            if ($d) {
                gb::log('copying %s:%s -> data:plugins/%s', gb::$site_dir . '/settings.json', $pluginn, $pluginn);
                gb::data('plugins/' . $pluginn)->storage()->set($d);
            }
        }
        gb::log('removing old %s', gb::$site_dir . '/settings.json');
        @unlink(gb::$site_dir . '/settings.json');
        # load gb-users.php
        $users = array();
        if (is_readable(gb::$site_dir . '/gb-users.php')) {
            gb::log('loading %s', gb::$site_dir . '/gb-users.php');
            eval('class GBUserAccount {
				static function __set_state($state) {
					return GBUser::__set_state($state);
				}
			}');
            require gb::$site_dir . '/gb-users.php';
            if (isset($db)) {
                $admin = isset($db['_admin']) ? $db['_admin'] : '';
                foreach ($db as $email => $user) {
                    if (is_object($user)) {
                        $user->admin = $email === $admin;
                        $users[$email] = $user;
                        gb::log('transponded user %s', $email);
                    }
                }
            }
        }
        # move gb-users.php to data/users.json
        gb::log('moving %s -> data:users', gb::$site_dir . '/gb-users.php');
        GBUser::storage()->set($users);
        @unlink(gb::$site_dir . '/gb-users.php');
        # commit any modifications
        if ($added) {
            try {
                git::commit('upgrade 0.1.4 modified ' . implode(', ', $added), GBUser::findAdmin()->gitAuthor(), $added);
            } catch (GitError $e) {
                if (strpos($e->getMessage(), 'no changes added to commit') === false) {
                    throw $e;
                }
            }
        }
    }
Example #15
0
        foreach ($state_fields as $k => $discard) {
            if ($k === 'body') {
                $modified_state[$k] = $post->rawBody();
            } else {
                $v = $post->{$k};
                if ($v instanceof GBDateTime) {
                    $v = strval($v);
                }
                $modified_state[$k] = $v;
            }
        }
    }
    # commit?
    if ($input['commit']) {
        git::add($post->name);
        git::commit(($created ? 'Created' : 'Updated') . ' post ' . r($post->title), gb::$authorized, $post->name);
    }
    # build response entity
    $rsp = array('name' => $post->name, 'version' => $post->id, 'exists' => $post->exists(), 'isTracked' => $post->isTracked(), 'isDirty' => $post->isDirty(), 'state' => $modified_state);
    # status
    $status = '200 OK';
    if ($created) {
        $status = '201 Created';
    }
    # send JSON response
    gb_admin::json_rsp($rsp, $status);
    gb::log('saved post %s', $post->name);
} catch (Exception $e) {
    gb::log('failed to save post: %s', GBException::format($e, true, false, null, 0));
    gb_admin::json_rsp($e->getMessage(), '400 Bad Request');
}
Example #16
0
 function writeComments(GBExposedContent $obj)
 {
     if (!$obj->comments) {
         return;
     }
     # sort
     ksort($obj->comments);
     # init comments db
     $cdb = $obj->getCommentsDB();
     $cdb->autocommitToRepo = false;
     $cdb->begin(true);
     try {
         foreach ($obj->comments as $comment) {
             $cdb->append($comment);
         }
     } catch (Exception $e) {
         $cdb->rollback();
         throw $e;
     }
     $cdb->commit();
     git::add($cdb->file);
 }
Example #17
0
 static function sync_site_state()
 {
     ignore_user_abort(true);
     # verify repo setup, which also makes sure the repo setup (hooks, config,
     # etc) is up to date:
     self::repair_repo_setup();
     # assure gitblog submodule is set up
     $dotgitmodules = gb::$site_dir . '/.gitmodules';
     if (!is_file($dotgitmodules) || !preg_match('/\\[submodule[\\s\\t ]+"gitblog"\\]/', file_get_contents($dotgitmodules))) {
         self::add_gitblog_submodule();
     }
     # read id of HEAD and current branch
     $gb_branch = 'master';
     $gb_head = '0000000000000000000000000000000000000000';
     try {
         $branches = trim(git::exec('branch --no-abbrev --verbose --no-color', null, gb::$dir . '/.git', gb::$dir));
         foreach (explode("\n", $branches) as $line) {
             if (!$line) {
                 continue;
             }
             if ($line[0] === '*') {
                 if (strpos($line, '(no branch)') !== false) {
                     $line = preg_split('/[ \\t]+/', $line, 5);
                     $gb_branch = null;
                     $gb_head_id = $line[3];
                 } else {
                     $line = preg_split('/[ \\t]+/', $line, 4);
                     $gb_branch = $line[1];
                     $gb_head_id = $line[2];
                 }
                 break;
             }
         }
     } catch (GitError $e) {
         gb::log(LOG_WARNING, 'failed to read branch info for gitblog -- git: %s', $e->getMessage());
     }
     # no previous state?
     if (!gb::$site_state) {
         gb::$site_state = array();
     }
     # Set current values
     gb::$site_state['url'] = gb::$site_url;
     gb::$site_state['version'] = gb::$version;
     gb::$site_state['posts_pagesize'] = gb::$posts_pagesize;
     # appeard in 0.1.3:
     gb::$site_state['gitblog'] = array('branch' => $gb_branch, 'head' => $gb_head_id);
     # Write site url for hooks
     $bytes_written = file_put_contents(gb::$site_dir . '/.git/info/gitblog-site-url', gb::$site_url, LOCK_EX);
     # Encode site.json
     $json = json::pretty(gb::$site_state) . "\n";
     $path = gb::$site_dir . '/data/site.json';
     # create data/ ?
     if (!is_dir(gb::$site_dir . '/data')) {
         mkdir(gb::$site_dir . '/data', 0775);
         chmod(gb::$site_dir . '/data', 0775);
     }
     # Write site.json
     $bytes_written += file_put_contents($path, $json, LOCK_EX);
     chmod($path, 0664);
     gb::log(LOG_NOTICE, 'wrote site state to %s (%d bytes)', $path, $bytes_written);
     return $bytes_written;
 }
Example #18
0
 /** Returns array($commits, $existing, $ntoc) */
 static function find($kwargs = null)
 {
     static $defaultkwargs = array('names' => null, 'treeish' => 'HEAD', 'limit' => -1, 'sortrcron' => true, 'detectRC' => true, 'mapnamestoc' => false);
     $kwargs = $kwargs ? array_merge($defaultkwargs, $kwargs) : $defaultkwargs;
     $commits = array();
     $existing = array();
     # tracks existing files
     $ntoc = $kwargs['mapnamestoc'] ? array() : null;
     $cmd = "log --name-status --pretty='format:" . self::$logFormat . "' " . "--encoding=UTF-8 --date=iso --dense";
     # do not sort reverse chronological
     $rcron = $kwargs['sortrcron'];
     if (!$rcron) {
         $cmd .= ' --reverse';
     }
     # detect renames and copies
     if ($kwargs['detectRC']) {
         $cmd .= ' -C';
     } else {
         $cmd .= ' --no-renames';
     }
     # limit
     if ($kwargs['limit'] > 0) {
         $cmd .= " --max-count=" . $kwargs['limit'];
     }
     # treeish
     $cmd .= " " . $kwargs['treeish'] . " -- ";
     # filter object names
     if ($kwargs['names']) {
         $cmd .= implode(' ', array_map('escapeshellarg', $kwargs['names']));
     }
     #var_dump($cmd);
     $out = git::exec($cmd);
     #var_dump($out);
     $a = 0;
     $len = strlen($out);
     while ($a !== false && $a <= $len) {
         $c = new self();
         foreach (self::$fields as $field) {
             if ($field == 'message') {
                 $b = strpos($out, "", $a);
             } else {
                 $b = strpos($out, "\n", $a);
             }
             if ($b === false) {
                 break;
             }
             if (substr($field, -4) == 'Date') {
                 $c->{$field} = new GBDateTime(substr($out, $a, $b - $a));
             } else {
                 $c->{$field} = substr($out, $a, $b - $a);
             }
             $a = $b + 1;
         }
         if ($b === false) {
             break;
         }
         $b = strpos($out, "\n\n", $a);
         $files = $b === false ? substr($out, $a) : substr($out, $a, $b - $a);
         $files = explode("\n", trim($files));
         $c->files = array();
         foreach ($files as $line) {
             $line = explode("\t", $line);
             if (count($line) < 2) {
                 continue;
             }
             $t = $line[0][0];
             $name = gb_normalize_git_name($line[1]);
             $previousName = null;
             # R|C have two names wherether the last is the new name
             if ($t === GitPatch::RENAME || $t === GitPatch::COPY) {
                 $previousName = $name;
                 $name = $line[2];
                 if ($c->previousFiles === null) {
                     $c->previousFiles = array($previousName);
                 } else {
                     $c->previousFiles[] = $previousName;
                 }
             }
             # add to files[tag] => [name, ..]
             if (isset($c->files[$t])) {
                 $c->files[$t][] = $name;
             } else {
                 $c->files[$t] = array($name);
             }
             # if kwarg mapnamestoc == true
             if ($ntoc !== null) {
                 if (!isset($ntoc[$name])) {
                     $ntoc[$name] = array($c);
                 } else {
                     $ntoc[$name][] = $c;
                 }
             }
             # update cached objects
             #if (isset($repo->objectCacheByName[$name])) {
             #	$obj = $repo->objectCacheByName[$name];
             #	if ($obj->_commit === null)
             #		$obj->_commit = $c;
             #}
             # update existing
             if (!$rcron) {
                 if ($t === GitPatch::CREATE || $t === GitPatch::COPY) {
                     $existing[$name] = $c;
                 } elseif ($t === GitPatch::DELETE && isset($existing[$name])) {
                     unset($existing[$name]);
                 } elseif ($t === GitPatch::RENAME) {
                     if (isset($existing[$previousName])) {
                         # move original CREATE
                         $existing[$name] = $existing[$previousName];
                         unset($existing[$previousName]);
                     } else {
                         $existing[$name] = $c;
                     }
                     # move commits from previous file if kwarg mapnamestoc == true
                     if ($ntoc !== null && isset($ntoc[$previousName])) {
                         $ntoc[$name] = array_merge($ntoc[$previousName], $ntoc[$name]);
                         unset($ntoc[$previousName]);
                     }
                 }
             }
         }
         $commits[$c->id] = $c;
         if ($b === false) {
             break;
         }
         $a = $b + 2;
     }
     return array($commits, $existing, $ntoc);
 }