DefaultPlugin.php 9.6 KB
Newer Older
1 2
<?php
/*
3
Copyright (C) 2014-2016, Siemens AG
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Author: Andreas Würl

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

namespace Fossology\Lib\Plugin;

22
use Fossology\Lib\Auth\Auth;
23
use Fossology\Lib\UI\Component\Menu;
24
use Fossology\Lib\UI\Component\MicroMenu;
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
use Monolog\Logger;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Twig_Environment;

abstract class DefaultPlugin implements Plugin
{
  const PERMISSION = "permission";
  const REQUIRES_LOGIN = "requiresLogin";
  const ENABLE_MENU = "ENABLE_MENU";
  const LEVEL = "level";
  const DEPENDENCIES = "dependencies";
  const INIT_ORDER = "initOrder";
  const MENU_LIST = "menuList";
  const MENU_ORDER = "menuOrder";
  const MENU_TARGET = "menuTarget";
  const TITLE = "title";
44

45 46 47 48 49 50 51 52 53 54
  /** @var ContainerBuilder */
  protected $container;
  /** @var Twig_Environment */
  protected $renderer;
  /** @var Session */
  private $session;
  /** @var Logger */
  private $logger;
  /** @var Menu */
  private $menu;
55 56
  /** @var MicroMenu */
  protected $microMenu;
57 58 59 60 61 62 63
  /** @var string */
  private $name;
  /** @var string */
  private $version = "1.0";
  /** @var string */
  private $title;
  /** @var int */
64
  private $permission = Auth::PERM_NONE;
65 66 67 68 69 70 71 72 73 74 75 76 77 78
  /** @var int */
  private $requiresLogin = true;
  /** @var int */
  private $PluginLevel = 10;
  /** @var array */
  private $dependencies = array();
  private $InitOrder = 0;

  private $MenuList = NULL;
  private $MenuOrder = 0;
  private $MenuTarget = NULL;

  public function __construct($name, $parameters = array())
  {
79
    if ($name === null || $name === "") {
80 81 82
      throw new \InvalidArgumentException("plugin requires a name");
    }
    $this->name = $name;
83
    foreach ($parameters as $key => $value) {
84
      $this->setParameter($key, $value);
85 86 87 88 89 90 91 92
    }

    global $container;
    $this->container = $container;
    $this->session = $this->getObject('session');
    $this->renderer = $this->getObject('twig.environment');
    $this->logger = $this->getObject('logger');
    $this->menu = $this->getObject('ui.component.menu');
93
    $this->microMenu = $this->getObject('ui.component.micromenu');
94 95 96 97
  }

  private function setParameter($key, $value)
  {
98
    switch ($key) {
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
      case self::TITLE:
        $this->title = $value;
        break;

      case self::PERMISSION:
        $this->permission = $value;
        break;

      case self::REQUIRES_LOGIN:
        $this->requiresLogin = $value;
        break;

      case self::LEVEL:
        $this->PluginLevel = $value;
        break;

      case self::DEPENDENCIES:
        $this->dependencies = $value;
        break;

      case self::INIT_ORDER:
        $this->InitOrder = $value;
        break;

      case self::MENU_LIST:
        $this->MenuList = $value;
        break;

      case self::MENU_ORDER:
        $this->MenuOrder = $value;
        break;

      case self::MENU_TARGET:
        $this->MenuTarget = $value;
        break;

      default:
        throw new \Exception("unhandled parameter $key in module " . $this->name);
    }
  }

  /**
   * @return string
   */
  public function getName()
  {
    return $this->name;
  }

  /**
   * @return string
   */
  public function getVersion()
  {
    return $this->version;
  }

  /**
   * @return string
   */
  public function getTitle()
  {
    return $this->title;
  }

  /**
   * @return int
   */
  public function isRequiresLogin()
  {
    return $this->requiresLogin;
  }

  /**
   * @return array
   */
  public function getDependency()
  {
    return $this->dependencies;
  }

  /**
   * @return int
   */
  public function getPluginLevel()
  {
    return $this->PluginLevel;
  }

  /**
   * @return int
   */
  public function getDBaccess()
  {
    return $this->permission;
  }

  /**
   * @return int
   */
  public function getState()
  {
    return PLUGIN_STATE_READY;
  }

  /**
   * @return int
   */
  public function getInitOrder()
  {
    return $this->InitOrder;
  }


  public function getNoMenu()
  {
    return 0;
  }

  /**
   * \brief Customize submenus.
   */
  protected function RegisterMenus()
  {
223
    if (isset($this->MenuList) && (!$this->requiresLogin || $this->isLoggedIn())) {
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
      menu_insert("Main::" . $this->MenuList, $this->MenuOrder, $this->name, $this->name);
    }
  }

  /**
   * @return Response
   */
  public function getResponse()
  {
    $request = Request::createFromGlobals();
    $request->setSession($this->session);

    $this->checkPrerequisites();

    $startTime = microtime(true);
    $response = $this->handle($request);
    $response->prepare($request);
    $this->logger->debug(sprintf("handle request in %.3fs", microtime(true) - $startTime));
    return $response;
  }

  /**
   * @param $name
   * @return object
   */
  public function getObject($name)
  {
    return $this->container->get($name);
  }

  public function preInstall()
  {
    $this->RegisterMenus();
  }

  public function postInstall()
  {
  }

  public function unInstall()
  {
  }

  public function execute()
  {
    $startTime = microtime(true);

    $response = $this->getResponse();

    $this->logger->debug(sprintf("prepare response in %.3fs", microtime(true) - $startTime));

    $response->send();
  }

  /**
   * @param Request $request
   * @return Response
   */
  protected abstract function handle(Request $request);

  /**
   * @param string $templateName
   * @param array $vars
   * @param string[] $headers
   * @return Response
   */
  protected function render($templateName, $vars = null, $headers = null)
  {
292
    if ($this->requiresLogin && !$this->isLoggedIn()) {
293 294 295
      new Response("permission denied", Response::HTTP_FORBIDDEN, array("contentType" => "text/plain"));
    }

296 297 298 299 300 301 302 303 304 305 306 307 308
    $startTime = microtime(true);

    $content = $this->renderer->loadTemplate($templateName)
        ->render($vars ?: $this->getDefaultVars());

    $this->logger->debug(sprintf("%s: render response in %.3fs", get_class($this), microtime(true) - $startTime));
    return new Response(
        $content,
        Response::HTTP_OK,
        $headers ?: $this->getDefaultHeaders()
    );
  }

