/**
  * Main page
  */
 public function index()
 {
     $submit = $this->param('validate');
     if ($submit == jLocale::get('hfnucontact~contact.form.saveBt')) {
         $form = jForms::fill('hfnucontact~admincontact');
         $rep = $this->getResponse('redirect');
         if (!$form->check()) {
             $rep->action = 'hfnucontact~admin:index';
             return $rep;
         }
         $HfnucontactConfig = new jIniFileModifier(jApp::configPath('defaultconfig.ini.php'));
         $HfnucontactConfig->setValue('email_contact', $this->param('contact'), 'hfnucontact');
         $HfnucontactConfig->save();
         jMessage::add(jLocale::get('hfnucontact~contact.admin.form.email.saved'), 'ok');
         jForms::destroy('hfnucontact~admincontact');
         $rep->action = 'hfnucontact~admin:index';
         return $rep;
     } else {
         $form = jForms::create('hfnucontact~admincontact');
     }
     $form->setData('contact', jApp::config()->hfnucontact['email_contact']);
     $rep = $this->getResponse('html');
     $tpl = new jTpl();
     $tpl->assign('form', $form);
     $rep->body->assign('MAIN', $tpl->fetch('hfnucontact~admincontact'));
     $rep->body->assign('selectedMenuItem', 'contact');
     return $rep;
 }
Exemple #2
0
 /**
  * 
  */
 function update()
 {
     $id = $this->param('j_user_login');
     $pwd = $this->param('pwd');
     $pwdconf = $this->param('pwd_confirm');
     $rep = $this->getResponse('redirect');
     if ($this->personalView && $id != jAuth::getUserSession()->login) {
         jMessage::add(jLocale::get('jelix~errors.acl.action.right.needed'), 'error');
         $rep->action = 'master_admin~default:index';
         return $rep;
     }
     if (trim($pwd) == '' || $pwd != $pwdconf) {
         jMessage::add(jLocale::get('crud.message.bad.password'), 'error');
         $rep->action = 'password:index';
         $rep->params['j_user_login'] = $id;
         return $rep;
     }
     if (jAuth::changePassword($id, $pwd)) {
         jMessage::add(jLocale::get('crud.message.change.password.ok', $id), 'notice');
         if ($this->personalView) {
             $rep->action = 'user:index';
         } else {
             $rep->action = 'default:view';
         }
         $rep->params['j_user_login'] = $id;
         return $rep;
     } else {
         jMessage::add(jLocale::get('crud.message.change.password.notok'), 'error');
         $rep->action = 'password:index';
         $rep->params['j_user_login'] = $id;
     }
     return $rep;
 }
 /**
  * Displays a list of project for a given repository.
  *
  * @param string $repository. Name of the repository.
  * @return Html page with a list of projects.
  */
 function index()
 {
     if ($this->param('theme')) {
         jApp::config()->theme = $this->param('theme');
     }
     $rep = $this->getResponse('html');
     // Get lizmap services
     $services = lizmap::getServices();
     // only maps
     if ($services->onlyMaps) {
         $repository = lizmap::getRepository($services->defaultRepository);
         if ($repository && jAcl2::check('lizmap.repositories.view', $repository->getKey())) {
             $project = lizmap::getProject($repository->getKey() . '~' . $services->defaultProject);
             if ($project) {
                 // test redirection to an other controller
                 $items = jEvent::notify('mainviewGetMaps')->getResponse();
                 foreach ($items as $item) {
                     if ($item->parentId == $repository->getKey() && $item->id == $services->defaultProject) {
                         $rep = $this->getResponse('redirectUrl');
                         $rep->url = $item->url;
                         return $rep;
                     }
                 }
                 // redirection to default controller
                 $rep = $this->getResponse('redirect');
                 $rep->action = 'view~map:index';
                 return $rep;
             }
         }
     }
     // Get repository data
     $repository = $this->param('repository');
     $repositoryList = array();
     if ($repository) {
         if (!jAcl2::check('lizmap.repositories.view', $repository)) {
             $rep = $this->getResponse('redirect');
             $rep->action = 'view~default:index';
             jMessage::add(jLocale::get('view~default.repository.access.denied'), 'error');
             return $rep;
         }
     }
     $title = jLocale::get("view~default.repository.list.title");
     $rep->body->assign('repositoryLabel', $title);
     $rep->body->assign('isConnected', jAuth::isConnected());
     $rep->body->assign('user', jAuth::getUserSession());
     if ($services->allowUserAccountRequests) {
         $rep->body->assign('allowUserAccountRequests', True);
     }
     if ($repository) {
         $lrep = lizmap::getRepository($repository);
         $title .= ' - ' . $lrep->getData('label');
     }
     $rep->title = $title;
     $rep->body->assignZone('MAIN', 'main_view', array('repository' => $repository));
     $rep->addJSCode("\n      \$(window).load(function() {\n        \$('.liz-project-img').parent().mouseenter(function(){\n          var self = \$(this);\n          self.find('.liz-project-desc').slideDown();\n          self.css('cursor','pointer');\n        }).mouseleave(function(){\n          var self = \$(this);\n          self.find('.liz-project-desc').hide();\n        }).click(function(){\n          var self = \$(this);\n          window.location = self.parent().find('a.liz-project-view').attr('href');\n          return false;\n        });\n      });\n      ");
     // Js hack to normalize the height of the project thumbnails to avoid line breaks with long project titles
     $bp = jApp::config()->urlengine['basePath'];
     $rep->addJSLink($bp . 'js/view.js');
     return $rep;
 }
 /**
  * 
  */
 function update()
 {
     $id = $this->param('id');
     $pwd = $this->param('pwd');
     $pwdconf = $this->param('pwd_confirm');
     $rep = $this->getResponse('redirect');
     if (trim($pwd) == '' || $pwd != $pwdconf) {
         jMessage::add(jLocale::get('crud.message.bad.password'), 'error');
         $rep->action = 'password:index';
         $rep->params['id'] = $id;
         return $rep;
     }
     if (jAuth::changePassword($id, $pwd)) {
         jMessage::add(jLocale::get('crud.message.change.password.ok', $id), 'notice');
         if ($this->personalView) {
             $rep->action = 'user:index';
         } else {
             $rep->action = 'default:view';
         }
         $rep->params['id'] = $id;
         return $rep;
     } else {
         jMessage::add(jLocale::get('crud.message.change.password.notok'), 'error');
         $rep->action = 'password:index';
         $rep->params['id'] = $id;
     }
     return $rep;
 }
 /**
  * Returns error
  */
 function error($message)
 {
     $rep = $this->getResponse('redirect');
     $rep->action = 'view~default:error';
     jMessage::add($message, 'error');
     return $rep;
 }
 protected function getcapabilities()
 {
     $result = parent::getcapabilities();
     if ($result->cached) {
         return $result;
     }
     $data = $result->data;
     if (empty($data) or floor($result->code / 100) >= 4) {
         jMessage::add('Server Error !', 'Error');
         return $this->serviceException();
     }
     if (preg_match('#ServiceExceptionReport#i', $data)) {
         return $result;
     }
     // Replace qgis server url in the XML (hide real location)
     $sUrl = jUrl::getFull("lizmap~service:index", array("repository" => $this->repository->getKey(), "project" => $this->project->getKey()));
     $sUrl = str_replace('&', '&', $sUrl);
     preg_match('/<get>.*\\n*.+xlink\\:href="(.+)"/i', $data, $matches);
     if (count($matches) < 2) {
         preg_match('/get onlineresource="(.+)"/i', $data, $matches);
     }
     if (count($matches) > 1) {
         $data = str_replace($matches[1], $sUrl, $data);
     }
     $data = str_replace('&amp;&amp;', '&amp;', $data);
     // Add response to cache
     $cacheId = $this->repository->getKey() . '_' . $this->project->getKey() . '_' . $this->param('service');
     $newhash = md5_file(realpath($this->repository->getPath()) . '/' . $this->project->getKey() . ".qgs");
     jCache::set($cacheId . '_hash', $newhash);
     jCache::set($cacheId . '_mime', $result->mime);
     jCache::set($cacheId . '_data', $data);
     return (object) array('code' => 200, 'mime' => $result->mime, 'data' => $data, 'cached' => False);
 }
 protected function getcapabilities()
 {
     $result = parent::getcapabilities();
     if ($result->cached) {
         return $result;
     }
     $data = $result->data;
     if (empty($data) or floor($result->code / 100) >= 4) {
         jMessage::add('Server Error !', 'Error');
         return $this->serviceException();
     }
     if (preg_match('#ServiceExceptionReport#i', $data)) {
         return $result;
     }
     // Remove no interoparable elements
     $data = preg_replace('@<GetPrint[^>]*?>.*?</GetPrint>@si', '', $data);
     $data = preg_replace('@<ComposerTemplates[^>]*?>.*?</ComposerTemplates>@si', '', $data);
     // Replace qgis server url in the XML (hide real location)
     $sUrl = jUrl::getFull("lizmap~service:index", array("repository" => $this->repository->getKey(), "project" => $this->project->getKey()));
     $sUrl = str_replace('&', '&amp;', $sUrl);
     preg_match('/<get>.*\\n*.+xlink\\:href="(.+)"/i', $data, $matches);
     if (count($matches) < 2) {
         preg_match('/get onlineresource="(.+)"/i', $data, $matches);
     }
     if (count($matches) > 1) {
         $data = str_replace($matches[1], $sUrl, $data);
     }
     $data = str_replace('&amp;&amp;', '&amp;', $data);
     if (preg_match('@WMS_Capabilities@i', $data)) {
         // Update namespace
         $schemaLocation = "http://www.opengis.net/wms";
         $schemaLocation .= " http://schemas.opengis.net/wms/1.3.0/capabilities_1_3_0.xsd";
         $schemaLocation .= " http://www.opengis.net/sld";
         $schemaLocation .= " http://schemas.opengis.net/sld/1.1.0/sld_capabilities.xsd";
         $schemaLocation .= " http://www.qgis.org/wms";
         $schemaLocation .= " " . $sUrl . "SERVICE=WMS&amp;REQUEST=GetSchemaExtension";
         $data = preg_replace('@xsi:schemaLocation=".*?"@si', 'xsi:schemaLocation="' . $schemaLocation . '"', $data);
         if (!preg_match('@xmlns:qgs@i', $data)) {
             $data = preg_replace('@xmlns="http://www.opengis.net/wms"@', 'xmlns="http://www.opengis.net/wms" xmlns:qgs="http://www.qgis.org/wms"', $data);
             $data = preg_replace('@GetStyles@', 'qgs:GetStyles', $data);
         }
         if (!preg_match('@xmlns:sld@i', $data)) {
             $data = preg_replace('@xmlns="http://www.opengis.net/wms"@', 'xmlns="http://www.opengis.net/wms" xmlns:sld="http://www.opengis.net/sld"', $data);
             $data = preg_replace('@GetLegendGraphic@', 'sld:GetLegendGraphic', $data);
         }
     }
     // Add response to cache
     $cacheId = $this->repository->getKey() . '_' . $this->project->getKey() . '_' . $this->param('service');
     $newhash = md5_file(realpath($this->repository->getPath()) . '/' . $this->project->getKey() . ".qgs");
     jCache::set($cacheId . '_hash', $newhash);
     jCache::set($cacheId . '_mime', $result->mime);
     jCache::set($cacheId . '_data', $data);
     return (object) array('code' => 200, 'mime' => $result->mime, 'data' => $data, 'cached' => False);
 }
 /**
  *
  */
 function index()
 {
     $resp = $this->getResponse('html');
     $resp->title = jLocale::get('gui.dashboard.title');
     $resp->body->assignZone('MAIN', 'dashboard');
     if (jAuth::getUserSession()->login == 'admin' && jAuth::getUserSession()->password == md5('admin')) {
         jMessage::add(jLocale::get('gui.message.admin.password'), 'error');
     }
     $resp->body->assign('selectedMenuItem', 'dashboard');
     return $resp;
 }
 function delete()
 {
     $id_notify = (int) $this->param('id_notify');
     $rep = $this->getResponse('redirect');
     $rep->action = 'hfnuadmin~notify:index';
     if ($id_notify == 0) {
         return $rep;
     }
     $dao = jDao::get('havefnubb~notify');
     $dao->delete($id_notify);
     jMessage::add(jLocale::get('hfnuadmin~notify.notify.deleted'), 'ok');
     return $rep;
 }
 /**
  *
  */
 function index()
 {
     $resp = $this->getResponse('html');
     $resp->title = jLocale::get('gui.dashboard.title');
     $resp->body->assignZone('MAIN', 'dashboard');
     $user = jAuth::getUserSession();
     $driver = jAuth::getDriver();
     if (method_exists($driver, 'checkPassword') && $user->login == 'admin' && $driver->checkPassword('admin', $user->password)) {
         jMessage::add(jLocale::get('gui.message.admin.password'), 'error');
     }
     $resp->body->assign('selectedMenuItem', 'dashboard');
     return $resp;
 }
 /**
  * Let use one of the available theme
  */
 function useit()
 {
     $theme = (string) $this->param('theme');
     $mainConfig = new jIniFileModifier(jApp::configPath() . 'defaultconfig.ini.php');
     $mainConfig->setValue('theme', strtolower($theme));
     $mainConfig->setValue('datepicker', strtolower($theme), 'forms');
     $mainConfig->save();
     jFile::removeDir(jApp::tempPath(), false);
     jMessage::add(jLocale::get('theme.selected'), 'information');
     $rep = $this->getResponse('redirect');
     $rep->action = 'default:index';
     return $rep;
 }
 function clear()
 {
     $confirm = $this->param('confirm');
     if ($confirm == 'Y') {
         jFile::removeDir(jApp::tempPath(), false);
         jMessage::add(jLocale::get('jelixcache~jelixcache.cache.clear.done'));
     } else {
         jMessage::add(jLocale::get('jelixcache~jelixcache.cache.clear.canceled'));
     }
     $rep = $this->getResponse('redirect');
     $rep->action = 'jelixcache~default:index';
     return $rep;
 }
