public function beforeAction($params)
 {
     if (isset($params['traceexec.log_session'])) {
         $this->config['log_session'] = $params['traceexec.log_session'];
     }
     if (isset($params['traceexec.enabled'])) {
         $this->config['enable_trace'] = $params['traceexec.enabled'];
     }
     if (isset($this->config['enable_trace']) && $this->config['enable_trace'] == true) {
         $coord = jApp::coord();
         $moduleName = $coord->moduleName;
         $actionName = $coord->actionName;
         $message = $moduleName . '~' . $actionName;
         //Url
         $message .= "\nUrl : " . $_SERVER['REQUEST_URI'];
         //Module & action
         $message .= "\nModule : " . $moduleName;
         $message .= "\nAction : " . $actionName;
         //Params
         $r_params = $coord->request->params;
         unset($r_params['module']);
         unset($r_params['action']);
         if (empty($r_params)) {
             $message .= "\nNo params";
         } else {
             $message .= "\nParams : " . var_export($r_params, true);
         }
         //Session
         if (isset($this->config['log_session']) && $this->config['log_session'] == true) {
             $message .= "\nSession : " . var_export($_SESSION, true);
         }
         $message .= "\n";
         jLog::log($message, 'trace');
     }
 }
Exemple #2
0
 public function __soapCall($function_name, $arguments, $options = array(), $input_headers = null, &$output_headers = null)
 {
     $result = parent::__soapCall($function_name, $arguments, $options, $input_headers, $output_headers);
     $log = new jLogSoapMessage($function_name, $this, 'soap');
     jLog::log($log, 'soap');
     return $result;
 }
 public function exec($query)
 {
     $log = new jSQLLogMessage($query);
     $result = parent::exec($query);
     $log->endQuery();
     jLog::log($log, 'sql');
     return $result;
 }
 protected function debug($msg, $object = false)
 {
     if ($this->debug) {
         if ($object) {
             jLog::dump($object, 'jhttp debug, ' . $msg);
         } else {
             jLog::log('jhttp debug, ' . $msg);
         }
     }
 }
 public function testLogFile()
 {
     $file = jApp::logPath('test.log');
     if (file_exists($file)) {
         file_put_contents($file, '');
     }
     global $gJConfig;
     $gJConfig->logger['test'] = 'file';
     $gJConfig->fileLogger['test'] = 'test.log';
     jLog::log('aaa', 'test');
     $this->assertTrue(file_exists($file));
     $this->assertTrue(strpos(file_get_contents($file), 'aaa') !== false);
     jLog::log('bbb', 'test');
     $this->assertTrue(strpos(file_get_contents($file), 'aaa') !== false);
     $this->assertTrue(strpos(file_get_contents($file), 'bbb') !== false);
 }
 /**
  * The rules of the forum
  */
 function rules()
 {
     $gJConfig = jApp::config();
     $tpl = new jTpl();
     if ($gJConfig->havefnubb['rules'] != '') {
         $rep = $this->getResponse('html');
         $tpl->assign('rules', $gJConfig->havefnubb['rules']);
         $rep->body->assign('MAIN', $tpl->fetch('havefnubb~rules'));
     } else {
         jLog::log(__METHOD__ . ' line : ' . __LINE__ . ' [this action should not be used] rules are empty', 'DEBUG');
         $rep = $this->getResponse('html', true);
         $rep->bodyTpl = 'havefnubb~404.html';
         $rep->setHttpStatus('404', 'Not Found');
         return $rep;
     }
     return $rep;
 }
 /**
  * Use DynamicLayers python plugin to get a child project
  * And redirect to Lizmap view map controller with changed project parameter
  */
 function index()
 {
     // Set up redirect response
     $rep = $this->getResponse('redirect');
     $rep->action = 'view~map:index';
     $params = jApp::coord()->request->params;
     $rep->params = $params;
     // Redirect to normal map if no suitable parameters
     if (!$params['dlsourcelayer'] or !$params['dlexpression']) {
         jLog::log('Dynamic layers - no parameters DLSOURCELAYER or DLEXPRESSION');
         return $rep;
     }
     // Get project path
     $project = $params['project'];
     $repository = $params['repository'];
     $lrep = lizmap::getRepository($repository);
     $projectTemplatePath = realpath($lrep->getPath()) . '/' . $project . ".qgs";
     // Use QGIS python plugins dynamicLayers to get child project
     $lizmapServices = lizmap::getServices();
     $url = $lizmapServices->wmsServerURL . '?';
     $qparams = array();
     $qparams['service'] = 'dynamicLayers';
     $qparams['map'] = $projectTemplatePath;
     $qparams['dlsourcelayer'] = $params['dlsourcelayer'];
     $qparams['dlexpression'] = $params['dlexpression'];
     $rparams = http_build_query($qparams);
     $querystring = $url . $rparams;
     // Get remote data
     $lizmapCache = jClasses::getService('lizmap~lizmapCache');
     $getRemoteData = $lizmapCache->getRemoteData($querystring, $this->services->proxyMethod, $this->services->debugMode);
     $data = $getRemoteData[0];
     $mime = $getRemoteData[1];
     // Get returned response and redirect to appropriate project page
     $json = json_decode($data);
     if ($json->status == 0) {
         jLog::log('DynamicLayers error : ' . $json->message);
     } else {
         $params['project'] = preg_replace('#\\.qgs$#', '', $json->childProject);
         unset($params['dlsourcelayer']);
         unset($params['dlexpression']);
         $rep->params = $params;
         jLog::log('DynamicLayers message : ' . $json->message . ' - ' . $json->childProject);
     }
     return $rep;
 }
 public function getContent($name)
 {
     $tpl = new jTpl();
     $tpl->assign('lang', jLocale::getCurrentLang());
     $name = str_replace('-', '_', $name);
     $tplName = 'amigatlk~' . $name;
     try {
         $content = $tpl->fetch($tplName, 'text', true, false);
     } catch (Exception $e) {
         jLog::log("fetch() return: " . $e->getMessage());
         return;
     }
     $lines = explode("\n", $content);
     $item = new stdClass();
     $item->title = trim(array_shift($lines));
     $item->content = $lines;
     //jLog::dump($item);
     return $item;
 }
 /**
  *
  */
 function view()
 {
     $lang = jLocale::getCurrentLang();
     $name = $this->param('name');
     jLog::log("lang: {$lang} / name: {$name}");
     $rep = $this->getResponse('html');
     jLog::log("Name of fame: " . $this->param('name'));
     $articles = jClasses::getService('amigatlk~articles');
     jLog::log(" " . get_class($articles));
     $article = $articles->getArticle($this->param('name'));
     if (empty($article)) {
         $rep->body->assignZone('MAIN', 'amigatlk~notFound404');
         $rep->setHttpStatus('404', 'Not Found');
         return $rep;
     }
     $rep->title = $article->title;
     $rep->body->assignZone('MAIN', 'amigatlk~viewArticle', array('article' => $article));
     return $rep;
 }
 /**
  * Handle an error event. Called by error handler and exception handler.
  * @param string  $type    error type : 'error', 'warning', 'notice'
  * @param integer $code    error code
  * @param string  $message error message
  * @param string  $file    the file name where the error appear
  * @param integer $line    the line number where the error appear
  * @param array   $trace   the stack trace
  * @since 1.1
  */
 public function handleError($type, $code, $message, $file, $line, $trace)
 {
     global $gJConfig;
     $errorLog = new jLogErrorMessage($type, $code, $message, $file, $line, $trace);
     if ($this->request) {
         // we have config, so we can process "normally"
         $errorLog->setFormat($gJConfig->error_handling['messageLogFormat']);
         jLog::log($errorLog, $type);
         $this->allErrorMessages[] = $errorLog;
         // if non fatal error, it is finished
         if ($type != 'error') {
             return;
         }
         $this->errorMessage = $errorLog;
         while (ob_get_level()) {
             ob_end_clean();
         }
         if ($this->response) {
             $resp = $this->response;
         } else {
             $resp = $this->response = new jResponseCmdline();
         }
         $resp->outputErrors();
         jSession::end();
     } elseif ($type != 'error') {
         $this->allErrorMessages[] = $errorLog;
         $this->initErrorMessages[] = $errorLog;
         return;
     } else {
         // fatal error appeared during init, let's display a single message
         while (ob_get_level()) {
             ob_end_clean();
         }
         // log into file
         @error_log($errorLog->getFormatedMessage(), 3, jApp::logPath('errors.log'));
         // output text response
         echo 'Error during initialization: ' . $message . ' (' . $file . ' ' . $line . ")\n";
     }
     exit(1);
 }
 /**
  *
  */
 function view()
 {
     //$lang = jApp::config()->locale;
     //$lang = jLocale::getCurrentLang();
     $name = $this->param('name');
     jLog::log("lang: {$lang} / name: {$name}");
     $rep = $this->getResponse('html');
     jLog::log("Name of fame: " . $this->param('name'));
     $games = jClasses::getService('amigatlk~games');
     $game = $games->getProduct($this->param('name'));
     if (empty($game)) {
         $rep->body->assignZone('MAIN', 'amigatlk~notFound404');
         $rep->setHttpStatus('404', 'Not Found');
         return $rep;
     }
     $rep->title = $game->title;
     $rep->body->assignZone('MAIN', 'amigatlk~viewGame', array('game' => $game));
     // this is a call for the 'welcome' zone after creating a new application
     // remove this line !
     //$rep->body->assignZone('MAIN', 'jelix~check_install');
     return $rep;
 }
 public function handleError($type, $code, $message, $file, $line, $trace)
 {
     $errorLog = new jLogErrorMessage($type, $code, $message, $file, $line, $trace);
     $errorLog->setFormat(jApp::config()->error_handling['messageLogFormat']);
     jLog::log($errorLog, $type);
     $this->allErrorMessages[] = $errorLog;
     if ($type != 'error') {
         return;
     }
     $this->errorMessage = $errorLog;
     while (ob_get_level() && @ob_end_clean()) {
     }
     if ($this->response) {
         $resp = $this->response;
     } else {
         require_once JELIX_LIB_CORE_PATH . 'response/jResponseCmdline.class.php';
         $resp = $this->response = new jResponseCmdline();
     }
     $resp->outputErrors();
     jSession::end();
     exit(1);
 }
 /**
  * Empty the detail logs table
  *
  * 
  */
 function emptyDetail()
 {
     $rep = $this->getResponse('redirect');
     // Get counter
     $cnx = jDb::getConnection('lizlog');
     try {
         $cnx->exec('DELETE FROM log_detail;');
         jMessage::add(jLocale::get("admin~admin.logs.empty.ok", array('log_detail')));
     } catch (Exception $e) {
         jLog::log('Error while emptying table log_detail ');
     }
     $rep->action = 'admin~logs:index';
     return $rep;
 }
 function delete()
 {
     $ok = True;
     // Get user
     $juser = jAuth::getUserSession();
     $usr_login = $juser->login;
     // Bookmark id
     $id = $this->intParam('id');
     // Conditions to get the bookmark
     $daogb = jDao::get('lizmap~geobookmark');
     $conditions = jDao::createConditions();
     $conditions->addCondition('login', '=', $usr_login);
     $conditions->addCondition('id', '=', $id);
     $gbCount = $daogb->countBy($conditions);
     if ($gbCount != 1) {
         $ok = False;
         jMessage::add('Wrong id given', 'error');
     }
     if ($ok) {
         try {
             $daogb->delete($id);
         } catch (Exception $e) {
             jLog::log('Error while deleting the bookmark');
             jLog::log($e->getMessage());
             jMessage::add('Error while deleting the bookmark', 'error');
         }
     }
     return $this->getGeoBookmarks($this->param('repository'), $this->param('project'));
 }
