Skip to content
Snippets Groups Projects
startup.php 12.83 KiB
<?php
/**
 * Copyright (c) 2012, Agence Française Informatique (AFI). All rights reserved.
 *
 * BOKEH is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation.
 *
 * There are special exceptions to the terms and conditions of the AGPL as it
 * is applied to this software (see README file).
 *
 * BOKEH 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 AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with BOKEH; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
 */


if (!function_exists('xdebug_break')) {
  function xdebug_break(){};
}


function setupOpac() {
  require_once('Class/Url.php');

  defineConstant('ROOT_URL', Class_Url::rootUrl());
  defineConstant('BASE_URL',  Class_Url::baseUrl());

  require_once "Zend/Loader.php";
  Zend_Loader::registerAutoload();

  setupConstants();
  require_once('requires.php');

  $cfg = loadConfig();
  setupSession();
  setupDatabase($cfg);
  Class_AdminVar::findAll();
  setupLanguage();
  setupDevOptions($cfg);
  setupControllerActionHelper();
  setupHTTPClient($cfg);
  setupCache($cfg);
  setupMail($cfg);

  $front_controller = setupFrontController($cfg);
  setupPagination();
  setupRestful();
  setupSearch();

  return $front_controller;
}


function defineConstant($name, $value) {
  if (!defined($name))
    define($name, $value);
}


function setupConstants() {
  defineConstant('BOKEH_MAJOR_VERSION','7.6');

  defineConstant('BOKEH_RELEASE_NUMBER', BOKEH_MAJOR_VERSION . '.1');
  defineConstant('BOKEH_REMOTE_FILES', 'http://git.afi-sa.fr/afi/opacce/');

  defineConstant('BOKEH_VERSION', (substr(BOKEH_MAJOR_VERSION, -1) % 2) ? 'master' : 'stable');

  defineConstant('ROOT_PATH',  realpath(dirname(__FILE__).'/..').'/');

  defineConstant('ZEND_FRAMEWORK_PATH',  ROOT_PATH . 'library/storm/zf/library/');

  defineConstant('MODULEDIRECTORY', ROOT_PATH . 'application/modules');
  defineConstant('LANG_DIR', ROOT_PATH . 'library/translation/');

  defineConstant('USERFILESPATH', './userfiles');
  defineConstant('USERFILESURL', BASE_URL . '/userfiles/');
  defineConstant('PATH_TEMP',  ROOT_PATH . 'temp/');

  defineConstant('CKBASEPATH',  'ckeditor/');
  defineConstant('CKBASEURL',  BASE_URL . '/ckeditor/');

  defineConstant('AMBERURL',  BASE_URL . '/amber/');

  defineConstant('URL_ADMIN_SKIN', BASE_URL . '/public/admin/skins/');
  defineConstant('URL_ADMIN_CSS', BASE_URL . '/public/admin/css/');
  defineConstant('URL_ADMIN_IMG', BASE_URL . '/public/admin/images/');
  defineConstant('URL_ADMIN_JS', BASE_URL . '/public/admin/js/');

  defineConstant('JQUERY', URL_ADMIN_JS . 'jquery-1.8.3.js');
  defineConstant('JQUERYMOBILE_VERSION',  '1.4.5');
  defineConstant('JQUERYUI', URL_ADMIN_JS . 'jquery_ui/jquery-ui-1.10.3.full.js');
  defineConstant("URL_JS", BASE_URL . "/public/opac/js/");
  defineConstant("URL_EPUB", BASE_URL . "/temp/epub/");
  defineConstant("URL_SHARED_IMG", BASE_URL . "/public/opac/images/");

  // il y a des autre define URL dans ZendAfi_Controller_Plugin_DefineURLs
  // par exemple URL_IMG, URL_CSS, URL_HTML et URL_JS va chercher dans 'URL_SKIN . 'nom de le module' . /html' etc.
  defineConstant('BR','<br />');
  defineConstant('NL',"\n");
  defineConstant('CRLF', chr(13).chr(10));

  defineConstant('URL_JAVA', BASE_URL . '/public/opac/java/');
  defineConstant('PATH_JAVA', ROOT_PATH . 'public/opac/java/');
  defineConstant('PATH_ADMIN_SUPPORTS', ROOT_PATH . 'public/admin/images/supports/');

  defineConstant('PATH_FONTS', ROOT_PATH . 'public/opac/fonts/');
  defineConstant('URL_CAPTCHA', BASE_URL . '/temp/');
  defineConstant('PATH_CAPTCHA', PATH_TEMP);
  defineConstant('CACHE_LIFETIME', 3600);
  defineConstant('MEMCACHED_ENABLE', false);
  defineConstant('MEMCACHED_HOST', 'localhost');
  defineConstant('MEMCACHED_PORT', '11211');

  defineConstant('IMAGE_MAGICK_PATH', 'convert');

  defineConstant('PATCH_PATH', ROOT_PATH . '/cosmogramme/sql/patch/');
}


