Example #1
0
function getdata($servers, $extensions)
{
    $line = '';
    $extbyhost = array();
    foreach ($extensions as $extension => $extension_data) {
        if (!array_key_exists('host', $extension_data)) {
            continue;
        }
        if (!array_key_exists($extension_data['host'], $extbyhost)) {
            $extbyhost[$extension_data['host']] = array();
        }
        $extbyhost[$extension_data['host']][$extension] = False;
    }
    unset($extensions);
    foreach ($extbyhost as $host => $extensions) {
        if ($line) {
            $line .= ',';
        }
        if (array_key_exists($host, $servers)) {
            $line .= get_data_from_server($host, $servers[$host]['port'], @array_keys($extbyhost[$host]));
        } else {
            $line .= get_data_from_server($servers[0]['host'], $servers[0]['port'], @array_keys($extbyhost[$host]));
        }
    }
    if (!$extbyhost) {
        return return_error(3, 'no extension states');
    }
    if (!$line) {
        return return_error(101, 'NO DATA');
    }
    return $line;
}
 public function run($arg)
 {
     static $created_table = array();
     $func_arg = $arg['function_info']['arg'];
     switch (strtolower($arg['function_info']['function'])) {
         case 'percentile':
             if ($func_arg[0]['expr_type'] != 'colref') {
                 return return_error('PERCENTILE: Only column references are allowed as the first argument to this function', $arg['tmp_shard'], 'ERR_SQ_INVALID_FUNC_CALL');
             }
             if ($func_arg[1]['expr_type'] != 'const') {
                 return return_error('PERCENTILE: Only constants are allowed as the second argument to this function', $arg['tmp_shard'], 'ERR_SQ_INVALID_FUNC_CALL');
             }
             if (!empty($func_arg[2])) {
                 return return_error('PERCENTILE: Wrong number of arguments to this function', $arg['tmp_shard'], 'ERR_SQ_INVALID_FUNC_CALL');
             }
             $colname = $arg['function_info']['colref_map'][$func_arg['0']['base_expr']];
             $conn = SimpleDAL::factory($arg['tmp_shard']);
             if ($conn->my_error()) {
                 return return_error('Failed to connect to storage node', $arg['tmp_shard'], $conn->my_error());
             }
             $conn->my_select_db($arg['tmp_shard']['db']);
             if (empty($created_table[$arg['func_call_id']])) {
                 $sql = "CREATE TABLE IF NOT EXISTS`" . $arg['func_call_id'] . "` (gb_hash char(40) primary key, retval double) ";
                 $result = $conn->my_query($sql);
                 if (!$result || $conn->my_error()) {
                     return return_error('SQL error:', $arg['tmp_shard'], $conn->my_error());
                 }
                 $created_table[$arg['func_call_id']] = 1;
             }
             $sql = "select count(distinct {$colname}) cnt from `" . $arg['table'] . "` where gb_hash = '" . $arg['gb_hash'] . "'";
             $result = $conn->my_query($sql);
             if (!$result || $conn->my_error()) {
                 return return_error('SQL error:', $arg['tmp_shard'], $conn->my_error());
             }
             $row = $conn->my_fetch_assoc();
             if (!$row) {
                 return return_error('No row found for given gb_hash:' . $arg['gb_hash'], $arg['tmp_shard'], 'ERR_SQ_NO_ROW_FOUND');
             }
             $percentile_at = $func_arg[1]['base_expr'];
             $limit = floor(0.01 * $percentile_at * $row['cnt']);
             if ($limit < 1) {
                 $limit = 0;
             }
             $sql = "insert into `" . $arg['func_call_id'] . "` select distinct '" . $arg['gb_hash'] . "', {$colname} from `" . $arg['table'] . "` where gb_hash ='" . $arg['gb_hash'] . "' order by {$colname} limit {$limit},1";
             $conn->my_query($sql);
             if (!$result || $conn->my_error()) {
                 return return_error('SQL error:', $arg['tmp_shard'], $conn->my_error());
             }
             return true;
             break;
     }
 }
function send_telegram($config, $name, $message)
{
    # Check if the message is base64 encoded
    if (!validBase64($message)) {
        return_error("Error: Message invalid");
    } else {
        $message = date("H:i:s") . " - " . $name . ": " . base64_decode($message);
    }
    $post_fields = array();
    $post_fields['chat_id'] = $config['userid'];
    $post_fields['disable_web_page_preview'] = 1;
    $post_fields['text'] = $message;
    $req = curl_init('https://api.telegram.org/bot' . $config['apikey'] . '/sendMessage');
    curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($req, CURLOPT_POSTFIELDS, $post_fields);
    $response = curl_exec($req);
    curl_close($req);
    $return_string = json_decode($response);
    return $return_string->ok;
}
Example #4
0
    if (is_null($node)) {
        return false;
    }
    if (!$node->hasAttribute('mode')) {
        return false;
    }
    $logout_mode = $node->getAttribute('mode');
    return $logout_mode;
}
if (!array_key_exists('session_id', $_SESSION)) {
    echo return_error(1, 'Usage: missing "session_id" $_SESSION parameter');
    die;
}
$ret = parse_logout_XML(@file_get_contents('php://input'));
if (!$ret) {
    return_error(2, 'Client does not send a valid XML');
}
$session = Abstract_Session::load($_SESSION['session_id']);
if (is_object($session)) {
    if ($ret == 'suspend') {
        $session->setStatus(Session::SESSION_STATUS_INACTIVE, Session::SESSION_END_STATUS_LOGOUT);
    } else {
        $session->setStatus(Session::SESSION_STATUS_WAIT_DESTROY, Session::SESSION_END_STATUS_LOGOUT);
    }
}
header('Content-Type: text/xml; charset=utf-8');
$dom = new DomDocument('1.0', 'utf-8');
$logout_node = $dom->createElement('logout');
$logout_node->setAttribute('mode', $ret);
$dom->appendChild($logout_node);
$xml = $dom->saveXML();
Example #5
0
/**
 * generates overview over routes
 */
