ControllerBase.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. <?php
  2. /**
  3. * Base class that all controllers extend
  4. *
  5. * @author Christopher Han <xiphux@gmail.com
  6. * @copyright Copyright (c) 2010 Christopher Han
  7. * @package GitPHP
  8. * @subpackage Controller
  9. */
  10. abstract class GitPHP_ControllerBase
  11. {
  12. /**
  13. * Config handler instance
  14. *
  15. * @var GitPHP_Config
  16. */
  17. protected $config;
  18. /**
  19. * User list instance
  20. *
  21. * @var GitPHP_UserList
  22. */
  23. protected $userList;
  24. /**
  25. * Resource handler instance
  26. *
  27. * @var GitPHP_Resource
  28. */
  29. protected $resource;
  30. /**
  31. * Smarty instance
  32. *
  33. * @var Smarty
  34. */
  35. protected $tpl;
  36. /**
  37. * Project list
  38. *
  39. * @var GitPHP_ProjectListBase
  40. */
  41. protected $projectList;
  42. /**
  43. * Current project
  44. *
  45. * @var GitPHP_Project
  46. */
  47. protected $project;
  48. /**
  49. * Flag if this is a multi project controller
  50. *
  51. * @var boolean
  52. */
  53. protected $multiProject;
  54. /**
  55. * Parameters
  56. *
  57. * @var array
  58. */
  59. protected $params = array();
  60. /**
  61. * HTTP Headers
  62. *
  63. * @var string[]
  64. */
  65. protected $headers = array();
  66. /**
  67. * Flag to preserve whitespace in output (for non-html output)
  68. *
  69. * @var boolean
  70. */
  71. protected $preserveWhitespace = false;
  72. /**
  73. * Logger instance
  74. *
  75. * @var GitPHP_DebugLog
  76. */
  77. protected $log;
  78. /**
  79. * Git executable instance
  80. *
  81. * @var GitPHP_GitExe
  82. */
  83. protected $exe;
  84. /**
  85. * Url router instance
  86. *
  87. * @var GitPHP_Router
  88. */
  89. protected $router;
  90. /**
  91. * Initialize controller
  92. */
  93. public function Initialize()
  94. {
  95. $this->InitializeConfig();
  96. $this->InitializeResource();
  97. $this->InitializeUserList();
  98. $this->EnableLogging();
  99. $this->InitializeGitExe();
  100. $this->InitializeProjectList();
  101. $this->InitializeSmarty();
  102. if ($this->multiProject) {
  103. $this->projectList->LoadProjects();
  104. }
  105. if (!empty($this->params['project'])) {
  106. $project = $this->projectList->GetProject($this->params['project']);
  107. if (!$project) {
  108. throw new GitPHP_InvalidProjectParameterException($this->params['project']);
  109. }
  110. if ($this->userList && ($this->userList->GetCount() > 0)) {
  111. if (!$project->UserCanAccess((!empty($_SESSION['gitphpuser']) ? $_SESSION['gitphpuser'] : null))) {
  112. throw new GitPHP_UnauthorizedProjectException($this->params['project']);
  113. }
  114. }
  115. $this->project = $project->GetProject();
  116. }
  117. if (!($this->project || $this->multiProject)) {
  118. throw new GitPHP_MissingProjectParameterException();
  119. }
  120. }
  121. /**
  122. * Initialize config
  123. */
  124. protected function InitializeConfig()
  125. {
  126. $this->config = new GitPHP_Config();
  127. $this->config->LoadConfig(GITPHP_CONFIGDIR . 'gitphp.conf.php');
  128. }
  129. /**
  130. * Initialize resource manager
  131. */
  132. protected function InitializeResource()
  133. {
  134. $locale = null;
  135. $baseurl = GitPHP_Util::BaseUrl();
  136. if (empty($baseurl) && $this->config->GetValue('cleanurl'))
  137. $baseurl = '/';
  138. if (!empty($this->params['lang'])) {
  139. /*
  140. * User picked something
  141. */
  142. setcookie(GitPHP_Resource::LocaleCookie, $this->params['lang'], time()+GitPHP_Resource::LocaleCookieLifetime, $baseurl);
  143. $locale = $this->params['lang'];
  144. } else if (!empty($_COOKIE[GitPHP_Resource::LocaleCookie])) {
  145. /**
  146. * Returning user with a preference
  147. */
  148. $locale = $_COOKIE[GITPHP_Resource::LocaleCookie];
  149. } else {
  150. /*
  151. * User's first time here, try by HTTP_ACCEPT_LANGUAGE
  152. */
  153. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  154. $locale = GitPHP_Resource::FindPreferredLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
  155. if (!empty($locale)) {
  156. setcookie(GitPHP_Resource::LocaleCookie, $locale, time()+GitPHP_Resource::LocaleCookieLifetime, $baseurl);
  157. }
  158. }
  159. }
  160. if (empty($locale) && $this->config) {
  161. /*
  162. * No preference, fall back on setting
  163. */
  164. $locale = $this->config->GetValue('locale');
  165. }
  166. if (!empty($locale) && ($locale != 'en_US')) {
  167. try {
  168. $this->resource = new GitPHP_Resource($locale);
  169. } catch (Exception $e) {
  170. }
  171. }
  172. }
  173. /**
  174. * Initialize user list
  175. */
  176. public function InitializeUserList()
  177. {
  178. $this->userList = new GitPHP_UserList();
  179. $this->userList->LoadUsers(GITPHP_CONFIGDIR . 'users.conf.php');
  180. if ($this->userList->GetCount() > 0) {
  181. if (!isset($_SESSION))
  182. session_start();
  183. }
  184. }
  185. /**
  186. * Initialize executable
  187. *
  188. * @param boolean $validate whether the exe should be validated
  189. */
  190. protected function InitializeGitExe($validate = true)
  191. {
  192. $this->exe = new GitPHP_GitExe($this->config->GetValue('gitbin'));
  193. if ($this->log)
  194. $this->exe->AddObserver($this->log);
  195. if ($validate && !$this->exe->Valid()) {
  196. throw new GitPHP_InvalidGitExecutableException($this->exe->GetBinary());
  197. }
  198. }
  199. /**
  200. * Initialize project list
  201. */
  202. protected function InitializeProjectList()
  203. {
  204. if (file_exists(GITPHP_CONFIGDIR . 'projects.conf.php')) {
  205. $this->projectList = GitPHP_ProjectList::Instantiate($this->config, GITPHP_CONFIGDIR . 'projects.conf.php', false);
  206. } else {
  207. $this->projectList = GitPHP_ProjectList::Instantiate($this->config, GITPHP_CONFIGDIR . 'gitphp.conf.php', true);
  208. }
  209. $this->projectList->SetMemoryCache(new GitPHP_MemoryCache($this->config->GetValue('objectmemory')));
  210. if ($this->config->GetValue('objectcache')) {
  211. $strategy = null;
  212. $servers = $this->config->GetValue('memcache');
  213. if ($servers) {
  214. if (class_exists('Memcached')) {
  215. $strategy = new GitPHP_Cache_Memcached($servers);
  216. } else if (class_exists('Memcache')) {
  217. $strategy = new GitPHP_Cache_Memcache($servers);
  218. } else {
  219. throw new GitPHP_MissingMemcacheException();
  220. }
  221. } else {
  222. $strategy = new GitPHP_Cache_File(GITPHP_CACHEDIR . 'objects', $this->config->GetValue('objectcachecompress'));
  223. }
  224. $cache = new GitPHP_Cache($strategy);
  225. $cache->SetLifetime($this->config->GetValue('objectcachelifetime'));
  226. $this->projectList->SetCache($cache);
  227. }
  228. $this->projectList->SetExe($this->exe);
  229. if ($this->log)
  230. $this->projectList->AddObserver($this->log);
  231. }
  232. /**
  233. * Initialize smarty
  234. */
  235. protected function InitializeSmarty()
  236. {
  237. require_once(GITPHP_SMARTYDIR . 'Smarty.class.php');
  238. $this->tpl = new Smarty;
  239. $this->tpl->error_reporting = E_ALL & ~E_NOTICE;
  240. $this->tpl->merge_compiled_includes = true;
  241. $this->tpl->addPluginsDir(GITPHP_INCLUDEDIR . 'smartyplugins');
  242. if ($this->config->GetValue('cache')) {
  243. $cacheDir = GITPHP_CACHEDIR . 'templates';
  244. if (file_exists($cacheDir)) {
  245. if (!is_dir($cacheDir)) {
  246. throw new Exception($cacheDir . ' exists but is not a directory');
  247. } else if (!is_writable($cacheDir)) {
  248. throw new Exception($cacheDir . ' is not writable');
  249. }
  250. } else {
  251. if (!mkdir($cacheDir, 0777))
  252. throw new Exception($cacheDir . ' could not be created');
  253. chmod($cacheDir, 0777);
  254. }
  255. $this->tpl->setCacheDir($cacheDir);
  256. $this->tpl->caching = Smarty::CACHING_LIFETIME_SAVED;
  257. if ($this->config->HasKey('cachelifetime')) {
  258. $this->tpl->cache_lifetime = $this->config->GetValue('cachelifetime');
  259. }
  260. $servers = $this->config->GetValue('memcache');
  261. if (isset($servers) && is_array($servers) && (count($servers) > 0)) {
  262. $this->tpl->registerCacheResource('memcache', new GitPHP_CacheResource_Memcache($servers));
  263. $this->tpl->caching_type = 'memcache';
  264. }
  265. }
  266. }
  267. /**
  268. * Set router instance
  269. *
  270. * @param GitPHP_Router $router router
  271. */
  272. public function SetRouter($router)
  273. {
  274. $this->router = $router;
  275. }
  276. /**
  277. * Get config instance
  278. *
  279. * @return GitPHP_Config
  280. */
  281. public function GetConfig()
  282. {
  283. return $this->config;
  284. }
  285. /**
  286. * Get log instance
  287. *
  288. * @return GitPHP_DebugLog
  289. */
  290. public function GetLog()
  291. {
  292. return $this->log;
  293. }
  294. /**
  295. * Enable logging
  296. */
  297. public function EnableLogging()
  298. {
  299. if ($this->log)
  300. return;
  301. $debug = $this->config->GetValue('debug');
  302. if ($debug) {
  303. $this->log = GitPHP_DebugLog::GetInstance();
  304. $this->log->init($debug, $this->config->GetValue('benchmark'));
  305. $this->log->SetStartTime(GITPHP_START_TIME);
  306. $this->log->SetStartMemory(GITPHP_START_MEM);
  307. if ($this->exe)
  308. $this->exe->AddObserver($this->log);
  309. if ($this->projectList)
  310. $this->projectList->AddObserver($this->log);
  311. }
  312. }
  313. /**
  314. * Disable logging
  315. */
  316. protected function DisableLogging()
  317. {
  318. if (!$this->log)
  319. return;
  320. if ($this->projectList)
  321. $this->projectList->RemoveObserver($this->log);
  322. if ($this->exe)
  323. $this->exe->RemoveObserver($this->log);
  324. $this->log->SetEnabled(false);
  325. $this->log = null;
  326. }
  327. /**
  328. * Gets the project for this controller
  329. *
  330. * @return GitPHP_Project|null project
  331. */
  332. public function GetProject()
  333. {
  334. if ($this->project)
  335. return $this->projectList->GetProject($this->project);
  336. return null;
  337. }
  338. /**
  339. * Gets the template for this controller
  340. *
  341. * @return string template filename
  342. */
  343. protected abstract function GetTemplate();
  344. /**
  345. * Gets the cache key for this controller
  346. *
  347. * @return string cache key
  348. */
  349. protected abstract function GetCacheKey();
  350. /**
  351. * Get the prefix for all cache keys
  352. *
  353. * @param boolean $projectKeys include project-specific key pieces
  354. * @return string cache key prefix
  355. */
  356. private function GetCacheKeyPrefix($projectKeys = true)
  357. {
  358. if ($this->resource)
  359. $cacheKeyPrefix = $this->resource->GetLocale();
  360. else
  361. $cacheKeyPrefix = 'en_US';
  362. if ($this->projectList) {
  363. $cacheKeyPrefix .= '|' . sha1(serialize($this->projectList->GetProjectListConfig())) . '|' . sha1(serialize($this->projectList->GetProjectSettings()));
  364. }
  365. if ($this->project && $projectKeys) {
  366. $cacheKeyPrefix .= '|' . sha1($this->project);
  367. }
  368. return $cacheKeyPrefix;
  369. }
  370. /**
  371. * Get the full cache key
  372. *
  373. * @return string full cache key
  374. */
  375. protected function GetFullCacheKey()
  376. {
  377. $cacheKey = $this->GetCacheKeyPrefix();
  378. $subCacheKey = $this->GetCacheKey();
  379. if (!empty($subCacheKey))
  380. $cacheKey .= '|' . $subCacheKey;
  381. if (strlen($cacheKey) > 100) {
  382. $cacheKey = sha1($cacheKey);
  383. }
  384. return $cacheKey;
  385. }
  386. /**
  387. * Gets the name of this controller's action
  388. *
  389. * @param boolean $local true if caller wants the localized action name
  390. * @return string action name
  391. */
  392. public abstract function GetName($local = false);
  393. /**
  394. * Set a parameter
  395. *
  396. * @param string $key key to set
  397. * @param mixed $value value to set
  398. */
  399. public function SetParam($key, $value)
  400. {
  401. if (empty($key))
  402. return;
  403. if (empty($value))
  404. unset($this->params[$key]);
  405. if (is_string($value))
  406. $value = str_replace(chr(0), '', $value);
  407. $this->params[$key] = $value;
  408. }
  409. /**
  410. * Loads headers for this template
  411. */
  412. protected function LoadHeaders()
  413. {
  414. $this->headers[] = 'Content-Type: text/html; charset=UTF-8';
  415. }
  416. /**
  417. * Loads data for this template
  418. */
  419. protected abstract function LoadData();
  420. /**
  421. * Loads common data used by all templates
  422. */
  423. private function LoadCommonData()
  424. {
  425. global $gitphp_version, $gitphp_appstring;
  426. $this->tpl->assign('version', $gitphp_version);
  427. $stylesheet = $this->config->GetValue('stylesheet');
  428. if ($stylesheet == 'gitphp.css') {
  429. // backwards compatibility
  430. $stylesheet = 'gitphpskin.css';
  431. }
  432. $this->tpl->assign('stylesheet', preg_replace('/\.css$/', '', $stylesheet));
  433. $this->tpl->assign('javascript', $this->config->GetValue('javascript'));
  434. $this->tpl->assign('googlejs', $this->config->GetValue('googlejs'));
  435. if ($this->config->HasKey('title')) {
  436. $this->tpl->assign('pagetitle', $this->config->GetValue('title'));
  437. } else {
  438. $this->tpl->assign('pagetitle', $gitphp_appstring);
  439. }
  440. if ($this->config->HasKey('homelink')) {
  441. $this->tpl->assign('homelink', $this->config->GetValue('homelink'));
  442. } else {
  443. if ($this->resource)
  444. $this->tpl->assign('homelink', $this->resource->translate('projects'));
  445. else
  446. $this->tpl->assign('homelink', 'projects');
  447. }
  448. $this->tpl->assign('action', $this->GetName());
  449. $this->tpl->assign('actionlocal', $this->GetName(true));
  450. if ($this->project)
  451. $this->tpl->assign('project', $this->GetProject());
  452. if ($this->config->GetValue('search'))
  453. $this->tpl->assign('enablesearch', true);
  454. if ($this->config->GetValue('filesearch'))
  455. $this->tpl->assign('filesearch', true);
  456. if (isset($this->params['search']))
  457. $this->tpl->assign('search', $this->params['search']);
  458. if (isset($this->params['searchtype']))
  459. $this->tpl->assign('searchtype', $this->params['searchtype']);
  460. if ($this->resource) {
  461. $this->tpl->assign('currentlocale', $this->resource->GetLocale());
  462. $this->tpl->assign('currentprimarylocale', $this->resource->GetPrimaryLocale());
  463. $this->tpl->assign('resource', $this->resource);
  464. } else {
  465. $this->tpl->assign('currentlocale', 'en_US');
  466. $this->tpl->assign('currentprimarylocale', 'en');
  467. }
  468. $this->tpl->assign('supportedlocales', GitPHP_Resource::SupportedLocales(true));
  469. if ($this->config->GetValue('graphs'))
  470. $this->tpl->assign('enablegraphs', true);
  471. $this->tpl->assign('baseurl', GitPHP_Util::BaseUrl());
  472. $requesturl = $_SERVER['REQUEST_URI'];
  473. $querypos = strpos($requesturl, '?');
  474. if ($querypos !== false)
  475. $requesturl = substr($requesturl, 0, $querypos);
  476. $this->tpl->assign('requesturl', $requesturl);
  477. if ($this->router) {
  478. $this->router->SetCleanUrl($this->config->GetValue('cleanurl') ? true : false);
  479. $this->router->SetAbbreviate($this->config->GetValue('abbreviateurl') ? true : false);
  480. if ($this->config->GetValue('self')) {
  481. $this->router->SetBaseUrl($this->config->GetValue('self'));
  482. }
  483. $this->tpl->assign('router', $this->router);
  484. }
  485. $getvars = array();
  486. if (isset($_SERVER['QUERY_STRING'])) {
  487. $getvars = explode('&', $_SERVER['QUERY_STRING']);
  488. }
  489. $getvarsmapped = array();
  490. foreach ($getvars as $varstr) {
  491. $eqpos = strpos($varstr, '=');
  492. if ($eqpos > 0) {
  493. $var = substr($varstr, 0, $eqpos);
  494. $val = substr($varstr, $eqpos + 1);
  495. if (!(empty($var) || empty($val) || ($var == 'q'))) {
  496. $getvarsmapped[$var] = urldecode($val);
  497. }
  498. }
  499. }
  500. $this->tpl->assign('requestvars', $getvarsmapped);
  501. $this->tpl->assign('snapshotformats', GitPHP_Archive::SupportedFormats());
  502. if ($this->userList && ($this->userList->GetCount() > 0)) {
  503. $this->tpl->assign('loginenabled', true);
  504. if (!empty($_SESSION['gitphpuser'])) {
  505. $user = $this->userList->GetUser($_SESSION['gitphpuser']);
  506. if ($user) {
  507. $this->tpl->assign('loggedinuser', $user->GetUsername());
  508. }
  509. }
  510. }
  511. if ($this->log && $this->log->GetEnabled()) {
  512. $this->tpl->assign('debug', true);
  513. }
  514. }
  515. /**
  516. * Renders any special headers
  517. */
  518. public function RenderHeaders()
  519. {
  520. $this->LoadHeaders();
  521. if (count($this->headers) > 0) {
  522. $hascontenttype = false;
  523. foreach ($this->headers as $hdr) {
  524. if (empty($hdr))
  525. continue;
  526. if (strncmp($hdr, 'Content-Type:', 13) === 0) {
  527. if ($hascontenttype)
  528. throw new Exception('Duplicate Content-Type header');
  529. $hascontenttype = true;
  530. }
  531. header($hdr);
  532. }
  533. }
  534. }
  535. /**
  536. * Renders the output
  537. */
  538. public function Render()
  539. {
  540. if (($this->config->GetValue('cache') == true) && ($this->config->GetValue('cacheexpire') === true))
  541. $this->CacheExpire();
  542. $log = GitPHP_DebugLog::GetInstance();
  543. if (!$this->tpl->isCached($this->GetTemplate(), $this->GetFullCacheKey())) {
  544. $this->tpl->clearAllAssign();
  545. $log->TimerStart();
  546. $this->LoadCommonData();
  547. $log->TimerStop('Common data');
  548. $log->TimerStart();
  549. $this->LoadData();
  550. $log->TimerStop('Data');
  551. }
  552. if (!$this->preserveWhitespace) {
  553. //$this->tpl->loadFilter('output', 'trimwhitespace');
  554. }
  555. $log->TimerStart();
  556. $this->tpl->display($this->GetTemplate(), $this->GetFullCacheKey());
  557. $log->TimerStop('Render');
  558. $this->tpl->clearAllAssign();
  559. if ($this->projectList)
  560. $log->Log('MemoryCache', 'Count: ' . $this->projectList->GetMemoryCache()->GetCount());
  561. if ($log->GetEnabled()) {
  562. $this->tpl->assign('debuglog', $log);
  563. $this->tpl->display('debug.tpl');
  564. }
  565. }
  566. /**
  567. * Expires the cache
  568. *
  569. * @param boolean $expireAll expire the whole cache
  570. */
  571. public function CacheExpire($expireAll = false)
  572. {
  573. if ($expireAll) {
  574. $this->tpl->clearAllCache();
  575. return;
  576. }
  577. if (!$this->project)
  578. return;
  579. $epoch = $this->GetProject()->GetEpoch();
  580. if (empty($epoch))
  581. return;
  582. $age = $this->GetProject()->GetAge();
  583. $this->tpl->clearCache(null, $this->GetCacheKeyPrefix(), null, $age);
  584. $this->tpl->clearCache('projectlist.tpl', $this->GetCacheKeyPrefix(false), null, $age);
  585. }
  586. }