Exemple #13
0
 /**
  * Reindexing the search engine
  */
 function reindexing()
 {
     $confirm = $this->param('confirm');
     if ($confirm == 'Y') {
         $idx = jClasses::getService('hfnusearch~search_index');
         $nbWords = $idx->searchEngineReindexing();
         jMessage::add(jLocale::get('hfnusearch~search.admin.reindexing.done', $nbWords));
     } else {
         jMessage::add(jLocale::get('hfnusearch~search.admin.reindexing.canceled'));
     }
     $rep = $this->getResponse('redirect');
     $rep->action = 'hfnusearch~admin:index';
     return $rep;
 }
 /**
  * Query
  */
 public function query()
 {
     $string = $this->param('hfnu_q');
     $additionnalParam = '';
     if ($this->param('param') != '') {
         $additionnalParam = $this->param('param');
     }
     $HfnuSearchConfig = parse_ini_file(jApp::configPath() . 'havefnu.search.ini.php', true);
     // get the list of authorized function we will find in the search_in "service" below
     $authorizedSearch = explode(',', $HfnuSearchConfig['perform_search_in']);
     if (!in_array($this->param('perform_search_in'), $authorizedSearch) or $string == '' or strlen($string) < 3) {
         jMessage::add(jLocale::get('hfnusearch~search.query.too.short'), 'warning');
         $rep = $this->getResponse('redirect');
         $rep->action = 'hfnusearch~default:index';
         return $rep;
     }
     // let's build the appropriate service to call
     $searchIn = 'searchIn' . ucfirst($this->param('perform_search_in'));
     $page = 0;
     if ($this->param('page') > 0) {
         $page = (int) $this->param('page');
     }
     if ($page < 0) {
         $page = 0;
     }
     $resultsPerPage = (int) $HfnuSearchConfig['results_per_page'];
     $result = jClasses::getService('hfnusearch~search_in')->{$searchIn}($string, $additionnalParam, $page, $resultsPerPage);
     $count = $result['total'];
     if ($count == 0) {
         jMessage::add(jLocale::get('hfnusearch~search.no.result'), 'ok');
         $rep = $this->getResponse('redirect');
         $rep->action = 'hfnusearch~default:index';
         return $rep;
     }
     $properties = array('start-label' => '', 'prev-label' => '', 'next-label' => '', 'end-label' => jLocale::get("hfnusearch~search.pagelinks.end"), 'area-size' => 5);
     $tpl = new jTpl();
     $tpl->assign('string', $string);
     $tpl->assign('count', $count);
     $tpl->assign('datas', $result['datas']);
     $tpl->assign('page', $page);
     $tpl->assign('resultsPerPage', $resultsPerPage);
     $tpl->assign('perform_search_in', $this->param('perform_search_in'));
     $tpl->assign('properties', $properties);
     $rep = $this->getResponse('html');
     $rep->title = jLocale::get('hfnusearch~search.results.of.search');
     $rep->body->assign('MAIN', $tpl->fetch('hfnusearch~result'));
     return $rep;
 }
 function save()
 {
     $rep = $this->getResponse('redirect');
     $rep->action = 'default:index';
     $form = jForms::fill('config');
     if (!$form) {
         return $rep;
     }
     if (!$form->check()) {
         return $rep;
     }
     $activeusers = jClasses::create('activeusers~connectedusers');
     try {
         $activeusers->saveVisitTimeout($form->getData('timeout_visit'));
         jMessage::add(jLocale::get('main.config.save.ok'));
     } catch (Exception $e) {
         jMessage::add('Error: ' . $e->getMessage(), 'error');
     }
     return $rep;
 }
 /**
  * to answer to jcommunity_save_account event
  * @param object $event the given event to answer to
  */
 function onjcommunity_save_account($event)
 {
     $gJConfig = jApp::config();
     $form = $event->getParam('form');
     $form->check();
     if ($form->getData('member_language') != '') {
         $_SESSION['JX_LANG'] = $form->getData('member_language');
         $gJConfig->locale = $form->getData('member_language');
     }
     $ext = '';
     $id = jAuth::getUserSession()->id;
     if ($form->getData('member_avatar') != '') {
         $max_width = $gJConfig->havefnubb['avatar_max_width'];
         $max_height = $gJConfig->havefnubb['avatar_max_height'];
         @unlink(jApp::wwwPath() . 'images/avatars/' . $id . '.png');
         @unlink(jApp::wwwPath() . 'images/avatars/' . $id . '.jpg');
         @unlink(jApp::wwwPath() . 'images/avatars/' . $id . '.jpeg');
         @unlink(jApp::wwwPath() . 'images/avatars/' . $id . '.gif');
         $avatar = $form->getData('member_avatar');
         if (strpos($avatar, '.png') > 0) {
             $ext = '.png';
         } elseif (strpos($avatar, '.jpg') > 0) {
             $ext = '.jpg';
         } elseif (strpos($avatar, '.jpeg') > 0) {
             $ext = '.jpeg';
         } elseif (strpos($avatar, '.gif') > 0) {
             $ext = '.gif';
         }
         $form->saveFile('member_avatar', jApp::wwwPath() . 'hfnu/images/avatars/', $id . $ext);
         list($width, $height) = getimagesize(jApp::wwwPath() . 'hfnu/images/avatars/' . $id . $ext);
         if (empty($width) || empty($height) || $width > $max_width || $height > $max_height) {
             @unlink(jApp::wwwPath() . 'images/avatars/' . $id . $ext);
             jMessage::add(jLocale::get('havefnubb~member.profile.avatar.too.wide', array($max_width . ' x ' . $max_height)), 'error');
             return;
         }
     }
     jMessage::add(jLocale::get('havefnubb~member.profile.updated'), 'ok');
 }
 /**
  * Empty a map service cache
  * @param string $repository Repository for which to remove all tile cache
  * @return Redirection to the index
  */
 function removeLayerCache()
 {
     // Create response to redirect to the index
     $rep = $this->getResponse("redirect");
     $rep->action = "admin~config:index";
     $repository = $this->param('repository');
     $lrep = lizmap::getRepository($repository);
     if (!$lrep) {
         jMessage::add('The repository ' . strtoupper($repository) . ' does not exist !', 'error');
         return $rep;
     }
     $project = $this->param('project');
     try {
         $lproj = lizmap::getProject($lrep->getKey() . '~' . $project);
         if (!$lproj) {
             jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'error');
             return $rep;
         }
         $layer = $this->param('layer');
         // Remove project cache
         $lproj->clearCache();
         // Remove the cache for the layer
         lizmapProxy::clearLayerCache($repository, $project, $layer);
         jMessage::add(jLocale::get("admin~admin.cache.layer.removed", array($layer)));
         return $rep;
     } catch (UnknownLizmapProjectException $e) {
         jLog::logEx($e, 'error');
         jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'error');
         return $rep;
     }
     return $rep;
 }