function showRoutes($amount = 50)
{
    //get page number
    $page = 1;
    if (isset($_GET["page"])) {
        $page = round($_GET["page"]);
    }
    //connect to database
    $con = connectToDB();
    //get number of entries
    $query = "SELECT COUNT(id) FROM osm_train_details";
    $result = @$con->query($query) or log_error(@$con->error);
    if ($result) {
        $row = $result->fetch_row();
        $count = $row[0];
        $lastpage = ceil($count / $amount);
        $start = $amount * ($page - 1);
    } else {
        $start = 0;
        $lastpage = "?";
    }
    //get order by and check if valid
    if (isset($_GET["order_by"])) {
        $order_by = $_GET["order_by"];
    }
    if (!isset($order_by) || $order_by != "ref" && $order_by != "from" && $order_by != "to" && $order_by != "operator" && $order_by != "length" && $order_by != "time" && $order_by != "ave_speed" && $order_by != "max_speed" && $order_by != "train") {
        $order_by = "ref";
    }
    //get order by and check if valid
    if (isset($_GET["dir"])) {
        $dir = $_GET["dir"];
    }
    if (!isset($dir) || $dir != "ASC" && $dir != "DESC") {
        $dir = "ASC";
    }
    $order_array = array("ref", "from", "to", "operator", "length", "time", "ave_speed", "max_speed", "train");
    foreach ($order_array as $order) {
        if ($order_by == $order) {
            if ($dir == "ASC") {
                $img_order_by[$order] = '<object type="image/svg+xml" data="img/arrow_desc.svg"></object> ';
                $dir_order_by[$order] = "DESC";
            } else {
                $img_order_by[$order] = '<object type="image/svg+xml" data="img/arrow_asc.svg"></object> ';
                $dir_order_by[$order] = "ASC";
            }
        } else {
            $img_order_by[$order] = "";
            $dir_order_by[$order] = "ASC";
        }
    }
    ?>
	<div class="panel panel-primary choose_route_save">
		<div class="panel-heading" data-toggle="collapse" aria-expanded="false" aria-controls="table" role="tab">
			<h3 class="panel-title"><a data-toggle="collapse" href="#table" aria-expanded="false" aria-controls="table"><?php 
    echo Lang::l_("By choosing a route from the list:");
    ?>
</a></h4>
		</div>
		<div id="table" class="collapse in">
			<div class="panel-body">
				<?php 
    pagination($page, $lastpage, $order_by, $dir);
    ?>
			</div>
			<div class="table-responsive">
				<table class="route_overview table table-striped table-condensed">
					<thead>
					<tr>
						<th><a href="?order_by=ref&page=<?php 
    echo $page;
    ?>
&dir=<?php 
    echo $dir_order_by["ref"];
    ?>
#table"><?php 
    echo $img_order_by["ref"] . Lang::l_('Line');
    ?>
</a></th>
						<th><a href="?order_by=from&page=<?php 
    echo $page;
    ?>
&dir=<?php 
    echo $dir_order_by["from"];
    ?>
#table"><?php 
    echo $img_order_by["from"] . Lang::l_('Origin');
    ?>
</a></th>
						<th><a href="?order_by=to&page=<?php 
    echo $page;
    ?>
&dir=<?php 
    echo $dir_order_by["to"];
    ?>
#table"><?php 
    echo $img_order_by["to"] . Lang::l_('Destination');
    ?>
</a></th>
						<th><a href="?order_by=operator&page=<?php 
    echo $page;
    ?>
&dir=<?php 
    echo $dir_order_by["operator"];
    ?>
#table"><?php 
    echo $img_order_by["operator"] . Lang::l_('Operator');
    ?>
</a></th>
						<th><a href="?order_by=length&page=<?php 
    echo $page;
    ?>
&dir=<?php 
    echo $dir_order_by["length"];
    ?>
#table"><?php 
    echo $img_order_by["length"] . Lang::l_('Route Length');
    ?>
</a></th>
						<th><a href="?order_by=time&page=<?php 
    echo $page;
    ?>
&dir=<?php 
    echo $dir_order_by["time"];
    ?>
#table"><?php 
    echo $img_order_by["time"] . Lang::l_('Duration');
    ?>
</a></th>
						<th><a href="?order_by=ave_speed&page=<?php 
    echo $page;
    ?>
&dir=<?php 
    echo $dir_order_by["ave_speed"];
    ?>
#table"><?php 
    echo $img_order_by["ave_speed"];
    ?>
v<sub>&#x2300;</sub></a></th>
						<th><a href="?order_by=max_speed&page=<?php 
    echo $page;
    ?>
&dir=<?php 
    echo $dir_order_by["max_speed"];
    ?>
#table"><?php 
    echo $img_order_by["max_speed"];
    ?>
v<sub>max</sub></a></th>
						<th><a href="?order_by=train&page=<?php 
    echo $page;
    ?>
&dir=<?php 
    echo $dir_order_by["train"];
    ?>
#table"><?php 
    echo $img_order_by["train"] . Lang::l_('Train');
    ?>
</a></th>
					</tr>
					</thead>
					<tbody>
	<?php 
    //generate and execute query
    $query = "SELECT * FROM osm_train_details ORDER BY `" . @$con->real_escape_string($order_by) . "` " . @$con->real_escape_string($dir) . " LIMIT " . $start . "," . $amount;
    $result = @$con->query($query);
    if ($result) {
        //show routes
        while ($row = @$result->fetch_array()) {
            $mysql_id = $row["id"];
            //get Train
            unset($train);
            $train = new Train($row["train"]);
            ?>
							<tr>
								<td><a href="?id=<?php 
            echo $row["id"];
            ?>
&train=<?php 
            echo $train->ref;
            ?>
" title="<?php 
            echo Lang::l_('Show Route');
            ?>
"><?php 
            echo Route::showRef($row["ref"], $row["route"], $row["service"], $row["ref_colour"], $row["ref_textcolour"]);
            ?>
</a></td>
								<td><?php 
            echo $row["from"];
            ?>
</td>
								<td><?php 
            echo $row["to"];
            ?>
</td>
								<td><?php 
            echo $row["operator"];
            ?>
</td>
								<td class="nowrap"><?php 
            echo round($row["length"], 1);
            ?>
 km</td>
								<td class="nowrap"><?php 
            echo round($row["time"], 0);
            ?>
 min</td>
								<td class="nowrap"><?php 
            echo round($row["ave_speed"]);
            ?>
 km/h</td>
								<td class="nowrap"><?php 
            echo round($row["max_speed"]);
            ?>
 km/h</td>
								<td style="width:150px"><div style="height:50px;width:150px;display:inline-block;background-image:url('img/trains/<?php 
            echo $train->image;
            ?>
');background-repeat:no-repeat;background-position:right;background-size:auto 50px" title="<?php 
            echo $train->name;
            ?>
"></div></td>
							</tr>
			<?php 
        }
    } else {
        ?>
							<tr>
								<td colspan="9">
									<?php 
        return_error("mysql", "message", $con);
        ?>
								</td>
							</tr>
		<?php 
    }
    ?>
					</tbody>
				</table>
			</div>
			<div class="panel-body">
				<?php 
    pagination($page, $lastpage, $order_by, $dir);
    ?>
			</div>
		</div>
	</div>
	<?php 
}
/**
 * Web service to tell if a given user is subscribed to the course
 * @param array $params Array of parameters (course and user_id)
 * @return bool|null|soap_fault A simple boolean (true if user is subscribed, false otherwise)
 */