function loadConfig($config_init_file_path = './config.ini') {
  // load configuration (local ou production)
  if(array_isset('REMOTE_ADDR', $_SERVER) and $_SERVER['REMOTE_ADDR'] == '127.0.0.1')
    $serveur='local';
  else
    $serveur='production';
  $cfg = new Zend_Config_Ini($config_init_file_path, $serveur);
  Zend_Registry::set('cfg', $cfg);


  setlocale(LC_TIME, 'fr_FR.UTF-8');
  date_default_timezone_set($cfg->timeZone);

  return $cfg;
}


function setupCache($cfg) {
  $frontendOptions = ['lifetime' => CACHE_LIFETIME, // durée du cache: 1h
                      'automatic_serialization' => false,
                      'caching' => true];

  $use_memcached = (MEMCACHED_ENABLE === true);
  $backendOptions = $use_memcached
    ? ['servers' => [ ['host' => MEMCACHED_HOST,
                       'port' => MEMCACHED_PORT] ]]
    : ['cache_dir' => PATH_TEMP ];

  // getting a Zend_Cache_Core object
  $cache = Zend_Cache::factory('Core',
                               $use_memcached ? 'Memcached' : 'File',
                               $frontendOptions,
                               $backendOptions);

  Storm_Cache::setDefaultZendCache($cache);
  Storm_Cache::setSeed($cfg->sgbd->config->dbname.md5(BASE_URL));
}


function setupSession() {
  // Start Session
  $session = new Zend_Session_Namespace(md5(BASE_URL));
  if (!isset($session->initialized))
    {
      Zend_Session::regenerateId();
      $session->initialized = true;
    }
  if (!isset($session->baseUrl)) $session->baseUrl = BASE_URL;
  Zend_Registry::set('session', $session);
}


function setupLanguage() {
  Zend_Locale::setDefault(Class_AdminVar::getDefaultLanguage());
  Zend_Registry::set('locale', new Zend_Locale());

  $translate = new ZendAfi_Translate('gettext', LANG_DIR.'fr.mo', 'fr');
  foreach (Class_AdminVar::getLanguesWithoutDefault() as $language) {
    $filename = LANG_DIR.$language.'.mo';
    if (file_exists($filename))
      $translate->addTranslation($filename, $language);
  }
  Zend_Registry::set('translate', $translate);

  Zend_Validate_Abstract::setDefaultTranslator($translate);
}


function setupDatabase($cfg) {
  // setup database
  $sql = Zend_Db::factory($cfg->sgbd->adapter, $cfg->sgbd->config->toArray());
  $sql->usePrepared(false);
  Zend_Db_Table::setDefaultAdapter($sql);

  $afi_sql = new Class_Systeme_Sql();
  Zend_Registry::set('sql', $afi_sql);

  Zend_Db_Table::getDefaultAdapter()->query('set names "UTF8"');
}


function setupDevOptions($cfg) {
  //permet d'activer les fonctions en développement
  if (null !== $experimental_dev = $cfg->get('experimental_dev'))
    defineConstant('DEVELOPMENT', $experimental_dev);
}


function setupControllerActionHelper() {
  Zend_Controller_Action_HelperBroker::resetHelpers();
  Zend_Controller_Action_HelperBroker::addHelper(new ZendAfi_Controller_Action_Helper_ViewRenderer());
  Zend_Controller_Action_HelperBroker::addPrefix('ZendAfi_Controller_Action_Helper');
}


function setupHTTPClient($cfg) {
  $httpClient = new Zend_Http_Client();

  if ( (isset ($cfg->proxy->host) ) && ($cfg->proxy->host != '') ){
    //set up HTTP Client to use proxy settings
    $proxy_config = [
                     'adapter'    => 'Zend_Http_Client_Adapter_Proxy',
                     'proxy_host' => $cfg->proxy->host,
                     'proxy_port' => $cfg->proxy->port,
                     'proxy_user' => $cfg->proxy->user,
                     'proxy_pass' => $cfg->proxy->pass ];
    Zend_Registry::set('http_proxy',$proxy_config);

    $proxy_adapter = new Zend_Http_Client_Adapter_Proxy();
    $proxy_adapter->setConfig($proxy_config);
    $httpClient->setAdapter($proxy_adapter);
  }

  $httpClient->setConfig(['timeout' => 2]);

  Zend_Registry::set('httpClient',$httpClient);
}