Exemple #18
0
 function saverightres()
 {
     $rep = $this->getResponse('redirect');
     $login = $this->param('user');
     $subjects = $this->param('subjects', array());
     if ($login == '') {
         $rep->action = 'jacl2db_admin~users:index';
         return $rep;
     }
     $rep->action = 'jacl2db_admin~users:rightres';
     $rep->params = array('user' => $login);
     $daogroup = jDao::get('jacl2db~jacl2group', 'jacl2_profile');
     $grp = $daogroup->getPrivateGroup($login);
     $subjectsToRemove = array();
     foreach ($subjects as $sbj => $val) {
         if ($val != '' || $val == true) {
             $subjectsToRemove[] = $sbj;
         }
     }
     jDao::get('jacl2db~jacl2rights', 'jacl2_profile')->deleteRightsOnResource($grp->id_aclgrp, $subjectsToRemove);
     jMessage::add(jLocale::get('acl2.message.user.rights.ok'), 'ok');
     return $rep;
 }
 function delgroup()
 {
     $rep = $this->getResponse('redirect');
     $rep->action = 'jacl2db_admin~groups:index';
     jAcl2DbUserGroup::removeGroup($this->param('group_id'));
     jMessage::add(jLocale::get('acl2.message.group.delete.ok'), 'ok');
     return $rep;
 }
 /**
  * save data of a form in a new record
  */
 function saveupdate()
 {
     $rep = $this->getResponse('redirect');
     $id = $this->param('id');
     $form = jForms::get($this->form, $id);
     $form->initFromRequest();
     if ($form === null || $id === null) {
         $rep->action = 'master_admin~default:index';
         return $rep;
     }
     $evresp = array();
     if ($form->check() && !jEvent::notify('jauthdbAdminCheckUpdateForm', array('form' => $form))->inResponse('check', false, $evresp)) {
         extract($form->prepareDaoFromControls($this->dao, $id, $this->dbProfile), EXTR_PREFIX_ALL, "form");
         // we call jAuth instead of using jDao, to allow jAuth to do
         // all process, events...
         jAuth::updateUser($form_daorec);
         $form->saveAllFiles($this->uploadsDirectory);
         $rep->action = 'user:index';
         jMessage::add(jLocale::get('crud.message.update.ok', $id), 'notice');
         jForms::destroy($this->form, $id);
     } else {
         $rep->action = 'user:editupdate';
     }
     $rep->params['id'] = $id;
     return $rep;
 }
 /**
  * delete a record
  */
 function delete()
 {
     $id = $this->param('id');
     $pwd = $this->param('pwd_confirm');
     $rep = $this->getResponse('redirect');
     if (jAuth::verifyPassword(jAuth::getUserSession()->login, $pwd) == false) {
         jMessage::add(jLocale::get('crud.message.delete.invalid.pwd'), 'error');
         $rep->action = 'default:confirmdelete';
         $rep->params['id'] = $id;
         return $rep;
     }
     if ($id !== null && jAuth::getUserSession()->login != $id) {
         if (jAuth::removeUser($id)) {
             jMessage::add(jLocale::get('crud.message.delete.ok', $id), 'notice');
             $rep->action = 'default:index';
         } else {
             jMessage::add(jLocale::get('crud.message.delete.notok'), 'error');
             $rep->action = 'default:view';
             $rep->params['id'] = $id;
         }
     } else {
         jMessage::add(jLocale::get('crud.message.delete.notok'), 'error');
         $rep->action = 'default:index';
     }
     return $rep;
 }
 /**
  * save new user and send an email for a confirmation, with
  * a key to activate the account
  */
 function save()
 {
     if (jAuth::isConnected()) {
         return $this->noaccess();
     }
     $rep = $this->getResponse("redirect");
     $rep->action = "registration:index";
     $form = jForms::get('registration');
     if (!$form) {
         return $rep;
     }
     jEvent::notify('jcommunity_registration_init_form', array('form' => $form));
     $form->initFromRequest();
     if (!$form->check()) {
         return $rep;
     }
     $login = $form->getData('reg_login');
     if (jAuth::getUser($login)) {
         $form->setErrorOn('reg_login', jLocale::get('register.form.login.exists'));
         return $rep;
     }
     $pass = jAuth::getRandomPassword(8);
     $key = substr(md5($login . '-' . $pass), 1, 10);
     $user = jAuth::createUserObject($login, $pass);
     $user->email = $form->getData('reg_email');
     $user->nickname = $login;
     $user->status = JCOMMUNITY_STATUS_NEW;
     $user->request_date = date('Y-m-d H:i:s');
     $user->keyactivate = $key;
     $ev = jEvent::notify('jcommunity_registration_prepare_save', array('form' => $form, 'user' => $user));
     if (count($form->getErrors())) {
         return $rep;
     }
     $responses = $ev->getResponse();
     $hasErrors = false;
     foreach ($responses as $response) {
         if (isset($response['errorRegistration']) && $response['errorRegistration'] != "") {
             jMessage::add($response['errorRegistration'], 'error');
             $hasErrors = true;
         }
     }
     if ($hasErrors) {
         return $rep;
     }
     jAuth::saveNewUser($user);
     jEvent::notify('jcommunity_registration_after_save', array('form' => $form, 'user' => $user));
     $gJConfig = jApp::config();
     $mail = new jMailer();
     $mail->From = $gJConfig->mailer['webmasterEmail'];
     $mail->FromName = $gJConfig->mailer['webmasterName'];
     $mail->Sender = $gJConfig->mailer['webmasterEmail'];
     $mail->Subject = jLocale::get('register.mail.new.subject');
     $tpl = new jTpl();
     $tpl->assign(compact('login', 'pass', 'key'));
     $tpl->assign('server', $_SERVER['SERVER_NAME']);
     $mail->Body = $tpl->fetch('mail_registration', 'text');
     $mail->AddAddress($user->email);
     $mail->Send();
     jForms::destroy('registration');
     $rep->action = "registration:confirmform";
     $rep->params = array('login' => $login);
     return $rep;
 }
 /**
  * Get parameters and set classes for the project and repository given.
  *
  * @return array List of needed variables : $params, $lizmapProject, $lizmapRepository, $lizmapCache.
  */
 protected function getServiceParameters()
 {
     // Get the project
     $project = $this->iParam('project');
     if (!$project) {
         jMessage::add('The parameter project is mandatory !', 'ProjectNotDefind');
         return false;
     }
     // Get repository data
     $repository = $this->iParam('repository');
     // Get the corresponding repository
     $lrep = lizmap::getRepository($repository);
     // Redirect if no rights to access this repository
     if (!jAcl2::check('lizmap.repositories.view', $lrep->getKey())) {
         jMessage::add(jLocale::get('view~default.repository.access.denied'), 'AuthorizationRequired');
         return false;
     }
     // Get and normalize the passed parameters
     $pParams = jApp::coord()->request->params;
     $pParams['map'] = realpath($lrep->getPath()) . '/' . $project . ".qgs";
     $lizmapCache = jClasses::getService('lizmap~lizmapCache');
     $params = $lizmapCache->normalizeParams($pParams);
     // Define class private properties
     $this->project = lizmap::getProject($repository . '~' . $project);
     $this->repository = $lrep;
     $this->services = lizmap::getServices();
     $this->params = $params;
     $this->lizmapCache = $lizmapCache;
     // Optionnaly filter data by login
     if (isset($params['request'])) {
         $request = strtolower($params['request']);
         if (in_array($request, array('getmap', 'getfeatureinfo', 'getfeature', 'getprint')) and !jAcl2::check('lizmap.tools.loginFilteredLayers.override', $lrep->getKey())) {
             $this->filterDataByLogin();
         }
     }
     return true;
 }
 /**
  * Get data from map service or from the cache.
  * @param lizmapProject $project The project.
  * @param array $params Array of parameters.
  * @return array $data Normalized and filtered array.
  */
 public static function getMap($project, $params, $forced = False)
 {
     // Get cache if exists
     $keyParams = array();
     foreach ($params as $pk => $value) {
         if (in_array($pk, array("bbox", "format", "height", "layers", "transparent"))) {
             $keyParams[$pk] = $value;
         }
     }
     ksort($keyParams);
     $layers = str_replace(',', '_', $params['layers']);
     $crs = preg_replace('#[^a-zA-Z0-9_]#', '_', $params['crs']);
     // Get repository data
     $ser = lizmap::getServices();
     $lrep = $project->getRepository();
     $lproj = $project;
     $project = $lproj->getKey();
     $repository = $lrep->getKey();
     // Change to true to put some information in debug files
     $debug = $ser->debugMode;
     // Read config file for the current project
     $layername = $params["layers"];
     $configLayers = $lproj->getLayers();
     $configLayer = null;
     if (property_exists($configLayers, $layername)) {
         $configLayer = $configLayers->{$layername};
     }
     // Set or get tile from the parent project in case of embedded layers
     if ($configLayer and property_exists($configLayer, 'sourceRepository') and property_exists($configLayer, 'sourceProject')) {
         $newRepository = (string) $configLayer->sourceRepository;
         $newProject = (string) $configLayer->sourceProject;
         $repository = $newRepository;
         $project = $newProject;
         $lrep = lizmap::getRepository($repository);
         if (!$lrep) {
             jMessage::add('The repository ' . strtoupper($repository) . ' does not exist !', 'RepositoryNotDefined');
             return array('error', 'text/plain', '404');
         }
         try {
             $lproj = lizmap::getProject($repository . '~' . $project);
             if (!$lproj) {
                 jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'ProjectNotDefined');
                 return array('error', 'text/plain', '404');
             }
         } catch (UnknownLizmapProjectException $e) {
             jLog::logEx($e, 'error');
             jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'ProjectNotDefined');
             return array('error', 'text/plain', '404');
         }
     }
     $key = md5(serialize($keyParams));
     // Get tile cache virtual profile (tile storage)
     // And get tile if already in cache
     // --> must be done after checking that parent project is involved
     $profile = lizmapProxy::createVirtualProfile($repository, $project, $layers, $crs);
     if ($debug) {
         lizmap::logMetric('LIZMAP_PROXY_READ_LAYER_CONFIG');
     }
     // Has the user asked for cache for this layer ?
     $useCache = False;
     if ($configLayer) {
         $useCache = strtolower($configLayer->cached) == 'true';
     }
     // Avoid using cache for requests concerning not square tiles or too big
     // Focus on real web square tiles
     $wmsClient = 'web';
     if ($useCache and $params['width'] != $params['height'] and ($params['width'] > 300 or $params['height'] > 300)) {
         $wmsClient = 'gis';
         $useCache = False;
     }
     if ($useCache and !$forced) {
         $tile = jCache::get($key, $profile);
         if ($tile) {
             $_SESSION['LIZMAP_GETMAP_CACHE_STATUS'] = 'read';
             $mime = 'image/jpeg';
             if (preg_match('#png#', $params['format'])) {
                 $mime = 'image/png';
             }
             if ($debug) {
                 lizmap::logMetric('LIZMAP_PROXY_HIT_CACHE');
             }
             return array($tile, $mime, 200);
         }
     }
     // ***************************
     // No cache hit : need to ask the tile from QGIS Server
     // ***************************
     // Construction of the WMS url : base url + parameters
     $url = $ser->wmsServerURL . '?';
     // Add project path into map parameter
     $params["map"] = realpath($lproj->getQgisPath());
     // Metatile : if needed, change the bbox
     // Avoid metatiling when the cache is not active for the layer
     $metatileSize = '1,1';
     if ($configLayer and property_exists($configLayer, 'metatileSize')) {
         if (preg_match('#^[3579],[3579]$#', $configLayer->metatileSize)) {
             $metatileSize = $configLayer->metatileSize;
         }
     }
     # Metatile buffer
     $metatileBuffer = 5;
     // Also checks if gd is installed
     if ($metatileSize and $useCache and $wmsClient == 'web' and extension_loaded('gd') && function_exists('gd_info')) {
         # Metatile Size
         $metatileSizeExp = explode(',', $metatileSize);
         $metatileSizeX = (int) $metatileSizeExp[0];
         $metatileSizeY = (int) $metatileSizeExp[1];
         # Get requested bbox
         $bboxExp = explode(',', $params['bbox']);
         $width = $bboxExp[2] - $bboxExp[0];
         $height = $bboxExp[3] - $bboxExp[1];
         # Calculate factors
         $xFactor = (int) ($metatileSizeX / 2);
         $yFactor = (int) ($metatileSizeY / 2);
         # Calculate the new bbox
         $xmin = $bboxExp[0] - $xFactor * $width - $metatileBuffer * $width / $params["width"];
         $ymin = $bboxExp[1] - $yFactor * $height - $metatileBuffer * $height / $params["height"];
         $xmax = $bboxExp[2] + $xFactor * $width + $metatileBuffer * $width / $params["width"];
         $ymax = $bboxExp[3] + $yFactor * $height + $metatileBuffer * $height / $params["height"];
         # Replace request bbox by metatile bbox
         $params["bbox"] = "{$xmin},{$ymin},{$xmax},{$ymax}";
         # Keep original param value
         $originalParams = array("width" => $params["width"], "height" => $params["height"]);
         # Replace width and height before requesting the image from qgis
         $params["width"] = $metatileSizeX * $params["width"] + 2 * $metatileBuffer;
         $params["height"] = $metatileSizeY * $params["height"] + 2 * $metatileBuffer;
     }
     // Build params before send the request to Qgis
     $builtParams = http_build_query($params);
     // Replace needed characters (not needed for php >= 5.4, just use the 4th parameter of the method http_build_query)
     $a = array('+', '_', '.', '-');
     $b = array('%20', '%5F', '%2E', '%2D');
     $builtParams = str_replace($a, $b, $builtParams);
     // Get data from the map server
     $proxyMethod = $ser->proxyMethod;
     $getRemoteData = lizmapProxy::getRemoteData($url . $builtParams, $proxyMethod, $debug);
     $data = $getRemoteData[0];
     $mime = $getRemoteData[1];
     $code = $getRemoteData[2];
     if ($debug) {
         lizmap::logMetric('LIZMAP_PROXY_REQUEST_QGIS_MAP');
     }
     if ($useCache && !preg_match('/^image/', $mime)) {
         $useCache = False;
     }
     // Metatile : if needed, crop the metatile into a single tile
     // Also checks if gd is installed
     if ($metatileSize and $useCache and $wmsClient == 'web' and extension_loaded('gd') && function_exists('gd_info')) {
         # Save original content into an image var
         $original = imagecreatefromstring($data);
         # crop parameters
         $newWidth = (int) $originalParams["width"];
         // px
         $newHeight = (int) $originalParams["height"];
         // px
         $positionX = (int) ($xFactor * $originalParams["width"]) + $metatileBuffer;
         // left translation of 30px
         $positionY = (int) ($yFactor * $originalParams["height"]) + $metatileBuffer;
         // top translation of 20px
         # create new gd image
         $image = imageCreateTrueColor($newWidth, $newHeight);
         # save transparency if needed
         if (preg_match('#png#', $params['format'])) {
             imagesavealpha($original, true);
             imagealphablending($image, false);
             $color = imagecolortransparent($image, imagecolorallocatealpha($image, 0, 0, 0, 127));
             imagefill($image, 0, 0, $color);
             imagesavealpha($image, true);
         }
         # crop image
         imagecopyresampled($image, $original, 0, 0, $positionX, $positionY, $newWidth, $newHeight, $newWidth, $newHeight);
         # Output the image as a string (use PHP buffering)
         ob_start();
         if (preg_match('#png#', $params['format'])) {
             imagepng($image, null, 9);
         } else {
             imagejpeg($image, null, 90);
         }
         $data = ob_get_contents();
         // read from buffer
         ob_end_clean();
         // delete buffer
         // Destroy image handlers
         imagedestroy($original);
         imagedestroy($image);
         if ($debug) {
             lizmap::logMetric('LIZMAP_PROXY_CROP_METATILE');
         }
     }
     $_SESSION['LIZMAP_GETMAP_CACHE_STATUS'] = 'off';
     // Store into cache if needed
     if ($useCache) {
         //~ jLog::log( ' Store into cache');
         $cacheExpiration = (int) $ser->cacheExpiration;
         if (property_exists($configLayer, 'cacheExpiration')) {
             $cacheExpiration = (int) $configLayer->cacheExpiration;
         }
         jCache::set($key, $data, $cacheExpiration, $profile);
         $_SESSION['LIZMAP_GETMAP_CACHE_STATUS'] = 'write';
         if ($debug) {
             lizmap::logMetric('LIZMAP_PROXY_WRITE_CACHE');
         }
     }
     return array($data, $mime, $code);
 }
 /**
  * Load the map page for the given project.
  * @param string $repository Name of the repository.
  * @param string $project Name of the project.
  * @return Page with map and content for the chose Qgis project.
  */
 function index()
 {
     if ($this->param('theme')) {
         jApp::config()->theme = $this->param('theme');
     }
     $rep = $this->getResponse('htmlmap');
     $rep->addJSLink(jUrl::get('view~translate:index'));
     $ok = true;
     // Get the project
     $project = filter_var($this->param('project'), FILTER_SANITIZE_STRING);
     // Get repository data
     $repository = $this->param('repository');
     // Get lizmapRepository class
     // if repository not found get the default
     $lrep = null;
     $lser = lizmap::getServices();
     if (!$repository) {
         $lrep = lizmap::getRepository($lser->defaultRepository);
         $repository = $lser->defaultRepository;
     } else {
         $lrep = lizmap::getRepository($repository);
     }
     if (!$lrep or !jAcl2::check('lizmap.repositories.view', $lrep->getKey())) {
         $rep = $this->getResponse('redirect');
         $rep->action = 'view~default:index';
         jMessage::add(jLocale::get('view~default.repository.access.denied'), 'error');
         return $rep;
     }
     // We must redirect to default repository project list if no project given
     if (!$project) {
         $lproj = lizmap::getProject($lrep->getKey() . '~' . $lser->defaultProject);
         if (!$lproj) {
             jMessage::add('The parameter project is mandatory !', 'error');
             $ok = false;
         } else {
             $project = $lser->defaultProject;
         }
     }
     // Get lizmapProject class
     if ($ok) {
         $lproj = lizmap::getProject($lrep->getKey() . '~' . $project);
         if (!$lproj) {
             jMessage::add('The lizmapProject ' . strtoupper($project) . ' does not exist !', 'error');
             $ok = false;
         }
     }
     // Redirect if project is hidden (lizmap plugin option)
     if ($ok and !$this->forceHiddenProjectVisible) {
         $pOptions = $lproj->getOptions();
         if (property_exists($pOptions, 'hideProject') && $pOptions->hideProject == 'True') {
             jMessage::add(jLocale::get('view~default.project.access.denied'), 'error');
             $ok = false;
         }
     }
     // Redirect if error encountered
     if (!$ok) {
         $rep = $this->getResponse('redirect');
         $rep->params = array('repository' => $lrep->getKey());
         $rep->action = 'view~default:index';
         return $rep;
     }
     // Add js link if google is needed
     if ($lproj->needsGoogle()) {
         $googleKey = $lproj->getGoogleKey();
         if ($googleKey != '') {
             $rep->addJSLink('https://maps.google.com/maps/api/js?v=3.5&sensor=false&key=' . $googleKey);
         } else {
             $rep->addJSLink('https://maps.google.com/maps/api/js?v=3.5&sensor=false');
         }
     }
     // Add the jForms js
     $bp = jApp::config()->urlengine['basePath'];
     $rep->addJSLink($bp . 'jelix/js/jforms_jquery.js');
     $rep->addJSLink($bp . 'jelix/js/jforms/datepickers/default/init.js');
     $rep->addJSLink($bp . 'jelix/js/jforms/datepickers/default/ui.en.js');
     $rep->addJSLink($bp . 'js/fileUpload/jquery.fileupload.js');
     $rep->addJSLink($bp . 'js/bootstrapErrorDecoratorHtml.js');
     // Add botom dock js
     $rep->addJSLink($bp . 'js/bottom-dock.js');
     // Pass some configuration options to the web page through javascript var
     $lizUrls = array("params" => array('repository' => $repository, 'project' => $project), "config" => jUrl::get('lizmap~service:getProjectConfig'), "wms" => jUrl::get('lizmap~service:index'), "media" => jUrl::get('view~media:getMedia'), "nominatim" => jUrl::get('lizmap~osm:nominatim'), "ign" => jUrl::get('lizmap~ign:address'), "edition" => jUrl::get('lizmap~edition:getFeature'), "permalink" => jUrl::getFull('view~map:index'), "dataTableLanguage" => $bp . 'js/dataTables/' . jApp::config()->locale . '.json', "basepath" => $bp, "geobookmark" => jUrl::get('lizmap~geobookmark:index'));
     // Get optionnal WMS public url list
     $lser = lizmap::getServices();
     if ($lser->wmsPublicUrlList) {
         $publicUrlList = $lser->wmsPublicUrlList;
         function f($x)
         {
             return jUrl::getFull('lizmap~service:index', array(), 0, trim($x));
         }
         $pul = array_map('f', explode(',', $publicUrlList));
         $lizUrls['publicUrlList'] = $pul;
     }
     if (jAcl2::check('lizmap.admin.repositories.delete')) {
         $lizUrls['removeCache'] = jUrl::get('admin~config:removeLayerCache');
     }
     $rep->addJSCode("var lizUrls = " . json_encode($lizUrls) . ";");
     $rep->addJSCode("var lizProj4 = " . json_encode($lproj->getAllProj4()) . ";");
     $rep->addStyle('#map', 'background-color:' . $lproj->getCanvasColor() . ';');
     // Get the WMS information
     $wmsInfo = $lproj->getWMSInformation();
     // Set page title from projet title
     if ($wmsInfo['WMSServiceTitle'] != '') {
         $rep->title = $wmsInfo['WMSServiceTitle'];
     } else {
         $rep->title = $repository . ' - ' . $project;
     }
     // Add date.js for timemanager
     if ($lproj->hasTimemanagerLayers()) {
         $rep->addJSLink($bp . 'js/date.js');
     }
     // Assign variables to template
     $assign = array_merge(array('repositoryLabel' => $lrep->getData('label'), 'repository' => $lrep->getKey(), 'project' => $project, 'onlyMaps' => $lser->onlyMaps), $wmsInfo);
     // WMS GetCapabilities Url
     $wmsGetCapabilitiesUrl = jAcl2::check('lizmap.tools.displayGetCapabilitiesLinks', $lrep->getKey());
     if ($wmsGetCapabilitiesUrl) {
         $wmsGetCapabilitiesUrl = $lproj->getData('wmsGetCapabilitiesUrl');
     }
     $assign['wmsGetCapabilitiesUrl'] = $wmsGetCapabilitiesUrl;
     // Get dockable and minidockable element
     $assign['dockable'] = $lproj->getDefaultDockable();
     $items = jEvent::notify('mapDockable', array('repository' => $repository, 'project' => $project))->getResponse();
     $assign['dockable'] = mapDockItemsMerge($assign['dockable'], $items);
     $assign['minidockable'] = $lproj->getDefaultMiniDockable();
     $items = jEvent::notify('mapMiniDockable', array('repository' => $repository, 'project' => $project))->getResponse();
     $assign['minidockable'] = mapDockItemsMerge($assign['minidockable'], $items);
     $assign['bottomdockable'] = $lproj->getDefaultBottomDockable();
     $items = jEvent::notify('mapBottomDockable', array('repository' => $repository, 'project' => $project))->getResponse();
     $assign['bottomdockable'] = mapDockItemsMerge($assign['bottomdockable'], $items);
     // Add dockable js
     foreach (array_merge($assign['dockable'], $assign['minidockable'], $assign['bottomdockable']) as $d) {
         if ($d->js != '') {
             $rep->addJsLink($d->js);
         }
     }
     $themePath = jApp::config()->urlengine['basePath'] . 'themes/' . jApp::config()->theme . '/';
     $rep->addCssLink($themePath . 'css/main.css');
     $rep->addCssLink($themePath . 'css/map.css');
     $rep->addCssLink($themePath . 'css/media.css');
     // Add dockable css
     foreach ($assign['dockable'] as $d) {
         if ($d->css != '') {
             $rep->addCssLink($d->css);
         }
     }
     // Replace default theme by theme found in
     // the repository folder media/themes/default/
     if ($lrep->getData('allowUserDefinedThemes')) {
         $repositoryPath = $lrep->getPath();
         $cssArray = array('main', 'map', 'media');
         $themeArray = array('default', $project);
         foreach ($cssArray as $k) {
             foreach ($themeArray as $theme) {
                 $cssRelPath = 'media/themes/' . $theme . '/css/' . $k . '.css';
                 $cssPath = $lrep->getPath() . '/' . $cssRelPath;
                 if (file_exists($cssPath)) {
                     $cssUrl = jUrl::get('view~media:getCssFile', array('repository' => $lrep->getKey(), 'project' => $project, 'path' => $cssRelPath));
                     //~ $rep->addCssLink( $cssUrl );
                     // Use addHeadContent and not addCssLink to be sure it will be loaded after minified code
                     $rep->addHeadContent('<link type="text/css" href="' . $cssUrl . '" rel="stylesheet" />');
                 }
             }
         }
         // Add JS files found in media/js
         $jsDirArray = array('default', $project);
         foreach ($jsDirArray as $dir) {
             $jsPathRoot = realpath($repositoryPath . '/' . 'media/js/' . $dir);
             if (is_dir($jsPathRoot)) {
                 foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($jsPathRoot)) as $filename) {
                     $path_parts = pathinfo($filename);
                     if ($path_parts['extension'] == 'js') {
                         $jsPath = realpath($filename);
                         $jsRelPath = 'media/js/' . $dir . str_replace($jsPathRoot, '', $jsPath);
                         $jsUrl = jUrl::get('view~media:getMedia', array('repository' => $lrep->getKey(), 'project' => $project, 'path' => $jsRelPath));
                         //~ $rep->addJSLink( $jsUrl );
                         // Use addHeadContent and not addJSLink to be sure it will be loaded after minified code
                         $rep->addContent('<script type="text/javascript" src="' . $jsUrl . '" ></script>');
                     }
                 }
             }
         }
     }
     // optionnally hide some tools
     // header
     $jsCode = '';
     $mapMenuCss = '';
     $h = $this->intParam('h', 1);
     if ($h == 0 or property_exists($pOptions, 'hideHeader') && $pOptions->hideHeader == 'True') {
         $h = 0;
         $rep->addStyle('#body', 'padding-top:0px;');
         $rep->addStyle('#header', 'display:none; height:0px;');
     }
     // menu = left vertical menu with icons
     $m = $this->intParam('m', 1);
     if ($m == 0 or property_exists($pOptions, 'hideMenu') && $pOptions->hideMenu == 'True') {
         $m = 0;
         $rep->addStyle('#mapmenu', 'display:none !important; width:0px;');
         $rep->addStyle('#dock', 'left:0px; border-left:none;');
     }
     // legend = legend open at startup
     $l = $this->intParam('l', 1);
     if ($l == 0 or property_exists($pOptions, 'hideLegend') && $pOptions->hideLegend == 'True') {
         $l = 0;
         //~ $rep->addStyle('#dock', 'display:none;');
         $jsCode .= "\n      \$( document ).ready( function() {\n        lizMap.events.on({\n          'uicreated':function(evt){\n            \$('#button-switcher').click();\n          }\n        });\n      });\n      ";
     }
     // navbar
     $n = $this->intParam('n', 1);
     if ($n == 0 or property_exists($pOptions, 'hideNavbar') && $pOptions->hideNavbar == 'True') {
         $rep->addStyle('#navbar', 'display:none !important;');
     }
     // overview-box = scale & overview
     $o = $this->intParam('o', 1);
     if ($o == 0 or property_exists($pOptions, 'hideOverview') && $pOptions->hideOverview == 'True') {
         $rep->addStyle('#overview-box', 'display:none !important;');
     }
     // Apply interface modifications
     if ($jsCode != '') {
         $rep->addJSCode($jsCode);
     }
     // Hide groups checkboxes
     if (property_exists($pOptions, 'hideGroupCheckbox') && $pOptions->hideGroupCheckbox == 'True') {
         $rep->addStyle('#switcher-layers button[name="group"]', 'display:none !important;');
     }
     // Add filter
     $filterParam = $this->param('filter');
     $filter = array();
     if ($filterParam) {
         $fExp = explode(';', $filterParam);
         foreach ($fExp as $item) {
             $iExp = explode(':', $item);
             if (count($iExp) == 2) {
                 $filter[$iExp[0]] = $iExp[1];
             }
         }
         if (count($filter) > 0) {
             $rep->addJSCode("var lizLayerFilter = " . json_encode($filter) . ";");
         }
     }
     // Add styles if needed
     $stylesParam = $this->param('layerStyles');
     $styles = array();
     if ($stylesParam) {
         $fExp = explode(';', $stylesParam);
         foreach ($fExp as $item) {
             $iExp = explode(':', $item);
             if (count($iExp) == 2) {
                 $styles[$iExp[0]] = $iExp[1];
             }
         }
         if (count($styles) > 0) {
             $rep->addJSCode("var lizLayerStyles = " . json_encode($styles) . ";");
         }
     }
     //$assign['auth_url_return'] = jUrl::get('view~default:index');
     // switcher-layers-actions javascript
     $rep->addJSLink($bp . 'js/switcher-layers-actions.js');
     $rep->body->assign($assign);
     // Log
     $eventParams = array('key' => 'viewmap', 'content' => '', 'repository' => $lrep->getKey(), 'project' => $project);
     jEvent::notify('LizLogItem', $eventParams);
     return $rep;
 }
 /**
  * Save the data for the services section.
  * @return Redirect to the index.
  */
 function saveAccount()
 {
     // Get lizmap services
     $services = lizmap::getServices();
     $rep = $this->getResponse('redirect');
     $rep->action = 'view~default:index';
     // Redirect if option not active
     if (!$services->allowUserAccountRequests) {
         return $rep;
     }
     // Redirect if already a logged user
     if (jAuth::isConnected()) {
         jMessage::add(jLocale::get("view~user.already.logged"));
         return $rep;
     }
     // Get the form
     $form = jForms::get('view~lizmap_user');
     // token
     $token = $this->param('__JFORMS_TOKEN__');
     if (!$token) {
         $rep->action = "view~user:createAccount";
         return $rep;
     }
     // If the form is not defined, redirection
     if (!$form) {
         $rep->action = "view~user:createAccount";
         return $rep;
     }
     // Set the other form data from the request data
     $form->initFromRequest();
     // Check the form
     $ok = true;
     if (!$form->check()) {
         $ok = false;
     }
     // Check the honey pot. Redirect if filled (means robot)
     $honey = $form->getData('name');
     if ($honey and !empty($honey)) {
         $rep->action = "view~user:createAccount";
         return $rep;
     }
     if (!$ok) {
         // Errors : redirection to the display action
         $rep->action = 'view~user:editAccount';
         return $rep;
     }
     // Save the data
     $evresp = array();
     if (!jEvent::notify('jauthdbAdminCheckCreateForm', array('form' => $form))->inResponse('check', false, $evresp)) {
         // Sanitize some fields
         $sanitize = array('login', 'firstname', 'lastname', 'organization', 'phonenumber', 'street', 'postcode', 'city', 'country', 'comment');
         foreach ($sanitize as $field) {
             $form->setData($field, filter_var($form->getData($field), FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES));
         }
         // Add user to database via jAuth methods
         try {
             $props = jDao::createRecord('jauthdb~jelixuser', 'jauth')->getProperties();
             $user = jAuth::createUserObject($form->getData('login'), $form->getData('password'));
             $form->setData('password', $user->password);
             $form->prepareObjectFromControls($user, $props);
             jAuth::saveNewUser($user);
             jMessage::add(jLocale::get("view~user.form.message.saved"));
             $ok = true;
             $rep->action = "view~user:validateAccount";
         } catch (exception $e) {
             $ok = false;
             jMessage::add(jLocale::get("view~user.form.message.not.saved"));
             $rep->action = "view~user:editAccount";
         }
         // Send email to the administrator
         if ($ok) {
             try {
                 $this->sendEmailToAdmin($user);
             } catch (Exception $e) {
                 jLog::log('error while sending email to admin: ' . $e->getMessage());
             }
         }
     }
     return $rep;
 }