function WSUserSubscribedInCourse ($params)
{
    global $debug;

    if ($debug) error_log('WSUserSubscribedInCourse');
    if ($debug) error_log('Params '. print_r($params, 1));
    if (!WSHelperVerifyKey($params)) {

        return return_error(WS_ERROR_SECRET_KEY);
    }
    $courseCode  = $params['course']; //Course code
    $userId      = $params['user_id']; //chamilo user id

    return (CourseManager::is_user_subscribed_in_course($userId,$courseCode));
}
function WSDeleteUserFromGroup($params)
{
    if (!WSHelperVerifyKey($params['secret_key'])) {
        return return_error(WS_ERROR_SECRET_KEY);
    }
    $userGroup = new UserGroup();
    return $userGroup->delete_user_rel_group($params['user_id'], $params['group_id']);
}
Example #8
0
$dom->appendChild($logout_node);
$xml = $dom->saveXML();
$dom = new DomDocument('1.0', 'utf-8');
$buf = @$dom->loadXML(query_sm_post_xml($sessionmanager_url . '/logout.php', $xml));
if (!$buf) {
    echo return_error(0, 'Invalid XML');
    die;
}
if (!$dom->hasChildNodes()) {
    echo return_error(0, 'Invalid XML');
    die;
}
$logout_nodes = $dom->getElementsByTagName('logout');
if (count($logout_nodes) != 1) {
    echo return_error(1, 'Invalid XML: No session node');
    die;
}
$logout_node = $logout_nodes->item(0);
if (!is_object($logout_node)) {
    echo return_error(1, 'Invalid XML: No session node');
    die;
}
$logout = array('mode' => $logout_node->getAttribute('mode'));
$dom = new DomDocument('1.0', 'utf-8');
$logout_node = $dom->createElement('logout');
$logout_node->setAttribute('mode', $logout['mode']);
$dom->appendChild($logout_node);
$xml = $dom->saveXML();
echo $xml;
unset($_SESSION['ovd-client']);
die;
Example #9
0
    $tb = new MWTrackback('', '');
    $trackbacks = $tb->auto_discovery($content);
}
if (!empty($trackbacks)) {
    foreach ($trackbacks as $t) {
        if (!empty($pinged) && in_array($t, $pinged)) {
            continue;
        }
        $toping[] = $t;
    }
}
$post->setVar('toping', !empty($toping) ? $toping : '');
$return = $edit ? $post->update() : $post->save();
if ($return) {
    if (!$edit) {
        $xoopsUser->incrementPost();
    }
    showMessage($edit ? __('Post updated successfully', 'mywords') : __('Post saved successfully', 'mywords'), 0);
    $url = MWFunctions::get_url();
    if ($mc->permalinks > 1) {
        $url .= $frontend ? 'edit/' . $post->id() : 'posts.php?op=edit&id=' . $post->id();
    } else {
        $url .= $frontend ? '?edit=' . $post->id() : 'posts.php?op=edit&id=' . $post->id();
    }
    $rtn = array('message' => $edit ? __('Post updated successfully', 'mywords') : __('Post saved successfully', 'mywords'), 'token' => $xoopsSecurity->createToken(), 'link' => '<strong>' . __('Permalink:', 'mywords') . '</strong> ' . $post->permalink(), 'post' => $post->id(), 'url' => $url);
    echo json_encode($rtn);
    die;
} else {
    return_error(__('Errors ocurred while trying to save this post.', 'mywords') . '<br />' . $post->errors(), true);
    die;
}
Example #10
0
$web_interface_settings = $prefs->get('general', 'web_interface_settings');
if (array_key_exists('public_webservices_access', $web_interface_settings) && $web_interface_settings['public_webservices_access'] == 1) {
    // ok
} elseif (array_key_exists('session_id', $_SESSION)) {
    $session = Abstract_Session::load($_SESSION['session_id']);
    if (!$session) {
        echo return_error(3, 'No such session "' . $_SESSION['session_id'] . '"');
        die;
    }
    /*if (! in_array($_GET['id'], $session->applications)) {
    		echo return_error(4, 'Unauthorized application');
    		die();
    	}*/
} else {
    Logger::debug('main', '(client/applications) No Session id nor public_webservices_access');
    echo return_error(7, 'No Session id nor public_webservices_access');
    die;
}
$applicationDB = ApplicationDB::getInstance();
$applications = $applicationDB->getApplicationsWithMimetype($_GET['id']);
$apps = array();
foreach ($applications as $application) {
    if (!$application->haveIcon()) {
        continue;
    }
    $score = count($application->groups());
    if ($application->getAttribute('type') == 'windows') {
        $score += 10;
    }
    $apps[$score] = $application;
}
/**
 * Get a list of sessions (id, title, url, date_start, date_end) and
 * return to caller. Date start can be set to ask only for the sessions
 * starting at or after this date. Date end can be set to ask only for the
 * sessions ending before or at this date.
 * Function registered as service. Returns strings in UTF-8.
 * @param array List of parameters (security key, date_start and date_end)
 * @return array Sessions list (id=>[title=>'title',url='http://...',date_start=>'...',date_end=>''])
 */