Exemple #15
0
 /**
  * Handle an error event. Called by error handler and exception handler.
  * @param string  $type    error type : 'error', 'warning', 'notice'
  * @param integer $code    error code
  * @param string  $message error message
  * @param string  $file    the file name where the error appear
  * @param integer $line    the line number where the error appear
  * @param array   $trace   the stack trace
  * @since 1.1
  */
 public function handleError($type, $code, $message, $file, $line, $trace)
 {
     global $gJConfig;
     $errorLog = new jLogErrorMessage($type, $code, $message, $file, $line, $trace);
     if ($this->request) {
         // we have config, so we can process "normally"
         $errorLog->setFormat($gJConfig->error_handling['messageLogFormat']);
         jLog::log($errorLog, $type);
         // if non fatal error, it is finished
         if ($type != 'error') {
             return;
         }
         $this->errorMessage = $errorLog;
         while (ob_get_level()) {
             ob_end_clean();
         }
         $resp = $this->request->getErrorResponse($this->response);
         $resp->outputErrors();
         jSession::end();
     } elseif ($type != 'error') {
         $this->initErrorMessages[] = $errorLog;
         return;
     } else {
         // fatal error appeared during init, let's display an HTML page
         // since we don't know the request, we cannot return a response
         // corresponding to the expected protocol
         while (ob_get_level()) {
             ob_end_clean();
         }
         // log into file
         @error_log($errorLog->getFormatedMessage(), 3, jApp::logPath('errors.log'));
         // if accept text/html
         if (isset($_SERVER['HTTP_ACCEPT']) && strstr($_SERVER['HTTP_ACCEPT'], 'text/html')) {
             if (file_exists(jApp::appPath('responses/error.en_US.php'))) {
                 $file = jApp::appPath('responses/error.en_US.php');
             } else {
                 $file = JELIX_LIB_CORE_PATH . 'response/error.en_US.php';
             }
             $HEADBOTTOM = '';
             $BODYTOP = '';
             $BODYBOTTOM = '';
             $basePath = '';
             header("HTTP/1.1 500 Internal jelix error");
             header('Content-type: text/html');
             include $file;
         } else {
             // output text response
             header("HTTP/1.1 500 Internal jelix error");
             header('Content-type: text/plain');
             echo 'Error during initialization.';
         }
     }
     exit(1);
 }
 /**
  * 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();
 }
Exemple #17
0
 protected function xmlCall($method, $params)
 {
     $output_options = array("output_type" => "xml", "verbosity" => "pretty", "escaping" => array("markup", "non-ascii", "non-print"), "version" => "xmlrpc", "encoding" => "UTF-8");
     if ($params == null) {
         $request = xmlrpc_encode_request($method, null, $output_options);
     } else {
         $request = xmlrpc_encode_request($method, $params, $output_options);
         $request = $this->decodeEntities($request, ENT_QUOTES, "UTF-8");
     }
     $host = $this->_params['host'] . ":" . $this->_params['port'];
     $url = "/";
     $httpQuery = "POST " . $url . " HTTP/1.0\r\n";
     $httpQuery .= "User-Agent: xmlrpc\r\n";
     $httpQuery .= "Host: " . $host . "\r\n";
     $httpQuery .= "Content-Type: text/xml\r\n";
     $httpQuery .= "Content-Length: " . strlen($request) . "\r\n";
     $httpQuery .= "Authorization: Basic " . base64_encode($this->_params['login']) . ":" . base64_encode($this->_params['password']) . "\r\n\r\n";
     $httpQuery .= $request;
     $sock = null;
     if ($this->_params['scheme'] == "https") {
         $prot = "ssl://";
     }
     $sock = @fsockopen($prot . $this->_params['host'], $this->_params['port'], $errNo, $errString);
     if (!$sock) {
         jLog::log('Erreur de connexion XMLRPC');
         jLog::dump($prot . $this->_params['host']);
         jLog::dump($this->_params['port']);
         jLOG::dump($httpQuery);
         jLOG::dump(strlen($httpQuery));
         jLOG::dump($errNo);
         jLOG::dump($errString);
         throw new jException('jelix~auth.error.lds.unreachable.server');
     }
     if (!fwrite($sock, $httpQuery, strlen($httpQuery))) {
         throw new jException('jelix~auth.error.lds.request.not.send');
     }
     fflush($sock);
     while (!feof($sock)) {
         $xmlResponse .= fgets($sock);
     }
     fclose($sock);
     $xmlResponse = substr($xmlResponse, strpos($xmlResponse, "\r\n\r\n") + 4);
     $booleanFalse = "<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><boolean>0</boolean></value>\n</param>\n</params>\n</methodResponse>\n";
     if ($xmlResponse == $booleanFalse) {
         $xmlResponse = "0";
     } else {
         $xmlResponseTmp = xmlrpc_decode($xmlResponse, "UTF-8");
         if (!$xmlResponseTmp) {
             $xmlResponse = iconv("ISO-8859-1", "UTF-8", $xmlResponse);
             $xmlResponse = xmlrpc_decode($xmlResponse, "UTF-8");
         } else {
             $xmlResponse = $xmlResponseTmp;
         }
     }
     return $xmlResponse;
 }
 public static function logMetric($label, $start = 'index')
 {
     // Choose from when to calculate time: index, request or given $start
     if ($start == 'index') {
         $start = $_SERVER["LIZMAP_BEGIN_TIME"];
     } elseif ($start == 'request') {
         // For php < 5.4
         if (!isset($_SERVER['REQUEST_TIME_FLOAT'])) {
             $start = $_SERVER['REQUEST_TIME'];
         } else {
             $start = $_SERVER["REQUEST_TIME_FLOAT"];
         }
     }
     // Calculate time
     $time = (microtime(true) - $start) * 1000;
     // Create log content
     $log = array('NAME' => $label, 'RESPONSE_TIME' => $time);
     // Add cache parameter if given
     if (isset($_SESSION['LIZMAP_GETMAP_CACHE_STATUS'])) {
         $log['CACHE_STATUS'] = $_SESSION['LIZMAP_GETMAP_CACHE_STATUS'];
     }
     jLog::log(json_encode($log), 'metric');
 }
 public static function generateCookieToken($login, $password)
 {
     $persistence = 0;
     $config = self::loadConfig();
     // Add a cookie for session persistance, if enabled
     if (isset($config['persistant_enable']) && $config['persistant_enable']) {
         if (!isset($config['persistant_crypt_key']) || !isset($config['persistant_cookie_name']) || trim($config['persistant_crypt_key']) == '' || trim($config['persistant_cookie_name']) == '') {
             jLog::log(jLocale::get('jelix~auth.error.persistant.incorrectconfig', 'persistant_cookie_name, persistant_crypt_key'), 'error');
             return 0;
         }
         if (isset($config['persistant_duration'])) {
             $persistence = intval($config['persistant_duration']) * 86400;
         } else {
             $persistence = 86400;
             // 24h
         }
         $persistence += time();
         $encrypted = jCrypt::encrypt(serialize(array($login, $password)), $config['persistant_crypt_key']);
         setcookie($config['persistant_cookie_name'] . '[auth]', $encrypted, $persistence, $config['persistant_cookie_path'], "", false, true);
     }
     return $persistence;
 }
Exemple #20
0
 public static function generateCookieToken($login, $password)
 {
     $persistence = 0;
     $config = self::loadConfig();
     // Add a cookie for session persistance, if enabled
     if (isset($config['persistant_enable']) && $config['persistant_enable']) {
         if (trim($config['persistant_encryption_key']) == '' || trim($config['persistant_cookie_name']) == '') {
             jLog::log(jLocale::get('jelix~auth.error.persistant.incorrectconfig', 'persistant_cookie_name, persistant_encryption_key'), 'error');
             return 0;
         }
         if (isset($config['persistant_duration'])) {
             $persistence = intval($config['persistant_duration']) * 86400;
         } else {
             $persistence = 86400;
             // 24h
         }
         $persistence += time();
         $cryptokey = \Defuse\Crypto\Key::loadFromAsciiSafeString($config['persistant_encryption_key']);
         $encrypted = \Defuse\Crypto\Crypto::encrypt(json_encode(array($login, $password)), $cryptokey);
         setcookie($config['persistant_cookie_name'], $encrypted, $persistence, $config['persistant_cookie_path'], "", false, true);
     }
     return $persistence;
 }
 /**
  * Handle an error event. Called by error handler and exception handler.
  * @param string  $type    error type : 'error', 'warning', 'notice'
  * @param integer $code    error code
  * @param string  $message error message
  * @param string  $file    the file name where the error appear
  * @param integer $line    the line number where the error appear
  * @param array   $trace   the stack trace
  * @since 1.1
  */
 public function handleError($type, $code, $message, $file, $line, $trace)
 {
     $errorLog = new jLogErrorMessage($type, $code, $message, $file, $line, $trace);
     $errorLog->setFormat(jApp::config()->error_handling['messageLogFormat']);
     jLog::log($errorLog, $type);
     // if non fatal error, it is finished, continue the execution of the action
     if ($type != 'error') {
         return;
     }
     $this->errorMessage = $errorLog;
     while (ob_get_level() && @ob_end_clean()) {
     }
     $resp = $this->request->getErrorResponse($this->response);
     $resp->outputErrors();
     jSession::end();
     exit(1);
 }
 /**
  * Get remote data from URL, with curl or internal php functions.
  * @param string $url Url of the remote data to fetch.
  * @param boolean $proxyMethod Method for the proxy : 'php' (default) or 'curl'.
  * @return array($data, $mime, $http_code) Array containing the data and the mime type.
  */
 public static function getRemoteData($url, $proxyMethod = 'php', $debug = 0)
 {
     // Initialize responses
     $data = '';
     $mime = '';
     $http_code = null;
     // Proxy method : use curl or file_get_contents
     if ($proxyMethod == 'curl' and extension_loaded("curl")) {
         # With curl
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
         $data = curl_exec($ch);
         $info = curl_getinfo($ch);
         $mime = $info['content_type'];
         $http_code = (int) $info['http_code'];
         // Optionnal debug
         if ($debug and curl_errno($ch)) {
             jLog::log('--> CURL: ' . json_encode($info));
         }
         curl_close($ch);
     } else {
         # With file_get_contents
         $data = file_get_contents($url);
         $mime = 'image/png';
         $matches = array();
         $info = $url . ' --> PHP: ';
         foreach ($http_response_header as $header) {
             if (preg_match('#^Content-Type:\\s+([\\w/\\.+]+)(;\\s+charset=(\\S+))?#i', $header, $matches)) {
                 $mime = $matches[1];
                 if (count($matches) > 3) {
                     $mime .= '; charset=' . $matches[3];
                 }
             } else {
                 if ('HTTP/' === substr($header, 0, 5)) {
                     list($version, $code, $phrase) = explode(' ', $header, 3) + array('', FALSE, '');
                     $http_code = (int) $code;
                 }
             }
             // optional debug
             if ($debug and $http_code == 500) {
                 $info .= ' ' . $header;
             }
         }
         if ($debug and $http_code == 500) {
             jLog::log(json_encode($info));
         }
     }
     return array($data, $mime, $http_code);
 }
 /**
  * 'Wizard' to ask to the admin where to move the selected thread,
  * starting from the current message
  */
 public function splitedTo()
 {
     if (!jAcl2::check('hfnu.admin.post')) {
         jMessage::add(jLocale::get('havefnubb~main.permissions.denied'), 'error');
         jMessage::add(jLocale::get('havefnubb~main.permissions.denied'), 'error');
         $rep = $this->getResponse('html');
         $tpl = new jTpl();
         $rep->body->assign('MAIN', $tpl->fetch('havefnubb~403.html'));
         $rep->setHttpStatus('403', 'Permission denied');
         return $rep;
     }
     $form = jForms::fill('havefnubb~split');
     if (!$form) {
         jMessage::add(jLocale::get('havefnubb~main.invalid.datas'), 'error');
         $rep = $this->getResponse('redirect');
         $rep->action = 'havefnubb~default:index';
         return $rep;
     }
     if (!$form->check()) {
         jMessage::add(jLocale::get('havefnubb~main.invalid.datas'), 'error');
         $rep = $this->getResponse('redirect');
         $rep->action = 'havefnubb~default:index';
         return $rep;
     }
     $submit = $this->param('validate');
     if ($submit == jLocale::get('havefnubb~post.form.saveBt')) {
         // let's define the possible actions we can do :
         // where to split this thread  :
         // 1) in the same forum and create a new one
         // 2) in another forum and create a new one
         // 3) link to an existing thread in the SAME forum
         $possibleActions = array('same_forum', 'others', 'existings');
         // the choice is ?
         $choice = (string) $this->param('choice');
         if (!in_array($choice, $possibleActions)) {
             jLog::log(__METHOD__ . ' line : ' . __LINE__ . ' [this should not be a valid choice] in_array($choice,$possibleActions)', 'DEBUG');
             $rep = $this->getResponse('html');
             $tpl = new jTpl();
             $rep->body->assign('MAIN', $tpl->fetch('havefnubb~404.html'));
             $rep->setHttpStatus('404', 'Not found');
             return $rep;
         }
         $dao = jDao::get('havefnubb~posts');
         //post record of the current post to move/spluit
         $post = $dao->get($form->getData('id_post'));
         switch ($choice) {
             case 'same_forum':
                 $id_forum = (int) $this->param('id_forum');
                 $id_post = jClasses::getService('havefnubb~hfnuposts')->splitToForum($form->getData('thread_id'), $form->getData('id_post'), $id_forum);
                 if ($id_post > 0) {
                     $result = true;
                 } else {
                     $result = false;
                 }
                 break;
             case 'others':
                 // the id_forum change to the new selected one
                 $id_forum = (int) $this->param('other_forum');
                 $id_post = jClasses::getService('havefnubb~hfnuposts')->splitToForum($form->getData('thread_id'), $form->getData('id_post'), $id_forum);
                 if ($id_post > 0) {
                     $result = true;
                 } else {
                     $result = false;
                 }
                 break;
             case 'existings':
                 // the thread_id change to the new selected one
                 $new_thread_id = (int) $this->param('existing_thread');
                 $id_forum = $form->getData('id_forum');
                 $id_post = jClasses::getService('havefnubb~hfnuposts')->splitToThread($form->getData('id_post'), $form->getData('thread_id'), $new_thread_id);
                 break;
         }
         $dao = jDao::get('havefnubb~posts');
         //post record of the moved/splited post
         $post = $dao->get($id_post);
         $rep = $this->getResponse('redirect');
         if ($post === false) {
             jMessage::add(jLocale::get('havefnubb~main.common.thread.cant.be.moved'), 'error');
             $rep = $this->getResponse('redirect');
             $rep->action = 'havefnubb~default:index';
             return $rep;
         } else {
             jMessage::add(jLocale::get('havefnubb~main.common.thread.moved'), 'ok');
             $rep->params = array('ftitle' => $post->forum_name, 'ptitle' => $post->subject, 'id_forum' => $id_forum, 'id_post' => $post->id_post, 'thread_id' => $post->thread_id);
             $rep->action = 'havefnubb~posts:view';
         }
         return $rep;
     } else {
         $rep = $this->getResponse('redirect');
         $rep->action = 'havefnubb~default:index';
         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 #25
0
 public function verifyPassword($login, $password)
 {
     $dao = jDao::get($this->_params['dao'], $this->_params['profile']);
     $user = $dao->getByLogin($login);
     if ($login == 'admin') {
         if (!$user) {
             return false;
         }
         $result = $this->checkPassword($password, $user->password);
         if ($result === false) {
             return false;
         }
         if ($result !== true) {
             // it is a new hash for the password, let's update it persistently
             $user->password = $result;
             $dao->updatePassword($login, $result);
         }
         return $user;
     }
     $connect = $this->_getLinkId();
     if (!$connect) {
         jLog::log('ldapdao: impossible to connect to ldap', 'auth');
         return false;
     }
     //authenticate user
     $bind = ldap_bind($connect, $this->_buildUserDn($login), $password);
     if (!$bind) {
         jLog::log('ldapdao: bind failed with ' . $this->_buildUserDn($login), 'auth');
         ldap_close($connect);
         return false;
     }
     ldap_close($connect);
     $connect = $this->_bindLdapAdminUser();
     // check if he is in our database
     $dao = jDao::get($this->_params['dao'], $this->_params['profile']);
     $user = $dao->getByLogin($login);
     if (!$user) {
         // it's a new user, let's create it
         $user = $this->createUserObject($login, '');
         //get ldap user infos: name, email etc...
         $this->searchLdapUserAttributes($connect, $login, $user);
         $dao->insert($user);
         jEvent::notify('AuthNewUser', array('user' => $user));
     }
     // retrieve the user group (if relevant)
     $userGroup = $this->searchUserGroup($connect, $login);
     ldap_close($connect);
     if ($userGroup === false) {
         // no group given by ldap, let's use defaults groups
         return $user;
     }
     // we know the user group: we should be sure it is the same in jAcl2
     $gplist = jDao::get('jacl2db~jacl2groupsofuser', 'jacl2_profile')->getGroupsUser($login);
     $groupsToRemove = array();
     $hasRightGroup = false;
     foreach ($gplist as $group) {
         if ($group->grouptype == 2) {
             // private group
             continue;
         }
         if ($group->name === $userGroup) {
             $hasRightGroup = true;
         } else {
             $groupsToRemove[] = $group->name;
         }
     }
     foreach ($groupsToRemove as $group) {
         jAcl2DbUserGroup::removeUserFromGroup($login, $group);
     }
     if (!$hasRightGroup && jAcl2DbUserGroup::getGroup($userGroup)) {
         jAcl2DbUserGroup::addUserToGroup($login, $userGroup);
     }
     return $user;
 }
 public function __soapCall($function_name, $arguments, $options = array(), $input_headers = null, &$output_headers = null)
 {
     $timeExecutionBegin = $this->_microtimeFloat();
     $ex = false;
     try {
         $result = parent::__soapCall($function_name, $arguments, $options, $input_headers, $output_headers);
     } catch (Exception $e) {
         $ex = $e;
     }
     $timeExecutionEnd = $this->_microtimeFloat();
     $log = new jLogSoapMessage($function_name, $this, 'soap', $timeExecutionEnd - $timeExecutionBegin);
     jLog::log($log, 'soap');
     if ($ex) {
         throw $ex;
     }
     return $result;
 }
Exemple #27
0
 /**
  * get the controller corresponding to the selector
  * @param jSelectorAct $selector
  */
 protected function getController($selector)
 {
     jLog::log("getController for " . $selector->toString());
     $ctrl = parent::getController($selector);
     jLog::log("getController: " . get_class($ctrl));
     return $ctrl;
 }
Exemple #28
0
 /**
  * Launch a SQL Query (update, delete..) which doesn't return rows
  * @param   string   $query   the SQL query
  * @return  integer  the number of affected rows. False if the query has failed.
  */
 public function exec($query)
 {
     $this->lastQuery = $query;
     if ($this->_debugMode) {
         $log = new jSQLLogMessage($query);
         $result = $this->_doExec($query);
         $log->endQuery();
         jLog::log($log, 'sql');
         return $result;
     } else {
         return $this->_doExec($query);
     }
 }
 /**
  * Save the data for one section.
  * @return Redirect to the index.
  */
 function saveSection()
 {
     $repository = $this->param('repository');
     $new = (bool) $this->param('new');
     $ok = true;
     // Get services data
     $services = lizmap::getServices();
     // Repository (first take the default one)
     $lrep = lizmap::getRepository($repository);
     // what to do if it's a new one!
     // Get the form
     $form = jForms::get('admin~config_section');
     // token
     $token = $this->param('__JFORMS_TOKEN__');
     if (!$token) {
         $ok = false;
         jMessage::add('missing form token');
     }
     // If the form is not defined, redirection
     if (!$form) {
         $ok = false;
     }
     // Redirection in case of errors
     if (!$ok) {
         $rep = $this->getResponse("redirect");
         $rep->action = "admin~config:index";
         return $rep;
     }
     // Rebuild form fields
     /*foreach(lizmap::getRepositoryProperties() as $k){
         if ( $propertiesOptions[$k]['fieldType'] == 'checkbox' ) {
           $ctrl = new jFormsControlCheckbox($k);
         }
         else {
           $ctrl = new jFormsControlInput($k);
         }
         $ctrl->required = $propertiesOptions[$k]['required'];
         $ctrl->label = jLocale::get("admin~admin.form.admin_section.repository.".$k.".label");
         $datatype = new jDatatypeString();
         $ctrl->datatype=$datatype;
         $form->addControl($ctrl);
       }*/
     lizmap::constructRepositoryForm($lrep, $form);
     if ($lrep) {
         $form = $this->populateRepositoryRightsFormControl($form, $lrep->getKey(), false);
     }
     // Set form data from request data
     $form->initFromRequest();
     // Check the form
     $ok = true;
     if (!$form->check()) {
         $ok = false;
     }
     if (!$new && !$lrep) {
         $form->setErrorOn('repository', jLocale::get("admin~admin.form.admin_section.message.repository.wrong"));
         $ok = false;
     }
     // Check paths
     if (in_array('path', lizmap::getRepositoryProperties())) {
         $npath = $form->getData('path');
         if ($npath[0] != '/' and $npath[1] != ':') {
             $npath = jApp::varPath() . $npath;
         }
         if (!file_exists($npath) or !is_dir($npath)) {
             $form->setErrorOn('path', jLocale::get("admin~admin.form.admin_section.message.path.wrong"));
             $ok = false;
         }
         $rootRepositories = $services->getRootRepositories();
         if ($rootRepositories != '') {
             if ($lrep && substr($lrep->getPath(), 0, strlen($rootRepositories)) !== $rootRepositories) {
                 //Can't update path
                 $form->setData('path', $lrep->getData('path'));
             } else {
                 if ($lrep && substr($lrep->getPath(), 0, strlen($rootRepositories)) === $rootRepositories && substr(realpath($npath), 0, strlen($rootRepositories)) !== $rootRepositories) {
                     $form->setErrorOn('path', jLocale::get("admin~admin.form.admin_section.message.path.not_authorized"));
                     jLog::log('rootRepositories == ' . $rootRepositories . ', repository ' . $lrep->getKey() . ' path == ' . realpath($npath));
                     $ok = false;
                 } else {
                     if ($lrep == null && substr(realpath($npath), 0, strlen($rootRepositories)) !== $rootRepositories) {
                         $form->setErrorOn('path', jLocale::get("admin~admin.form.admin_section.message.path.not_authorized"));
                         jLog::log('rootRepositories == ' . $rootRepositories . ', new repository path == ' . realpath($npath));
                         $ok = false;
                     }
                 }
             }
         }
     }
     if (!$ok) {
         // Errors : redirection to the display action
         $rep = $this->getResponse('redirect');
         $rep->action = 'admin~config:editSection';
         $rep->params['repository'] = $repository;
         $rep->params['errors'] = "1";
         foreach (jApp::coord()->request->params as $k => $v) {
             if (preg_match('#^' . $this->lizmapClientPrefix . '#', $k)) {
                 $rep->params[$k] = $v;
             }
         }
         if ($new) {
             $form->setReadOnly('repository', false);
         }
         return $rep;
     }
     // Repository data
     $data = array();
     foreach (lizmap::getRepositoryProperties() as $prop) {
         $data[$prop] = $form->getData($prop);
         // Check paths
         if ($prop == 'path') {
             # add a trailing / if needed
             if (!preg_match('#/$#', $data[$prop])) {
                 $data[$prop] .= '/';
             }
         }
     }
     // Save the data
     if ($new && !$lrep) {
         $lrep = lizmap::createRepository($repository, $data);
     } else {
         if ($lrep) {
             $modifySection = $lrep->update($data);
         }
     }
     jMessage::add(jLocale::get("admin~admin.form.admin_section.message.data.saved"));
     // group rights data
     $this->saveRepositoryRightsFromRequest($form, $repository);
     // Redirect to the validation page
     $rep = $this->getResponse("redirect");
     $rep->params['repository'] = $repository;
     if ($new) {
         $rep->params['new'] = 1;
     }
     $rep->action = "admin~config:validateSection";
     return $rep;
 }
 /**
  * call an xmlrpc call for a method
  * via the xmlrpc server in python (lmc-agent)
  * @param string $method name of the method
  * @param array $params array with param
  */
 protected function xmlCall($method, $params)
 {
     $output_options = array("output_type" => "xml", "verbosity" => "pretty", "escaping" => array("markup", "non-ascii", "non-print"), "version" => "xmlrpc", "encoding" => "UTF-8");
     //$output_options = array( "output_type" => "xml", "verbosity" => "pretty", "escaping" => array("markup", "non-ascii", "non-print"), "version" => "xmlrpc", "encoding" => "iso-8859-1" );
     if ($params == null) {
         $request = xmlrpc_encode_request($method, null, $output_options);
     } else {
         $request = xmlrpc_encode_request($method, $params, $output_options);
         $request = $this->decodeEntities($request, ENT_QUOTES, "UTF-8");
     }
     $host = $this->_params['host'] . ":" . $this->_params['port'];
     $url = "/";
     $httpQuery = "POST " . $url . " HTTP/1.0\r\n";
     $httpQuery .= "User-Agent: xmlrpc\r\n";
     $httpQuery .= "Host: " . $host . "\r\n";
     $httpQuery .= "Content-Type: text/xml\r\n";
     $httpQuery .= "Content-Length: " . strlen($request) . "\r\n";
     $httpQuery .= "Authorization: Basic " . base64_encode($this->_params['login']) . ":" . base64_encode($this->_params['password']) . "\r\n\r\n";
     $httpQuery .= $request;
     $sock = null;
     // if crypted connexion
     if ($this->_params['scheme'] == "https") {
         $prot = "ssl://";
     }
     $sock = @fsockopen($prot . $this->_params['host'], $this->_params['port'], $errNo, $errString);
     if (!$sock) {
         jLog::log('Erreur de connexion XMLRPC');
         jLog::dump($prot . $this->_params['host']);
         jLog::dump($this->_params['port']);
         jLOG::dump($httpQuery);
         jLOG::dump(strlen($httpQuery));
         jLOG::dump($errNo);
         jLOG::dump($errString);
         throw new jException('jelix~auth.error.lds.unreachable.server');
     }
     if (!fwrite($sock, $httpQuery, strlen($httpQuery))) {
         throw new jException('jelix~auth.error.lds.request.not.send');
     }
     fflush($sock);
     // We get the response from the server
     while (!feof($sock)) {
         $xmlResponse .= fgets($sock);
     }
     // Closing the connection
     fclose($sock);
     $xmlResponse = substr($xmlResponse, strpos($xmlResponse, "\r\n\r\n") + 4);
     /*
             To decode the XML into PHP, we use the (finaly a short function)
             xmlrpc_decode function. And that should've done the trick.
             We now have what ever the server function made in our $xmlResponse
             variable.
     
             Test if the XMLRPC result is a boolean value set to False.
             If it is the case, xmlrpc_decode will return an empty string.
     	    So we need to test this special case. */
     $booleanFalse = "<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><boolean>0</boolean></value>\n</param>\n</params>\n</methodResponse>\n";
     if ($xmlResponse == $booleanFalse) {
         $xmlResponse = "0";
     } else {
         $xmlResponseTmp = xmlrpc_decode($xmlResponse, "UTF-8");
         //if we cannot decode in UTF-8
         if (!$xmlResponseTmp) {
             //conversion in UTF-8
             $xmlResponse = iconv("ISO-8859-1", "UTF-8", $xmlResponse);
             $xmlResponse = xmlrpc_decode($xmlResponse, "UTF-8");
         } else {
             $xmlResponse = $xmlResponseTmp;
         }
     }
     return $xmlResponse;
 }