function setupMail($cfg) {
  if (isset($cfg->mail->transport->smtp)) {
    ZendAfi_Mail::setDefaultTransport(new Zend_Mail_Transport_Smtp($cfg->mail->transport->smtp->host,
                                                                   $cfg->mail->transport->smtp->toArray()));
    return;
  }

  if (defined('SMTP_HOST'))
    ZendAfi_Mail::setDefaultTransport(new Zend_Mail_Transport_Smtp(SMTP_HOST));
}


function newFrontController() {
  return Zend_Controller_Front::getInstance()
    ->setDispatcher(new ZendAfi_Controller_Dispatcher_Standard())
    ->addModuleDirectory(MODULEDIRECTORY)
    ->setDefaultModule('opac')
    ->registerPlugin(new ZendAfi_Controller_Plugin_SetupDomain())
    ->registerPlugin(new ZendAfi_Controller_Plugin_AdminAuth())
    ->registerPlugin(new ZendAfi_Controller_Plugin_SetupLocale())
    ->registerPlugin(new ZendAfi_Controller_Plugin_DefineURLs())
    ->registerPlugin(new ZendAfi_Controller_Plugin_InitModule())
    ->registerPlugin(new ZendAfi_Controller_Plugin_SelectionBib())
    ->registerPlugin(new ZendAfi_Controller_Plugin_System())
    ->registerPlugin(new ZendAfi_Controller_Plugin_Popup())
    ->registerPlugin(new ZendAfi_Controller_Plugin_TogetherJS())
    ->registerPlugin(new ZendAfi_Controller_Plugin_CustomFields())
    ->registerPlugin(new ZendAfi_Controller_Plugin_Lectura())
    ->registerPlugin(new ZendAfi_Controller_Plugin_InspectorGadget())
    ->registerPlugin(new ZendAfi_Controller_Plugin_CnilConsent())
    ->registerPlugin(new ZendAfi_Controller_Plugin_Redmine())
    ->setParam('useDefaultControllerAlways', false);
}

function setupFrontController($cfg) {
  $front_controller = newFrontController()
    ->addControllerDirectory(ROOT_PATH.'afi/application/modules/opacpriv/controllers','opacpriv')
    ->setBaseURL(BASE_URL);

  setupRoutes($front_controller, $cfg);

  if (!Class_Users::isCurrentUserSuperAdmin())
    return $front_controller;

  $front_controller->registerPlugin(new ZendAfi_Controller_Plugin_XHProfile());
  return $front_controller;
  set_include_path(get_include_path() . PATH_SEPARATOR . ROOT_PATH.'library/ZFDebug/library');
  return $front_controller
    ->registerPlugin(new ZFDebug_Controller_Plugin_Debug(['plugins' =>
                                                          [
                                                           'Variables',
                                                           'Constants',
                                                           'Html',
                                                           'Database',
                                                           'Memory',
                                                           'Time',
                                                           'Exception']
                                                          ]
                                                         ));
}


function setupRoutes($front_controller, $cfg) {
  if ('1' == $cfg->get('enable_rewriting')) {
    $front_controller
      ->setBaseUrl('')
      ->setRouter(new ZendAfi_Controller_Router_RewriteWithoutBaseUrl());

    Class_Url::doNotAddBaseUrl();
  }

  $front_controller
    ->getRouter()
    ->addRoute('embed',
               new Zend_Controller_Router_Route(
                                                'embed/:controller/:action/*',
                                                ['module' => 'telephone',
                                                 'controller' => 'index',
                                                 'action' => 'index']))
    ->addRoute('flash',
               new Zend_Controller_Router_Route('flash/:action/*',
                                                ['module' => 'opacpriv',
                                                 'controller' => 'flash',
                                                 'action' => 'index']))
    ->addRoute('sitemap',
               new Zend_Controller_Router_Route_Static('sitemap.xml',
                                                       ['module' => 'opac',
                                                        'controller' => 'index',
                                                        'action' => 'sitemap']));
  return $front_controller;
}


function setupPagination() {
  Zend_Paginator::setDefaultScrollingStyle('Sliding');
  Zend_View_Helper_PaginationControl::setDefaultViewPartial('pagination.phtml');
}


function setupRestful() {
  if (!(new Class_Testing_FileSystem())->file_exists(ROOT_PATH . 'restful.php'))
    return;

  set_include_path(ROOT_PATH . '/restful/library' . PATH_SEPARATOR .
                   get_include_path());

  $config = new Zend_Config(include ROOT_PATH . 'restful.php');
  Restful_Model_Configuration::setConfig($config);
  Restful_Bootstrap::asPlugin(Zend_Controller_Front::getInstance(),
                              'rest',
                              Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer'));
}


function setupSearch() {
  defineConstant('MAX_SEARCH_RESULTS', '');
  Class_CriteresRecherche::setMaxSearchResults(MAX_SEARCH_RESULTS);
}