function WSListSessions($params)
{
    if (!WSHelperVerifyKey($params)) {
        return return_error(WS_ERROR_SECRET_KEY);
    }
    $sql_params = array();
    // Dates should be provided in YYYY-MM-DD format, UTC
    if (!empty($params['date_start'])) {
        $sql_params['date_start >='] = $params['date_start'];
    }
    if (!empty($params['date_end'])) {
        $sql_params['date_end <='] = $params['date_end'];
    }
    $sessions_list = SessionManager::get_sessions_list($sql_params);
    $return_list = array();
    foreach ($sessions_list as $session) {
        $return_list[] = array('id' => $session['id'], 'title' => $session['name'], 'url' => api_get_path(WEB_CODE_PATH) . 'session/index.php?session_id=' . $session['id'], 'date_start' => $session['date_start'], 'date_end' => $session['date_end']);
    }
    return $return_list;
}
Example #12
0
 $rarr = array('success' => false, 'notify' => array());
 switch ($_POST['step']) {
     case '1':
         // read template database file
         $conts = @file_get_contents('inc/common/site/default/database.php');
         if ($conts === false) {
             return_error('Failed to read database.php file. Does server have read permissions?', 'Read Failed');
         }
         // replace values
         $conts = str_replace('%dbhost%', $_POST['db']['host'], $conts);
         $conts = str_replace('%dbuser%', $_POST['db']['user'], $conts);
         $conts = str_replace('%dbpass%', $_POST['db']['pass'], $conts);
         $conts = str_replace('%dbname%', $_POST['db']['name'], $conts);
         // write database file
         if (@file_put_contents('inc/common/site/database.php', $conts) === false) {
             return_error('Failed to write database.php file. Does server have write permissions?', 'Write Failed');
         }
         // create database tables & default users
         if ($_POST['db']['create'] == 'Y') {
             require 'inc/common/site/database.php';
             require 'inc/classes/database.class.php';
             $db = new database();
             // drop tables if they exist
             $db->query('DROP TABLE IF EXISTS groups');
             $db->query('DROP TABLE IF EXISTS users');
             // create groups table
             $db->query('CREATE TABLE IF NOT EXISTS groups (
                     id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                     grp VARCHAR(20),
                     description VARCHAR(255)
                 );');
Example #13
0
    $_SESSION['ovd-client']['gateway'] = true;
}
$user_node = $session_node->getElementsByTagName('user');
if (count($user_node) != 1) {
    echo return_error(2, 'internal_error');
    die;
}
$user_node = $user_node->item(0);
if (!is_object($user_node)) {
    echo return_error(2, 'internal_error');
    die;
}
$_SESSION['ovd-client']['session_displayname'] = $user_node->getAttribute('displayName');
$server_nodes = $session_node->getElementsByTagName('server');
if (count($server_nodes) < 1) {
    echo return_error(3, 'internal_error');
    die;
}
$_SESSION['ovd-client']['explorer'] = false;
$profile_node = $session_node->getElementsByTagName('profile')->item(0);
$sharedfolder_node = $session_node->getElementsByTagName('sharedfolder')->item(0);
$sharedfolder_nodes = $session_node->getElementsByTagName('sharedfolder');
if (is_object($profile_node) || is_object($sharedfolder_node) && is_object($sharedfolder_nodes)) {
    if (is_dir(dirname(__FILE__) . '/ajaxplorer/')) {
        $_SESSION['ovd-client']['explorer'] = true;
    }
    $_SESSION['ovd-client']['ajxp'] = array();
    $_SESSION['ovd-client']['ajxp']['applications'] = '';
    $_SESSION['ovd-client']['ajxp']['repositories'] = array();
    $_SESSION['ovd-client']['ajxp']['folders'] = array();
}
Example #14
0
//проверка пользовательского запроса
include ".php/track.php";
//отслеживание посетителей
if (test(REQUEST_AJAX)) {
    include ".php/ajax.php";
} else {
    if (test(ERROR_AJAX)) {
        return_error(AUTORIZATION_ERROR);
    } else {
        if (test(REQUEST_UPLOAD)) {
            include ".php/upload.php";
        } else {
            if (test(REQUEST_DOWNLOAD)) {
                include ".php/download.php";
            } else {
                if (test(REQUEST_AUTHORIZATION)) {
                    include ".php/main.php";
                } else {
                    if (test(ERROR_UPLOAD)) {
                        return_error(UPLOAD_AUTORIZATION_ERROR);
                    } else {
                        include ".php/login.php";
                    }
                }
            }
        }
    }
}
#ini_set('display_errors', 1);
#error_reporting(E_ALL);
exit;
Example #15
0
function getDTD($col_info,$layer_type,$layer_tablename){
  if(count($col_info) > 0) {
    $dtd = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
    $dtd .= "<!ELEMENT kml    (Document)>\n";
    $dtd .= "<!ATTLIST kml xmlns CDATA \"\">\n";
    $dtd .= "<!ELEMENT Document  (Folder+)>\n";
    $dtd .= "<!ELEMENT Folder  (name,Placemark+)>\n";
    $dtd .= "<!ELEMENT Placemark  (description,Point)>\n";
    $dtd .= "<!ELEMENT description (";
    foreach($col_info as $col_name => $col_desc){
      $dtd .= $col_name .",";
    }
    $dtd .= ")>\n<!ELEMENT ".strtolower($layer_type)."  (coordinates)>\n";
    $dtd .= "<!ELEMENT coordinates  (#PCDATA)>\n";
    $dtd .= "<!ELEMENT name (#PCDATA)>";
    foreach($col_info as $col_name => $col_desc){
      $dtd .= "<!ELEMENT ".$col_name." (#PCDATA)>\n";
      $dtd .= "<!-- ".$col_name." ".$col_desc." -->\n";
    }

  } else {
     $dtd = "";
  }
  $file = "upload/dtd_".$layer_tablename.".xml";
  if (!($fp = fopen($file, "w+"))) {
       die(return_error("Error opening DTD file"));
  }
  fwrite($fp,$dtd);
  fclose($fp);
  return htmlentities($dtd);
}
Example #16
0
if (!array_key_exists('public_webservices_access', $web_interface_settings) || $web_interface_settings['public_webservices_access'] == 0) {
    Logger::debug('main', '(client/applications) Public webservices access is disabled, aborting');
    echo return_error(1, 'Public webservices access is disabled');
    die;
}
if (!array_key_exists('user', $_REQUEST)) {
    Logger::error('main', '(client/applications) - no user given');
    echo return_error(1, 'No user given');
    die;
}
$user_login = $_REQUEST['user'];
$userDB = UserDB::getInstance();
$user = $userDB->import($user_login);
if (!is_object($user)) {
    Logger::error('main', '(client/applications) - Unknown user ' . $_REQUEST['user']);
    echo return_error(3, 'Unknown user ' . $_REQUEST['user']);
    die;
}
/*
ToDo: implement this kind of generic authentication

try {
	$sessionManagement = SessionManagement::getInstance();
}
catch (Exception $err) {
	throw_response(INTERNAL_ERROR);
}

if (! $sessionManagement->initialize()) {
	Logger::error('main', '(client/applications) SessionManagement initialization failed');
	throw_response(INTERNAL_ERROR);
Example #17
0
function shutdown()
{
    $isError = false;
    if ($error = error_get_last()) {
        switch ($error['type']) {
            case E_ERROR:
            case E_CORE_ERROR:
            case E_COMPILE_ERROR:
            case E_USER_ERROR:
                $isError = true;
                break;
        }
    }
    if ($isError) {
        return_error($error['message']);
    }
}
Example #18
0
    }
    $ret['application']['id'] = $application_node->getAttribute('id');
    return $ret;
}
$ret = parse_icon_XML(@file_get_contents('php://input'));
if (!$ret) {
    echo return_error(1, 'Server does not send a valid XML');
    die;
}
$server = Abstract_Server::load($ret['server']);
if (!$server) {
    echo return_error(2, 'Server does not exist');
    die;
}
if (!$server->isAuthorized()) {
    echo return_error(3, 'Server is not authorized');
    die;
}
$applicationDB = ApplicationDB::getInstance();
$app = $applicationDB->import($ret['application']['id']);
if (!is_object($app)) {
    echo return_error(4, 'No such application "' . $ret['application']['id'] . '"');
    die;
}
$path = $app->getIconPath();
if (!file_exists($path)) {
    echo return_error(5, 'No icon available for application "' . $ret['application']['id'] . '"');
    die;
}
header('Content-Type: image/png');
echo @file_get_contents($path, LOCK_EX);
 /**
  * Load XML file
  * 
  * This function loads the XML file and extracts the nodes and ways
  */
 function loadXml()
 {
     // show error when file does not exist
     if (!file_exists($this->filexml)) {
         return_error("no_xml_file", "full");
         die;
     }
     // load xml file
     $xml = @simplexml_load_file($this->filexml);
     if (!$xml) {
         return_error("invalid_xml_file", "full");
         die;
     }
     // go through each node
     foreach ($xml->node as $node) {
         // load attributes
         foreach ($node->attributes() as $a => $b) {
             if ($a == "id") {
                 $id = (string) $b;
             }
             if ($a == "lat") {
                 $lat = (string) $b;
             }
             if ($a == "lon") {
                 $lon = (string) $b;
             }
         }
         // set lat and lon for node
         $this->node[$id]["lat"] = $lat;
         $this->node[$id]["lon"] = $lon;
         // set tags for nodes
         $node_tags = array();
         foreach ($node->tag as $tag) {
             foreach ($tag->attributes() as $a => $b) {
                 if ($a == "k") {
                     $k = strtolower((string) $b);
                 } elseif ($a == "v") {
                     $v = (string) $b;
                 }
             }
             // set tags
             if ($k != "lat" && $k != "lon") {
                 $this->node[$id][$k] = $v;
             }
         }
     }
     // go through each way
     foreach ($xml->way as $way) {
         // load attributes
         foreach ($way->attributes() as $a => $b) {
             if ($a == "id") {
                 $id = (string) $b;
             }
         }
         // set tags for ways
         foreach ($way->tag as $tag) {
             foreach ($tag->attributes() as $a => $b) {
                 if ($a == "k") {
                     $k = strtolower((string) $b);
                 } elseif ($a == "v") {
                     $v = (string) $b;
                 }
             }
             $this->way_tags[$id][$k] = $v;
         }
         //add nodes to ways
         foreach ($way->nd as $nd) {
             foreach ($nd->attributes() as $a => $b) {
                 if ($a == "ref") {
                     $this->way_nodes[$id][] = (string) $b;
                 }
             }
         }
         //calculate length of way
         $this->way_length[$id] = 0;
         //go through all nodes
         $i = 0;
         while (isset($this->way_nodes[$id][$i])) {
             if ($i > 0) {
                 //add distance between this node and node before
                 $this->way_length[$id] += $this->getDistance($this->node[$this->way_nodes[$id][$i - 1]]["lat"], $this->node[$this->way_nodes[$id][$i - 1]]["lon"], $this->node[$this->way_nodes[$id][$i]]["lat"], $this->node[$this->way_nodes[$id][$i]]["lon"]);
             }
             if (!isset($this->node_way[$this->way_nodes[$id][$i]]) || $i > 0) {
                 /*add distance of node from beginning of way
                 		(also set for nodes that are only at beginning of way (distance=0) */
                 $this->node_distance[$this->way_nodes[$id][$i]] = $this->way_length[$id];
                 $this->node_way[$this->way_nodes[$id][$i]] = $id;
             }
             $i++;
         }
         //set id of first and last node
         $this->first_node[$id] = $this->way_nodes[$id][0];
         $this->last_node[$id] = $this->way_nodes[$id][$i - 1];
     }
     $rel_done = false;
     //load all relations
     foreach ($xml->relation as $relation) {
         //load attributes
         foreach ($relation->attributes() as $a => $b) {
             if ($a == "id") {
                 $rel_id = (string) $b;
             }
         }
         //temporary array for tags
         $temp_relation_array = array();
         //load relation tags
         foreach ($relation->tag as $tag) {
             foreach ($tag->attributes() as $a => $b) {
                 if ($a == "k") {
                     $k = strtolower((string) $b);
                 } elseif ($a == "v") {
                     $v = (string) $b;
                 }
             }
             $temp_relation_array[$k] = $v;
             //store tags temporary
         }
         // check if tags are relevant (type of relation is either route or route_master)
         if (isset($temp_relation_array["type"]) && ($temp_relation_array["type"] == "route" || $temp_relation_array["type"] == "route_master")) {
             foreach ($temp_relation_array as $c => $d) {
                 //do not overwrite tags for route_master when tag is already set in route
                 if ($temp_relation_array["type"] != "route_master" || !isset($this->relation_tags[$c])) {
                     // type tag should only be route
                     if ($c != "type" || $d == "route") {
                         // add tags to relation
                         $this->relation_tags[$c] = $d;
                     }
                 }
             }
         }
         // only ways of relation with the loaded id is needed - this is needed only once (sometimes relations are more than once in the data)
         if ($rel_id != $this->id || $rel_done) {
             continue;
         }
         $rel_done = true;
         // relation was parsed already -> dos not need to be parsed again.
         //load relation members
         foreach ($relation->member as $member) {
             $type = "";
             foreach ($member->attributes() as $a => $b) {
                 // get type of member
                 if ($a == "type") {
                     if ($b == "way") {
                         $type = "w";
                     } elseif ($b == "node") {
                         $type = "n";
                     } else {
                         $type = "r";
                     }
                 }
                 // get ref of member
                 if ($a == "ref") {
                     $member_ref = (string) $b;
                     if ($type == "w") {
                         // add ref to ways list
                         $this->relation_ways[] = $member_ref;
                     }
                 }
                 //get role of member
                 if ($a == "role") {
                     $role = $b;
                 }
                 //member is a stop -> add to stops list
                 if ($a == "role" && ($b == "stop" || strstr($b, "stop_"))) {
                     $this->relation_stops[] = $member_ref;
                     $this->relation_stops_type[] = $type;
                 }
             }
             $this->role_way[$member_ref] = $role;
         }
     }
     // loaded relation is not a valid route (type and route values not correct)
     if (!isset($this->relation_tags["type"]) || $this->relation_tags["type"] != "route" || !isset($this->relation_tags["route"]) || !($this->relation_tags["route"] == "train" || $this->relation_tags["route"] == "tram" || $this->relation_tags["route"] == "light_rail" || $this->relation_tags["route"] == "subway" || $this->relation_tags["route"] == "rail")) {
         //connect to database
         $con = connectToDB();
         // delete id from database
         @$con->query("DELETE FROM osm_train_details WHERE `id` = " . @$con->real_escape_string($this->id)) or log_error(@$con->error);
         // show error
         return_error("no_route", "full");
         die;
     }
 }
Example #20
0
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 **/
require_once dirname(__FILE__) . '/includes/core.inc.php';
function return_error($errno_, $errstr_)
{
    $dom = new DomDocument('1.0', 'utf-8');
    $node = $dom->createElement('error');
    $node->setAttribute('id', $errno_);
    $node->setAttribute('message', $errstr_);
    $dom->appendChild($node);
    return $dom->saveXML();
}
header('Content-Type: text/xml; charset=utf-8');
$xml = query_sm($sessionmanager_url . '/news.php');
if (!$xml) {
    echo return_error(0, 'Invalid XML');
    die;
}
$dom = new DomDocument('1.0', 'utf-8');
$buf = @$dom->loadXML($xml);
if (!$buf) {
    echo return_error(0, 'Invalid XML');
    die;
}
if (!$dom->hasChildNodes()) {
    echo return_error(0, 'Invalid XML');
    die;
}
echo $xml;
die;
Example #21
0
function WSRemoveCourseFromPortal($params)
{
    if (!WSHelperVerifyKey($params['secret_key'])) {
        return return_error(WS_ERROR_SECRET_KEY);
    }
    $courseInfo = CourseManager::getCourseInfoFromOriginalId($params['original_course_id_value'], $params['original_course_id_name']);
    $courseId = $courseInfo['real_id'];
    $portalId = $params['portal_id'];
    UrlManager::delete_url_rel_course($courseId, $portalId);
    $result = UrlManager::relation_url_course_exist($courseId, $portalId);
    if (empty($result)) {
        return true;
    }
    return false;
}
Example #22
0
    $status += ACCESS_PASSWORD;
}
if (test(HAS_REQUEST_PAGE) && preg_match("/^\\d{1,3}\$/", $_POST['user_page'])) {
    $status += ACCESS_PAGE;
}
//всеряем логин и пароль по БД
if (test(ACCESS_LOGIN) && (test(ACCESS_PASSWORD) || test(HAS_HASH))) {
    //поиск клиента в БД
    $response = mysql_query("SELECT * FROM `" . MYSQL_USER_TBL . "` WHERE `mail`='" . $_POST['user_login'] . "'  LIMIT 1");
    if ($response) {
        $row = mysql_fetch_assoc($response);
        mysql_free_result($response);
        unset($response);
    } else {
        if (test(HAS_NAME)) {
            return_error(DATABASE_UPLOAD_UNKNOWN);
        } else {
            return_error(DATABASE_ERROR);
        }
    }
    //сверяем хэш пароля по БД
    if (isset($row['hash'])) {
        if (test(HAS_HASH) && $_POST['user_code'] == $row['hash']) {
            $status += USER_HASH_ACCESS;
        } else {
            if (test(HAS_PASSWORD) && md5($_POST['user_pass']) == $row['hash']) {
                $status += USER_HASH_ACCESS;
            }
        }
    }
}
Example #23
0
    echo return_error(1, 'Server does not send a valid XML');
    die;
}
$server = Abstract_Server::load($ret['name']);
if (!$server) {
    echo return_error(2, 'Server does not exist');
    die;
}
if (!$server->isAuthorized()) {
    echo return_error(3, 'Server is not authorized');
    die;
}
$old_roles = $server->getAttribute('roles');
if ($ret['status'] == Server::SERVER_STATUS_ONLINE) {
    if (!$server->getConfiguration()) {
        echo return_error(4, 'Server does not send a valid configuration');
        die;
    }
}
// check if server's roles have been changes
$new_roles = $server->getAttribute('roles');
foreach ($old_roles as $a_role => $enable) {
    if (array_key_exists($a_role, $new_roles) == false) {
        // the server has not anymore the role
        Abstract_Server::removeRole($server->getAttribute('fqdn'), $a_role);
    }
}
$server->setStatus($ret['status']);
Abstract_Server::save($server);
header('Content-Type: text/xml; charset=utf-8');
$dom = new DomDocument('1.0', 'utf-8');
Example #24
0
function call_sp($mysqli, $sp_name, $parameter_string)
{
    if (!($result = $mysqli->query("CALL " . $sp_name . "(" . $parameter_string . ")"))) {
        return_error("CALL " . $sp_name . "() failed: (" . $mysqli->errno . ") \n ", $mysqli->error);
    }
    return $result;
}
Example #25
0
define("DATABASE_UPLOAD_UNKNOWN", 13);
define("UPLOAD_FILE_ERROR", 14);
//Коды ошибок для бэкенда:
define("AUTORIZATION_ERROR", 20);
define("DATABASE_UNKNOWN", 21);
define("DATABASE_ERROR", 22);
define("FILE_NOT_FOUND", 23);
//
define("TEMP_UPLOAD_PATH", "..\\deposite.host.by\\.downloads\\");
//директория хранилища
//
$db = mysql_connect(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD);
if ($db) {
    mysql_select_db(MYSQL_DATABASE);
} else {
    return_error(DATABASE_UPLOAD_UNKNOWN);
}
function return_error($error)
{
    if ($error <= UPLOAD_FILE_ERROR) {
        echo "<script language='javascript' type='text/javascript'>window.top.window.stopUpload(" . $error . ");</script>";
    } else {
        if ($error) {
            header("HTTP/1.0 406 Not Acceptable");
            switch ($error) {
                case DATABASE_UNKNOWN:
                    echo "Сервер БД не найден!";
                    break;
                case DATABASE_ERROR:
                    echo "Сервер БД не отвечает!";
                    break;
Example #26
0
 public function GetSqlFile(){
    /* dump the sql statements in a file and return the file name */
   $sqlfile = "upload/".$this->layer_tablename.".sql";
   if (!($sqlfp = fopen($sqlfile, "w+"))) {
      die(return_error("Error opening SQL file"));
   }
   fwrite($sqlfp,$this->sql);
   fclose($sqlfp);
   return $sqlfile;
 }
Example #27
0
 // form validation
 $error_message = "";
 // name
 $name_exp = "/^[a-z0-9 .\\-]+\$/i";
 if (!preg_match($name_exp, $name)) {
     $this_error = 'Please enter a valid name.';
     $error_message .= $error_message == "" ? $this_error : "<br/>" . $this_error;
 }
 $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$/';
 if (!preg_match($email_exp, $email)) {
     $this_error = 'Please enter a valid email address.';
     $error_message .= $error_message == "" ? $this_error : "<br/>" . $this_error;
 }
 // if there are validation errors
 if (strlen($error_message) > 0) {
     return_error($error_message);
 }
 // prepare email message
 $email_message = "Form details below.\n\n";
 function clean_string($string)
 {
     $bad = array("content-type", "bcc:", "to:", "cc:", "href");
     return str_replace($bad, "", $string);
 }
 $email_message .= "Name: " . clean_string($name) . "\n";
 $email_message .= "Email: " . clean_string($email) . "\n";
 $email_message .= "Message: " . clean_string($message) . "\n";
 // create email headers
 $headers = 'From: ' . $email_from . "\r\n" . 'Reply-To: ' . $email . "\r\n" . 'X-Mailer: PHP/' . phpversion();
 if (mail($email_to, $email_subject, $email_message, $headers)) {
     echo 'Your message was received and you will be contacted shortly. You are now being redirected.';
Example #28
0
      $layer_tablename=$_REQUEST['layer_tablename'];
      $format=$_REQUEST['format'];
    }
    else {
      die(return_error('Required parameters are not set'));
    }
    require_once("LayerData.php");
    get_download_url($layer_tablename, $format);
    break;

  case "getDownloadFormats":
    if (isset($_REQUEST['layer_tablename'])) {
      $layer_tablename=$_REQUEST['layer_tablename'];
    }
    else {
      die(return_error('Required parameters are not set'));
    }
    require_once("LayerData.php");
    get_download_formats($layer_tablename);
    break;

  // LayerData.php ends
  default:
    die('Error: Action not implemented');
}
// switch
function check_layer_tablename_provided() {
  if (isset($_REQUEST['layer_tablename']) && !empty($_REQUEST['layer_tablename'])) {
    return $_REQUEST['layer_tablename'];
  }
  else {
 /**
  * Get a list of sessions (id, coach_id, name, courses_num, users_num, classes_num,
  * access_start_date, access_end_date, access_days_before_num, session_admin_id, visibility,
  * session_category_id, promotion_id,
  * validated_user_num, waiting_user_num,
  * extra, course) the validated_usernum and waiting_user_num are
  * used when have the plugin for advance incsription enables.
  * The extra data (field_name, field_value)
  * The course data (course_id, course_code, course_title,
  * coach_username, coach_firstname, coach_lastname)
  * @param array $params List of parameters (id, category_name, access_url_id, secret_key)
  * @return array|soap_fault Sessions list (id=>[title=>'title',url='http://...',date_start=>'...',date_end=>''])
  */
 public static function WSListSessionsDetailsByCategory($params)
 {
     global $debug;
     if ($debug) {
         error_log('WSListSessionsDetailsByCategory');
         error_log('Params ' . print_r($params, 1));
     }
     $secretKey = $params['secret_key'];
     // Check if secret key is valid
     if (!WSHelperVerifyKey($secretKey)) {
         return return_error(WS_ERROR_SECRET_KEY);
     }
     // Check if category ID is set
     if (!empty($params['id']) && empty($params['category_name'])) {
         $sessionCategoryId = $params['id'];
     } elseif (!empty($params['category_name'])) {
         // Check if category name is set
         $sessionCategoryId = SessionManager::getSessionCategoryIdByName($params['category_name']);
         if (is_array($sessionCategoryId)) {
             $sessionCategoryId = current($sessionCategoryId);
         }
     } else {
         // Return soap fault Not valid input params
         return return_error(WS_ERROR_INVALID_INPUT);
     }
     // Get the session List by category
     $sessionList = SessionManager::getSessionListAndExtraByCategoryId($sessionCategoryId);
     if (empty($sessionList)) {
         // If not found any session, return error
         return return_error(WS_ERROR_NOT_FOUND_RESULT);
     }
     // Get validated and waiting queue users count for each session
     $plugin = AdvancedSubscriptionPlugin::create();
     foreach ($sessionList as &$session) {
         // Add validated and queue users count
         $session['validated_user_num'] = self::$plugin->countQueueByParams(array('sessions' => array($session['id']), 'status' => array(ADVANCED_SUBSCRIPTION_QUEUE_STATUS_ADMIN_APPROVED)));
         $session['waiting_user_num'] = self::$plugin->countQueueByParams(array('sessions' => array($session['id']), 'status' => array(ADVANCED_SUBSCRIPTION_QUEUE_STATUS_START, ADVANCED_SUBSCRIPTION_QUEUE_STATUS_BOSS_APPROVED)));
     }
     return $sessionList;
 }
Example #30
0
    header('Content-Type: text/xml; charset=utf-8');
    $dom = new DomDocument('1.0', 'utf-8');
    $node = $dom->createElement('error');
    $node->setAttribute('id', $errno_);
    $node->setAttribute('message', $errstr_);
    $dom->appendChild($node);
    Logger::error('main', "(webservices/application_icon) return_error({$errno_}, {$errstr_})");
    return $dom->saveXML();
}
$server = Abstract_Server::load($_SERVER['REMOTE_ADDR']);
if (!$server) {
    echo return_error(1, 'Server does not exist');
    die;
}
if (!$server->isAuthorized()) {
    echo return_error(2, 'Server is not authorized');
    die;
}
header('Content-Type: text/xml; charset=utf-8');
$dom = new DomDocument('1.0', 'utf-8');
$node = $dom->createElement('applications');
$applications = $server->getApplications();
if (is_array($applications)) {
    foreach ($applications as $app) {
        if (!$app->getAttribute('static')) {
            continue;
        }
        if ($app->getAttribute('type') != $server->getAttribute('type')) {
            continue;
        }
        $app_node = $dom->createElement('application');