309 310
  public function isLoggedIn()
  {
311
    return (!empty($_SESSION[Auth::USER_NAME]) && $_SESSION[Auth::USER_NAME] != 'Default User');
312 313
  }

314 315
  private function checkPrerequisites()
  {
316
    if ($this->requiresLogin && !$this->isLoggedIn()) {
317 318 319
      throw new \Exception("not allowed without login");
    }

320
    foreach ($this->dependencies as $dependency) {
321
      $id = plugin_find_id($dependency);
322
      if ($id < 0) {
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
        $this->unInstall();
        throw new \Exception("unsatisfied dependency '$dependency' in module '" . $this->getName() . "'");
      }
    }
  }

  /**
   * @return array
   */
  protected function getDefaultHeaders()
  {
    return array(
        'Content-type' => 'text/html',
        'Pragma' => 'no-cache',
        'Cache-Control' => 'no-cache, must-revalidate, maxage=1, post-check=0, pre-check=0',
        'Expires' => 'Expires: Thu, 19 Nov 1981 08:52:00 GMT');
  }

  /**
   * @return array
   */
  protected function getDefaultVars()
  {
    $vars = array();

    $metadata = "<meta name='description' content='The study of Open Source'>\n";
    $metadata .= "<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'>\n";

    $vars['metadata'] = $metadata;

353
    if (!empty($this->title)) {
354 355 356
      $vars[self::TITLE] = htmlentities($this->title);
    }

357 358
    $styles = "<link rel='stylesheet' href='/javascript/jquery-ui/themes/base/jquery-ui.css'>\n";
    $styles .= "<link rel='stylesheet' href='/javascript/select2.js/select2.css'>\n";
359
    $styles .= "<link rel='stylesheet' href='css/jquery.dataTables.css'>\n";
360
    $styles .= "<link rel='stylesheet' href='css/fossology.css'>\n";
361 362 363 364 365 366 367 368 369 370
    $styles .= "<link rel='icon' type='image/x-icon' href='favicon.ico'>\n";
    $styles .= "<link rel='shortcut icon' type='image/x-icon' href='favicon.ico'>\n";

    $styles .= $this->menu->OutputCSS();

    $vars['styles'] = $styles;

    $vars['menu'] = $this->menu->Output($this->title);

    global $SysConf;
371 372 373 374
    if (array_key_exists('BUILD', $SysConf)) {
      $vars['versionInfo'] = array(
          'version' => $SysConf['BUILD']['VERSION'],
          'buildDate' => $SysConf['BUILD']['BUILD_DATE'],
375
          'commitHash' => $SysConf['BUILD']['COMMIT_HASH'],
376 377
          'commitDate' => $SysConf['BUILD']['COMMIT_DATE'],
          'branchName' => $SysConf['BUILD']['BRANCH']
378 379
      );
    }
380 381 382 383 384 385 386 387 388

    return $vars;
  }

  protected function mergeWithDefault($vars)
  {
    return array_merge($this->getDefaultVars(), $vars);
  }

389 390 391 392
  protected function flushContent($content)
  {
    return $this->render("include/base.html.twig",$this->mergeWithDefault(array("content"=>$content)));
  }
393

394 395 396 397 398 399 400
  /**
   * @param string $name
   * @throws \Exception
   * @return string|null
   */
  public function __get($name)
  {
401
    if (method_exists($this, ($method = 'get' . ucwords($name)))) {
402
      return $this->$method();
403
    } else {
404 405 406 407 408 409 410 411
      throw new \Exception("property '$name' not found in module " . $this->name);
    }
  }

  function __toString()
  {
    return getStringRepresentation(get_object_vars($this), get_class($this));
  }
412
}