Exemple #27
0
 /**
  * check the validity of an IP address
  * @param string $ip IP of the member
  * @return boolean
  */
 public static function checkIp($ip)
 {
     $validIp = false;
     $newIp = '';
     //0) checking the content : list or range but not list AND range :
     if (strpos($ip, ',') > 0 and strpos($ip, '-') > 0) {
         jMessage::add(jLocale::get('havefnubb~ban.list.ip.or.range'));
         return false;
     } elseif (strpos($ip, ',') > 0) {
         $list = preg_split('/,/', $ip);
         foreach ($list as $item) {
             $validIp = jFilter::isIPv4($item);
             if ($validIp === false) {
                 jMessage::add(jLocale::get('havefnubb~ban.invalid.list.of.ip'));
                 return false;
             }
         }
     } elseif (strpos($ip, '-') > 0) {
         // ip is xxx.yyy.zzz-aaa
         $list = preg_split('/-/', $ip);
         // find xxx.yyy.
         $pos = strrpos($list[0], '.');
         // start is xxx.yyy.zzz
         $start = $list[0];
         // end is xxx.yyy.aaa
         $end = substr($list[0], 0, $pos) . '.' . $list[1];
         // validate each of them
         $validIp1 = jFilter::isIPv4($start);
         $validIp2 = jFilter::isIPv4($end);
         if ($validIp1 === false or $validIp2 === false) {
             jMessage::add(jLocale::get('havefnubb~ban.invalid.range.of.ip', array($start, $end)));
             return false;
         } else {
             return true;
         }
     } else {
         $validIp = jFilter::isIPv4($ip);
         if ($validIp === false) {
             jMessage::add(jLocale::get('havefnubb~ban.invalid.ip'));
             return false;
         }
     }
     return $validIp;
 }
 /**
  * Unlink child feature from their parent ( 1:n ) relation
  * by setting the foreign key to NULL
  *
  * @param string $repository Lizmap Repository
  * @param string $project Name of the project
  * @param string $layerId Child layer id.
  * @param string $pkey Child layer primary key value -> id of the line to update
  * @param string $fkey Child layer foreign key column (pointing to the parent layer primary key)
  * @return Redirect to the validation action.
  */
 function unlinkChild()
 {
     $lid = $this->param('lid');
     $fkey = $this->param('fkey');
     $pkey = $this->param('pkey');
     $pkeyval = $this->param('pkeyval');
     $project = $this->param('project');
     $repository = $this->param('repository');
     if (!$lid or !$fkey or !$pkey or !$pkeyval or !$project or !$repository) {
         jMessage::add(jLocale::get("view~edition.link.error.missing.parameter"), 'error');
         return $this->serviceAnswer();
     }
     // Get project configuration
     $lrep = lizmap::getRepository($repository);
     $lproj = lizmap::getProject($repository . '~' . $project);
     $this->project = $lproj;
     $this->repository = $lrep;
     // Get child layer information
     $layerXml = $lproj->getXmlLayer($lid);
     $layerXmlZero = $layerXml[0];
     $_layerName = $layerXmlZero->xpath('layername');
     $layerName = (string) $_layerName[0];
     $this->layerXml = $layerXml;
     // Get editLayer capabilities
     $eLayers = $lproj->getEditionLayers();
     $eLayer = $eLayers->{$layerName};
     if ($eLayer->capabilities->modifyAttribute != 'True') {
         jMessage::add('Modify feature attributes for this layer ' . $layerName . ' is not in the capabilities!', 'LayerNotEditable');
         return $this->serviceAnswer();
     }
     // Get fields data from the edition database
     $_datasource = $layerXmlZero->xpath('datasource');
     $datasource = (string) $_datasource[0];
     $s_provider = $layerXmlZero->xpath('provider');
     $this->provider = (string) $s_provider[0];
     $this->layerId = $lid;
     $this->layerName = $layerName;
     $this->getDataFields($datasource);
     // Check fields
     if (!array_key_exists($fkey, $this->dataFields) or !array_key_exists($pkey, $this->dataFields)) {
         jMessage::add('Given fields do not exists !', 'error');
         return $this->serviceAnswer();
     }
     // Build SQL
     $sql = '';
     $cnx = jDb::getConnection($this->layerId);
     $msg = false;
     $val = (int) $pkeyval;
     if ($this->dataFields[$key2]->type != 'int') {
         $val = $cnx->quote($val);
     }
     $sql = ' UPDATE ' . $this->table;
     $sql .= ' SET "' . $fkey . '" = NULL';
     $sql .= ' WHERE "' . $pkey . '" = ' . $val;
     $sql .= ';';
     // Need to break SQL ( if sqlite
     try {
         $rs = $cnx->query($sql);
         if (!$msg) {
             jMessage::add(jLocale::get('view~edition.unlink.success'), 'success');
         }
         $msg = true;
     } catch (Exception $e) {
         jLog::log("An error has been raised when modifiying data : " . $e->getMessage(), 'error');
         jLog::log("SQL = " . $sql);
         jMessage::add(jLocale::get('view~edition.unlink.error.sql'), 'error');
     }
     return $this->serviceAnswer();
 }
 /**
  * Get a CSS file stored in the repository in a "media/themes" folder.
  * Url to images are replaced by getMedia URL
  *
  * @param string $repository Repository of the project.
  * @param string $project Project key.
  * @param string $path Path to the CSS file relative to the project file.
  * @return binary object The transformed CSS file.
  */
 function getCssFile()
 {
     // Get repository data
     $repository = $this->param('repository');
     $lrep = lizmap::getRepository($repository);
     if (!jAcl2::check('lizmap.repositories.view', $lrep->getKey())) {
         $rep = $this->getResponse('redirect');
         $rep->action = 'view~default:error';
         jMessage::add(jLocale::get('view~default.repository.access.denied'), 'error');
         return $rep;
     }
     // Get the project
     $project = $this->param('project');
     // Get the file
     $path = $this->param('path');
     $repositoryPath = realpath($lrep->getPath());
     $abspath = realpath($repositoryPath . '/' . $path);
     $n_repositoryPath = str_replace('\\', '/', $repositoryPath);
     $n_abspath = str_replace('\\', '/', $abspath);
     $ok = True;
     // Only allow files within the repository for safety reasons
     // and in the media/themes/ folder
     if (!preg_match("#^" . $n_repositoryPath . "(/)?media/themes/#", $n_abspath)) {
         $ok = False;
     }
     // Check if file exists
     if ($ok and !file_exists($abspath)) {
         $ok = False;
     }
     // Check if file is CSS
     $path_parts = pathinfo($abspath);
     if (strtolower($path_parts['extension']) != 'css') {
         $ok = False;
     }
     // Redirect if errors
     if (!$ok) {
         $content = "No CSS file in the specified path";
         $rep = $this->getResponse('text');
         $rep->content = $content;
         return $rep;
     }
     // Prepare the file to return
     $rep = $this->getResponse('binary');
     $rep->doDownload = false;
     $rep->fileName = $abspath;
     // Get the name of the file
     $name = $path_parts['basename'] . '.' . $path_parts['extension'];
     $rep->outputFileName = $name;
     // Mime type
     $rep->mimeType = 'text/css';
     // Read content from file
     $content = jFile::read($abspath);
     // Replace relative images URL with getMedia URL
     $newPath = preg_replace("#" . $path_parts['basename'] . "\$#", '', $path);
     $baseUrl = jUrl::get('view~media:getMedia', array('repository' => $lrep->getKey(), 'project' => $project, 'path' => $newPath));
     $pattern = 'url\\((.+)\\)';
     $replacement = 'url(' . $baseUrl . '/\\1)';
     $content = preg_replace("#{$pattern}#", $replacement, $content);
     $content = str_replace('"', '', $content);
     $rep->content = $content;
     $rep->setExpires('+60 seconds');
     return $rep;
 }
 /**
  * change the status of the current THREAD (not just one post) !
  * @param integer $thread_id id of the thread
  * @param string $status the status to switch to
  * @return DaoRecord $record
  */
 public function switchStatus($thread_id, $id_post, $status)
 {
     if (!in_array($status, $this->statusAvailable)) {
         jMessage::add(jLocale::get('havefnubb~post.invalid.status'), 'error');
         return false;
     }
     if ($thread_id < 0) {
         return false;
     }
     if (jDao::get('havefnubb~posts')->updateStatusByThreadId($thread_id, $status)) {
         jEvent::notify('HfnuPostAfterStatusChanged', array('id' => $thread_id, 'status' => $status));
     }
     $daoThread = jDao::get('havefnubb~threads');
     $rec = $daoThread->get($thread_id);
     $rec->status_thread = $status;
     if ($status == 1 or $status == 2) {
         $rec->ispined_thread = 1;
     } else {
         $rec->ispined_thread = 0;
     }
     $daoThread->update($rec);
     return $this->getPost($id_post);
 }