function loginAsPublic() { #for the API, assume the identify of the "public" user $db = CreateObject('s3dbapi.db'); $db->Halt_On_Error = 'no'; $db->Host = $GLOBALS['s3db_info']['server']['db']['db_host']; $db->Type = $GLOBALS['s3db_info']['server']['db']['db_type']; $db->Database = $GLOBALS['s3db_info']['server']['db']['db_name']; $db->User = $GLOBALS['s3db_info']['server']['db']['db_user']; $db->Password = $GLOBALS['s3db_info']['server']['db']['db_pass']; $db->connect(); $user_info = publicUserId($db); $user_id = $user_info['account_id']; if ($user_id == '') { return formatReturn($GLOBALS['error_codes']['something_missing'], 'A public user was not found. To authenticate a user, please specify a key', $_REQUEST['format'], ''); exit; } return array($db, $user_info, $user_id); }
} else { echo formatReturn('2', 'Your authentication was valid but a key could not be created.', $format, ''); exit; } } } else { #if a key has been provided, validate the key $key = $_REQUEST['key']; include_once 'core.header.php'; #$user_proj = $GLOBALS['users_project']; if (is_file($GLOBALS['uploads'] . '/userManage.s3db')) { $user_proj = unserialize(file_get_contents($GLOBALS['uploads'] . '/userManage.s3db')); } if ($user_id != '1') { $msg = "A project to manage users has not been created. This project can only be created by the generic Admin users. Please add your Admin key to apilogin.php to create it automatically."; echo formatReturn('5', $msg, $format, ''); exit; } #if it does not exist, create it and save it in config.inc.php; $user_proj = create_user_proj(compact('user_id', 'db', 'user_proj', 'timer')); #now, if query is not empyt, read it, parse it, interpret it. if ($_REQUEST['query']) { $query = $_REQUEST['query']; $q = compact('query', 'format', 'key', 'user_proj', 'user_id', 'db'); $s3ql = parse_xml_query($q); ##now interpret the query $q['s3ql'] = $s3ql; $return = actBasedOnQuery($q); } #if user is trying to authenticate, one of the options will be query that user item on the users project for alternative authentication }
function parse_xml_query($q) { extract($q); $xml = stripslashes($query); ##When value brings tags, they will be parsed along with the rest of the xml. Avoid that by encoding it first. ereg('<authentication_id>(.*)</authentication_id>', $xml, $val); if ($val[1] != '') { $xml = str_replace('<authentication_id>' . $val[1] . '</authentication_id>', '<authentication_id>' . base64_encode($val[1]) . '</authentication_id>', $xml); } if (ereg('^http.*', $xml)) { $xmlFile = @file_get_contents($xml); if (empty($xmlFile)) { echo formatReturn($GLOBALS['error_codes']['something_missing'], 'Query file is not valid', $_REQUEST['format'], ''); exit; } else { $xml = $xmlFile; ereg('<authentication_id>(.*)</authentication_id>', $xml, $val); if ($val[1] != '') { $xml = str_replace('<authentication_id>' . $val[1] . '</authentication_id>', '<authentication_id>' . base64_encode($val[1]) . '</authentication_id>', $xml); } } } if ($xml != '') { try { $tmp = @simplexml_load_string($xml); if (!$tmp) { $tmp = @simplexml_load_string(urldecode($xml)); } if (!$tmp) { throw new Exception(formatReturn($GLOBALS['error_codes']['something_went_wrong'], 'XML query is badly formatted. Please check your start/end tags', $_REQUEST['format'], '')); } } catch (Exception $e) { echo formatReturn($GLOBALS['error_codes']['something_went_wrong'], $e->getMessage(), $format, ''); exit; } $xml = $tmp; $s3ql = $xml; $s3ql = get_object_vars($s3ql); $s3ql['key'] = $s3ql['key'] != '' ? $s3ql['key'] : $key; #read data in the "where" tag if (get_object_vars($s3ql['where']) != '') { $s3ql['where'] = get_object_vars($s3ql['where']); } elseif ($_REQUEST['where'] != '') { $s3ql['where'] = $_REQUEST['where']; } if ($s3ql['where']['authentication_id'] != '') { $s3ql['where']['authentication_id'] = base64_decode($s3ql['where']['authentication_id']); } } return $s3ql; }
function selectQuery($D) { extract($D); if ($s3ql['from'] == 'deployment') { $data[0] = array('mothership' => $GLOBALS['s3db_info']['deployment']['mothership'], 'deployment_id' => $GLOBALS['s3db_info']['deployment']['Did'], 'description' => $GLOBALS['s3db_info']['server']['site_intro'], 'url' => S3DB_URI_BASE, 'message' => 'Successfully connected to deployment ' . $GLOBALS['s3db_info']['deployment']['Did'] . '. Please provice a key to query the data (for example: ' . ($_SERVER['https'] == 'on' ? 'https://' : 'http://') . $def . S3DB_URI_BASE . '/URI.php?key=xxxxxxxx. For syntax specification and instructions refer to http://s3db.org/'); return $data; } #echo '<pre>';print_r($s3ql); if (in_array($s3ql['from'], array_keys($GLOBALS['plurals']))) { $s3ql['from'] = $GLOBALS['plurals'][$s3ql['from']]; } #echo '<pre>';print_r($s3ql);exit; if ($s3ql['from'] == 'classes') { $s3ql['from'] = 'collections'; } if ($s3ql['from'] == 'instances') { $s3ql['from'] = 'items'; } if ($s3ql['from'] == 'keys' && $_SESSION['db'] == '') { return formatReturn($GLOBALS['error_codes']['not_a_query'], 'Access keys cannot be queried in the API.', $s3ql['format'], ''); exit; } $target = $s3ql['from']; $letter = strtoupper(substr($s3ql['from'], 0, 1)); $table = strval($target); $element = $target; $cols = $GLOBALS['dbstruct'][$target]; $element_id = $s3ql['where'][$GLOBALS['s3ids'][$element]]; if ($table != '' && !in_array($table, array_keys($GLOBALS['dbstruct']))) { return formatReturn($GLOBALS['error_codes']['not_a_query'], 'Not a valid query.', '', $s3ql['format']); } #manage data in select #echo '<pre>';print_r($s3ql); #array_keys contains the things to replace and array_values the replacements if ($s3ql['select'] != '' && $s3ql['select'] != '*') { $s3ql_out = ereg_replace(' ', '', $s3ql['select']); #take out all the spaces $returnFields = explode(',', $s3ql_out); if (!ereg($GLOBALS['s3ids'][$element], $s3ql['select'])) { if (ereg('count|max|min', $s3ql['select'])) { $SQLfun = ereg_replace("\\(.*\\)", "", $select); $SQLfun = ereg_replace("count as count", "count", $SQLfun); $s3ql['select'] = '*'; } else { $s3ql['select'] .= ',' . $GLOBALS['s3ids'][$element]; } } } else { $s3ql['select'] = '*'; } #echo '<pre>';print_r($s3ql);exit; $toreplace = array_keys($GLOBALS['s3map'][$target]); $replacements = array_values($GLOBALS['s3map'][$target]); $s3ql['select'] = str_replace($toreplace, $replacements, $s3ql['select']); $select = urldecode($s3ql['select']); $select = eregi_replace('uid', $GLOBALS['s3ids'][$element] . ' as uid', $select); $select = eregi_replace('uri', $GLOBALS['s3ids'][$element] . ' as uri', $select); #echo $P['out'].$P['SQLfun']; if ($select == $SQLfun) { $SQLfun = ''; } #$s3ql_where_keys = str_replace(array('item_id', 'collection_id'), array('instance_id', 'class_id'), array_keys($s3ql['where'])); #$s3ql['where'] = array_combine($s3ql_where_keys, $s3ql['where']); #transofrmt s3ql and get the return Fields $tranformed = S3QLselectTransform(compact('s3ql', 'db', 'user_id')); extract($tranformed); #If there is any sort of S3 UID in the query, check its score when compared to the from $score = array('D' => '7', 'G' => '6', 'U' => '5', 'P' => '4', 'C' => '3', 'R' => '3', 'I' => '2', 'S' => '1'); $fromScore = $score[strtoupper(substr($target, 0, 1))]; $s3Ids = array_merge($GLOBALS['COREids'], array('rulelog' => 'rule_id', 'statementlog' => 'statement_id')); #echo '<pre>';print_r($s3ql);exit; $shared_with_query = array(); foreach ($s3Ids as $COREelement => $COREelement_id) { if ($s3ql['where'][$COREelement_id] != '' && !ereg('^~|regexp', $s3ql['where'][$COREelement_id])) { $id_name = $COREelement_id; $id_letter = strtoupper(substr($id_name, 0, 1)); $whereScore[strtoupper(substr($id_name, 0, 1)) . $s3ql['where'][$COREelement_id]] = $score[strtoupper(substr($id_name, 0, 1))]; #when idNameScore is < $fromScore, then we know: we are trying to query all resources that can view another particular resource (for example,all users that can view project x #echo $id_name;exit; $uid = strtoupper(substr($COREelement, 0, 1)) . $s3ql['where'][$COREelement_id]; $uid_info = uid($uid); $element_info = URIinfo($uid, $user_id, $key, $db); $WhereInfo[$uid_info['uid']] = $element_info; #echo '<pre>';print_r($user_info); #echo '<pre>';print_r($element_info);exit; if (!is_array($element_info)) { return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], $uid . ' does not exist', $s3ql['format'], ''); exit; } elseif ($id_letter != strtoupper(substr($element, 0, 1))) { ##Shared_with is any UID that can eb shared with any of the elements being requested (for example, Collection_id is shared_with Project, but Project_id is not shared with Project array_push($shared_with_query, $uid); #do permissions on this uid propagate? #echo '<pre>';print_r($whereScore);exit; } else { $self_id = $s3ql['where'][$COREelement_id]; if (!$element_info['view']) { return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User does not have permission on ' . $uid, $s3ql['format'], ''); exit; } } } } #echo '<pre>';print_r($WhereInfo);exit; if ($self_id != '') { $data[0] = $element_info; } else { #start building the query: $user_query = "select " . $select . " from s3db_" . $GLOBALS['s3tables'][$table]; if (!user_is_admin($user_id, $db)) { $cols = array_diff($cols, array('account_pwd', 'account_phone', 'account_email', 'project_folder')); } #remove a few cols from query #echo $user_query;exit; #now add some constrains necessary due to the type of resource if (!(user_is_admin($user_id, $db) && $s3ql['where']['status'] == 'I')) { if (ereg('projects|classes|instances|rules|statements', $target)) { $status = "status!='I' and "; } } $user_query_const .= " where " . $status . $GLOBALS['s3ids'][$target] . "!='0'"; ### #Filter query according to the element being requested $user_query_const .= filterByElement($s3ql, $user_id, $db); if ($user_query_const) { $user_query .= $user_query_const; } else { exit; } if (!empty($shared_with_query) && strtoupper(substr($target, 0, 1)) != 'U') { ##Added 15Apr08 for faster queries (taking too long on MySQL using table joins) $uidQuery = simpleQueryUID($shared_with_query, $element, $db); if ($uidQuery) { extract($uidQuery); $user_query .= $finalUID; } elseif ($user_id != '1') { return formatReturn($GLOBALS['error_codes']['no_results'], 'Your query on ' . $target . ' did not return any results', $format, ''); } } #echo 'ola'.$uidQuery;exit; #now constrainthe query to resources that user cann access. Check for inherited permissions and direct permissions. Project is connected to deployment, rule and class to project, and so on. (see S3DB third report for the schema) #Fetch the cols of what is to be returned. Check for SqL functions. This will only affect the output if ($s3ql['select'] != '') { $out = urldecode($s3ql['select']); $SQLfun = ereg_replace("\\(.*\\)", "", $out); $SQLfun = ereg_replace("count as count", "count", $SQLfun); $P['out'] . $P['SQLfun']; if ($out == $SQLfun) { $SQLfun = ''; } else { $extracol = $out; } } #echo $SQLfun; #Extract from the s3ql the value that are part of the syntax and assume the rest are the SQL extras (limit, creted_by, etc) $syntax = array('key', 'select', 'from', 'where', 'format'); foreach ($s3ql as $i => $value) { if (!in_array($i, $syntax) && $value != '') { $SQLextra[$i] = ' ' . ereg_replace('_', ' ', $i) . ' ' . $value; } } #echo '<pre>';print_r($SQLextra);exit; #if there is orderby, move to the beginnign of the array if ($SQLextra['order_by'] != '') { $SQLextra = array_merge(array('order_by' => $SQLextra['order_by']), $SQLextra); } if (is_array($SQLextra)) { foreach ($SQLextra as $key => $value) { $query_extra .= $value; } } #Put in $P the values of what is queried, add to cols, if not already there, whatever is queried. Check if there are regular expressions anywhere. equalit will be replace by the regular expression $cols = $GLOBALS['dbstruct'][$table]; foreach ($cols as $col) { if ($s3ql['where'][$col] != '') { if (!in_array($col, $GLOBALS['COREids']) && $col != $GLOBALS['COREids'][$element]) { $user_query_fields .= ' and ' . $col . ' ' . parse_regexp($s3ql['where'][$col]); } $P[$col] = parse_regexp($s3ql['where'][$col]); } } #glue them together. $user_query .= $user_query_fields . $query_extra; ###Finally perform the query on whatever table is specified #$user_query = "select * from s3db_resource where resource_class_id = '389';"; //echo $user_query; //exit; #run it #complete query on LOCAL resources $db->query($user_query, __LINE__, __FILE__); $dbdata = get_object_vars($db); #echo '<pre>';print_r($dbdata); #exit; if ($dbdata['Errno'] != '0') { return formatReturn($GLOBALS['error_codes']['something_went_wrong'], $dbdata['Error'], $format, ''); } #put it in a nice structured variable $cols = $GLOBALS['dbstruct'][$target]; if (is_array($returnFields) && $extracol == '') { $cols = array_unique(array_merge($cols, $returnFields)); } #echo '<pre>';print_r($cols); while ($db->next_record()) { #echo '<pre>';print_r($db); $resultStr .= "\$data[] = Array("; if ($extracol != '') { $resultStr .= "'" . $extracol . "'=>'" . $db->f($SQLfun) . "',"; } foreach ($cols as $col) { $resultStr .= "'" . $col . "'=>'" . addslashes($db->f($col)) . "'"; if ($col != end($cols)) { $resultStr .= ","; } if ($col == $GLOBALS['s3ids'][$target]) { $retrieved['ids_str'] .= $retrieved['ids_str'] == '' ? $db->f($col) : '|' . $db->f($col); } } $resultStr .= ");"; } #echo $resultStr; #evaluate the long string eval($resultStr); if (is_array($data)) { $data = array_filter($data); } #echo '<pre>';print_r($data); #BEFORE outputting data, are there any remote resources where the user is allowed? $ucode = strtoupper(substr($element, 0, 1)); $ucode_and_id = $ucode . $element_id; ##Added ability to search locally on april 15 to optimize queries if (!ereg('users|group|projects|keys|rulelog|statementlog', $s3ql['from']) && !ereg('true|1', $s3ql['where']['local'])) { #REMOTE USERS< GROUPS< PROJECTS ARE INSERTED INTO DEPLOYMENT,M NO NEED TO FIND THEM AGAIN #Remote permissions query: changed 23Mar08 for specifying query in uid $remote_permissions_query .= "select * from s3db_permission where uid " . $regexp . " '^" . $GLOBALS['s3codesInv'][$GLOBALS['singulars'][$s3ql['from']]] . "' and permission_level " . $regexp . " '(1|2)\$'"; #the idea is to select anything that does not exist locally $remote_permissions_query .= " and id not in (select " . $GLOBALS['s3ids'][$GLOBALS['s3codes'][$letter]] . " from s3db_" . $GLOBALS['s3tables'][$GLOBALS['s3codes'][$letter]] . ")"; if ($user_self_query != '') { $remote_permissions_query .= " and id = '" . $self_id . "'"; } if ($uidQuery != '') { $remote_permissions_query .= " and id " . $regexp . " '^(" . $uidQuery['str_ids'] . ")\$'"; } if ($permissionsQuery != '') { $remote_permissions_query .= " and id " . $regexp . " '^(" . $permissionsQuery['str_ids'] . ")\$'"; } #echo $remote_permissions_query;exit; $db->query($remote_permissions_query, __LINE__, __FILE__); #this will return ALL the elements shared by USER while ($db->next_record()) { $remote_id[] = array('uid' => $db->f('uid'), 'shared_with' => $db->f('shared_with'), 'permission_level' => $db->f('permission_level')); } if (is_array($remote_id)) { foreach ($remote_id as $rem_id) { #$rem_uid = substr($rem_id['uid'],1,strlen($rem_id['uid'])); $rem_uid = $rem_id['uid']; $rem_resource_data = URIinfo($rem_uid, $user_id, $s3ql['key'], $db); #echo '<pre>';print_r($rem_resource_data);exit; if (is_array($rem_resource_data)) { $rem_resource_data['shared_with'] = $rem_id['shared_with']; $rem_resource_data['uid'] = $rem_id['uid']; $rem_resource_data['permission_level'] = $rem_id['permission_level']; } #echo '<pre>';print_r($rem_resource_data);exit; #concatenate them in the results; THIS SHOWS ONLY REMOTE RESOURCES THAT ARE AVAILABLE AT THE MOMENT! if (is_array($s3ql['where'])) { foreach ($s3ql['where'] as $query_field => $query_value) { if ($query_value != $rem_resource_data[$query_field]) { if (!in_array($query_field, $GLOBALS['COREids'])) { $rem_resource_data = array(); } } } } if (is_array($data) && is_array($rem_resource_data)) { array_push($data, $rem_resource_data); } elseif (is_array($rem_resource_data) && !empty($rem_resource_data)) { $data[] = $rem_resource_data; } } } } if (is_array($array)) { $data = array_filter($data); } #echo '<pre>';print_r($data);exit; #now we're ready to display the data $pack = compact('data', 'whereScore', 'WhereInfo', 'fromScore', 's3ql', 'key', 'target', 'db', 'user_id', 'cols', 'returnFields', 'target', 'uidQuery'); if (!ereg('keys|accesslog', $s3ql['from'])) { $data = includeAllData($pack); } } #echo '<pre>';print_r($data);exit; #$data = filterDataForQuery($data, $cols,$returnFields, $whereScore, $fromScore, $s3ql, $key, $target, $db, $user_id); if (is_array($data) && !empty($data)) { $data = array_combine(range(0, count($data) - 1), $data); return $data; } else { return formatReturn($GLOBALS['error_codes']['no_results'], 'Your query returned no results', $format, ''); } }
function remoteURIOLD($uid, $key, $user_id, $db) { #function remoteURI performs a call on a remote Did for retrieving information on a specific s3id #syntax: remoteURI($uid, $key, $db) #uid should be a concatenation of Did and user_id. Did is either a URL or an alphanumeric string that can be called on mothership #echo $uid; #find this user's id #$local_user = $GLOBALS['Did'].'/'.'U'.$user_id; #$myip = captureIp(); #$myip = ($myip!='')?$myip:$_SERVER['SERVER_NAME']; #$local_user = (($_SERVER['HTTPS']!='')?'https://':'http://'.$myip.'/'.strtok($_SERVER['PHP_SELF'], '/')).'/'.'U'.$user_id; #test Did. Is it a url? or a way to find a url? #ereg('(.*)(/|_)(D|U|G|P|C|R|I|S)([0-9]+$)', $uid, $out); #ereg('(D(.*)|http://(.*)|https://(.*))(_|/)(U|G|P|C|R|I|S)([0-9]+$|D|http://|https://)', $uid, $out); $local_user = S3DB_URI_BASE . '/' . 'U' . $user_id; #echo $local_user;exit; $uid_info = uid($uid); #echo $uid; #echo '<pre>';print_r($uid_info);exit; $letter = substr($uid_info['uid'], 0, 1); #echo $uid; if (ereg('^(U|G|P|C|R|I|S)', $uid)) { $uid = substr($uid, 1, strlen($uid)); #if uid brings a letter, leave just a the id $Did = substr($uid_info['Did'], 1, strlen($uid_info['Did'])); } else { $Did = $uid_info['Did']; } $remoteId = $uid_info['uid']; #echo $Did;exit; #echo http_test_existance($Did);exit; #test Did. if is not url, must find url first #First let's try calling the remote resource without authientication; it might be a public resource ereg('^(D|http.*)/(D|P|C|R|I|S|G|U)([0-9]+)', $uid, $uid_in_remote); $did_call = $Did . '/URI.php?uid=' . $uid_in_remote[2] . $uid_in_remote[3] . '&format=php'; $did_data = stream_get_contents(@fopen($did_call, 'r')); $msg = unserialize($did_data); $msg = $msg[0]; #$msg=html2cell($did_data);$msg = $msg[2]; if ($msg['uri'] != '') { #Good, it's a public resource return $msg; } $did_call = $Did . '/URI.php?key=' . $key . '&user_id=' . $local_user . '&uid=' . $uid_in_remote[2] . $uid_in_remote[3]; $did_data = stream_get_contents(@fopen($did_call, 'r')); if ($did_data == '') { $did_url = findDidUrl($Did, $db); #internal - does it exist on inside table? $dateDiff_min = (strtotime(date('Y-m-d H:i:s')) - strtotime($did_url['checked_valid'])) / 60; #did_url empty? Mothership working?#checked no longer than an hour? if (empty($did_url['url']) || $dateDiff_min > 60) { $mothership = $uid_info['MS'] != '' ? $uid_info['MS'] : $GLOBALS['s3db_info']['deployment']['mothership']; #because s3db.org is under sourceforge, find the real url of that mother ship first. if (ereg('http://s3db.org|http://www.s3db.org', $mothership)) { if (http_test_existance('http://s3db.org/ms.txt')) { $handle = fopen('http://s3db.org/ms.txt', 'rb'); $real_ms = stream_get_contents($handle); fclose($handle); } else { $real_ms = 'http://s3db.virtual.vps-host.net/central/'; } if (ereg('frameset', $real_ms)) { ereg('src="(http.*" )', $real_ms, $out); if (http_test_existance(trim($out[1], "\" "))) { $mothership = fread(fopen(trim($out[1], "\" "), 'r'), '100'); } } } if (http_test_existance($mothership)) { #call mothership, find true url $true_url = fread(fopen($mothership . '/s3rl.php?Did=' . $Did, 'r'), '100000'); #echo '<pre>';print_r($true_url);exit; if (!empty($true_url)) { $data = html2cell($true_url); } #echo '<pre>data';print_r($data);exit; $data[2]['deployment_id'] = substr($Did, 1, strlen($Did)); if (http_test_existance(trim($data[2]['url']))) { $data[2]['checked_valid'] = date('Y-m-d H:i:s'); } else { $data[2]['checked_valid'] = ''; } #now update true url in local if (empty($did_url)) { insertDidUrl($data[2], $db); } else { updateDidUrl($data[2], $db); } #and define the variable $url = trim($data[2]['url']); } else { #motherhsips seems to be down... try asking the url that gave the this uid for a URL. #need the url from the deployment where this ID is being shared from. } } else { $url = trim($did_url['url']); } #echo '<pre>';print_r($did_url);exit; } else { $url = $Did; } #secho $url; #build the call url $url = substr($url, -1) == '/' ? $url : $url . '/'; $key = $key != '' ? $key : get_user_key($user_id, $db); $url2call = $url . 'URI.php?uid=' . $remoteId . '&key=' . $key . '&user_id=' . $local_user; #echo $url2call;exit; if (!http_test_existance($url2call)) { return $GLOBALS['messages']['something_does_not_exist'] . '<message>' . $remoteId . ' does not appear to be a valid remote resource</message>'; } $data = array('uid' => $remoteId, 'key' => $key, 'user_id' => $local_user); #now try to access it. I am assuming user already has access in the remote resource $h = fopen($url2call, 'r'); $urldata = fread($h, '10000'); if ($urldata == '') { return "could not find user on the url provided"; } else { #now, which part of the data am I waiting? what element is this? #$relevant_fields = $GLOBALS['dbstruct'][$GLOBALS['s3codes'][substr($remoteId, 0,1)]]; $element = $GLOBALS['s3codes'][substr($remoteId, 0, 1)]; $id_name = $GLOBALS['s3ids'][$element]; #some remote header require translation $remote_resource_names = array('created_by' => 'user_id', 'project_owner' => 'user_id', 'resource_id' => ereg('I|S', substr($remoteId, 0, 1)) ? 'instance_id' : 'class_id', 'subject_id' => 'class_id', 'object_id' => 'class_id', 'verb_id' => 'instance_id'); $data = html2cell($urldata); #echo 'before or after?<pre>';print_r($data); if (is_array($data)) { $relevant_fields = $data[1]; $data = $data[2]; $relevant_data = array_intersect_key($data, array_flip($relevant_fields)); #whatever points to resources must come with the remote ID foreach ($relevant_data as $fieldName => $fieldData) { if (in_array($fieldName, array_keys($remote_resource_names)) || ereg('_id$', $fieldName) && !ereg('http://|https://|_', $fieldData)) { $uidLetter = $remote_resource_names[$fieldName] != '' ? strtoupper(substr($remote_resource_names[$fieldName], 0, 1)) : strtoupper(substr($fieldName, 0, 1)); #echo $fieldName; if ($fieldData != '') { $DidData[$fieldName] = $Did . '/' . $uidLetter . $fieldData; } } else { $DidData[$fieldName] = $fieldData; } } #translate old acl into new permission_levels if ($DidData['acl'] != '' && strlen($DidData['acl']) == '1') { $DidData['acl'] = $DidData['acl'] == '3' ? '222' : ($DidData['acl'] == '2' && ereg('I|S', $letter) ? '222' : ($DidData['acl'] == '2' && ereg('P|C|R', $letter) ? '202' : ($DidData['acl'] == '1' && ereg('P|C|R', $letter) ? '201' : ($DidData['acl'] == '1' && ereg('I|S', $letter) ? '211' : ($DidData['acl'] == '0' ? '000' : '000'))))); } #return the original uid to the apporpriate id_name $DidData[$id_name] = $uid; #figure out if user also has local permission on this resource $info = $DidData; $id = $letter . $uid; $P = permissionOnResource(compact('info', 'key', 'user_id', 'db', 'id')); #given permission on 2 deploykents, (local+rmote), find which one user has the most permission if ($P != '' && $DidData['acl'] != '') { $view = max(array(substr($DidData['acl'], 0, 1), substr($P, 0, 1))); $change = max(array(substr($DidData['acl'], 1, 1), substr($P, 1, 1))); $add_data = max(array(substr($DidData['acl'], 2, 1), substr($P, 2, 1))); $DidData['acl'] = $view . $change . $add_data; } else { $DidData['acl'] = $P != '' ? $P : $DidData['acl']; } $element_info = $DidData; #echo '<pre>';print_r($element_info); #Define if ser can view or not view data. View is the first number in the 3 d code. It ranges from 0 to 2 if (ereg('^2', $element_info['acl']) || ereg('^1', $element_info['acl']) && $element_info['created_by'] == $user_id) { #2 means user can view anything associated with this resource (downstream). 1 means he can see, as long as resource was created by himself $element_info['view'] = '1'; #yes, access is granted. } else { $element_info['view'] = '0'; #no, sorry :-( } #Decide if user can change (update) or not change data on resource $change_digit = substr($element_info['acl'], 1, strlen($element_info['acl'])); #it is the second digit who specifies this if (ereg('^2', $change_digit) || ereg('^1', $change_digit) && $element_info['created_by'] == $user_id) { $element_info['change'] = '1'; } else { $element_info['change'] = '0'; #nope. } #can user insert data in this resource? Information is in the very last digit. In case it only has 2 digits, reading th last digit will work too because it propagates if (ereg('2$', $element_info['acl']) || ereg('1$', $element_info['acl']) && $element_info['created_by'] == $user_id) { $element_info['add_data'] = '1'; } else { $element_info['add_data'] = '0'; } #create the element "delete", in case it is eventually created...For now it is the same as change $element_info['delete'] = $element_info['change']; $element_info['delete_data'] = $element_info['add_data']; return $element_info; } else { #return ($GLOBALS['messages']['something_went_wrong'].'<message> Deployment '.$Did.' responded: '.$urldata.'</message>'); return formatReturn($GLOBALS['error_codes']['no_results'], 'Deployment ' . $Did . ' responded: ' . $urldata, $format, ''); } } #echo $resp; }
include_once S3DB_SERVER_ROOT . '/s3dbcore/S3QLaction.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/htmlgen.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/acceptFile.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/URIaction.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/common_functions.inc.php'; $format = $_REQUEST['format']; if ($format == '') { $format = 'html'; } #if a key has been provided, validate the key $key = $_REQUEST['key']; include_once 'core.header.php'; #echo '<pre>';print_r($db); $query = $_REQUEST['query'] != "" ? $_REQUEST['query'] : $_REQUEST['q']; if ($query == '') { echo formatReturn('3', 'Please input an S3QL query.', $format, ''); exit; } $q = compact('query', 'format', 'key', 'user_id', 'db'); $s3ql = parse_xml_query($q); $s3ql['db'] = $db; $s3ql['user_id'] = $user_id; $data = S3QLaction($s3ql); #echo '<pre>';print_r($data); if (count($data) > 1) { $s3ql['order_by'] = 'created_on desc'; $s3ql['limit'] = '1'; $data = S3QLaction($s3ql); } if ($data[0]['file_name'] == '') { echo $data[0]['value'];
function sparql($I) { ##Parse the query and build the dataset #global $timer; if (is_file(S3DB_SERVER_ROOT . '/pearlib/Benchmark/Timer.php')) { require_once S3DB_SERVER_ROOT . '/pearlib/Benchmark/Timer.php'; $timer = new Benchmark_Timer(); $timer->start(); } extract($I); ##To use SPARQL with ARC library, we will need it to work with a remote endpoint. That means that we do not want to configure ARC as a datastore, but rather to retrieve the data from s3db deployments, convert it to RDF and then use ARC to run the query on it /* ARC2 static class inclusion */ ini_set("include_path", S3DB_SERVER_ROOT . "/pearlib/arc" . PATH_SEPARATOR . ini_get("include_path")); include_once "ARC2.php"; $s3ql['url'] = $in['url'] != '' ? $in['url'] : $default_uri; $s3ql['key'] = $in['key'] != '' ? $in['key'] : get_user_key($user_id, $db); $q = $in['query']; list($query, $triples, $prefixes) = parse_sparql_query($q, $s3ql); #Altered 4/23/2010 #from this moment on, we need first to SELECT even if that is not the query form; the query form will matter when we finally return the data $query_form = $query['select'] != '' ? 'select' : ($query['ask'] != '' ? 'ask' : ($query['describe'] != '' ? 'describe' : ($query['construct'] != '' ? 'construct' : '??'))); if ($query_form == 'describe') { $format = 'n3'; } $bq .= "PREFIX " . implode("\n PREFIX ", $query['prefix']) . "\n "; $bq .= "SELECT " . $query[$query_form][0] . "\n "; $bq .= "FROM" . implode(" FROM ", $query['from']) . "\n "; $bq .= "WHERE " . $query['where'][0] . "\n "; /* $bq .= "PREFIX ".implode("\n PREFIX ", $query['prefix'])."\n "; $bq .= "SELECT ".$query['select'][0]."\n "; $bq .= "FROM".implode(" FROM ", $query['from'])."\n "; $bq .= "WHERE ".$query['where'][0]."\n "; */ preg_match_all('(\\?[A-Za-z0-9_]+) ', $bq, $vars); if ($vars[0]) { $vars = array_unique($vars[0]); $sparql_vars = implode(" ", $vars); } if ($query['select'][0] != "" && $query['select'][0] != "*") { $outputCols = explode(" ", trim($query['select'][0])); $outputCols = array_filter($outputCols); $outputCols = array_intersect($vars, $outputCols); } $sparql = ereg_replace("FROM(.*)WHERE", "WHERE", $bq); #Validate the query first include_once RDFAPI_INCLUDE_DIR . "sparql/SparqlParser.php"; try { $parser = new SparqlParser(); $parsed = $parser->parse($sparql); } catch (Exception $e) { echo formatReturn('1', 'Parse error: ' . $e->getMessage(), $_REQUEST['format'], ''); exit; } #lets preprocess the order by which the must be queries must be performed to optimize speedness $filename = S3DB_SERVER_ROOT . '/tmp/' . md5($sparql . $user_id); if ($clean && is_file($filename)) { unlink($filename); } if (!is_file($filename)) { list($iterations, $scrambled) = iterationOrder($triples, $prefixes, true); ##$rdf_results will contain the totality of triples retrieved from s3db; ##Start a rdf-api model $iterations = array_values($iterations); $rdf = S3DB_URI_BASE . '/s3dbcore/model.n3'; #base s3db rdf model $rdffilename = md5($rdf); $file_place = $GLOBALS['uploads'] . '/'; #$queryModel = rdf2php($rdf); #$data = $queryModel->sparqlQuery($sparql); #echo '<pre>';print_r($data);exit; if ($timer) { $timer->setMarker('Core model read into results'); } $rdf_results = array(); # add the dictionary data if ($complete) { $dicfile = S3DB_SERVER_ROOT . '/tmp/' . md5('query_dictionary'); if ($clean && is_file($dicfile) && $_REQUEST['clean'] == 'dic') { unlink($dicfile); } if (!is_file($dicfile)) { include_once S3DB_SERVER_ROOT . '/s3dbcore/dictionary.php'; $s3qlN = compact('user_id', 'db'); $s3qlN['from'] = 'link'; $s3qlN['format'] = 'php'; $links = query_user_dictionaries($s3qlN, $db, $user_id); file_put_contents($dicfile, $links); $links = unserialize($links); } else { $links = unserialize(file_get_contents($dicfile)); } $rdf_results['E'][0] = $links; $nsfile = S3DB_SERVER_ROOT . '/tmp/' . md5('query_ns'); if ($clean && is_file($nsfile) && $_REQUEST['clean'] == 'ns') { unlink($nsfile); } if (!is_file($nsfile)) { include_once S3DB_SERVER_ROOT . '/s3dbcore/dictionary.php'; $s3qlN = compact('user_id', 'db'); $s3qlN['from'] = 'namespaces'; $s3qlN['format'] = 'php'; $ns = query_user_dictionaries($s3qlN, $db, $user_id); file_put_contents($nsfile, $ns); $ns = unserialize($ns); } else { $ns = unserialize(file_get_contents($nsfile)); } if ($timer) { $timer->setMarker('Dictionary links retrieved'); } ##Because dictionary queries are too generic, variables need to be bound before writting S3QL $tmp_triples = rdf_encode($links, "E", 'array', $s3ql['db'], $ns); $file = make_rdf_model($tmp_triples); $queryModel = rdf2php($file); #Query needs to be parcial, triple by triple... foreach ($triples as $g => $gPat) { $tmp = explode(" ", $gPat); foreach ($tmp as $t) { if (ereg("http", $t)) { $t = "<" . $t . ">"; } $tgPat .= $t . " "; } $part .= "PREFIX " . implode("\n PREFIX ", $query['prefix']) . "\n "; $part .= "SELECT " . $query['select'][0] . "\n "; $part .= "FROM" . implode(" FROM ", $query['from']) . "\n "; $part .= "WHERE {" . $tgPat . " . }"; $dic_bound_data = $queryModel->sparqlQuery($part); if ($dic_bound_data) { foreach ($dic_bound_data as $l => $varsvals) { if ($vars) { foreach ($vars as $v) { if ($varsvals[$v]->uri) { if (!is_array($discovered[$v]) || !in_array($varsvals[$v]->uri, $discovered[$v])) { $discovered[$v][] = $varsvals[$v]->uri; } } elseif ($varsvals[$v]->literal) { if (!is_array($discovered[$v]) || !in_array($varsvals[$v]->literal, $discovered[$v])) { $discovered[$v][] = $varsvals[$v]->literal; } } } } } } } } $performedQueries = array(); $r = 0; foreach ($iterations as $it => $triples2query) { $S3QL = array(); $S3QLfinal = array(); $queried_elements = array(); $lQueries = array(); $rQueries = array(); foreach ($triples2query as $i => $tripleInd) { $tripleString = $tripleInd; $tmp = explode(" ", trim($tripleString)); $subject = $tmp[0]; //once the subjec is known, predicate may be found ereg("^\\" . $subject . '(.*)', trim($tripleString), $tmp1); $tmp2 = explode(" ", trim($tmp1[1])); $predicate = $tmp2[0]; //With known subject and predicate, object will be the string with that portion truncated ereg("^\\" . $predicate . '(.*)', trim($tmp1[1]), $tmp3); $object = trim($tmp3[1]); #list($subject, $predicate) = explode(' ',trim($tripleString)); #$object = trim(str_replace(array($subject, $predicate), array("", ""), $tripleString)); //Method 1 to breaking the triple /*$tmp = explode(' ',trim($tripleString)); $subject = $tmp[0]; $predicate = $tmp[1]; if(count($tmp)>3){ for ($t=2; $t <count($tmp) ; $t++) { if($object!='') $object .= " "; $object .= $tmp[$t]; } } */ $subject = ereg_replace('^<|>$', '', $subject); $predicate = ereg_replace('^<|>$', '', $predicate); $object = ereg_replace('^<|>$', '', $object); $triple = compact('subject', 'predicate', 'object'); #sparql triple is used to calculate the values of the variables in the triple #$sparql_triple = $sparql_prefixes_default.' SELECT * WHERE { '.ltrim($tripleString).' . }'; #now lets interpret the triple to explore the space of possible queries on S3QL $pack = compact('triple', 's3ql', 'user_id', 'db', 'prefixes', 'varType', 'discoveredData', 'discovered', 'it', 'varTypeWhere', 'collected_data', 'performedQueries'); $sp = sparql_navigator($pack); extract($sp); # if($timer) $timer->setMarker('Built query '.$i); ##Remove queries that were already performed if ($S3QL[0]) { foreach ($S3QL as $s => $q) { if (!in_array($q, $S3QLfinal)) { $S3QLfinal[] = $q; $queried_elements[] = $element[$s]; $lQueries[] = $localQueries[$s]; $rQueries[] = $remoteQueries[$s]; } } #$S3QLfinal[] =$S3QL[0]; #$queried_elements[] = $element; #$localQueries[$tripleString] = $localQueries[0]; #$remoteQueries[$tripleString] = $remoteQueries[0]; #$localQueries = array_filter($localQueries); #$remoteQueries = array_filter($remoteQueries); } } $S3QL = $S3QLfinal; $localQueries = $lQueries; $remoteQueries = $rQueries; ##Remove repeated queries #$S3QL=array_unique($S3QL); #$S3QL = array_values($S3QL); #if only the s3ql is requested, we can return it now if ($in['output'] == 'S3QL') { foreach ($localQueries as $sparqlVersion => $s3qlVersion) { $Q[]['S3QL'] = S3QLQuery($s3qlVersion); } foreach ($remoteQueries as $rq) { $Q[]['S3QL'] = $rq; } $root = 's3ql'; #root is just the word that xml should parse as the root for each entry $data = $Q; $cols = array('S3QL'); $format = $in['format'] == '' ? 'html' : $in['format']; $z = compact('data', 'cols', 'format', 'root'); $out = outputFormat($z); return array(true, $out); } #If paralel library is activated, use it for the data. Otherwise use the custom version #$query_answers_file = 'sparql_query_ans'.rand(100,200); $a=fopen($query_answers_file, 'a'); if (!empty($S3QL)) { if (extension_loaded('curl') && $goparallel) { // Create cURL handlers if ($timer) { $timer->setMarker('Starting queries from group ' . $it); } foreach ($S3QL as $k => $url) { $qURL = $url; $ch[$k] = curl_init(); // Set options curl_setopt($ch[$k], CURLOPT_URL, $qURL . '&format=php'); curl_setopt($ch[$k], CURLOPT_RETURNTRANSFER, 1); } $mh = curl_multi_init(); foreach ($S3QL as $k => $url) { curl_multi_add_handle($mh, $ch[$k]); } $running = null; do { curl_multi_exec($mh, $running); if ($timer) { $timer->setMarker('Query ' . $k . ' of group ' . $it . ' executed'); } } while ($running > 0); foreach ($S3QL as $k => $url) { $answer[$k] = curl_multi_getcontent($ch[$k]); if (!empty($answer[$k])) { #@fwrite($a, $answer[$k]); ##This is what takes the longest after the query, can it be replaced? $ans = unserialize($answer[$k]); #$letter = $queried_elements[$r][0]; $letter = $queried_elements[$k]; if (empty($ans)) { ##is this query part is not optional, then the result will be null ##TO BE DEVELOPED SOON } else { $rdf_results[$letter][] = $ans; } $r++; ##Add the triples to already existing triples #Line up the answer with the model if ($timer) { $timer->setMarker('Query ' . $it . '=>' . $k . ' converted to php '); } } } curl_multi_close($mh); ####Time count #$time_end = microtime(true); #$time = $time_end - $time_start; #echo "Query took ".$time." seconds\n";exit; ### } else { #Now solve the remaining triples with the constants found in this one if (is_array($localQueries) && !empty($localQueries)) { foreach ($localQueries as $s => $locals3ql) { $locals3ql = array_filter(array_diff_key($locals3ql, array('url' => ''))); $tmpqueryfile = S3DB_SERVER_ROOT . '/tmp/' . md5(S3QLQuery($locals3ql)); ##Has this query been performed? if ($clean == '2' && is_file($tmpqueryfile)) { unlink($tmpqueryfile); } #If query results are stored in cache, use them! if (is_file($tmpqueryfile)) { $answer = unserialize(file_get_contents($tmpqueryfile)); } else { $answer = S3QLAction($locals3ql); file_put_contents($tmpqueryfile, serialize($answer)); } //$answer = S3QLAction($locals3ql); if (!empty($answer)) { $letter = letter($locals3ql['from']); $rdf_results[$letter][] = $answer; } } } if (is_array($remoteQueries) && !empty($remoteQueries[0])) { $k = 0; foreach ($remoteQueries as $remoteQuery) { $answer = remoteQ($remoteQuery); if (!empty($answer)) { $letter = $queried_elements[$k]; $rdf_results[$letter][] = $answer; $k++; #$rdfanswer = rdf2php($answer); #Line up the answer with the model #$queryModel->addModel($rdfanswer); #Now perform the query on the small model to find a constant for the remaining queries #list($data,$discovered, $discoveredData,$queryModel) = executeQuery($queryModel,$sparql_triple,$discovered,$format); } } } } } } ##Get the data from the file ##Convert the result into an RDF file $data_triples = array(); if (is_array($rdf_results)) { foreach ($rdf_results as $letter => $results2rdfize) { $dont_skip_core_name = false; $dont_skip_serialized = true; if (ereg('S', $letter)) { $dont_skip_serialized = false; } if (ereg('C|R|P', $letter)) { $dont_skip_core_name = true; } foreach ($results2rdfize as $k => $data) { $tmp_triples = rdf_encode($data, $letter, 'array', $s3ql['db'], $ns, $collected_data, $dont_skip_serialized, $dont_skip_core_name); if (is_array($tmp_triples)) { $data_triples = array_merge($data_triples, $tmp_triples); } } } } if (is_array($outputCols) && !empty($outputCols)) { ##only this one are to be shown in the final result $vars = $outputCols; } $cleanCols = array(); foreach ($vars as $varname) { $cleanCols[] = ereg_replace('^\\?', '', $varname); } if (empty($data_triples)) { ##still return the headers $cols = $cleanCols; $format = $_REQUEST['format'] != "" ? $_REQUEST['format'] : 'html'; $data = array(); $z = compact('data', 'cols', 'format', 'root'); $out = outputFormat($z); return array(1, $out); #return true because query was valid... just did not return any results } #echo $filename;exit; $tmp['ns'] = $prefixes; /* #this one for turtle $parser = ARC2::getComponent('TurtleParser', $a); $index = ARC2::getSimpleIndex($triples, false) ; # false -> non-flat version $rdf_doc = $parser->toTurtle($index,$prefixes); */ $parser = ARC2::getComponent('RDFXMLParser'); $index = ARC2::getSimpleIndex($data_triples, false); /* false -> non-flat version */ $rdf_doc = $parser->toRDFXML($index); #$filename = S3DB_SERVER_ROOT.'/tmp/'.md5($sparql.date('d')); $rr = fopen($filename, 'a+'); fwrite($rr, $rdf_doc); fclose($rr); if ($timer) { $timer->setMarker(count($data_triples) . ' triples written to file ' . $filename); } ##The better strategy would be to let the client cpu resolve the query; return the graphs with the rdf so that a sparql on the client can handle it } if ($_REQUEST['filename']) { $url2search = str_replace(S3DB_SERVER_ROOT, S3DB_URI_BASE, $filename); if (filesize($filename) > 0) { return array(true, $url2search); } else { return array(false); } exit; } if ($redirect) { ##And now use an external service ( I gave up with ARC) to parse the query $url2search = str_replace(S3DB_SERVER_ROOT, S3DB_URI_BASE, $filename); $bq = stripslashes($bq); ##Giving up on ARC, surrender to sparql.com $remote_endpoint = "http://sparql.org/sparql?query="; $bq = ereg_replace("FROM <.*>", "FROM <" . $url2search . ">", $bq); #$sparql=ereg_replace("FROM <.*>", "FROM <".$url2search.">", $sparql); $bq = urlencode($bq); $remote_endpoint .= $bq . '&default-graph-uri=&stylesheet=/xml-to-html.xsl'; #$remote_endpoint .= $sparql.'&default-graph-uri=&stylesheet=/xml-to-html.xsl'; return array(true, $remote_endpoint); } #And finally perform the query on the model. $queryModel = rdf2php($filename); $format = $in['format'] != '' ? $in['format'] : 'html'; if ($timer) { $timer->setMarker('Data converted to a model the rdf-api can query'); } if (eregi('^(sparql-xml|sparql-html)$', $format)) { switch ($format) { case 'sparql-xml': $result = $queryModel->sparqlQuery($sparql, 'XML'); break; case 'sparql-html': $result = $queryModel->sparqlQuery($sparql, 'HTML'); if ($_REQUEST['su3d']) { $timer->stop(); $profiling = $timer->getProfiling(); echo "Query took " . $profiling[count($profiling) - 1]['total'] . ' sec'; } break; } if ($result) { return array(true, $result); } else { return false; } } elseif ($format == 'html.form') { $form .= ' <html> <head> </head><body> <form method="GET" action="sparql.php" id="sparqlform"> <h5>Target Deployment(s)</h5> <input type="hidden" name="key" value="' . $s3ql['key'] . '"/> <input type="hidden" name="format" value="' . $_REQUEST['format'] . '"/> <input type = "text" id="url" size = "100%" value="' . $GLOBALS['url'] . '" name="url"> <h5>SPARQL <a href="http://www.w3.org/TR/rdf-sparql-query/" target="_blank">(help!!)</a></h5> <br /> <textarea cols="100" id="sparql" rows="10" name = "query">' . stripslashes($sparql) . '</textarea><br /> <input type="submit" value="SPARQL this!" id="submitsparql"></body> </form> '; $form .= '<br />' . count($data) . " rows"; $form .= '<br />Query took ' . (strtotime(date('His')) - $start) . ' sec'; if (count($data) > 0) { return array(true, $form); } else { return array(false); } } else { #and output the result according to requested format $queryResultCache = S3DB_SERVER_ROOT . '/tmp/' . md5($sparql . $user_id . 'result'); if ($clean && is_file($queryResultCache)) { unlink($queryResultCache); } $sparql = stripslashes($sparql); if (!is_file($queryResultCache)) { $data = $queryModel->sparqlQuery($sparql); file_put_contents($queryResultCache, serialize($data)); chmod($queryResultCache, 0777); if ($timer) { $timer->setMarker('Query on SPARQL data executed by rdf-api.'); } } else { $data = unserialize(file_get_contents($queryResultCache)); } if (is_array($outputCols) && !empty($outputCols)) { ##only this one are to be shown in the final result $vars = $outputCols; } $cleanCols = array(); foreach ($vars as $varname) { $cleanCols[] = ereg_replace('^\\?', '', $varname); } $outputData = array(); if (is_array($data)) { foreach ($data as $s => $sparql_line) { foreach ($sparql_line as $sparql_var => $sparql_var_value) { if ($sparql_var_value->uri != '') { $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = $sparql_var_value->uri; } elseif ($sparql_var_value->label != '') { $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = $sparql_var_value->label; } else { $outputData[$s][ereg_replace('^\\?', '', $sparql_var)] = ""; } } } } if ($timer) { $timer->setMarker('Data converted in a format that fun outputformat can read'); } #$timer ->display(); #root is just the word that xml should parse as the root for each entry $root = 'sparql'; if ($timer) { $timer->setMarker('All variables fitted into their places to represent in the final output'); } $data = $outputData; $cols = $cleanCols; if ($_REQUEST['su3d']) { if ($timer) { $timer->stop(); $profiling = $timer->getProfiling(); } echo "Query took " . $profiling[count($profiling) - 1]['total'] . ' sec<br>'; } $z = compact('data', 'cols', 'format', 'root'); $out = outputFormat($z); #if($_REQUEST['su3d']){ # echo $out;exit; #} #if(count($data)>0){ return array(true, $out); #} #else { # return (array(false)); #} } #else { #$out= formatReturn($GLOBALS['error_codes']['no_results'], 'Your query did not return any results.', $format,''); #} }
} } echo $msg; } } #if there is no data besides the key, ask for a filename and filesize #if($filename == '') $filename = $xml -> filename; #$filesize = $_REQUEST['filesize']; #if($filesize == '') $filesize = $xml -> filesize; ##Copy file from Php tmp directory } else { $filekey = $xml->filekey; if ($filekey == '') { $filekey = $_REQUEST['filekey']; } if ($filekey != '') { include_once 'core.filekeyheader.php'; #add a form to the page such that it accepts both POST and GET #echo '<form name="file" method="POST">'; #echo '<input type="hidden" name="query"> <!-- this form is for programming environments that support sending POST -->'; #echo '</form>'; #echo receiveFileFragments(compact('filekey', 'db')); echo formatReturn('0', receiveFileFragments(compact('filekey', 'db')), $format, ''); exit; } else { include_once S3DB_SERVER_ROOT . '/s3dbcore/callback.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/display.php'; echo formatReturn('3', "Filekey is missing.", $format, ''); exit; } }
############################################################################# ##define the Classes in the ontology of s3db if ($inputs['all'] == 1) { $s3Types = array('deployment' => array('user', 'group', 'project'), 'group' => array('user'), 'project' => array('collection', 'rule'), 'collection' => array('item'), 'rule' => array('statement')); } else { ##avoid non domain stuff $s3Types = array('deployment' => array('user', 'group', 'project'), 'group' => array('user'), 'project' => array('collection', 'rule'), 'collection' => array('item')); } ############################################################## #the unique identifier for each table $s3idNames = $GLOBALS['COREids']; #now is there any id specified? $specifiedInput = rootIDinfo($s3idNames, $inputs, $argv, $user_id, $key, $db); extract($specifiedInput); if (!$specified_id_info['view']) { echo formatReturn($GLOBALS['messages']['no_permission_message'], "User does not have access in this " . $specified_id_type, $input['format']); exit; } $triples = array(); $rootUID = letter($specified_id_type) . $specifiedInput['rootID']; $rootTriples = rdf_encode(array(0 => $specified_id_info), letter($specified_id_type), 'array', $db); $triples = array_merge($triples, $rootTriples); #Export user permissions on object #retrieve permission info on this URI if (in_array('permissions', array_keys($inputs))) { $s3ql = compact('user_id', 'db'); $s3ql['from'] = 'users'; $s3ql['where'][$specified_id] = $specified_id_info[$specified_id]; $users = S3QLaction($s3ql); $me = $user_info; $me = include_all(array('elements' => 'users', 'element_info' => $me, 'user_id' => $user_id, 'db' => $db));
} } } } } if (!$privateKey) { echo formatReturn(7, "Could not retrieve a private key. Please specify a valid private key to decript this string", $_REQUEST["format"]); exit; } } else { include_once S3DB_SERVER_ROOT . "/s3dbcore/encryption.php"; } if ($str) { $decrypted = decrypt($str, $privateKey); if (!$decrypted) { echo formatReturn(7, "Your private key appears to be the wrong key for the string.", $_REQUEST["format"]); exit; } echo $decrypted; } else { if (is_array($queryData)) { foreach ($queryData as $d => $data) { foreach ($data as $e => $data_value) { $decrypted = decrypt($data_value, $privateKey); if ($decrypted) { $queryData[$d][$e] = $decrypted; } } } } $data = $queryData;
function readInputMessage($query) { #echo '<pre>';print_r($$_SERVER[]); $xml = stripslashes($query); if ($action == '') { $action = 'select'; } #Determine if XML is a URL or a string if (ereg('^http.*', $xml)) { $xmlFile = @file_get_contents($xml); if (empty($xmlFile)) { echo formatReturn($GLOBALS['error_codes']['something_missing'], 'Query file is not valid', $_REQUEST['format'], ''); exit; } else { $xml = $xmlFile; } } elseif (ereg('^(select|insert|edit|update|grant)', $query, $action)) { #it is text, read it frmo text $Q = explode(' ', $query); #if(ereg('^(projects|rules|classes|instances|statements|users|groups|keys)', $Q[1])) if (in_array($Q[1], array_keys($GLOBALS['s3input']))) { $s3ql['from'] = $Q[1]; if (array_search("in", $Q)) { $where_ind = array_search("in", $Q); $s3ql['where'][$Q[$where_ind + 1]] = $Q[$where_ind + 2]; } } else { $s3ql[$action[1]] = $Q[1]; } if (array_search("in", $Q)) { $where_ind = array_search("in", $Q); $s3ql['where'][$Q[$where_ind + 1]] = $Q[$where_ind + 2]; } if (array_search("where", $Q)) { $where_ind = array_search("where", $Q); if ($Q[$where_ind + 2] == '=') { $s3ql['where'][$Q[$where_ind + 1]] = $Q[$where_ind + 3]; } else { $s3ql['where'][$Q[$where_ind + 1]] = $Q[$where_ind + 2] . $Q[$where_ind + 3]; } } #find a "from". If there is one, then the from and the next for a key=>value pair if (array_search('from', $Q)) { $s3ql['from'] = $Q[array_search('from', $Q)]; } if (array_search('where', $Q)) { $pairsA = range(array_search('where', $Q) + 1, count($Q) + 1, 4); $pairsB = range(array_search('where', $Q) + 2, count($Q) + 2, 4); $equality = range(array_search('where', $Q) + 3, count($Q) + 3, 4); $intersect = range(array_search('where', $Q) + 2, count($Q) + 4, 4); } } #clean up values that might affect parsing the xml ereg('<value>(.*)</value>', $xml, $val); if ($val[1] != '') { $xml = str_replace('<value>' . $val[1] . '</value>', '<value>' . base64_encode($val[1]) . '</value>', $xml); } ereg('<notes>(.*)</notes>', $xml, $notes); if ($notes[0] != '') { $xml = str_replace('<notes>' . $notes[1] . '</notes>', '<notes>' . base64_encode($notes[1]) . '</notes>', $xml); } if ($xml != '') { try { $tmp = @simplexml_load_string($xml); if (!$tmp) { $tmp = @simplexml_load_string(urldecode($xml)); } if (!$tmp) { throw new Exception(formatReturn($GLOBALS['error_codes']['something_went_wrong'], 'XML query is badly formatted. Please check your start/end tags', $_REQUEST['format'], '')); } #$timer->setMarker('XML parsed'); } catch (Exception $e) { print $e->getMessage(); exit; } $xml = $tmp; #When there is no XML, rely on GET $s3ql = $xml; $s3ql = get_object_vars($s3ql); #echo '<pre>';print_r($s3ql); $s3ql['key'] = $s3ql['key'] != '' ? $s3ql['key'] : $_REQUEST['key']; if (get_object_vars($s3ql['where']) != '') { $s3ql['where'] = get_object_vars($s3ql['where']); } elseif ($_REQUEST['where'] != '') { $s3ql['where'] = $_REQUEST['where']; } if ($s3ql['where']['value'] != '') { $s3ql['where']['value'] = base64_decode($s3ql['where']['value']); } if ($s3ql['where']['notes'] != '') { $s3ql['where']['notes'] = base64_decode($s3ql['where']['notes']); } #echo '<pre>';print_r($s3ql);exit; #if(get_object_vars($s3ql['where']['or'])!='') #$s3ql['where']['or'] = get_object_vars($s3ql['where']['or']); #elseif($_REQUEST['where']['or']!='') #$s3ql['where']['or'] = $_REQUEST['where']['or']; if (get_object_vars($s3ql['set']) != '') { $s3ql['set'] = get_object_vars($s3ql['set']); if ($s3ql['set']['value'] != '') { $s3ql['set']['value'] = base64_decode($s3ql['set']['value']); } if ($s3ql['set']['notes'] != '') { $s3ql['set']['notes'] = base64_decode($s3ql['set']['notes']); } } elseif ($_REQUEST['set'] != '') { $s3ql['set'] = $_REQUEST['set']; } $s3ql['select'] = $s3ql['select'] != '' ? $s3ql['select'] : ($_REQUEST['select'] != '' ? $_REQUEST['select'] : (is_array($s3ql) && in_array('from', array_keys($s3ql)) ? '*' : '')); $s3ql['from'] = $s3ql['from'] != '' ? $s3ql['from'] : ($_REQUEST['from'] != '' ? $_REQUEST['from'] : 'projects'); if ($s3ql == '') { $s3ql = $_GET; } if ($s3ql['format'] == '' && $_REQUEST['format'] != '') { $s3ql['format'] = $_REQUEST['format']; } #interpred the "or" and "and" } else { $s3ql['select'] = '*'; $s3ql['from'] = 'projects'; } #echo '<pre>';print_r($s3ql); return $s3ql; }
require_once S3DB_SERVER_ROOT . '/pearlib/Benchmark/Timer.php'; $timer = new Benchmark_Timer(); $timer->start(); } $RSAkeys = generate_key_pair(); if ($_REQUEST['action'] == 'save' || $_REQUEST['action'] == 'view') { list($created, $encryption) = createEncryptionProject($user_id, $db, $RSAkeys); if ($created && $_REQUEST['action'] == 'save') { echo formatReturn("0", "RSA Key pair saved. Use an s3db key from the current user to decrypt messages using decrypt.php", $_REQUEST['format']); exit; } elseif ($created && $_REQUEST['action'] == 'view') { $RSAKeys = array(); $data[0]['public_key'] = $encryption['public_key']; $data[0]['private_key'] = $encryption['private_key']; } else { echo formatReturn("1", "Could not save the key pair.", $_REQUEST['format']); exit; } } else { $data = array(0 => array('public_key' => $RSAkeys['public'], 'private_key' => $RSAkeys['private'])); } $cols = array('public_key', 'private_key'); $format = $_REQUEST['format'] != "" ? $_REQUEST['format'] : 'html'; $z = compact('data', 'cols', 'format'); echo outputFormat($z); exit; function generate_key_pair() { $key_length = '64'; $key_pair = new Crypt_RSA_KeyPair($key_length); check_error_pair($key_pair);
if (file_exists('../config.inc.php')) { include '../config.inc.php'; } else { Header('Location: http://' . $def . '/s3db/'); exit; } $key = $_GET['key']; #Get the key, send it to check validity include_once '../core.header.php'; if (!$key) { $key = get_user_key($user_id, $db); } $item_id = $_REQUEST['item_id']; $rule_id = $_REQUEST['rule_id']; if (!$item_id || !$rule_id) { echo formatReturn('3', "Please specify item_id and rule_id", $_REQUEST['format'], ''); exit; } $url = $GLOBALS['URI'] . "/multi_upload.php?key=" . $key . "&rule_id=" . $rule_id . "&item_id=" . $item_id; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> header </title> </head> <body> <applet name="jumpLoaderApplet" code="jmaster.jumploader.app.JumpLoaderApplet.class" archive="jumploader_z.jar"
function readInputMessage($query) { #echo '<pre>';print_r($$_SERVER[]); #echo $query;exit; $xml = $query; ##When value brings tags, they will be parsed along with the rest of the xml. Avoid that by encoding it first. #echo $xml;exit; ereg('<value>(.*)</value>', $xml, $val); #echo '<pre>';print_r($val); if ($val[1] != '') { $xml = ereg_replace($val[1], base64_encode($val[1]), $xml); } ereg('<notes>(.*)</notes>', $xml, $notes); if ($notes[0] != '') { $xml = str_replace($notes[1], base64_encode($notes[1]), $xml); } #echo $xml;exit; #echo '<pre>';print_r($_SERVER); if ($action == '') { $action = 'select'; } #if($s3ql['from']=='') # $s3ql['from']='projects'; #Determine if XML is a URL or a string if (!ereg('^<S3QL>.*', $xml)) { $xmlFile = @file_get_contents($xml); //$xml = ereg_replace("\\\\","\\", $xml); //$xml = "C:\Documents and Settings\mhdeus\My Documents\\2008\TCGA\query.xml"; //$newXMLFile = $GLOBALS['uploads'].'/tmps3db/query.xml'; //copy($xml, $newXMLFile); //exit; if (empty($xmlFile)) { echo formatReturn($GLOBALS['error_codes']['something_missing'], 'Query file is not valid', $_REQUEST['format'], ''); exit; } else { $xml = $xmlFile; } //$handle = fopen ($xml, 'r'); //$xml = fread($handle, '1000000'); //fclose($handle); } elseif (ereg('^(select|insert|edit|update|grant)', $query, $action)) { #it is text, read it frmo text $Q = explode(' ', $query); #if(ereg('^(projects|rules|classes|instances|statements|users|groups|keys)', $Q[1])) if (in_array($Q[1], array_keys($GLOBALS['s3input']))) { $s3ql['from'] = $Q[1]; if (array_search("in", $Q)) { $where_ind = array_search("in", $Q); $s3ql['where'][$Q[$where_ind + 1]] = $Q[$where_ind + 2]; } } else { $s3ql[$action[1]] = $Q[1]; } if (array_search("in", $Q)) { $where_ind = array_search("in", $Q); $s3ql['where'][$Q[$where_ind + 1]] = $Q[$where_ind + 2]; } if (array_search("where", $Q)) { $where_ind = array_search("where", $Q); if ($Q[$where_ind + 2] == '=') { $s3ql['where'][$Q[$where_ind + 1]] = $Q[$where_ind + 3]; } else { $s3ql['where'][$Q[$where_ind + 1]] = $Q[$where_ind + 2] . $Q[$where_ind + 3]; } } #find a "from". If there is one, then the from and the next for a key=>value pair if (array_search('from', $Q)) { $s3ql['from'] = $Q[array_search('from', $Q)]; } if (array_search('where', $Q)) { $pairsA = range(array_search('where', $Q) + 1, count($Q) + 1, 4); $pairsB = range(array_search('where', $Q) + 2, count($Q) + 2, 4); $equality = range(array_search('where', $Q) + 3, count($Q) + 3, 4); $intersect = range(array_search('where', $Q) + 2, count($Q) + 4, 4); } // echo '<pre>';print_r($pairsA); // echo '<pre>';print_r($pairsB); // echo '<pre>';print_r($equality); // echo '<pre>';print_r($Q); # echo '<pre>';print_r($s3ql); // exit; } if ($xml != '') { #echo $xml;exit; try { if (!@simplexml_load_string($xml)) { throw new Exception(formatReturn($GLOBALS['error_codes']['something_went_wrong'], 'XML query is badly formatted. Please check your start/end tags', $_REQUEST['format'], '')); } } catch (Exception $e) { print $e->getMessage(); exit; } $xml = simplexml_load_string($xml); #echo $xml;exit; #When there is no XML, rely on GET $s3ql = $xml; $s3ql = get_object_vars($s3ql); $s3ql['key'] = $s3ql['key'] != '' ? $s3ql['key'] : $_REQUEST['key']; if (get_object_vars($s3ql['where']) != '') { $s3ql['where'] = get_object_vars($s3ql['where']); } elseif ($_REQUEST['where'] != '') { $s3ql['where'] = $_REQUEST['where']; } if ($s3ql['where']['value'] != '') { $s3ql['where']['value'] = base64_decode($s3ql['where']['value']); } if ($s3ql['where']['notes'] != '') { $s3ql['where']['notes'] = base64_decode($s3ql['where']['notes']); } #if(get_object_vars($s3ql['where']['or'])!='') #$s3ql['where']['or'] = get_object_vars($s3ql['where']['or']); #elseif($_REQUEST['where']['or']!='') #$s3ql['where']['or'] = $_REQUEST['where']['or']; if (get_object_vars($s3ql['set']) != '') { $s3ql['set'] = get_object_vars($s3ql['set']); if ($s3ql['set']['value'] != '') { $s3ql['set']['value'] = base64_decode($s3ql['set']['value']); } if ($s3ql['set']['notes'] != '') { $s3ql['set']['notes'] = base64_decode($s3ql['set']['notes']); } } elseif ($_REQUEST['set'] != '') { $s3ql['set'] = $_REQUEST['set']; } $s3ql['select'] = $s3ql['select'] != '' ? $s3ql['select'] : ($_REQUEST['select'] != '' ? $_REQUEST['select'] : (is_array($s3ql) && in_array('from', array_keys($s3ql)) ? '*' : '')); $s3ql['from'] = $s3ql['from'] != '' ? $s3ql['from'] : ($_REQUEST['from'] != '' ? $_REQUEST['from'] : 'projects'); if ($s3ql == '') { $s3ql = $_GET; } if ($s3ql['format'] == '' && $_REQUEST['format'] != '') { $s3ql['format'] = $_REQUEST['format']; } #interpred the "or" and "and" } else { $s3ql['select'] = '*'; $s3ql['from'] = 'projects'; } #echo '<pre>';print_r($s3ql); return $s3ql; }
function selectQuery($D) { global $timer; extract($D); if ($s3ql['from'] == 'deployment') { $data[0] = array('mothership' => $GLOBALS['s3db_info']['deployment']['mothership'], 'deployment_id' => $GLOBALS['s3db_info']['deployment']['Did'], 'self' => '1', 'description' => $GLOBALS['s3db_info']['server']['site_intro'], 'url' => S3DB_URI_BASE, 'message' => 'Successfully connected to deployment ' . $GLOBALS['s3db_info']['deployment']['Did'] . '. Please provice a key to query the data (for example: ' . ($_SERVER['https'] == 'on' ? 'https://' : 'http://') . $def . S3DB_URI_BASE . '/URI.php?key=xxxxxxxx. For syntax specification and instructions refer to http://s3db.org/'); #return $data; } #echo '<pre>';print_r($s3ql); if (in_array($s3ql['from'], array_keys($GLOBALS['plurals']))) { $s3ql['from'] = $GLOBALS['plurals'][$s3ql['from']]; } #echo '<pre>';print_r($s3ql);exit; if ($s3ql['from'] == 'classes') { $s3ql['from'] = 'collections'; } if ($s3ql['from'] == 'instances') { $s3ql['from'] = 'items'; } if ($s3ql['from'] == 'keys' && $_SESSION['db'] == '') { return formatReturn($GLOBALS['error_codes']['not_a_query'], 'Access keys cannot be queried in the API.', $s3ql['format'], ''); exit; } if (eregi('^t', $s3ql['shared'])) { $shared = true; #shared being set to true will tell s3ql that he should not only retrieved uid native to the upstream resource being queried, but those that propagate toward it $s3ql = array_delete($s3ql, 'shared'); } if ($s3ql['from'] == 'permission' && $user_id != 1) { return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User cannot query permissions.', $s3ql['format'], ''); exit; } if (eregi('^t', $s3ql['shared'])) { $shared = true; #shared being set to true will tell s3ql that he should not only retrieved uid native to the upstream resource being queried, but those that propagate toward it $s3ql = array_delete($s3ql, 'shared'); } if (eregi('complete', $s3ql['display'])) { $complete = true; #complete will tell s3ql that dictionary terms should be added to the output $s3ql = array_delete($s3ql, 'display'); } $target = $s3ql['from']; $letter = strtoupper(substr($s3ql['from'], 0, 1)); $table = strval($target); $element = $target; $cols = $GLOBALS['dbstruct'][$target]; $element_id = $s3ql['where'][$GLOBALS['s3ids'][$element]]; if ($table != '' && !in_array($table, array_keys($GLOBALS['dbstruct']))) { return formatReturn($GLOBALS['error_codes']['not_a_query'], 'Not a valid query.', '', $s3ql['format']); } #manage data in select #echo '<pre>';print_r($s3ql); #array_keys contains the things to replace and array_values the replacements if ($s3ql['select'] != '' && $s3ql['select'] != '*') { $s3ql_out = ereg_replace(' ', '', $s3ql['select']); #take out all the spaces $returnFields = explode(',', $s3ql_out); if (!ereg($GLOBALS['s3ids'][$element], $s3ql['select'])) { if (ereg('count|max|min', $s3ql['select'])) { $SQLfun = ereg_replace("\\(.*\\)", "", $select); $SQLfun = ereg_replace("count as count", "count", $SQLfun); $s3ql['select'] = '*'; } else { $s3ql['select'] .= ',' . $GLOBALS['s3ids'][$element]; } } ##Because of the new code, will also have to add the parent ids to the query #$parents = $GLOBALS['inherit'][$GLOBALS['s3ids'][$element]]; $parents = $GLOBALS['inherit'][$GLOBALS['COREids'][$GLOBALS['singulars'][$element]]]; ##duuuhhh if (is_array($parents)) { foreach ($parents as $p) { if (!in_array($p, $returnFields)) { $s3ql['select'] .= ',' . str_replace($toreplace, $replacements, $p); } } } } else { $s3ql['select'] = '*'; } #echo $s3ql['select'];exit; #echo '<pre>';print_r($s3ql);exit; $toreplace = array_keys($GLOBALS['s3map'][$target]); $replacements = array_values($GLOBALS['s3map'][$target]); #to replace query str with replacements, remove the spaces and explode by commas $select = explode(',', str_replace(' ', '', $s3ql['select'])); foreach ($select as $s_key => $str_select) { if (in_array($str_select, $toreplace)) { $select[$s_key] = $replacements[array_search($str_select, $toreplace)]; } } #echo '<pre>';print_r($select);exit; $s3ql['select'] = implode(',', array_unique($select)); #$s3ql['select'] = str_replace($toreplace, $replacements, $s3ql['select']); #echo '<pre>';print_r($s3ql['select']); $select = urldecode($s3ql['select']); $select = eregi_replace('uid', $GLOBALS['s3ids'][$element] . ' as uid', $select); $select = eregi_replace('uri', $GLOBALS['s3ids'][$element] . ' as uri', $select); $select = eregi_replace('(,).*permissionOnResource', '', $select); #echo $P['out'].$P['SQLfun']; if ($select == $SQLfun) { $SQLfun = ''; } #$s3ql_where_keys = str_replace(array('item_id', 'collection_id'), array('instance_id', 'class_id'), array_keys($s3ql['where'])); #$s3ql['where'] = array_combine($s3ql_where_keys, $s3ql['where']); #transofrmt s3ql and get the return Fields $tranformed = S3QLselectTransform(compact('s3ql', 'db', 'user_id')); extract($tranformed); #anything that is queried must also go come out in the select if ($s3ql['where'] && $select != '*') { foreach ($s3ql['where'] as $more_outputs => $more_value) { if (!substr($select, $more_outputs)) { $select .= "," . str_replace($toreplace, $replacements, $more_outputs); } } } ##for statements, select must find file_name a well so that it is transofmred into a link if ($letter == 'S' && !ereg('file_name', $select)) { $select .= ',file_name'; } $s3ql['select'] = $select; if ($timer) { $timer->setMarker('queryInterpreted'); } #If there is any sort of S3 UID in the query, check its score when compared to the from $score = array('D' => '7', 'G' => '6', 'U' => '5', 'P' => '4', 'C' => '3', 'R' => '3', 'I' => '2', 'S' => '1'); $fromScore = $score[strtoupper(substr($target, 0, 1))]; $s3Ids = array_merge($GLOBALS['COREids'], array('rulelog' => 'rule_id', 'statementlog' => 'statement_id')); #echo '<pre>';print_r($s3ql); $shared_with_query = array(); foreach ($s3Ids as $COREelement => $COREelement_id) { if ($s3ql['where'][$COREelement_id] != '' && !ereg('^~|regexp', $s3ql['where'][$COREelement_id])) { $id_name = $COREelement_id; $id_letter = strtoupper(substr($id_name, 0, 1)); $whereScore[strtoupper(substr($id_name, 0, 1)) . $s3ql['where'][$COREelement_id]] = $score[strtoupper(substr($id_name, 0, 1))]; #when idNameScore is < $fromScore, then we know: we are trying to query all resources that can view another particular resource (for example,all users that can view project x #echo $id_name;exit; $uid = strtoupper(substr($COREelement, 0, 1)) . $s3ql['where'][$COREelement_id]; $uid_info = uid($uid); #Use URIinfo to find all data about this resource $element_info = URIinfo($uid, $user_id, $key, $db, $timer); $WhereInfo[$uid_info['uid']] = $element_info; if (!is_array($element_info)) { return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], $uid . ' does not exist', $s3ql['format'], ''); exit; } elseif ($id_letter != strtoupper(substr($element, 0, 1))) { ##Shared_with is any UID that can eb shared with any of the elements being requested (for example, Collection_id is shared_with Project, but Project_id is not shared with Project array_push($shared_with_query, $uid); #do permissions on this uid propagate? #echo '<pre>';print_r($whereScore);exit; } else { $self_id = $s3ql['where'][$COREelement_id]; if (!$element_info['view']) { return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User does not have permission on ' . $uid, $s3ql['format'], ''); exit; } } } } #echo '<pre>';print_r($WhereInfo);exit; if ($self_id != '') { $data[0] = $element_info; if (ereg('^(U|G)$', $letter) && count($WhereInfo) == 2) { $whereId = array_diff(array_keys($WhereInfo), array($letter . $self_id)); $D = array('shared_with' => $letter . $self_id, 'uid' => $whereId[0], 'strictsharedwith' => 1, 'strictuid' => 1, 'db' => $db, 'user_id' => $user_id, 'stream' => 'upstream', 'timer' => $timer); ##Look for shared_with in uid instead of uid in shared_with #echo 'ola';exit; #$data[0]['permissionOnResource']=permission4Resource($D); $p = array('shared_with' => $letter . $self_id, 'uid' => $whereId[0]); $hasP = has_permission($p, $db); $effective_permission_resource = permission4resource(array('user_id' => $self_id, 'shared_with' => $letter . $self_id, 'db' => $db, 'uid' => $whereId[0], 'strictsharedwith' => 1, 'strictuid' => 1, 'timer' => $timer, 'toFindInfo' => $WhereInfo[$whereId[0]])); if ($hasP || $effective_permission_resource != '') { $data[0]['permissionOnResource'] = $effective_permission_resource; $data[0]['assigned_permissionOnEntity'] = $hasP != "" ? $hasP : '---'; $data[0]['effective_permissionOnEntity'] = $effective_permission_resource; } else { return array(); } } } else { #echo 'ola';exit; #start building the query: $user_query = "select " . $select . " from s3db_" . $GLOBALS['s3tables'][$table]; if (!user_is_admin($user_id, $db)) { $cols = array_diff($cols, array('account_pwd', 'account_phone', 'account_email', 'project_folder')); } #remove a few cols from query if ($timer) { $timer->setMarker('user is admin check'); } #echo $user_id;exit; ## echo $user_query;exit; #now add some constrains necessary due to the type of resource if (!(user_is_admin($user_id, $db) && $s3ql['where']['status'] == 'I')) { if (ereg('projects|classes|instances|rules|statements', $target)) { $status = "status!='I' and "; } } $user_query_const .= " where " . $status . $GLOBALS['s3ids'][$target] . "!='0'"; ### #Filter query according to the element being requested $user_query_const .= filterByElement($s3ql, $user_id, $db); if ($user_query_const) { $user_query .= $user_query_const; } else { exit; } if ($timer) { $timer->setMarker('query filter'); } if ($shared && !empty($shared_with_query) && strtoupper(substr($target, 0, 1)) != 'U') { #the "shared with" are the upstream resources being queried. These may or not be in the permissions table (if the are remote). This basically finds not only elements that were created within a certain uid (for example Ix of Cx), but those that were later shared with that uid (for example Iy created within Cy but later shared with Iy) $uidQuery = simpleQueryUID($shared_with_query, $element, $db); if ($uidQuery) { extract($uidQuery); if (!ereg('G', $letter)) { #query groups has a special syntax, it is already included in the query $user_query .= $finalUID; } ##IS IT INCREASING THE QUERY TIME ABSURDELLY? } #else { #Go on with the regular query # return formatReturn($GLOBALS['error_codes']['no_results'], 'Your query on '.$target.' did not return any results', $format,''); # } if ($timer) { $timer->setMarker('Query to find shared UID'); } } #now constrainthe query to resources that user cann access. Check for inherited permissions and direct permissions. Project is connected to deployment, rule and class to project, and so on. (see S3DB third report for the schema) #Fetch the cols of what is to be returned. Check for SqL functions. This will only affect the output if ($s3ql['select'] != '') { $out = urldecode($s3ql['select']); $SQLfun = ereg_replace("\\(.*\\)", "", $out); $SQLfun = ereg_replace("count as count", "count", $SQLfun); $P['out'] . $P['SQLfun']; if ($out == $SQLfun) { $SQLfun = ''; } else { $extracol = $out; } } #echo $SQLfun; #Extract from the s3ql the value that are part of the syntax and assume the rest are the SQL extras (limit, creted_by, etc) $syntax = array('key', 'select', 'from', 'where', 'format'); foreach ($s3ql as $i => $value) { if (!in_array($i, $syntax) && $value != '') { $SQLextra[$i] = ' ' . ereg_replace('_', ' ', $i) . ' ' . $value; } } #echo '<pre>';print_r($SQLextra);exit; #if there is orderby, move to the beginnign of the array if ($SQLextra['order_by'] != '') { $SQLextra = array_merge(array('order_by' => $SQLextra['order_by']), $SQLextra); } if (is_array($SQLextra)) { foreach ($SQLextra as $key => $value) { $query_extra .= $value; } } #Put in $P the values of what is queried, add to cols, if not already there, whatever is queried. Check if there are regular expressions anywhere. equalit will be replace by the regular expression $cols = $GLOBALS['dbstruct'][$table]; foreach ($cols as $col) { if ($s3ql['where'][$col] != '') { if (!in_array($col, $GLOBALS['COREids']) && $col != $GLOBALS['COREids'][$element]) { $user_query_fields .= ' and ' . $col . ' ' . parse_regexp($s3ql['where'][$col]); } $P[$col] = parse_regexp($s3ql['where'][$col]); } } #when the default query is performed, that is, not shared ids are requested, the query is faster is core_id are added if (!$shared) { if (is_array($s3ql['where']) && !empty($s3ql['where'])) { foreach ($s3ql['where'] as $q_field => $q_value) { if (in_array($q_field, $GLOBALS['COREids']) || $q_field == $GLOBALS['COREids'][$element]) { $sql_col = str_replace($toreplace, $replacements, $q_field); if (!ereg('U|G', $letter)) { ## Users and groups do not have the reousrce in the users table $user_query_fields .= ' and ' . $sql_col . ' ' . parse_regexp($q_value); } else { #Because users queries do not include the parent_id in the talbe itself, they will involve a query in perm table #$u_uid=letter($q_field).$q_value; } } } } } #glue them together. $user_query .= $user_query_fields . $query_extra; if ($timer) { $timer->setMarker('done building query'); } ###Finally perform the query on whatever table is specified #$user_query = "select * from s3db_resource where resource_class_id = '389';"; #if($_REQUEST['su3d']){ #echo $user_query; #$timer->display(); #exit; #} ##run it #complete query on LOCAL resources $db->query($user_query, __LINE__, __FILE__); $dbdata = get_object_vars($db); if ($timer) { $timer->setMarker('done with query'); } if ($dbdata['Errno'] != '0') { return formatReturn($GLOBALS['error_codes']['something_went_wrong'], $dbdata['Error'], $format, ''); } #put it in a nice structured variable $cols = $GLOBALS['dbstruct'][$target]; if (is_array($returnFields) && $extracol == '') { $cols = array_unique(array_merge($cols, $returnFields)); } #echo '<pre>';print_r($cols); while ($db->next_record()) { #echo '<pre>';print_r($db); $resultStr .= "\$data[] = Array("; if ($extracol != '') { $resultStr .= "'" . $extracol . "'=>'" . $db->f($SQLfun) . "',"; } foreach ($cols as $col) { $resultStr .= "'" . $col . "'=>'" . addslashes($db->f($col)) . "'"; if ($col != end($cols)) { $resultStr .= ","; } if ($col == $GLOBALS['s3ids'][$target]) { $retrieved['ids_str'] .= $retrieved['ids_str'] == '' ? $db->f($col) : '|' . $db->f($col); } } $resultStr .= ");"; } #echo $resultStr; #evaluate the long string eval($resultStr); if (is_array($data)) { $data = array_filter($data); } if ($timer) { $timer->setMarker('query results captured'); } #more often than not, a query is made that retrieves all rules/collection data; this data can be reused for permission migration if ($user_query_fields == "" && $SQLextra == "") { $all_data[letter($target)] = $data; } #BEFORE outputting data, are there any remote resources where the user is allowed? $ucode = strtoupper(substr($element, 0, 1)); $ucode_and_id = $ucode . $element_id; ##Added ability to search locally on april 15 2008 to optimize queries ###Added ability to seeek permissions from file on jan 12 2009 to speed permissiosn query if (!ereg('users|groups|projects|keys|rulelog|statementlog|permission', $s3ql['from']) && !ereg('true|1', $s3ql['where']['local'])) { #REMOTE USERS< GROUPS< PROJECTS ARE INSERTED INTO DEPLOYMENT,M NO NEED TO FIND THEM AGAIN ##Added ability to search locally on april 15 to optimize queries ###Added ability to seeek permissions from file on jan 12 2009 to speed permissiosn query list($remoteIDS, $local_not_native) = remotePermissions(compact('s3ql', 'self_id', 'uidQuery', 'permissionsQuery', 'user_id', 'db', 'timer', 'shared_with_query', 'user_self_query', 'letter')); if ($timer) { $timer->setMarker('remote permisions queried'); } ##NOTE: Local_not_native data need to be retrieve as well if (is_array($remoteIDS) && !empty($remoteIDS)) { foreach ($remoteIDS as $rem_id) { #$rem_uid = substr($rem_id['uid'],1,strlen($rem_id['uid'])); $rem_uid = $rem_id['uid']; $rem_resource_data = URIinfo($rem_uid, $user_id, $s3ql['key'], $db); #echo '<pre>';print_r($rem_resource_data);exit; if (is_array($rem_resource_data)) { $rem_resource_data['shared_with'] = $rem_id['shared_with']; $rem_resource_data['uid'] = $rem_id['uid']; $rem_resource_data['permission_level'] = $rem_id['permission_level']; } #echo '<pre>';print_r($rem_resource_data);exit; #concatenate them in the results; THIS SHOWS ONLY REMOTE RESOURCES THAT ARE AVAILABLE AT THE MOMENT! if (is_array($s3ql['where'])) { foreach ($s3ql['where'] as $query_field => $query_value) { if ($query_value != $rem_resource_data[$query_field]) { if (!in_array($query_field, $GLOBALS['COREids'])) { $rem_resource_data = array(); } } } } if (is_array($data) && is_array($rem_resource_data)) { array_push($data, $rem_resource_data); } elseif (is_array($rem_resource_data) && !empty($rem_resource_data)) { $data[] = $rem_resource_data; } } if ($timer) { $timer->setMarker('Remote data retrieved'); } } } if (is_array($data)) { $data = array_filter($data); } #now we're ready to display the data $pack = compact('data', 'whereScore', 'WhereInfo', 'fromScore', 's3ql', 'key', 'target', 'db', 'user_id', 'cols', 'returnFields', 's3ql_out', 'target', 'uidQuery', 'timer', 'shared_with_query', 'all_data', 'letter', 'model'); if (!ereg('keys|accesslog|rulelog|statementlog|permission', $s3ql['from'])) { $data = includeAllData($pack); } } ##if complete was requested, let's retrieve every link and distribute accordingly rather that querying by uid, would would take much longer if ($complete) { $alluid = array(); foreach ($data as $kuid => $data_info) { array_push($alluid, $letter . $data_info[$GLOBALS['s3ids'][$element]]); } include_once S3DB_SERVER_ROOT . '/s3dbcore/dictionary.php'; $s3qlL = compact('user_id', 'db'); $s3qlL['from'] = 'links'; $formatL = 'array'; $links = query_user_dictionaries($s3qlL, $db, $user_id, $formatL); if (is_array($links) && !empty($links)) { foreach ($links as $moreData) { if ($moreData['uid'] != '') { $foundIt = array_search($moreData['uid'], $alluid); if ($foundIt) { $data[$foundIt]['links'][$moreData['relation']] = $moreData['value']; } #$data[$moreData['uid']]['links'][$moreData['relation']]=$moreData['value']; } } } if ($timer) { $timer->setMarker('Dictionary data included!'); } } if (is_array($data) && !empty($data)) { $data = array_combine(range(0, count($data) - 1), $data); return $data; } else { #$emptycols = array(array_combine($cols, array_fill(1,count($cols), ''))); #echo '<pre>';print_r($emptycols);exit; return array(); #return formatReturn($GLOBALS['error_codes']['no_results'], 'Your query returned no results', $format,''); } }
function outputFormat($z) { ##$z = compact('data','cols', 'format'); extract($z); if (!ereg('json|php|xml|rdf|n3|sif|turtle', $format)) { if ($format == 'html.pretty') { $format = 'html'; echo '<script type="text/javascript"> <!-- function paintRows(){ lines = document.getElementsByTagName(\'tr\'); lines[0].setAttribute("style", "font-weight: bold"); for (i=0; i<lines.length; i=i+2) {lines[i].style.backgroundColor = \'#CCFFFF\'} for (i=1; i<lines.length; i=i+2) {lines[i].style.backgroundColor = \'#FFFFFF\'}; } //--> </script>'; echo '<body onload = paintRows()>'; } elseif (ereg('html.(.*)', $format, $css)) { $format = 'html'; $style = @stream_get_contents(@fopen($css[1], 'r')); echo '<style type="text/css">'; echo $style; echo '</style>'; } $format = get_parser_characters($format); #Fetch the cols of what is to be returned if ($s3ql['select'] != '') { $P['out'] = urldecode($s3ql['select']); $P['SQLfun'] = ereg_replace("\\(.*\\)", "", $P['out']); if ($P['out'] == $P['SQLfun']) { $P['SQLfun'] = ''; } } #else { # $P['out'] = implode(',',array_keys($data[0])); #} #After the query, resume the cols that are supposed to be displayed. Remove the sensitivy cols that should not be displayed if ($P['out'] != '' && $P['out'] != '*') { if ($P['SQLfun'] == 'distinct') { $P['out'] = str_replace(array($P['SQLfun'], "(", ")"), "", $P['out']); } $cols = array_map('trimmit', explode(',', $P['out'])); } #echo '<pre>';print_r($cols);exit; $c = 0; foreach ($cols as $i => $name) { $pCol = $name; #if($c==count($cols)-1) if ($c < count($cols) - 1) { $header .= trim($pCol) . $format['middle']; } else { $header .= trim($pCol); } $c++; } $x = array('data' => $data, 'format' => $format, 'header' => $header, 'columns' => $cols); return display($x); #exit; } else { #if dictionary is requested, get the namespaces if ($namespaces_needed) { $s3qlN = compact('user_id', 'db'); $s3qlN['from'] = 'namespaces'; $formatN = 'array'; $namespaces = query_user_dictionaries($s3qlN, $db, $user_id, $formatN); if ($timer) { $timer->setMarker('Namespaces retrieved'); } } if ($_REQUEST['out'] == 'header' || $format == 'json' && $_SERVER['HTTPS']) { header("Pragma: public"); header("Expires: 0"); // set expiration time header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Type: application/force-download"); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); #header("Content-Type: ".$ext.""); // use the Content-Disposition header to supply a recommended filename and // force the browser to display the save dialog. header("Content-Disposition: attachment; filename=s3db." . $format . ""); header("Content-Transfer-Encoding: binary"); } if ($format == 'json') { #$callback = ($_REQUEST['jsonp']=='')?'s3db_json':$_REQUEST['jsonp']; $callback = $_REQUEST['jsonp'] == '' ? $_REQUEST['callback'] == '' ? 's3db_json' : $_REQUEST['callback'] : $_REQUEST['jsonp']; $onLoad = $_REQUEST['onload'] == '' ? '' : '; ' . stripslashes($_REQUEST['onload']) . (ereg('\\(.*\\)', $_REQUEST['onload']) ? '' : '()'); $jsonpp = $_REQUEST['jsonpp'] == '' ? '' : ', "' . $_REQUEST['jsonpp'] . '"'; return $callback . '(' . json_encode($data) . $jsonpp . ')' . $onLoad; exit; } elseif ($format == 'php') { return serialize($data); #echo '$data = '; #print_r($data); exit; } elseif ($format == 'xml') { #header("Content-type: application/xml"); return xml_encode($data, $letter, $root, $namespaces); exit; } elseif (ereg('rdf|n3|turtle', $format)) { if (!in_array(S3DB_SERVER_ROOT . '/rdfheader.inc.php', get_included_files())) { include_once S3DB_SERVER_ROOT . '/rdfheader.inc.php'; } return rdf_encode($data, $letter, $format, $db, $namespaces); exit; } elseif ($format == 'sif') { return tab_encode($data, $returnFields); exit; } } if (is_array($s3qlOut) && !empty($s3qlOut)) { #this menas data was removed return formatReturn($GLOBALS['error_codes']['no_permission_message'], "User does not have permission to access resource(s)", $s3ql['format']); } }
include 'config.inc.php'; } else { Header('Location: http://' . $def . '/s3db/'); exit; } $key = $_REQUEST['key']; include_once 'core.header.php'; ##Find the projecct if ($_REQUEST['project_id'] == '') { echo formatReturn($GLOBALS['error_codes']['something_missing'], "Please provide a project_id.", $format); exit; } $project_id = $_REQUEST['project_id']; $project_info = URIinfo('P' . $project_id, $user_id, $key, $db); if (!$project_info['view']) { echo formatReturn($GLOBALS['error_codes']['no_permission_message'], "You don't have permission to view this project.", $format); exit; } ##$getAllRules $s3ql = compact('user_id', 'db'); $s3ql['from'] = 'rule'; $s3ql['where']['project_id'] = $project_id; $rules = S3QLaction($s3ql); ##now separate the the rules, get the collections an drules $nodes = array(); $node_names = array(); $edges = array(); foreach ($rules as $rule_info) { if (!in_array($rule_info['subject_id'], array_keys($nodes))) { $nodes[$rule_info['subject_id']]['name'] = $rule_info['subject']; }
if ($s3qlout != '' && $s3qlout[1] != '0') { echo formatReturn($s3qlout[1], $s3qlout[2]); exit; } else { $data[0] = $element_info; } $data[0]['uid'] = $GLOBALS['Did'] . ($letter != 'U' ? '|U' . $user_id : '') . '|' . $letter . $ID; $data[0]['uri'] = S3DB_URI_BASE . '/' . $uid; $data[0] = array_filter(array_diff_key($data[0], array('project_folder' => '', 'account_pwd' => '', 'status' => '', 'view' => '', 'change' => '', 'add_data' => '', 'delete' => ''))); if ($letter == 'U' && ($user_id != 1 && $user_id != $element_info['created_by'] && $user_id != $element_info['account_id'])) { $data[0]['email'] = ""; $data[0]['account_email'] = ""; } } } if (!is_array($data[0])) { echo formatReturn($GLOBALS['error_codes'][$something_does_not_exist], "uid " . $uid . " does not exist", $s3ql['format'], ''); exit; } $cols = columnsToDisplay($letter); if ($complete) { if ($data[0]['links']) { foreach ($data[0]['links'] as $newCol => $moreData) { $data[0][$newCol] = $moreData; array_push($cols, $newCol); } } } $z = compact('data', 'cols', 'format', 'letter'); echo outputFormat($z); exit;
function apiQuery($s3ql, $user_proj = false) { extract($s3ql); #if it does not exist, create it and save it in config.inc.php; if (!$user_proj) { $user_proj = create_authentication_proj($s3ql['db'], $s3ql['user_id']); } if (!$user_proj) { $msg = "A project to manage users has not been created. This project can only be created by the generic Admin users. Please add your Admin key to apilogin.php to create it automatically."; return array(false, formatReturn('5', $msg, $format, '')); exit; } if ($s3ql['insert'] != '') { $target = $s3ql['insert']; $action = 'insert'; } if ($s3ql['update'] != '') { $target = $s3ql['update']; $action = 'update'; } if ($s3ql['delete'] != '') { $target = $s3ql['delete']; $action = 'delete'; } if ($s3ql['from'] != '') { $target = $s3ql['from']; $action = 'select'; } if ($target == 'authorities') { $target = 'authority'; } if ($action == 'insert') { switch ($target) { case 'authentication': #does the user_id specified exist? #authentication_id is to always be built from what is provided $user2add = ereg_replace('^U', '', $s3ql['where']['user_id']); #validate the authentication inputs if ($s3ql['where']['authentication_id'] == '') { if (!$s3ql['where']['authority'] || !$s3ql['where']['username']) { $msg = formatReturn($GLOBALS['error_codes']['something_missing'], 'Please provide all the necessary fields. These include either <authentication_id> or <protocol>, <authority> and <username>', $_REQUEST['format'], ''); return array(false, $msg); exit; } else { $prot = $s3ql['where']['protocol']; $auth = $s3ql['where']['authority']; $email = $s3ql['where']['username']; $s3ql['where']['authentication_id'] = ($prot != 'http' ? $prot . ':' : '') . $auth . ':' . $email; $s3ql['where'] = array_delete($s3ql['where'], array('protocol', 'authority', 'username')); } } if ($s3ql['where']['user_id'] == '') { $s3ql['where']['user_id'] = $user_id; $user2add = $user_id; #$msg= (formatReturn($GLOBALS['error_codes']['something_missing'],'Please provide the user_id whose authentication you wish to add.', $format,'')); #return (array(false, $msg)); #exit; } #this function will actually validate the authentication feasibility list($valid, $msg) = validate_authentication($s3ql, $user_id, $db); if ($valid) { #does the user_id have an item assigned to him already? while (!$user_proj['users']['items'][$user2add]['item_id'] && $try < 5) { $user_proj = insert_authentication_tuple(array('user_proj' => $user_proj, 'user_id' => '1', 'db' => $db, 's3ql' => $s3ql)); #$user_proj = insert_authentication_tuple(compact('user_proj', 'user_id','db','s3ql')); $try++; } if ($user_proj['users']['items'][$user2add]['item_id'] == '') { $msg = formatReturn($GLOBALS['error_codes']['something_missing'], "Could not create an item for this user.", $format, ''); return array(false, $msg); exit; } #now let's create an statement for this authentication. Since these can be many, we run the query either way and let s3ql tell us whether this already exists if (!is_array($user_proj[$user2add]['R' . $user_proj['email']['rule_id']])) { $user_proj[$user2add]['R' . $user_proj['email']['rule_id']] = array(); } $s3ql_new = compact('user_id', 'db'); $s3ql_new['insert'] = 'statement'; $s3ql_new['where']['rule_id'] = $user_proj['email']['rule_id']; $s3ql_new['where']['item_id'] = $user_proj['users']['items'][$user2add]['item_id']; $s3ql_new['where']['value'] = $s3ql['where']['authentication_id']; $s3ql_new['format'] = 'php'; $done = S3QLaction($s3ql_new); $msg = unserialize($done); $msg = $msg[0]; if ($msg['statement_id']) { array_push($user_proj[$user2add]['R' . $user_proj['email']['rule_id']], $s3ql['where']['authentication_id']); file_put_contents($GLOBALS['uploads'] . '/userManage.s3db', serialize($user_proj)); $msg1 = formatReturn($GLOBALS['error_codes']['success'], "Authentication inserted", $format, array('authentication_id' => $s3ql['where']['authentication_id'])); return array(false, $msg1); exit; } elseif ($msg['error_code'] == '4') { $msg1 = formatReturn('4', 'The provided authentication already exists for this user.', $format, ''); return array(false, $msg1); exit; } elseif ($msg['error_code'] == '11') { $msg1 = formatReturn('7', 'Invalid authentication format. ' . $msg['message'], $format, ''); return array(false, $msg1); exit; } elseif ($msg['error_code'] == '4') { $msg1 = formatReturn($msg['error_code'], "Authentication already exists.", $format, ''); return array(false, $msg1); exit; } else { $msg1 = formatReturn($msg['error_code'], $msg['message'], $format, ''); return array(false, $msg1); exit; } } else { return array(false, $msg); } break; default: } //if($q_syntax['where']['authority_id']=='') #return ($user_proj); return true; } elseif ($action == 'select') { #if authentication is being asked for switch ($target) { case 'authentication': ##if user id is not indicated in the query, use self. S3DB will take care of permisison management if ($s3ql['where']['user_id'] != '') { $user2find = ereg_replace('^U', '', $s3ql['where']['user_id']); if (!$user_proj[$user2find]['I']) { $s3ql_new = compact('user_id', 'db'); $s3ql_new['from'] = 'statement'; $s3ql_new['where']['rule_id'] = $user_proj['user_id']['rule_id']; $s3ql_new['where']['value'] = $user2find; $done = S3QLaction($s3ql_new); if (is_array($done)) { $user_proj[$user2find]['I'] = $done[0]['item_id']; $user_proj[$user2find]['R' . $user_proj['user_id']['rule_id']] = $done[0]['statement_id']; } } if ($user_proj[$user2find]['I'] != '') { $s3ql_new = compact('user_id', 'db'); $s3ql_new['from'] = 'statements'; $s3ql_new['where']['item_id'] = $user_proj[$user2find]['I']; $s3ql_new['where']['rule_id'] = $user_proj['email']['rule_id']; $user_authentications[$user2find] = S3QLaction($s3ql_new); } else { $data = array(); } } else { $s3ql_new = compact('user_id', 'db'); $s3ql_new['from'] = 'statements'; $s3ql_new['where']['rule_id'] = $user_proj['user_id']['rule_id']; $users = S3QLaction($s3ql_new); foreach ($users as $user_info) { $s3ql_new = compact('user_id', 'db'); $s3ql_new['from'] = 'statements'; $s3ql_new['where']['item_id'] = $user_info['item_id']; $s3ql_new['where']['rule_id'] = $user_proj['email']['rule_id']; $tmp = S3QLaction($s3ql_new); $user_authentications[$user_info['value']] = $tmp; } } #to display data, choose the headers $headers = array('user_id', 'authentication_id', 'created_on'); if (is_array($user_authentications)) { foreach ($user_authentications as $user4auth => $auths) { if (!empty($auths)) { foreach ($auths as $auth_info) { $data[] = array('user_id' => $user4auth, 'authentication_id' => $auth_info['value'], 'created_on' => $auth_info['created_on']); } } } return array(true, $data, $headers); } else { $msg = formatReturn($GLOBALS['error_codes']['something_missing'], "No authentications were found matching your search criteria!", $_REQUEST['format'], ''); return array(false, $msg); } break; case 'authority': #what is the collection_id of the collection that holds autohorittier $s3qlnew = compact('user_id', 'db'); $s3qlnew['from'] = 'items'; $s3qlnew['where']['collection_id'] = $user_proj['authorities']['collection_id']; #ups, just noticed i called it authorities; hehe, i'll leave it :-) $authorities = S3QLaction($s3qlnew); if (is_array($authorities) && !empty($authorities)) { foreach ($authorities as $tmp) { $authority_data[$tmp['item_id']] = array(); } } if (is_array($authorities) && !empty($authorities)) { #now find, for item, for each rule of authorities, the values $headers2show[] = 'item_id'; foreach ($user_proj['authorities']['rules'] as $auth_attr) { $s3qlnew = compact('user_id', 'db'); $s3qlnew['from'] = 'statements'; $s3qlnew['where']['rule_id'] = $auth_attr; $data_values = S3QLaction($s3qlnew); #now reorganize them according to item_id if (is_array($data_values) && !empty($data_values)) { foreach ($data_values as $stat) { #we expect 1 value per rule per item, but in case there is more, this is the right time to do it :-) if (is_array($authority_data[$stat['item_id']])) { if (!is_array($authority_data[$stat['item_id']][$auth_attr])) { $authority_data[$stat['item_id']][$auth_attr] = array(); } array_push($authority_data[$stat['item_id']][$auth_attr], $stat); } #now stored header data if (!in_array($stat['object'], $headers2show)) { $headers2show[$stat['rule_id']] = $stat['object']; } } } } $ItemLine = array(); foreach ($authority_data as $item_id => $rule_values) { $extraItemLine = 0; $thisItemLine = array(); $thisItemLine['item_id'] = $item_id; #foreach ($rule_values as $rule_id=>$rule_value_stats) { foreach ($headers2show as $rule_id => $headerName) { $rule_value_stats = array(); if ($headerName != 'item_id') { if ($rule_values[$rule_id] != '') { $rule_value_stats = $rule_values[$rule_id]; } #every item will have a line. Except if the item has more than 1 statement per headers, in which case it will have as many as the number of stats if (count($rule_value_stats) > $extraItemLine) { $extraItemLine = count($rule_value_stats); } if ($extraItemLine <= 1) { $thisItemLine[$headers2show[$rule_id]] = $rule_value_stats[0]['value']; } else { #echo '<pre>';print_r($rule_value_stats); # } #$item_data_line[] = #array('item_id'=>$item_id, # $headers2show } } array_push($ItemLine, $thisItemLine); } $data = $ItemLine; #save it $user_proj['authorities']['local_data'] = $data; file_put_contents($GLOBALS['uploads'] . 'user_proj', serialize($user_proj)); #now it's time to trim the data according to user requests #now discover which authority is being requested $newData = array(); foreach ($data as $tuple) { if ($s3ql['where'] != '') { #match the where array keys with the data array keys $query = array_intersect(array_keys($s3ql['where']), array_keys($tuple)); foreach ($query as $query_attr) { #does it have regular expressions? $qval = ''; ereg('(\\~|\\!|\\i )(.*)', $s3ql['where'][$query_attr], $qval); if (!$qval) { #if no reg exp are specified, do a precise match if ($s3ql['where'][$query_attr] != $tuple[$query_attr]) { $tuple = array(); } } elseif ($qval[1] == '~') { if (!ereg($qval[2], $tuple[$query_attr])) { $tuple = array(); } } elseif ($qval[1] == 'i ') { if (!eregi($qval[2], $tuple[$query_attr])) { $tuple = array(); } } elseif ($qval[1] == '!') { #when what is asked for is different, clear if the are equal if ($qval[2] == $tuple[$query_attr]) { $tuple = array(); } } } } $newData[] = $tuple; #if(eregi('^'.$projAuthority['DisplayLabel'].'$',$authority)){ # $reqAuth = $projAuthority; # #} } $data = array_values(array_filter($newData)); #save it $user_proj['authoritities']['local_data'] = $data; file_put_contents($GLOBALS['uploads'] . 'user_proj', serialize($user_proj)); $headers = array_values($headers2show); #return (array(true, $data,$headers)); #exit; } #now for each of the items, find the statements associated and create the corresponding array break; case 'protocol': $s3qlnew = compact('user_id', 'db'); $s3qlnew['from'] = 'items'; $s3qlnew['where']['collection_id'] = $user_proj['protocols']['collection_id']; $done = S3QLaction($s3qlnew); $headers = array('item_id', 'label', 'created_on'); if (is_array($done)) { foreach ($done as $protocol) { $data[] = array('item_id' => $protocol['item_id'], 'label' => $protocol['notes'], 'created_on' => $protocol['created_on']); } #return (array(true,$data,$headers)); } break; default: echo "Funcionality not developed yet."; exit; } #now it's time to trim the data according to user requests #now discover which authority is being requested $newData = array(); foreach ($data as $tuple) { if ($s3ql['where'] != '') { #match the where array keys with the data array keys $query = array_intersect(array_keys($s3ql['where']), array_keys($tuple)); foreach ($query as $query_attr) { #does it have regular expressions? $qval = ''; ereg('(\\~|\\!|\\i )(.*)', $s3ql['where'][$query_attr], $qval); if (!$qval) { #if no reg exp are specified, do a precise match if ($s3ql['where'][$query_attr] != $tuple[$query_attr]) { $tuple = array(); } } elseif ($qval[1] == '~') { if (!ereg($qval[2], $tuple[$query_attr])) { $tuple = array(); } } elseif ($qval[1] == 'i ') { if (!eregi($qval[2], $tuple[$query_attr])) { $tuple = array(); } } elseif ($qval[1] == '!') { #when what is asked for is different, clear if the are equal if ($qval[2] == $tuple[$query_attr]) { $tuple = array(); } } } } $newData[] = $tuple; } $data = array_values(array_filter($newData)); if (is_array($data)) { return array(true, $data, $headers); } } elseif ($action == 'delete' || $action == 'update') { #only authentication_id is accepted as a parameter for deletion. if ($target == 'authentication') { if ($s3ql['where']['authentication_id'] == '') { $msg = formatReturn($GLOBALS['error_codes']['something_missing'], 'Please provide the value for <authentication_id> to be updated/deleted', $_REQUEST['format'], ''); return array(false, $msg); exit; } elseif ($action == 'update' && $s3ql['set']['authentication_id'] == '') { $msg = formatReturn($GLOBALS['error_codes']['something_missing'], 'Please provide the authentication_id to replace.', $_REQUEST['format'], ''); return array(false, $msg); exit; } else { #delete an authentication will delete a statement. Which statement_id are we looking for? $s3ql_new = compact('user_id', 'db'); $s3ql_new['from'] = 'statements'; $s3ql_new['where']['rule_id'] = $user_proj['email']['rule_id']; $s3ql_new['where']['value'] = $s3ql['where']['authentication_id']; $done = S3QLaction($s3ql_new); if (!$done[0]['statement_id']) { $msg = formatReturn($GLOBALS['error_codes']['something_missing'], 'Authentication ' . $s3ql['where']['authentication_id'] . ' was not found or user does not have permission to delete.', $_REQUEST['format'], ''); return array(false, $msg); exit; } else { #we will let s3db permission manageent take care of permission to delete $s3ql_new = compact('user_id', 'db'); $s3ql_new[$action] = 'statement'; $s3ql_new['where']['statement_id'] = $done[0]['statement_id']; if ($action == 'update') { $s3ql_new['set']['value'] = $s3ql['set']['authentication_id']; } $done = S3QLaction($s3ql_new); if ($done['error_code'] == '0') { return array(true, $done); } else { return array(false, $done); } } } } } }
<?php ini_set('display_errors', 0); if ($_REQUEST['su3d']) { ini_set('display_errors', 1); } $username = $_REQUEST['login']; #check if this username exists if (!reset_password($username)) { echo formatReturn($GLOBALS['error_codes']['something_missing'], "No email was found related to this user. Please ask an administrator of your database to replace your password.", $_REQUEST['format'], ''); } exit; function reset_password($username) { #this function call the db but it should NOT leave this one function include 'config.inc.php'; include_once S3DB_SERVER_ROOT . '/webActions.php'; require_once S3DB_SERVER_ROOT . '/s3dbcore/class.db.inc.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/common_functions.inc.php'; include_once S3DB_SERVER_ROOT . '/dbstruct.php'; require_once S3DB_SERVER_ROOT . '/pearlib/Net/SMTP.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/validation_engine.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/SQL.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/s3email.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/display.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/callback.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/S3QLRestWrapper.php'; //include_once(S3DB_SERVER_ROOT.'/s3dbcore/find_acl.php'); include_once S3DB_SERVER_ROOT . '/s3dbcore/URIaction.php'; include_once S3DB_SERVER_ROOT . '/s3dbcore/S3QLaction.php'; $db = CreateObject('s3dbapi.db');
function validate_authentication($s3ql, $user_id, $db) { $format = $s3ql['format'] != '' ? $s3ql['format'] : 'html'; #user must already exist before a new authentication can be created for him $user2update = ereg_replace('^U', '', $s3ql['where']['user_id']); $sql = "select * from s3db_account where account_id ='" . $user2update . "'"; $db->query($sql); if (!$db->next_record() && $s3ql['insert'] != '') { $msg = formatReturn($GLOBALS['error_codes']['something_missing'], 'User ' . $user2update . ' does not exist.', $format, ''); return array(false, $msg); exit; } #autentication must not exist already for any other user. This is a task for the Admin $user_proj = file_get_contents($GLOBALS['uploads'] . '/userManage.s3db'); $user_proj = unserialize($user_proj); $sql = "select * from s3db_statement where rule_id = '" . $user_proj['email']['rule_id'] . "' and value ='" . $s3ql['where']['authentication_id'] . "'"; #echo $sql;exit; $db->query($sql); if ($db->next_record() && $s3ql['insert'] != '') { $msg = formatReturn($GLOBALS['error_codes']['something_missing'], 'Authentication ' . $s3ql['where']['authentication_id'] . ' already exists.', $format, ''); return array(false, $msg); exit; } #authentication must not also exist as a remote user id $sql = "select * from s3db_account where account_id ='" . $s3ql['where']['authentication_id'] . "'"; #echo $sql;exit; $db->query($sql); if ($db->next_record() && $s3ql['insert'] != '') { $msg = formatReturn($GLOBALS['error_codes']['something_missing'], 'Authentication ' . $s3ql['where']['authentication_id'] . ' already exists.', $format, ''); return array(false, $msg); exit; } return array(true); }
xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:vcard="http://www.w3.org/2001/vcard-rdf/3.0#" xmlns:ns1="http://s3db.org/"> </rdf:RDF>'; file_put_contents(S3DB_SERVER_ROOT . '/s3dbupdates.rdf', $emptyRDF); } if (!is_file(S3DB_SERVER_ROOT . '/s3dbupdates.rdf')) { return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], "Apache was unable to write to S3DB directory. Please make sure all files under " . S3DB_SERVER_ROOT . " have write permission.", ''); exit; } $updates = findUpdates(S3DB_SERVER_ROOT . '/s3dbupdates.rdf', $remoteFile); #echo '<pre>';print_r($updates);exit; } else { return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], "Mothership update file could not be read. Please try again later.", $_REQUEST['format'], ''); exit; } ### #Follow the link provided by the mothership, stored as value and place it under the correct path, stored as key if (is_array($updates)) { $paths = array_keys($updates); $uris = array_values($updates); for ($i = 0; $i < count($updates); $i++) { $fid = fopen($uris[$i], "r"); $filedata = stream_get_contents($fid); $oldFile = S3DB_SERVER_ROOT . '/' . $paths[$i]; $bak = S3DB_SERVER_ROOT . '/' . $paths[$i] . date('dmY', time()); ### #Make a copy of the old file, if exists $c = copy($oldFile, $bak);
function registerURL($U) { #this function call the db but it should NOT leave this one function extract($U); include_once 'config.inc.php'; $key = $GLOBALS['deployment_project']['key']; include 'core.header.php'; #include (S3DB_SERVER_ROOT.'/webActions.php'); #require_once(S3DB_SERVER_ROOT.'/s3dbcore/class.db.inc.php'); #include_once(S3DB_SERVER_ROOT.'/s3dbcore/common_functions.inc.php'); #include_once(S3DB_SERVER_ROOT.'/s3dbcore/callback.php'); #Generate Did, and, since we're on it, name if empty if (!$Did && $case == 'registernewURL') { $Did = s3id(); } if (!$name && $case == 'registernewURL') { $name = 'D' . $Did; $U['name'] = $name; } $db = CreateObject('s3dbapi.db'); $db->Halt_On_Error = 'no'; $db->Host = $GLOBALS['s3db_info']['server']['db']['db_host']; $db->Type = $GLOBALS['s3db_info']['server']['db']['db_type']; $db->Database = $GLOBALS['s3db_info']['server']['db']['db_name']; $db->User = $GLOBALS['s3db_info']['server']['db']['db_user']; $db->Password = $GLOBALS['s3db_info']['server']['db']['db_pass']; $db->connect(); $U['db'] = $db; list($inputValid, $errMessage) = validate_register_inputs($U); if ($inputValid) { switch ($case) { case 'registernewURL': $protocol = $_SERVER['HTTPS'] != '' ? 'https://' : 'http://'; $url = ereg('localhost', $url) ? $protocol . getClientIP() . str_replace($protocol . 'localhost', '', $url) : $url; #echo $sql;exit; #echo $s3rl;exit; if ($Did != '') { $sql = "select * from s3db_deployment where deployment_id = '" . $Did . "'"; $db->query($sql, __LINE__, __FILE__); if ($db->next_record()) { return array(False, 'Did already exists. Please provide another one or leave that field blank for an arbitrary value'); } } #if($Did!=''){ $sql = "insert into s3db_deployment (deployment_id, url, publickey, message, created_on) values ('" . $Did . "', '" . $url . "', '" . $publicKey . "', '" . random_string(20) . "', now())"; #echo $sql; $db->query($sql, __LINE__, __FILE__); $s3rl = $Did; #} #else{ #include('s3id.php'); #$sql = "insert into s3db_deployment (deployment_id, url, publickey, message, created_on) values ('".$Did."', '".$url."', '".$publicKey."', '".random_string(20)."', now())"; #echo $sql;exit; #$db->query($sql, __LINE__, __FILE__); if ($db->Errno == 0) { ##Now create an entry in the project of deployemnts; #create a remote user to access this entry $s3ql = compact('user_id', 'db'); $s3ql['insert'] = 'user'; $s3ql['where']['user_id'] = $url . (substr($url, strlen($url) - 1, 1) == '/' ? '' : '/') . 'U1'; $s3ql['where']['permission_level'] = '111'; $s3ql['format'] = 'php'; $done = unserialize(S3QLaction($s3ql)); //$msg=html2cell($done); $msg = $done[0]; if (ereg('^(4|9|0)$', $msg['error_code'])) { $remoteUser = $s3ql['where']['user_id']; $user_id = '1'; $s3ql = compact('user_id', 'db'); $s3ql['insert'] = 'item'; $s3ql['where']['collection_id'] = $GLOBALS['deployment_project']['collection_id']; $s3ql['where']['item_id'] = $Did; $s3ql['where']['notes'] = $name == '' ? urlencode('Deployment ' . $Did) : $name; $s3ql['format'] = 'php'; $done = unserialize(S3QLaction($s3ql)); $msg = $done[0]; if ($msg['error_code'] == '0' || $msg['error_code'] == '4') { $s3ql = compact('user_id', 'db'); $s3ql['insert'] = 'user'; $s3ql['where']['item_id'] = $msg['item_id']; $s3ql['where']['user_id'] = $remoteUser; $s3ql['where']['permission_level'] = '222'; $done = S3QLaction($s3ql); $item_id = $msg['item_id']; $msg = html2cell($done); $msg = $msg[2]; #find the collectiont rules $s3ql = compact('user_id', 'db'); $s3ql['from'] = 'rules'; $s3ql['where']['subject_id'] = $GLOBALS['deployment_project']['collection_id']; $rules = S3QLaction($s3ql); if (!empty($rules)) { $s3ql = compact('user_id', 'db'); $s3ql['insert'] = 'statement'; $s3ql['where']['item_id'] = $item_id; foreach ($rules as $key => $rule_info) { if (in_array($rule_info['object'], array_keys($_GET))) { $s3ql['where']['rule_id'] = $rule_info['rule_id']; if ($rule_info['object'] == 'keywords') { $keywords = explode(',', $_GET['keywords']); foreach ($keywords as $word) { if (is_base64_encoded($word)) { $word = base64_decode($word); } $s3ql['where']['value'] = $word; $done = S3QLaction($s3ql); } } elseif ($rule_info['object'] == 'url') { $s3ql['where']['value'] = $url; $done = S3QLaction($s3ql); } elseif ($rule_info['object'] == 'description') { $v = $_GET[$rule_info['object']]; if (is_base64_encoded($v)) { $v = base64_decode($v); } $s3ql['where']['value'] = $v; $done = S3QLaction($s3ql); } elseif ($rule_info['object'] == 'name') { $s3ql['where']['value'] = $name; $done = S3QLaction($s3ql); } else { $v = $_GET[$rule_info['object']]; $s3ql['where']['value'] = $v; $done = S3QLaction($s3ql); } } } } } } } #After registering url, return Did if ($Did != '') { return array(True, array('deployment_id' => $Did, 'name' => $name)); } else { return array(False, ''); } break; case 'findURL': ##Let's first check if there is already a deployment in this URL if ($url != '') { $sql = "select * from s3db_deployment where url = '" . $url . "'"; $db->query($sql, __LINE__, __FILE__); if ($db->next_record()) { $reg = array('deployment_id' => $db->f('deployment_id'), 'url' => $db->f('url'), 'modified_on' => $db->f('modified_on')); return array(True, $reg); } } elseif ($Did != '') { $sql = "select * from s3db_deployment where deployment_id = '" . str_replace('D', '', $Did) . "'"; $db->query($sql, __LINE__, __FILE__); if ($db->next_record()) { $reg = array('url' => $db->f('url'), 'publicKey' => $db->f('publickey'), 'modified_on' => $db->f('modified_on')); return array(True, $reg); } else { return array(False, 'Did not found'); } } break; case 'updateURL': #did the user send the decripted message already? Validate and change the message if ($message != '') { $sql = "select * from s3db_deployment where deployment_id = '" . str_replace('D', '', $Did) . "'"; $db->query($sql, __LINE__, __FILE__); if ($db->next_record()) { $oldUrl = $db->f('url'); $storedMessage = $db->f('message'); #do messages match? if ($storedMessage != $message) { #$sql = "update s3db_register set message= '".random_string(20)."' where deployment_id = '".str_replace('D', '', $Did)."'"; return array(False, 'Error code:<error>3</error><description> Decripted Message does not match the request</description>'); } else { #echo 'ahaa, you found it :-)'; #update key $sql = "update s3db_deployment set url = '" . $newUrl . "', message= '" . random_string(20) . "', modified_on = now() where deployment_id = '" . str_replace('D', '', $Did) . "'"; $db->query($sql, __LINE__, __FILE__); ##Now update the entry on s3db $sql = "update s3db_statement set url='" . $newUrl . "' where rule_id='' and item_id=''"; $dbdata = get_object_vars($db); if ($dbdata['Errno'] == '0') { return array(True, 'Error code:<error>0</error><description> URL updated</description>'); } else { return array(False, 'Error code:<error>1</error><description> Could not update URL</description>'); } } } else { return array(False, 'Error code:<error>2</error> Could not find Did'); } } else { #send a message to the url to make sure he is who he says he is $sql = "select * from s3db_deployment where deployment_id = '" . ereg_replace('^D', '', $Did) . "'"; $db->query($sql); if ($db->next_record()) { $publicKey = $db->f('publickey'); $message = $db->f('message'); } else { return array(False, 'Could not find URL'); } #encript it require_once 'pearlib/RSACrypt/RSA.php'; $encripted = encrypt($message, $publicKey); if ($encripted == '') { $encripted = encrypt($message, urlencode($publicKey)); } $ErrMessage = "For authentication, please decript this message using your private key: <message>" . rawurlencode($encripted) . "</message><br />(Note: you might need to remove url encoding that your browser might have added before decoding. Plase refer to http://www.asciitable.com/ for the correct characters.)"; echo formatReturn($GLOBALS['error_codes']['success'], $ErrMessage, $format, array('encripted' => $encripted)); exit; #echo "For authentication, please decript this message using your private key: <message>".rawurlencode($encripted)."</message>"; #echo "<br />(Note: you might need to remove url encoding that your browser might have added before decoding. Plase refer to http://www.asciitable.com/ for the correct characters.)"; # exit; } } } else { echo formatReturn($GLOBALS['error_codes']['wrong_input'], $errMessage, $format, ''); } }