コード例 #1
0
ファイル: item.php プロジェクト: helenadeus/s3db.map
function render_statements($I)
{
    $action = $GLOBALS['action'];
    #all the possible links were separated ina script that gets always included
    extract($I);
    $_SESSION['current_color'] = '0';
    $_SESSION['previous_verb'] = '';
    #display all the rules in this class where the user has permission
    $s3ql = compact('user_id', 'db');
    $s3ql['select'] = '*';
    $s3ql['from'] = 'statements';
    $s3ql['where']['instance_id'] = $instance_info['instance_id'];
    $statements = S3QLaction($s3ql);
    #echo '<pre>';print_r($statements);exit;
    #divide them by rules
    if (is_array($statements)) {
        foreach ($statements as $stat_info) {
            $stats_per_rule[$stat_info['rule_id']][$stat_info['statement_id']] = $stat_info;
        }
        if (is_array($rules)) {
            $rule_ids = array_map('grab_rule_id', $rules);
            $tRules = array_combine($rule_ids, $rules);
        }
        #echo '<pre>';print_r($stats_per_rule);exit;
        if (is_array($stats_per_rule) && is_array($tRules)) {
            $stats = '';
            $index = 1;
            foreach ($stats_per_rule as $rule_id => $exist_stats) {
                if ($tRules[$rule_id]['object'] != 'UID' && $tRules[$rule_id]['verb'] != 'has UID') {
                    $subject = $tRules[$rule_id]['subject'];
                    $verb = $tRules[$rule_id]['verb'];
                    $object = $tRules[$rule_id]['object'];
                    $rule_id = $tRules[$rule_id]['rule_id'];
                    #$rule_notes = preg_replace('/\(.*\)/', '', $rules[$i]['notes']);
                    $rule_notes = $tRules[$rule_id]['notes'];
                    $stats .= sprintf("\n%s\n", '<table width="100%" border="0"><tr bgcolor="lightyellow"><td colspan="2">');
                    $stats .= sprintf("%s\n", $index++ . '. ' . printVerbinColor($verb) . ' | <font size=4><b>' . $object . '</b></font> (R' . $rule_id . ') </td></tr><tr><td>&nbsp;&nbsp;<font size-=2>' . $rule_notes . '</font></td><td align="right">');
                    if ($tRules[$rule_id]['add_data']) {
                        $stats .= sprintf("%s\n", '<input type="button" value="Add"  onClick="window.open(\'' . $action['insertstatement'] . '&rule_id=' . $rule_id . '\', \'_blank\', \'width=600, height=500, location=no, titlebar=no, scrollbars=yes, resizable=yes\')">');
                    }
                    $stats .= sprintf("%s\n", '	</td></tr>');
                    $stat = '';
                    $stat .= sprintf("%s\n", '	<tr><td colspan="2" style="color: navy; font-size: normal">');
                    if (is_array($exist_stats)) {
                        $stat .= render_substatements_without_grid($exist_stats, $db);
                    }
                    //$stat .= render_substatements($exist_stats, 'value', 'DESC');
                    $stat .= sprintf("%s\n", '	</td></tr>');
                    $stats .= $stat;
                    $stats .= sprintf("%s\n", '     <tr><td colspan="2"><br>');
                    $stats .= sprintf("%s\n", '     </td></tr>');
                    $stats .= sprintf("%s\n", '</table>');
                }
            }
        }
    }
    return $stats;
}
コード例 #2
0
ファイル: create.php プロジェクト: helenadeus/s3db.map
function create_resource($R)
{
    extract($R);
    if ($resource_info['iid'] == '') {
        $resource_info['iid'] = '1';
    }
    $R['resource_info']['resource_id'] = find_latest_UID('resource', $db) + 1;
    $resource_id_created = insert_resource($R);
    if ($resource_id_created) {
        $resource_id = find_latest_UID('resource', $db);
        $resource_info['resource_id'] = $resource_id;
        if ($resource_info['iid'] == '0') {
            #INSERT LINE ON RULES TABLE
            $rule_info = array('project_id' => $resource_info['project_id'], 'owner' => $user_id, 'subject' => $resource_info['entity'], 'subject_id' => $resource_info['resource_id'], 'verb' => 'has UID', 'object' => 'UID', 'notes' => nl2br($resource_info['notes']));
            $db->query($sql, __LINE__, __FILE__);
            $R['rule_info'] = $rule_info;
            $rule_inserted = insert_rule($R);
            if ($rule_inserted) {
                $rule_info['rule_id'] = find_latest_UID('rule', $db);
                $inputs = array('newsubject' => $resource_info['entity'], 'newverb' => 'has UID', 'newobject' => 'UID', 'newnotes' => nl2br($resource_info['notes']));
                $action = 'create';
                $log = compact('action', 'rule_info', 'user_id', 'project_id', 'db', 'inputs');
                insert_rule_log($log);
            }
            #now check if there is any rule in the same project that already has this class as object.
            $s3ql = compact('user_id', 'db');
            $s3ql['from'] = 'rules';
            $s3ql['where']['object'] = $resource_info['entity'];
            $s3ql['where']['project_id'] = $resource_info['project_id'];
            $object_rules = S3QLaction($s3ql);
            if (is_array($object_rules)) {
                foreach ($object_rules as $key => $rule_to_change) {
                    $s3ql = compact('user_id', 'db');
                    $s3ql['edit'] = 'rule';
                    $s3ql['where']['rule_id'] = $rule_to_change['rule_id'];
                    $s3ql['set']['object_id'] = $resource_id;
                    $done = S3QLaction($s3ql);
                }
            }
        } else {
            $statement_info = array('project_id' => $resource_info['project_id'], 'resource_id' => $resource_id, 'rule_id' => get_rule_id_by_entity_id($resource_info['resource_class_id'], $resource_info['project_id'], $db), 'value' => $resource_id, 'notes' => $resource_info['notes'], 'created_by' => $resource_info['owner'], 'db' => $db);
            $R['statement_info'] = $statement_info;
            insert_statement($R);
        }
        return $resource_id;
    }
}
コード例 #3
0
ファイル: xmlimport.php プロジェクト: helenadeus/s3db.map
         #echo '<pre>';print_r($rule);
         if (urldecode($rule['OBJECT']) != 'UID') {
             $s3ql['insert'] = 'rule';
             $s3ql['where'] = '';
             $s3ql['where']['project_id'] = $project_id;
             $s3ql['where']['subject_id'] = $class_id;
             $s3ql['where']['verb'] = urldecode($rule['VERB']);
             if ($classes[urldecode($rule['OBJECT'])] != '') {
                 #was there a class created with this object name?
                 $s3ql['where']['object_id'] = $classes[$rule['OBJECT']]['class_id'];
             } else {
                 $s3ql['where']['object'] = urldecode($rule['OBJECT']);
             }
             $s3ql['where']['notes'] = urldecode($rule['NOTES']);
             $s3ql['format'] = 'html';
             $ruleInserted = S3QLaction($s3ql);
             $msg = html2cell($ruleInserted);
             $msg = $msg[2];
             #echo $ruleInserted;
             #ereg('<error>([0-9]+)</error>(.*)<(rule_id|message)>(.*)</(rule_id|message)>', $ruleInserted, $s3qloutRule);
             if ($msg['error_code'] == '0') {
                 $rule_id = $msg['rule_id'];
                 $report .= '<tr><td><font color = "#00CC33">Rule ' . $rule['SUBJECT'] . ' ' . $rule['VERB'] . ' ' . $rule['OBJECT'] . ' created</font></td></tr>';
             } else {
                 echo urldecode($rule['OBJECT']) != 'UID';
                 #echo '<pre>';print_r($rule);
                 $report .= '<tr><td><font color = "red">Rule ' . $rule['SUBJECT'] . ' ' . $rule['VERB'] . ' ' . $rule['OBJECT'] . ' was NOT created. Reason: ' . $msg['message'] . '</font></td></tr>';
             }
         }
     }
 }
コード例 #4
0
ファイル: read.php プロジェクト: helenadeus/s3db.map
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'];
} else {
    $statement_info = $data[0];
    pushDownload2Header(compact('statement_info', 'db', 'user_id', 'format'));
}
コード例 #5
0
ファイル: createuser.php プロジェクト: helenadeus/s3db.map
$account_status = 'Active';
$account_type = 'User';
$checked = 'checked';
$loginid_required = '*';
$uname_required = '*';
$password_required = '*';
$password2_required = '*';
$default_message = '* required';
$email_warn = '*';
#list all the groups where this user can make changes
$s3ql = compact('user_id', 'db');
$s3ql['select'] = '*';
$s3ql['from'] = 'groups';
#$s3ql['where']['user_id']=$user_id;
#echo '<pre>';print_r($s3ql);
$groups = S3QLaction($s3ql);
#echo '<pre>';print_r($groups);
#make a select list
//	if ($user_id=='1') {
//		$group_select_list .= '<option value="1">Admin</option>';
//	}
if (is_array($groups)) {
    foreach ($groups as $group_info) {
        if ($group_info['account_id'] == '3') {
            $selected = " selected";
        } else {
            $selected = "";
        }
        $group_select_list .= '<option value="' . $group_info['account_id'] . '" ' . $selected . '>' . $group_info['account_lid'] . '</option>';
    }
}
コード例 #6
0
ファイル: deleteuser.php プロジェクト: helenadeus/s3db.map
if ($_POST['deleteuser']) {
    #and make the user inactive
    $s3ql = compact('user_id', 'db');
    if ($_POST['deleteuser'] == 'Remove from Deployment') {
        $s3ql['delete'] = 'user';
        $s3ql['where']['user_id'] = $imp_user_id;
        $s3ql['flag'] = 'resource';
    } elseif ($_POST['deleteuser'] == 'Deactivate Account') {
        $s3ql['update'] = 'user';
        $s3ql['where']['user_id'] = $imp_user_id;
        $s3ql['where']['account_status'] = 'I';
        #$s3ql['where']['permission_level']='000';
    }
    $s3ql['format'] = 'html';
    #echo '<pre>';print_r($s3ql);exit;
    $deleted = S3QLaction($s3ql);
    $deleted = html2cell($deleted);
    #echo $deleted;
    #exit;
    if ($deleted[2]['error_code'] == '0') {
        Header('Location: ' . $action['listusers']);
        exit;
    } else {
        ereg('<message>(.*)</message>', $deleted, $s3qlouput);
        $message = $s3qlouput[0];
    }
}
include '../S3DBjavascript.php';
include '../tabs.php';
#echo '<pre>';print_r($users);exit;
#$user_list=create_user_list($users);
コード例 #7
0
ファイル: allprojects.php プロジェクト: helenadeus/s3db.map
$sortorder = $_REQUEST['orderBy'];
$direction = $_REQUEST['direction'];
$project_id = $_REQUEST['project_id'];
#$acl = find_final_acl($user_id, $project_id, $db);
$uni = compact('db', 'acl', 'user_id', 'key', 'project_id', 'dbstruct');
#relevant extra arguments
$args = '?key=' . $_REQUEST['key'];
include '../webActions.php';
#include the specification of the link map. Must be put in here becuase arguments vary.
#Find all the projects for this user
$s3ql = compact('user_id', 'db');
$s3ql['from'] = 'projects';
if ($sortorder != '') {
    $s3ql['order_by'] = $sortorder . ' ' . $direction;
}
$projects = S3QLaction($s3ql);
$_SESSION[$user_id]['projects'] = $projects;
#this is the directory where upload of xml or n3 will go before i start using it for building projects
#$totaldirname = S3DB_SERVER_ROOT.$GLOBALS['s3db_info']['server']['db']['uploads_file'].'/schemas';
$totaldirname = $GLOBALS['s3db_info']['server']['db']['uploads_folder'] . $GLOBALS['s3db_info']['server']['db']['uploads_file'] . '/tmps3db';
if ($_POST['submitschema']) {
    if (!file_exists($totaldirname)) {
        mkdir($totaldirname, 0777);
    }
    $indexfile = $totaldirname . '/index.php';
    if (file_exists($totaldirname)) {
        file_put_contents($indexfile, 'This folder cannot be accessed');
    }
    $uploadfile = $totaldirname . '/xmlschema.s3db';
    list($filename, $extension) = explode(".", $_FILES['schema']['name']);
    #read the first 100 lines or so and chech if it is XML
コード例 #8
0
ファイル: mapproject.php プロジェクト: helenadeus/s3db.map
function create_nodes($O)
{
    $action = $GLOBALS['action'];
    extract($O);
    $project_info = s3info('project', $project_id, $db);
    $project_node .= sprintf("\t\t%s\n", '<NODE nodeID="P' . $project_info['project_id'] . '">');
    $project_node .= sprintf("\t\t\t%s\n", '<NODE_LOCATION x="0" y="0" visible="true"/>');
    $project_node .= sprintf("\t\t\t%s\n", '<NODE_HINT hint="' . str_replace("\"", "", htmlentities($project_info['project_description'])) . '" width="300" height="-1" isHTML="false"/>');
    $project_node .= sprintf("\t\t\t%s\n", '<NODE_LABEL label="' . $project_info['project_name'] . '" shape="3" backColor="0000FF" textColor="FFFF00" fontSize="12"/>');
    $project_node .= sprintf("\t\t\t%s\n", '<NODE_URL url="' . htmlentities($action['project']) . '" urlIsLocal="true" urlIsXML="false"/>');
    #$project_node.= sprintf("\t\t\t%s\n",'<NODE_URL url="../project/project.php?project_id='.$_REQUEST['project_id'].'" urlIsLocal="true" urlIsXML="false"/>');
    $project_node .= sprintf("\t\t%s\n", '</NODE>');
    $s3ql['db'] = $db;
    $s3ql['user_id'] = $user_id;
    $s3ql['select'] = '*';
    $s3ql['from'] = 'rules';
    $s3ql['where']['project_id'] = $_REQUEST['project_id'];
    $s3ql['where']['object'] = "!=UID";
    #$rules = s3list($s3ql);
    $rules = S3QLaction($s3ql);
    $GLOBALS['rules'] = $rules;
    #Create the node for the regular resources
    #List all classes in project
    $s3ql = compact('user_id', 'db');
    $s3ql['select'] = '*';
    $s3ql['from'] = 'classes';
    $s3ql['where']['project_id'] = $_REQUEST['project_id'];
    #$resources = s3list($s3ql);
    $resources = S3QLaction($s3ql);
    $GLOBALS['collections'] = $resources;
    if (is_array($resources)) {
        $C = grab_id('collection', $resources);
        #=>these are the ids of all allowed nodes
        foreach ($resources as $resource_info) {
            //Lena -created this session because map doesn't allow more than 1 get, but for queryresource to run properly we need at least 2 get's
            $rule_id = get_rule_id_by_entity_id($resource_info['resource_id'], $resource_info['project_id'], $db);
            $subject = str_replace($toReplace, $replace, htmlentities($resource_info['entity']));
            $notes = str_replace($toReplace, $replace, htmlentities($resource_info['notes']));
            if ($resource_info['project_id'] == $_REQUEST['project_id']) {
                $color = 'FF0000';
            } else {
                $color = 'FF6600';
            }
            $resource_id = $resource_info['resource_id'];
            $subject_node .= sprintf("\t\t%s\n", '<NODE nodeID="C' . $resource_id . '">');
            $subject_node .= sprintf("\t\t\t%s\n", '<NODE_LOCATION x="0" y="0" visible="false"/>');
            $subject_node .= sprintf("\t\t\t%s\n", '<NODE_HINT hint="' . $notes . '" width="300" height="-1" isHTML="true"/>');
            $subject_node .= sprintf("\t\t\t%s\n", '<NODE_LABEL label="' . $subject . '" shape="2" backColor="' . $color . '" textColor="FFFFFF" fontSize="14"/>');
            $subject_node .= sprintf("\t\t\t%s\n", '<NODE_URL url="' . htmlentities($action['resource']) . '&amp;class_id=' . $resource_info['resource_id'] . '" urlIsLocal="true" urlIsXML="false"/>');
            $subject_node .= sprintf("\t\t%s\n", '</NODE>');
        }
        #and finally... the nodes for the objects...
        if (is_array($rules)) {
            #foreach($objects as $object)
            foreach ($rules as $rule_info) {
                $subject = str_replace($toReplace, $replace, htmlentities($rule_info['subject']));
                $verb = str_replace($toReplace, $replace, htmlentities($rule_info['verb']));
                $object = str_replace($toReplace, $replace, htmlentities($rule_info['object']));
                $notes = str_replace($toReplace, $replace, htmlentities($rule_info['notes']));
                #is the rule from this project? if not, print a different color
                if ($rule_info['project_id'] == $_REQUEST['project_id']) {
                    $objcolor = '336600';
                    $classColor = 'FF0000';
                } else {
                    $objcolor = '009900';
                    $classColor = 'FF6600';
                }
                if ($rule_info['object'] != 'UID' || $rule_info['verb'] != 'has UID') {
                    $object_node .= sprintf("\t\t%s\n", '<NODE nodeID="R' . $rule_info['rule_id'] . '">');
                    $object_node .= sprintf("\t\t\t%s\n", '<NODE_LOCATION x="0" y="0" visible="false"/>');
                    if ($rule_info['object_id'] == '') {
                        $object_node .= sprintf("\t\t\t%s\n", '<NODE_LABEL label="' . $object . '" shape="1" backColor="' . $objcolor . '" textColor="FFFF00" fontSize="12"/>');
                        $object_node .= sprintf("\t\t\t%s\n", '<NODE_URL url="' . htmlentities($action['rule']) . '&amp;class_id=' . $rule_info['subject_id'] . '&amp;rule_id=' . $rule_info['rule_id'] . '" urlIsLocal="true" urlIsXML="false"/>');
                        $object_node .= sprintf("\t\t\t%s\n", '<NODE_HINT hint="' . $notes . '" width="300" height="-1" isHTML="false"/>');
                    } elseif (in_array($rule_info['object_id'], $C)) {
                        ##Collection must either exist already as a visible node or the map will crash
                        $object_node .= sprintf("\t\t\t%s\n", '<NODE_LABEL label="' . $object . '" shape="1" backColor="' . $classColor . '" textColor="FFFFFF" fontSize="12"/>');
                        $object_node .= sprintf("\t\t\t%s\n", '<NODE_URL url="' . htmlentities($action['resource']) . '&amp;class_id=' . $rule_info['object_id'] . '" urlIsLocal="true" urlIsXML="false"/>');
                        $object_node .= sprintf("\t\t\t%s\n", '<NODE_HINT hint="' . $notes . '" width="300" height="-1" isHTML="false"/>');
                    } else {
                        $object_node .= sprintf("\t\t\t%s\n", '<NODE_LABEL label="' . $object . '" shape="1" backColor="#EFEFEF" textColor="FFFF00" fontSize="12"/>');
                        $object_node .= sprintf("\t\t\t%s\n", '<NODE_HINT hint="User is not allowed in this Collection" width="300" height="-1" isHTML="false"/>');
                    }
                    $object_node .= sprintf("\t\t%s\n", '</NODE>');
                }
            }
        }
        #find all projects involved in the rules of this project
        #find out how many project_ids there are
        if (is_array($rules)) {
            $extraproject_ids = array_map('grab_project_id', $rules);
            $extraproject_ids = array_diff(array_unique($extraproject_ids), array($_REQUEST['project_id']));
            #echo '<pre>';print_r($extraproject_ids);
            #Create extra projects nodes
            if (is_array($extraproject_ids)) {
                foreach ($extraproject_ids as $extra_project_id) {
                    $project_info = get_info('project', $extra_project_id, $db);
                    $extra_project_node .= sprintf("\t\t%s\n", '<NODE nodeID="P' . $extra_project_id . '">');
                    $extra_project_node .= sprintf("\t\t\t%s\n", '<NODE_LOCATION x="1" y="1" visible="true"/>');
                    $extra_project_node .= sprintf("\t\t\t%s\n", '<NODE_HINT hint="' . str_replace("\"", "", $project_info['project_description']) . '" width="300" height="-1" isHTML="false"/>');
                    $extra_project_node .= sprintf("\t\t\t%s\n", '<NODE_LABEL label="' . $project_info['project_name'] . '" shape="3" backColor="406AFD" textColor="FFFF00" fontSize="12"/>');
                    #$extra_project_node .= sprintf("\t\t\t%s\n", '<NODE_URL url="'.$action['project'].'" urlIsLocal="true" urlIsXML="false"/>');
                    #$project_node.= sprintf("\t\t\t%s\n",'<NODE_URL url="../project/project.php?project_id='.$_REQUEST['project_id'].'" urlIsLocal="true" urlIsXML="false"/>');
                    $extra_project_node .= sprintf("\t\t%s\n", '</NODE>');
                }
            }
        }
        return $project_node . $extra_project_node . $subject_node . $object_node;
    }
}
コード例 #9
0
ファイル: tuplesView.php プロジェクト: helenadeus/s3db.map
     } else {
         $s3ql = compact('db', 'user_id');
         $s3ql['select'] = '*';
         $s3ql['from'] = 'items';
         $s3ql['where']['collection_id'] = $class_id;
         #$s3ql['where']['project_id'] = $project_id;
         $instances = S3QLaction($s3ql);
     }
     #echo '<pre>';print_r($instances);
     #For finding all the rules that this resource involves, change S a little bit
     $s3ql = compact('db', 'user_id');
     $s3ql['select'] = '*';
     $s3ql['from'] = 'rules';
     $s3ql['where']['subject_id'] = $class_id;
     $s3ql['where']['object'] = "!='UID'";
     $rules = S3QLaction($s3ql);
     #$rules = include_all_class_id(compact('rules', 'project_id', 'db'));
 } else {
     #Building the query
     $ruleScope = array();
     foreach ($inputs as $key => $value) {
         $ruleScope[ereg_replace('^R', '', $key)] = stripslashes($value);
     }
     $q = array('rules' => array_keys($ruleScope), 'logical' => array_fill(0, count($inputs), 'and'), 'RuleValuePair' => $ruleScope, 'db' => $db);
     $instances = query_statements($q);
 }
 ##Find the values that are to be sent to datamatrix.php, both header and data
 if (is_array($rules) && !empty($rules)) {
     $verbs = array_map('grab_verb', $rules);
     foreach ($verbs as $i => $value) {
         $objects = array_map('grab_object', $rules, $verbs);
コード例 #10
0
ファイル: access_keys.php プロジェクト: helenadeus/s3db.map
#	$create_key_line .= '<option value="'.$s3.'">'.$s3.'</option>';
#}
$create_key_line .= '</select></td>';
#$create_key_line .= '<td  width="10%"><input type="text" name="ID"></td>';
$create_key_line .= '<td  width="10%"><input type ="submit" name="Submit_key" value="New Key"></td></tr>';
include S3DB_SERVER_ROOT . '/s3style.php';
include S3DB_SERVER_ROOT . '/tabs.php';
#Find existing keys
$s3ql = compact('user_id', 'db');
$s3ql['select'] = '*';
$s3ql['from'] = 'keys';
if ($_REQUEST['orderBy'] != '') {
    $s3ql['order_by'] = $_REQUEST['orderBy'] . ' ' . $_REQUEST['direction'];
}
#echo '<pre>';print_r($s3ql);
$user_keys = S3QLaction($s3ql);
#echo '<pre>';print_r($user_keys);exit;
#Create the table with exsiting keys
#Parse to the template
$add_key_form = $create_key_line;
if (is_array($user_keys) && !empty($user_keys)) {
    $existing_keys_header = "<tr bgcolor='#80BBFF'><td colspan='9' align='center'>Existing Keys</td></b></tr><td><BR></td>";
    $columns = array('Key', 'Requested By', 'Expires', 'Notes', 'Actions');
    #echo '<pre>';print_r($user_keys);
    $user_keys = replace_created_by($user_keys, $db);
    $keys_table = render_elements($user_keys, $acl, $columns, 'access_keys');
}
?>
<table class="contents">
	<table class="top" align="center">
	<tr><td>
コード例 #11
0
ファイル: rdfWrite.php プロジェクト: helenadeus/s3db.map
function readWriteExtInput($element, $info, $s3ql_in)
{
    extract($s3ql_in);
    #$idReplacements=($GLOBALS['idReplacements']=='')?array():$GLOBALS['idReplacements'];
    //if($info[$element.'_id']=="") { $info[$element.'_id'] = s3id(); }
    #echo $element.$info[$element.'_id'].chr(13).chr(10).'<br />';
    if ($info[$element . '_id'] != '' && $info['object'] != 'UID') {
        $s3ql = $s3ql_in;
        $s3ql['insert'] = $element;
        if ($element == 'item' && $info['notes'] == '') {
            ##insert something for ntoes, otherwise, rdf import will not create a new item
            $info['notes'] = " ";
        }
        #echo "Building s3ql query".chr(10);
        foreach ($info as $info_key => $info_value) {
            if (is_array($GLOBALS['idReplacements']) && in_array($info_value, array_keys($GLOBALS['idReplacements'])) && ereg('_id$|created_by', $info_key)) {
                $info_value = $GLOBALS['idReplacements'][$info_value];
            }
            if (in_array($info_key, $GLOBALS['s3input'][$element]) && $info_key != 'password') {
                #test for file
                if ($element == 'statement' && $info_key == 'value') {
                    if (isS3DBfile($info_value) || isS3DBLink($info_value)) {
                        #write file to folder
                        #echo "Creating file ".$info_value.chr(10);
                        #echo $info_value;
                        $filekey = moveS3DBfile($info_value, $db, $user_id);
                        $s3ql['insert'] = 'file';
                        $info_key = 'filekey';
                        $info_value = $filekey;
                        $s3ql['where'][$info_key] = $info_value;
                    }
                }
                $s3ql['where'][$info_key] = urldecode($info_value);
            }
        }
        #echo "Run the query for ".$element.' '.$info[$element.'_id'].chr(10);
        $s3ql['format'] = 'php';
        $inserted = S3QLaction($s3ql);
        $msg = unserialize($inserted);
        $inserted = $msg[0];
        #$inserted = html2cell($inserted);$inserted=$inserted[2];
        $newS3QL = $s3ql;
        $try = 1;
        #while(ereg('^9|4$',$inserted['error_code']) && $try<10) #this means this resource already existed.
        while (!ereg('^0$', $inserted['error_code']) && $try < 10) {
            $newS3QL['where'][$element . '_id']++;
            $newS3QL['format'] = 'php';
            $inserted = S3QLaction($newS3QL);
            $msg = unserialize($inserted);
            $inserted = $msg[0];
            #$inserted = html2cell($inserted);$inserted=$inserted[2];
            $try++;
        }
        #if(ereg('^9|4$',$inserted['error_code']))
        if (!ereg('^0$', $inserted['error_code'])) {
            $error_log .= "Could not create " . $newS3QL['insert'] . ". Gave up after 5 attempts. " . $inserted['message'] . '<br />';
        }
        if ($inserted['error_code'] != '0' && $inputs['su3d']) {
            $eeee = @fopen('tmp/error_log_' . date('Ymd'), 'a+');
            @fwrite($eeee, serialize(array('q' => $s3ql, 'new' => $newS3QL, 'ms' => $inserted['message'])));
            echo "Here are the queries that were not valid:";
            echo '<pre>';
            print_r($s3ql);
            echo '<pre>';
            print_r($newS3QL);
            echo '<pre>';
            print_r($inserted);
        }
        //	if($s3ql['insert']=='file')
        //	{
        //	echo '<pre>';print_r($s3ql);
        //	echo '<pre>';print_r($inserted);
        //	exit;
        //	}
        ##User that is inserting must have permission to further insert stuff in this id
        if ($inserted['error_code'] == '0') {
            switch ($element) {
                case 'project':
                    $permission_info = array('uid' => 'P' . $inserted[$element . '_id'], 'shared_with' => 'U' . $user_id, 'permission_level' => '222');
                case 'collection':
                    $permission_info = array('uid' => 'C' . $inserted[$element . '_id'], 'shared_with' => 'U' . $user_id, 'permission_level' => '222');
                    break;
                case 'rule':
                    $permission_info = array('uid' => 'R' . $inserted[$element . '_id'], 'shared_with' => 'U' . $user_id, 'permission_level' => '222');
                    break;
                case 'item':
                    $permission_info = array('uid' => 'I' . $inserted[$element . '_id'], 'shared_with' => 'U' . $user_id, 'permission_level' => '222');
                case 'statement':
                    $permission_info = array('uid' => 'S' . $inserted[$element . '_id'], 'shared_with' => 'U' . $user_id, 'permission_level' => '222');
                    break;
            }
            $p = insert_permission(array('permission_info' => $permission_info, 'db' => $db, 'user_id' => "'-100'"));
        }
        if ($inserted[$element . '_id'] != '' && $inserted[$element . '_id'] != $s3ql['where'][$element . '_id']) {
            ##need to re-issue all the ids that rely on this one fro this moment forward
            $GLOBALS['idReplacements'][$s3ql['where'][$element . '_id']] = $inserted[$element . '_id'];
            #array_push($idReplacements, array($s3ql['where'][$element.'_id']=>$inserted[$element.'_id']));
        }
        #echo '<pre>';print_r($GLOBALS['idReplacements']);
        #if($element=='statement' && $filekey!='')
        #	{
        #echo '<pre>';print_r($s3ql);
        #echo '<pre>';print_r($inserted);
        #
        #}
        #echo '<pre>';print_r($s3ql);
        #echo '<pre>';print_r($inserted);exit;
        if ($element == 'user' && $info['password'] != '' && $s3ql_in['user_id'] == '1') {
            #password is already md5
            insertUserPassword($info['user_id'], $info['password'], $s3ql_in['db']);
        }
        if ($inserted[2][$element . '_id'] == '') {
            echo $error_log;
            return array(False, $inserted[2]['message']);
        } else {
            return array(True, $inserted);
        }
    }
}
コード例 #12
0
ファイル: S3QLaction1.php プロジェクト: helenadeus/s3db.map
function S3QLaction($s3ql)
{
    extract($s3ql);
    #grab a few relevant varuales
    $regexp = $GLOBALS['regexp'];
    $dbstruct = $GLOBALS['dbstruct'];
    #map a few vairables
    $s3map = $GLOBALS['s3map'];
    $format = $s3ql['format'];
    #Error messages
    extract($GLOBALS['messages']);
    #database and user identification
    if (!is_object($db)) {
        $db = $_SESSION['db'];
    }
    $key = $_REQUEST['key'] ? $_REQUEST['key'] : $s3ql['key'];
    $user_id = $user_id ? $user_id : $_SESSION['user']['account_id'];
    $user_info = s3info('users', $user_id, $db);
    if (!$user_id && !$db) {
        if (!$key) {
            return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'Please specify user_id and db or a key', $format, '');
        }
        #re-chekc if user provided is the same for key provided
    }
    $s3ql = array_diff_key($s3ql, array('db' => '', 'user_id' => ''));
    #take out from the array what needed to be included for wihitn S3DB queries
    if ($s3ql['update'] != '') {
        $s3ql['edit'] = $s3ql['update'];
        #update is closer to SQL, although original was edit. Must keep edit to be backward compatible
        $s3ql = array_filter(array_diff_key($s3ql, array('update' => 1)));
    }
    #identify the action
    $possible_actions = array('insert', 'edit', 'delete', 'select', 'update', 'grant');
    foreach ($possible_actions as $someaction) {
        if ($s3ql[$someaction] != '') {
            $action = $someaction;
        }
    }
    #if there is nothing as action, assume a select
    if ($action == '') {
        $action = 'select';
    }
    #identify the target
    if (ereg('(insert|edit|update|delete|grant)', $action)) {
        $s3ql['from'] = $s3ql[$action] == '' ? $_REQUEST[$action] : $s3ql[$action];
    } elseif (ereg('(select)', $action)) {
        $s3ql['from'] = $s3ql['from'] == '' ? $_REQUEST['from'] : $s3ql['from'];
    }
    #if there is no target, assume projects
    if ($s3ql['from'] == '') {
        $s3ql['from'] = 'projects';
    }
    if ($s3ql['from'] == 'permission') {
        $s3ql['from'] = 'user';
    }
    if ($s3ql['from'] == 'class') {
        $s3ql['from'] = 'collection';
    }
    if ($s3ql['from'] == 'instance') {
        $s3ql['from'] = 'item';
    }
    #these are targets ONLY for insert/edit/delete. Select takes plurals... was a bad idea, I know :-( but is much more intuitive :-)
    $possible_targets = array('permission', 'user', 'group', 'key', 'project', 'collection', 'item', 'rule', 'statement', 'filekey');
    #start taking action
    switch ($action) {
        case 'select':
            $data = selectQuery(compact('s3ql', 'db', 'user_id', 'format'));
            return $data;
            break;
            #Close select queries
        #Close select queries
        case 'insert':
            #echo '<pre>';print_r($s3ql);exit;
            #map s3ql input to s3db structure requirements
            if ($s3ql['insert'] == 'class') {
                $s3ql['insert'] = 'collection';
            }
            if ($s3ql['insert'] == 'instance') {
                $s3ql['insert'] = 'item';
            }
            if ($s3ql['where']['notes'] != '') {
                $s3ql['where']['notes'] = $s3ql['where']['notes'];
            }
            if ($s3ql['where']['value'] != '') {
                $s3ql['where']['value'] = $s3ql['where']['value'];
            }
            ##build inputs and oldvalues for validation and insert functions
            $tranformed = S3QLselectTransform(compact('s3ql', 'db', 'user_id'));
            $s3ql = $tranformed['s3ql'];
            $element = $s3ql['insert'];
            $element_id = $s3ql['where'][$element . '_id'];
            $letter = strtoupper(substr($element, 0, 1));
            $uid = $letter . $element_id;
            $required = array('key' => array(), 'project' => array('project_name'), 'collection' => array('project_id', 'entity'), 'rule' => array('project_id', 'subject_id', 'verb', 'object'), 'item' => array('collection_id'), 'statement' => array('item_id', 'rule_id', 'value'), 'file' => array('item_id', 'rule_id', 'filekey'), 'user' => array('account_lid', 'account_email'), 'group' => array('account_lid'));
            if (!in_array($element, array_keys($required))) {
                return formatReturn($GLOBALS['error_codes']['wrong_input'], $element . ' is not a valid S3DB element. Valid elements: key, project, collection, rule, item, statement, file', $format, '');
            }
            #if a subject is provided instead of a subject id in rule, dont break because of that. Find the subject
            #THIS PART NEEDS TO B HERE BECAUSE IT THE MANDATORY FIELDS ARE 'OR'
            if ($element == 'rule') {
                $s3ql = ruleInputsInfer($s3ql, $db, $user_id);
            }
            #echo '<pre>';print_r($s3ql);
            #translate some s3ql inputs into s3db names:
            #IS there anythi ng still missing? There are 2 types fo required inputs: thsoe from the user and those into the table. The firstare verified here, the rest are verified in "validation"
            $diff = array_diff($required[$element], array_keys($s3ql['where']));
            if ($element_id == '' && !empty($diff)) {
                return formatReturn($GLOBALS['error_codes']['something_missing'], 'Please provide all the necessary fields: ' . rtrim(array_reduce($required[$element], "comma_split"), ", ") . '. ' . $syntax_message, $s3ql['format'], '');
            }
            #echo '<pre>';print_r($required[$element]);exit;
            #if there is any sort of id, check if user has permissions on that. In case of statement, permission must be checked on both rule and instance
            $inserteable = array('group' => 'group_id', 'user' => 'user_id', 'project' => 'project_id', 'rule' => 'rule_id', 'collection' => 'collection_id', 'item' => 'item_id', 'statement' => 'statement_id');
            #insert overal view
            #element_id is not empty
            #upstream resource provided
            #if all permissions clear up, grant permission to upper on loewer score;
            #upstream resource not provided
            #infer deployment if user, group or project, else nothing to do
            #element_id is empty
            #upstream resources provided
            #all permissions clear up, create new entry.
            #scoreTable will allow us to score the elements according to their position in the inheritance model. To nisert an "inserteable" A into an "inserteable" B,
            $scoreTable = array_reverse($inserteable, 0);
            $scoreTable = array_combine(array_keys($scoreTable), range(1, count($inserteable)));
            $elementScore = $scoreTable[$element];
            #check the score of target. All other score will be chacked against this one
            #for user, group and project, inserts occur in deployment (local). Except when there is indication on group or any other Id.
            $input_ids = array_intersect($inserteable, array_keys($s3ql['where']));
            if (ereg('^(U|G|P)$', $letter) && (count($input_ids) <= 1 || count(array_filter(array_diff_key($s3ql['where'], array($element . '_id' => '')))) == 0)) {
                $s3ql['where']['deployment_id'] = $s3ql['where']['deployment_id'] != '' ? $s3ql['where']['deployment_id'] : substr($GLOBALS['Did'], 1, strlen($GLOBALS['Did']));
                $info[$GLOBALS['Did']] = URI($GLOBALS['Did'], $user_id, $db);
                $permission2add[$GLOBALS['Did']] = $info[$GLOBALS['Did']]['add_data'];
                $core_score[$GLOBALS['Did']] = 8;
            }
            #echo '<pre>';print_r($input_ids);exit;
            #echo '<pre>';print_r($inserteable);
            #echo '<pre>';print_r($s3ql);exit;
            ############################
            #this next segment finds all the s3ids in the query, and checks permission of user/session on it (user/session beause user ccna be using a group)
            #echo '<pre>';print_r($s3ql);
            if (ereg('^(U|G|P|C|R|I|S|F)$', strtoupper(substr($element, 0, 1)))) {
                foreach ($inserteable as $s3element => $id) {
                    if ($s3ql['where'][$id] != '') {
                        $element_name = $s3element;
                        $id_name = $id;
                        $uid_info = uid(strtoupper(substr($element, 0, 1)) . $s3ql['where'][$id_name]);
                        $element_info = retrieveUIDInfo($s3element, $id, $scoreTable, $s3ql, $letter, $input_ids, $user_id, $db);
                        #echo '<pre>';print_r($element_info);
                        $info[strtoupper(substr($element_name, 0, 1)) . $s3ql['where'][$id_name]] = $element_info;
                        $permission2add[strtoupper(substr($element_name, 0, 1)) . $s3ql['where'][$id_name]] = $element_info['add_data'];
                        $core_score[strtoupper(substr($element_name, 0, 1)) . $s3ql['where'][$id_name]] = $scoreTable[$element_name];
                        #when element id is present (customized elemnt-id, and is the only ID, and id already exists, user cannot recreat it. To update it, he must go through update. That is the only ID that can "Not" exist
                        if ($id == $GLOBALS['s3ids'][$element] && !is_array($element_info)) {
                            #if a particular id was not found and user is trying to customize a new element_id, then user will have permission to add to it.
                            $permission2add[strtoupper(substr($element_name, 0, 1)) . $s3ql['where'][$id_name]] = '1';
                        } else {
                            if (!is_array($element_info) && $uid_info['Did'] == $GLOBALS['Did']) {
                                return formatReturn($GLOBALS['error_codes']['no_results'], 'Resource ' . strtoupper(substr($element_name, 0, 1)) . $s3ql['where'][$id_name] . ' was not found', $format, '');
                                #if($s3ql['format']=='')
                                #return ('<TABLE><TR><TD>error_code</TD><TD>message</TD></TR><TR><TD>'.ereg_replace('[^(0-9)]', '',$GLOBALS['messages']['something_does_not_exist']).'</TD><TD>>Resource '.strtoupper(substr($element_name, 0,1)).$s3ql['where'][$id_name].' was not found</TD></TR></TABLE>');
                                #else
                                #return ($GLOBALS['messages']['something_does_not_exist'].'<message>Resource '.strtoupper(substr($element_name, 0,1)).$s3ql['where'][$id_name].' was not found</message>');
                            }
                        }
                    }
                }
                #echo 'ola<pre>';print_r($info);exit;
                #echo '<pre>';print_r($permission2add);
                #echo '<pre>';print_r($core_score);
                #exit;
                $result = array_combine($core_score, $permission2add);
                #score as index and permissions as values
                #a group and a user can be inserted in any one resource... as long as user does have permission on the resource
                if (ereg('^(U|G)$', $letter)) {
                    if ($result[min(array_keys($result))] || $user_info['account_type'] == 'a' && max(array_keys($result)) == 8) {
                        $result[max(array_keys($result))] = '1';
                    }
                }
                $has_permission2add = $result[max(array_keys($result))];
                #this means the highest scored element does NOT have permission to add
                #echo '<pre>';print_r($result);exit;
                #how many IDS?Min ID is 1; if two, then it can be inserting a statement or adding remote resource on local resource
                #print $info
                ####If any s3ids were found, Variable $info was created, and variable $permission2add was created from the first.
                #now,interpret what was found.
                #Permissions need to be checek if any ID is supplied that already exists.
                #if (ereg('(group|user|project|collection|rule|item|statement|file)', $element)) {
                if (ereg('(G|U|P|C|R|I|S|F)', strtoupper(substr($element, 0, 1)))) {
                    if (count($info) == '1' || count($info) == '2' && $info[$GLOBALS['Did']] != '' || count($info) == '2' && ereg('^(statement|file)$', $element)) {
                        #is this ID from the element we are trying to insert?
                        #does it exist?
                        if ($s3ql['where'][$GLOBALS['COREids'][$element]] != '' && isLocal($uid, $db) && !$info[$uid]['is_remote']) {
                            #cannot recreate id. Do nothing.
                            return formatReturn($GLOBALS['error_codes']['wrong_input'], $uid . ' already exists. Could not recreate it.', $format, '');
                        } elseif (count($info) == '1' && $element_id != '') {
                            return formatReturn($GLOBALS['error_codes']['something_missing'], 'Please provide the uid where this ' . $element . ' should be inserted.', $format, '');
                        } else {
                            #take inputs, validate them, check permission on ONE id, create resource. Do the switch cases here.
                            if ($has_permission2add) {
                                #this means the highest value on permission2asd is 1.
                                if ($info[$uid]['to_create'] == '1' || $element_id == '') {
                                    $create_info = $s3ql['where'];
                                    #echo '<pre>';print_r($create_info);	exit;
                                    #echo 'ola';exit;
                                    $inputs = gatherInputs(array('element' => $element, 'info' => $info, 'to_create' => $create_info, 'user_id' => $user_id, 'db' => $db));
                                    $info = $inputs;
                                    #echo 'inputs<pre>';print_r($inputs);exit;
                                    if (!is_array($inputs)) {
                                        return formatReturn('3', $inputs, $format, '');
                                    }
                                    $validity = validateInputs(compact('element', 'inputs', 'oldvalues', 'info', 'db', 'action', 'key', 'user_id', 'format'));
                                    #echo 'validity<pre>';print_r($validity);exit;
                                    if ($validity[0]) {
                                        $key = $s3ql['key'];
                                        $inserted = insert_s3db(compact('element', 'inputs', 'user_id', 'db', 'key'));
                                        #echo '<pre>';print_r($inserted);exit;
                                        return formatReturn('0', $inserted[4], $format, array($element . '_id' => $inserted[$element . '_id']));
                                    } else {
                                        #echo '<pre>';print_r($validity);
                                        return formatReturn($validity['error_code'], $validity['message'], $format, '');
                                    }
                                } elseif ($info[$uid]['is_remote'] == '1') {
                                    #insert the permission on local
                                    #remote users an dgroups are inserted ON TABLE
                                    if (ereg('user|group|project', $element)) {
                                        #echo '<pre>';print_r($info[$uid]);exit;
                                        $create_info = $info[$uid];
                                        $create_info['account_email'] = $info[$uid]['account_email'] == '' ? '*****@*****.**' : $info[$uid]['account_email'];
                                        $create_info['account_lid'] = $info[$uid]['account_lid'] != '' ? $info[$uid]['account_lid'] : $info[$uid]['account_id'];
                                        $inputs = gatherInputs(array('element' => $element, 'info' => $info, 'to_create' => $create_info, 'user_id' => $user_id, 'db' => $db));
                                        #echo '<pre>';print_r($inputs);exit;
                                        if (!is_array($inputs)) {
                                            return $inputs;
                                        }
                                        $validity = validateInputs(compact('element', 'inputs', 'oldvalues', 'info', 'db', 'action', 'key'));
                                        #echo '<pre>';print_r($validity);exit;
                                        if ($validity[0]) {
                                            $key = $s3ql['key'];
                                            $inserted = insert_s3db(compact('element', 'inputs', 'user_id', 'db', 'key'));
                                            return formatReturn('0', $element . ' inserted.', array($element . '_id' => $inserted[$element . '_id'], $s3ql['format']));
                                        } else {
                                            return $validity[1];
                                        }
                                    }
                                    $permission_info = array('uid' => $uid, 'shared_with' => 'U' . $user_id, 'permission_level' => $info[$uid]['acl']);
                                    $permission_added = insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                                    if (!$permission_added) {
                                        $permission_added = update_permission(compact('permission_info', 'db', 'user_id', 'info'));
                                    }
                                    if ($permission_added) {
                                        return formatReturn($GLOBALS['error_codes']['success'], $uid . " shared_with in " . $permission_info['shared_with'], $format, '');
                                        #return $GLOBALS['messages']['success']."<message> ".$uid." shared_with in ".$permission_info['shared_with']."</message>";
                                    } else {
                                        return formatReturn($GLOBALS['error_codes']['something_went_wrong'], "Could not share " . $uid . " with " . $permission_info['shared_with'], $format, '');
                                        #return $GLOBALS['messages']['something_went_wrong']."<message>Could not share ".$uid." with ".$permission_info['shared_with']."</message>";
                                    }
                                }
                            } else {
                                $no_permission_id = array_search('0', $permission2add);
                                return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User does not have permission to insert in ' . $no_permission_id, $format, '');
                                exit;
                                #return ($GLOBALS['messages']['no_permission_message'].' Reason: <message>User does not have permission to insert in '.$no_permission_id.'</message>');
                            }
                        }
                    } elseif (count($info) >= 2) {
                        #echo '<pre>';print_r($info);exit;
                        #2 or + ids in info.
                        #these IDS can be entity_id OR membership
                        if ($element_id != '' && !$info[$uid]['to_create']) {
                            #grant permissions
                            $shared_with = array_diff(array_keys($permission2add), array($uid));
                            #take uid from the keys of permission2add, that point to the uid we are sharing with
                            $shared_with = $shared_with[0];
                            $add_resource_on_resource = substr(has_permission(compact('uid', 'shared_with'), $db), 2, 1);
                            if (!$has_permission2add) {
                                #statement has rule_id and instance_id, user must have permission on both.
                                return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User does not have permission to insert in resource ' . key($permission2add), $format, '');
                            }
                            #return ($GLOBALS['messages']['no_permission_message'].'<message>User does not have permission to insert in resource '.key($permission2add).'</message>');
                            if ($result[max(array_keys($result))] == '0' && $result[min(array_keys($result))] == '1' && $add_resource_on_resource != '1' && $element != 'user') {
                                return formatReturn($GLOBALS['error_codes']['something_missing'], 'To share ' . $uid . ' owner of ' . $shared_with . ' must insert first ' . $uid . ' in ' . $shared_with . '.', $s3ql['format'], '');
                            } else {
                                #if is remote and user cna insert in resource, must be inserted first
                                if ($info[$uid]['to_create']) {
                                    $create_info = $s3ql['where'];
                                    #echo '<pre>';print_r($create_info);	exit;
                                    $inputs = gatherInputs(array('element' => $element, 'info' => $info, 'to_create' => $create_info, 'user_id' => $user_id));
                                    if (!is_array($inputs)) {
                                        return $inputs;
                                    }
                                    $validity = validateInputs(compact('element', 'inputs', 'oldvalues', 'info', 'db', 'action', 'key'));
                                    if ($validity[0]) {
                                        $key = $s3ql['key'];
                                        $inserted = insert_s3db(compact('element', 'inputs', 'user_id', 'db', 'key'));
                                        return formatReturn('0', $element . ' inserted.', array($element . '_id' => $inserted[$element . '_id'], $s3ql['format']));
                                    } else {
                                        return $validity[1];
                                    }
                                }
                                if ($info[$uid]['is_remote']) {
                                    #the other iD, non element id, should be the upper ID, where user shoulsd already have intert permission
                                    $diff = array_diff(array_keys($permission2add), array($uid));
                                    $shared_with = $diff[0];
                                    $permission_info = array('uid' => $uid, 'shared_with' => $shared_with, 'permission_level' => $info[$uid]['acl']);
                                    $permission_added = insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                                    if (!$permission_added) {
                                        $permission_added = update_permission(compact('permission_info', 'db', 'user_id', 'info'));
                                    }
                                    if ($permission_added) {
                                        return formatReturn($GLOBALS['error_codes']['success'], $uid . " inserted in " . $shared_with, $s3ql['format'], '');
                                    } else {
                                        return formatReturn($GLOBALS['error_codes']['something_went_wrong'], "Could not share " . $uid . " with " . $permission_info['shared_with'], $format, '');
                                        #return $GLOBALS['messages']['something_went_wrong']."<message>Could not share ".$uid." with ".$permission_info['shared_with']."</message>";
                                    }
                                }
                                if (!$info[$uid]['to_create'] && $s3ql['where']['permission_level'] == '') {
                                    #does it exist already in upper resource?
                                    $diff = array_diff(array_keys($permission2add), array($uid));
                                    $shared_with = $diff[0];
                                    $sql = str_replace($GLOBALS['regexp'], '=', select(compact('uid', 'shared_with')));
                                    #echo $sql;exit;
                                    $db->query($sql, __LINE__, __FILE__);
                                    if ($db->next_record()) {
                                        return formatReturn($GLOBALS['error_codes']['repeating_action'], $uid . ' already shared with ' . $shared_with . '. You can change its level of permission by indicating permission_level.', $s3ql['format'], '');
                                    }
                                }
                            }
                            #share according to permissions
                            $uid2share = array_search(min($core_score), $core_score);
                            $shared_with = array_search(max($core_score), $core_score);
                            $uid_info = uid($uid2share);
                            if ($result[max(array_keys($result))] == '1' || $add_resource_on_resource && $result[min(array_keys($result))] == '1') {
                                #echo 'ola';exit;
                                $case = '2';
                                $uid_info = uid($uid2share);
                                if ($uid_info['Did'] == $GLOBALS['Did']) {
                                    $uid2share = $uid_info['uid'];
                                }
                                #$uid2share = strtoupper(substr($uid_info['uid'],0,1)).$GLOBALS['Did'].'/'.$uid_info['uid'];
                                $permission_info = array('uid' => $uid2share, 'shared_with' => $shared_with, 'permission_level' => $s3ql['where']['permission_level'] != '' ? $s3ql['where']['permission_level'] : '210');
                                #echo '<pre>';print_r($permission_info);exit;
                                $validity = validate_permission(compact('permission_info', 'user_id', 'db', 'info'));
                                #grant project_id permission on rule_id
                                #echo $validity;exit;
                                if ($validity == '0') {
                                    $permission_added = insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                                } elseif ($validity == '2') {
                                    $permission_added = update_permission(compact('permission_info', 'db', 'user_id', 'info'));
                                } elseif ($validity == '6' && ereg('^G', $shared_with) && ereg('^U', $uid)) {
                                    $permission_added = insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                                    #grant rule_id permission on project_id
                                    $permission_added = update_permission(compact('permission_info', 'db', 'user_id', 'info'));
                                } elseif ($validity == '6') {
                                    return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User must have permission ' . $permission_info['permission_level'] . ' or greater to grant permission ' . $permission_info['permission_level'] . ' on ' . $permission_info['shared_with'], $format, '');
                                }
                                #return ($GLOBALS['messages']['no_permission_message'].'<message>User must have permission '.$permission_info['permission_level'].' or greater to grant permission '.$permission_info['permission_level'].' on '.$permission_info['shared_with'].'.</message>');
                            } elseif ($result[max(array_keys($result))] == '1' && $result[min(array_keys($result))] == '0') {
                                $case = '1';
                                if ($uid_info['Did'] == $GLOBALS['Did']) {
                                    $uid2share = strtoupper(substr($uid_info['uid'], 0, 1)) . $GLOBALS['Did'] . '/' . $uid_info['uid'];
                                }
                                $permission_info = array('shared_with' => $shared_with, 'uid' => $uid2share, 'permission_level' => '001');
                                $permission_added = insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                                if (!$permission_added) {
                                    $permission_added = update_permission(compact('permission_info', 'db', 'user_id', 'info'));
                                }
                                #This step will leave rule insert pending until owner of the rule comes by and inserts it in project
                            }
                            if ($permission_added) {
                                #Missing: Create an entry in access_rules with "Pending" statuss
                                if ($case == '1') {
                                    return formatReturn($GLOBALS['error_codes']['success'], "Permission on " . $permission_info['uid'] . " requested and pending.", $format, '');
                                } else {
                                    return formatReturn($GLOBALS['error_codes']['success'], $permission_info['uid'] . " inserted in " . $permission_info['shared_with'], $s3ql['format'], '');
                                }
                            } else {
                                return formatReturn($GLOBALS['error_codes']['something_went_wrong'], "Could not share " . $permission_info['uid'] . " with " . $permission_info['shared_with'], $s3ql['format'], '');
                            }
                        } elseif ($info[$uid]['to_create'] || $info[$uid]['is_remote']) {
                            #insert IF is remote or was asserted to be inserted
                            if (is_array($info[$uid]) && $info[$uid]['is_remote']) {
                                $create_info = $info[$uid];
                            } else {
                                $create_info = $s3ql['where'];
                            }
                            $inputs = gatherInputs(array('element' => $element, 'to_create' => $create_info, 'user_id' => $user_id, 'info' => $info));
                            #echo '<pre>';print_r($inputs);exit;
                            if (!is_array($inputs)) {
                                return $inputs;
                            }
                            $validity = validateInputs(compact('element', 'inputs', 'oldvalues', 'info', 'db', 'action', 'key'));
                            if ($validity[0]) {
                                $key = $s3ql['key'];
                                $inserted = insert_s3db(compact('element', 'inputs', 'user_id', 'db', 'key'));
                                return formatReturn('0', $element . ' inserted.', array($element . '_id' => $inserted[$element . '_id']), $s3ql['format']);
                            } else {
                                return $validity[1];
                            }
                        }
                    }
                }
            }
            #permissions to add are stored in $permission2add, but when we are inserting an existing idA on an existing idB, we do not need permission to add_data on A, only on B. So the users does not need insert permission on idA, if idA is further down the graph then idB.
            #if there is only 1 id, and there is no insert permission, it can break
            #start some special cases
            switch ($element) {
                case 'key':
                    ##INSERT KEY
                    #when no key is given, generate a random one
                    if ($s3ql['where']['key_id'] == '') {
                        $s3ql['where']['key_id'] = random_string('15');
                    }
                    if ($s3ql['where']['expires'] == '') {
                        $s3ql['where']['expires'] = date('Y-m-d H:i:s', time() + 1 * 24 * 60 * 60);
                    }
                    #expires in 24h
                    #user can chose to insert a key for a specific ID, be it group, project, rule or statement (anywhere where permissions can be defined)
                    $I['inputs'] = array_merge($s3ql['where'], array('account_id' => $user_id));
                    $validate = validate_access_key_inputs(array('inputs' => $I['inputs'], 'db' => $db, 'user_id' => $user_id));
                    switch ($validate) {
                        case 0:
                            return formatReturn($GLOBALS['error_codes']['something_missing'], 'Expiration date is missing', $s3ql['format'], '');
                            break;
                        case 1:
                            return formatReturn($GLOBALS['error_codes']['wrong_input'], 'Key is too short. Please input a key longer than 10 char', $s3ql['format'], '');
                            break;
                        case 2:
                            return formatReturn($GLOBALS['error_codes']['wrong_input'], 'Invalid date format', $s3ql['format'], '');
                            break;
                        case 3:
                            return formatReturn($GLOBALS['error_codes']['repeating_action'], 'Key ' . $s3ql['where']['key_id'] . ' is not valid. Please chose another key', $s3ql['format'], '');
                            break;
                        case 4:
                            return formatReturn($GLOBALS['error_codes']['wrong_input'], 'Expiration date must be bigger than present date.', $s3ql['format'], '');
                            break;
                        case 6:
                            return formatReturn($GLOBALS['error_codes']['wrong_input'], 'UID ' . $s3ql['where']['UID'] . ' does not exist', $s3ql['format'], '');
                            break;
                        case 7:
                            return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'UID ' . $s3ql['where']['UID'] . ' does not belong to user.', $s3ql['format'], '');
                            break;
                        case 8:
                            return formatReturn($GLOBALS['error_codes']['wrong_input'], 'Please use only numbers and letter in your keys.', $s3ql['format'], '');
                            break;
                        case 5:
                            add_entry('access_keys', $I['inputs'], $db);
                            $output = formatReturn($GLOBALS['error_codes']['success'], 'Key created.', $s3ql['format'], array('key_id' => $s3ql['where']['key_id']));
                            return $output;
                    }
                    break;
                case 'file':
                    $resource_id = $s3ql['where']['item_id'] != '' ? $s3ql['where']['item_id'] : $s3ql['where']['instance_id'];
                    $rule_id = $s3ql['where']['rule_id'];
                    $filekey = $s3ql['where']['filekey'];
                    $notes = $s3ql['where']['notes'];
                    if ($resource_id == '' || $rule_id == '' || $filekey == '') {
                        return formatReturn($GLOBALS['error_codes']['something_missing'], 'Please provide all the necessary inputs: rule_id, item_id, filekey', $format, '');
                        #return ($GLOBALS['messages']['something_missing'].'<message>Please provide all the necessary inputs: rule_id, item_id, filekey</message>');
                    }
                    #Check permission on inserting statements for specific projects
                    #Check permission on inserting statements for specific projects
                    $rule_info = $info['R' . $rule_id];
                    $instance_info = $info['I' . $resource_id];
                    #$instance_info = URIinfo('I'.$resource_id, $user_id, $key, $db);
                    if ($rule_info['object'] == 'UID') {
                        return formatReturn($GLOBALS['error_codes']['wrong_input'], 'Please use this query only for rules that do NOT enumerate classes. For inserting on other rules, use the query for insert instance', $format, '');
                        #return $wrong_input."<message>Please use this query only for rules that do NOT enumerate classes. For inserting on other rules, use the query for insert instance</message>";
                    } elseif (!is_array($instance_info)) {
                        return formatReturn($GLOBALS['error_codes']['no_results'], 'Item ' . $resource_id . ' was not found', $format, '');
                        #return ($something_does_not_exist.'<message>Instance '.$resource_id.' was not found</message>');
                    } elseif ($instance_info['resource_class_id'] != $rule_info['subject_id']) {
                        return formatReturn($GLOBALS['error_codes']['wrong_input'], 'Subject of rule does match Class of instance', $format, '');
                        #return $wrong_input."<message>Subject of rule does match Class of instance</message>";
                    } elseif ($filekey == '') {
                        return formatReturn($GLOBALS['error_codes']['something_missing'], 'Please indicate a filekey for this file', $format, '');
                    }
                    #return $wrong_input."<message>Please indicate a filekey for this file</message>";
                    #Find out if the file already exists in the tmp directory
                    $fileFinalName = get_entry('file_transfer', 'filename', 'filekey', $filekey, $db);
                    $file_id = get_entry('file_transfer', 'file_id', 'filekey', $filekey, $db);
                    ereg('([A-Za-z0-9]+)\\.*([A-Za-z0-9]*)$', $fileFinalName, $tokens);
                    $name = $tokens[1];
                    $extension = $tokens[2];
                    #list($name, $extension) = explode('.', $fileFinalName);
                    $maindir = $GLOBALS['s3db_info']['server']['db']['uploads_folder'] . $GLOBALS['s3db_info']['server']['db']['uploads_file'] . '/tmps3db';
                    $old_file = $maindir . '/' . $file_id . '.' . $extension;
                    if (!is_file($old_file)) {
                        return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], 'File not found, please upload file first.', $format, '');
                    } else {
                        #project_id will be that of the rule, except if user does not have permission on it.
                        $project_info = URI('P' . $rule_info['project_id'], $user_id, $db);
                        $project_id = $s3ql['where']['project_id'] != '' ? $s3ql['where']['project_id'] : ($project_info['add_data'] ? $class_info['project_id'] : '');
                        if ($project_id == '') {
                            $project_id = $rule_info['project_id'];
                            #$user_projects = findUserProjects($user_id, $db);
                            //							$user_projects = array_map('grab_project_id', $user_projects);
                            //
                            //
                            //							#find the projects that can access the rule
                            //							$allowed_projects = array_filter(explode('_', $rule_info['permission']));
                            //
                            //							$both = array_intersect($allowed_projects, $user_projects);
                            //
                            //							if (is_array($both)) {
                            //								foreach ($both as $key=>$allowed_project_id) {
                            //									if(substr(has_permission(array('uid'=>'R'.$rule_id, 'shared_with'=>'P'.$allowed_project_id), $db), 2,1))
                            //										$project_id = $allowed_project_id;
                            //								}
                            //							}
                        }
                        if ($project_id == '') {
                            return formatReturn($GLOBALS['error_codes']['something_went_wrong'], 'Failed to find a project_in for this intance', '', $s3ql['format']);
                        }
                        $value = project_folder_name($project_id, $db);
                        $created_by = $user_id;
                        $filesize = filesize($old_file);
                        $filename = $fileFinalName;
                        ##Create the row in the statements table
                        $create_info = $s3ql['where'];
                        #echo '<pre>';print_r($s3ql);
                        $inputs = gatherInputs(array('element' => 'file', 'info' => $info, 'to_create' => $create_info, 'user_id' => $user_id, 'db' => $db));
                        $info = $inputs;
                        if (!is_array($inputs)) {
                            return formatReturn('3', $inputs, $s3ql['format'], '');
                        }
                        $validity = validateInputs(compact('element', 'inputs', 'oldvalues', 'info', 'db', 'action', 'key', 'user_id'));
                        #echo '<pre>';print_r($validity);exit;
                        if ($validity[0]) {
                            $key = $s3ql['key'];
                            $inserted = insert_s3db(compact('element', 'inputs', 'user_id', 'db', 'key'));
                            ##Move the file
                            $S = compact('user_id', 'project_id', 'resource_id', 'rule_id', 'value', 'notes', 'created_by', 'filename', 'filesize', 'extension', 'db');
                            $S['statement_id'] = $inserted['statement_id'];
                            $S['uploadedfile'] = $old_file;
                            $fileRelocated = movefile2folder($S);
                            if (!$fileRelocated) {
                                $sql = "delete from s3db_statement where statement_id = '" . $S['statement_id'] . "'";
                                $db->query($sql, __FILE__, __LINE__);
                                #echo $sql;
                                return formatReturn('2', 'File could not be imported. Please try again.', '', $s3ql['format']);
                                #unlink($old_file);
                            } else {
                                return formatReturn($GLOBALS['error_codes']['success'], 'File inserted.', $s3ql['format'], array('file_id' => $inserted['1']));
                                #if($s3ql['format']=='')
                                #	return ('<TABLE><TR><TD>error_code</TD><TD>message</TD><TD>'.$element.'_id</TD></TR><TR><TD>'.ereg_replace('[^(0-9)]', '', $inserted[3]).'</TD><TD>'.$inserted[4].'</TD><TD>'.$inserted[$element.'_id'].'</TD></TR></TABLE>');
                                #else
                                #	return ($inserted[1]);
                            }
                        } else {
                            #echo '<pre>';print_r($validity);
                            return formatReturn(ereg_replace('[^(0-9)]', '', $inserted[3]), $validity[1], $format, '');
                            #if($s3ql['format']=='')
                            #	return ('<TABLE><TR><TD>error_code</TD><TD>message</TD></TR><TR><TD>'.ereg_replace('[^(0-9)]', '', $inserted[3]).'</TD><TD>'.$validity[1].'</TD></TR></TABLE>');
                            #else
                            #return ($validity[1]);
                        }
                        ##Move the file
                        if ($statement_inserted) {
                            $S['statement_id'] = find_latest_UID('statement', $db);
                            $S['uploadedfile'] = $old_file;
                            $fileRelocated = movefile2folder($S);
                            if ($fileRelocated) {
                                return formatReturn($GLOBALS['error_codes']['success'], "File inserted", array('file_id' => $S['file_id']), $s3ql['format']);
                            } else {
                                return formatReturn($GLOBALS['error_codes']['something_went_wrong'], 'Failed to move file', $format, '');
                            }
                            #else return $something_went_wrong."<message>Failed to move file</message>";
                        }
                    }
                    #This ends "is not a file"
                    #This ends insert file
                    break;
            }
            #finish element switch
            break;
            #Finish insert
        #Finish insert
        case 'edit':
            if ($s3ql['edit'] == 'class') {
                $s3ql['edit'] = 'collection';
            }
            if ($s3ql['edit'] == 'instance') {
                $s3ql['edit'] = 'item';
            }
            if ($s3ql['set']['notes'] != '') {
                $s3ql['set']['notes'] = utf8_encode($s3ql['set']['notes']);
            }
            if ($s3ql['set']['value'] != '') {
                $s3ql['set']['value'] = utf8_encode($s3ql['set']['value']);
            }
            #$element = $s3ql[$action];
            $element = $s3ql['edit'];
            #echo 'ola<pre>';print_r($s3ql);exit;
            $set = array('project' => array('project_name', 'project_description', 'project_owner', 'permission_level'), 'collection' => array('project_id', 'entity', 'notes'), 'rule' => array('project_id', 'subject', 'verb', 'object', 'subject_id', 'verb_id', 'object_id', 'notes', 'validation'), 'item' => array('project_id', 'collection_id', 'notes'), 'statement' => array('project_id', 'item_id', 'rule_id', 'value', 'notes'), 'user' => array('account_lid', 'account_pwd', 'account_uname', 'account_email', 'account_phone', 'addr1', 'addr2', 'account_type', 'city', 'postal_code', 'state', 'country', 'account_status'), 'group' => array('account_lid'));
            $E = compact('db', 'user_id', 's3ql');
            #first of all, is this a valid target?
            if (!in_array($s3ql['edit'], array_keys($set))) {
                return formatReturn($GLOBALS['error_codes']['wrong_input'], $s3ql['edit'] . " is not a valid S3DB element. Valid elements: project, collection, rule, item, statement", $s3ql['format'], '');
            }
            #is there an ID to locate the appropriate resource?
            if ($s3ql['where'][$element . '_id'] == '') {
                return formatReturn($GLOBALS['error_codes']['something_missing'], 'ID of ' . $element . ' to edit is missing', $s3ql['format'], '');
            }
            if ($s3ql['set'] == '') {
                #is it in where?
                $s3ql['set'] = array_diff_key($s3ql['where'], array($element . '_id' => ''));
                if ($s3ql['set'] == '') {
                    return formatReturn($GLOBALS['error_codes']['something_missing'], 'Please specify what you want to update.' . $syntax_message, $s3ql['format'], '');
                }
            }
            #interpret input
            $s3map = $GLOBALS['s3map'];
            foreach ($s3map[$GLOBALS['plurals'][$element]] as $alter_name => $name) {
                if ($s3ql['set'][$alter_name] != '') {
                    $s3ql['set'][$name] = $s3ql['set'][$alter_name];
                }
            }
            $s3ql['set'] = array_diff_key($s3ql['set'], $s3map[$GLOBALS['plurals'][$element]]);
            $s3ql['set'] = array_filter($s3ql['set']);
            #detect is something that is something in set that cannot be updated
            $test_set = array_intersect($set[$element], array_keys($s3ql['set']));
            $extra_fields = array_diff(array_keys($s3ql['set']), $test_set);
            if (count($s3ql['set']) > count($test_set)) {
                #this means that there are fields that don't exist
                foreach ($extra_fields as $field_name) {
                    $output .= '<message>Warning: ' . $field_name . ' is not a valid property of ' . $element . '. ' . $field_name . ' will not be updated. Valid properties: ' . rtrim(array_reduce($set[$element], 'comma_split'), ', ') . '</message>';
                }
            }
            #retrieve information about resource
            $element_id = $s3ql['where'][$element . '_id'];
            $uid = strtoupper(substr($element, 0, 1)) . $element_id;
            $e_info = URIinfo($uid, $user_id, $key, $db);
            #echo '<pre>';print_r($e_info);
            if (!is_array($e_info)) {
                return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], '' . $element . ' ' . $element_id . ' was not found.');
            } elseif (!$e_info['change']) {
                return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User does not have permission to change this ' . $element, $s3ql['format'], '');
            }
            foreach ($e_info as $field => $data) {
                if ($s3ql['set'][$field] != '' || $field == 'notes') {
                    if (in_array($field, $set[$element])) {
                        $oldvalues[$field] = $e_info[$field];
                        $e_info[$field] = $s3ql['set'][$field];
                        $inputs[$field] = $s3ql['set'][$field];
                    }
                }
            }
            #echo '<pre>';print_r($inputs);
            switch ($element) {
                case 'user':
                    ##EDIT USER
                    $user_to_change_info = get_info('user', $element_id, $db);
                    #this is necessary because password will not come in the $e_info var.
                    #permission was checked before the switch
                    #map values
                    $s3map = array('login' => 'account_lid', 'password' => 'account_pwd', 'username' => 'account_uname', 'email' => 'account_email', 'phone' => 'account_phone', 'address' => 'addr1', 'address2' => 'addr2', 'city' => 'city', 'state' => 'state', 'postal_code' => 'postal_code', 'country' => 'country', 'account_type' => 'account_type');
                    #encript the password
                    #echo '<pre>';print_r($s3ql);exit;
                    if ($s3ql['set']['password'] != '' || $s3ql['set']['account_pwd']) {
                        $s3ql['set']['password'] = $s3ql['set']['account_pwd'] != '' ? md5($s3ql['set']['account_pwd']) : md5($s3ql['set']['password']);
                    } else {
                        $s3ql['set']['password'] = $user_to_change_info['account_pwd'];
                    }
                    #echo '<pre>';print_r($s3ql);
                    #login, password and email cannot be deleted so if they come empty, fill them out with the old values
                    $non_erasable = array('login', 'email', 'username', 'password');
                    foreach ($non_erasable as $fieldname) {
                        if (in_array($fieldname, array_keys($s3ql['set']))) {
                            if ($s3ql['set'][$fieldname] == '') {
                                return formatReturn($GLOBALS['error_codes']['wrong_input'], 'login, email, username and password cannot be deleted', $s3ql['format'], '');
                            }
                        } elseif (!in_array($fieldname, array_keys($s3ql['set']))) {
                            #then start filling out input with the old values
                            $inputs[$s3map[$fieldname]] = $e_info[$s3map[$fieldname]];
                        }
                    }
                    #now map the valid values
                    foreach (array_keys($s3ql['set']) as $set) {
                        if (in_array($set, array_keys($s3map))) {
                            if ($s3ql['set'][$set] != '') {
                                $inputs[$s3map[$set]] = $s3ql['set'][$set];
                            }
                        }
                    }
                    #echo '<pre>';print_r($e_info);
                    $inputs['account_type'] = $s3ql['set']['account_type'] != '' ? $s3ql['set']['account_type'] : $user_to_change_info['account_type'];
                    $inputs['account_status'] = $s3ql['set']['account_status'] != '' ? $s3ql['set']['account_status'] : $user_to_change_info['account_status'];
                    $inputs['account_group'] = $inputs['account_type'];
                    #replace in $e_info the values with the inputs. First clean the existing one, then merge with the new one
                    $user_info = array_diff_key($e_info, $inputs);
                    $user_info = array_merge($user_info, $inputs);
                    $validity = validate_user_inputs(array('inputs' => $inputs, 'imp_user_id' => $e_info['account_id'], 'db' => $db, 'action' => 'update'));
                    $info = $e_info;
                    #echo '<pre>';print_r($inputs);
                    #$validity = validateInputs(compact('element','info', 'inputs', 'oldvalues', 'user_id', 'db'));
                    #echo '<pre>';print_r($validity);
                    switch ($validity) {
                        case 0:
                            #echo '<pre>';print_r($user_info);	exit;
                            if (!update_user(compact('user_info', 'db', 'user_id'))) {
                                #$output .= $something_went_wrong;
                                return formatReturn($GLOBALS['error_codes']['something_went_wrong'], 'User could not be updated. Undetermined reasons.', $s3ql['format'], '');
                            } else {
                                #$output .= $GLOBALS['messages']['success'];
                                #$output .= '<message> User updated</message>';
                                return formatReturn($GLOBALS['error_codes']['success'], 'User updated', $s3ql['format'], '');
                            }
                            break;
                        case 1:
                            #$output .= $GLOBALS['messages']['something_missing'];
                            #$output .= '<message> Login is missing.'.$syntax_message.'</message>';
                            return formatReturn($GLOBALS['error_codes']['something_missing'], 'Login is missing.' . $syntax_message, $s3ql['format'], '');
                            break;
                        case 2:
                            #$output .= $GLOBALS['messages']['something_missing'];
                            #$output .= '<message> Account_type is missing.'.$syntax_message.'</message>';
                            return formatReturn($GLOBALS['error_codes']['something_missing'], 'Account_type is missing.' . $syntax_message, $s3ql['format'], '');
                            break;
                        case 3:
                            #$output .= $GLOBALS['messages']['something_missing'];
                            #$output .= '<message> Username is missing.'.$syntax_message.'</message>';
                            return formatReturn($GLOBALS['error_codes']['something_missing'], 'Username is missing.' . $syntax_message, $s3ql['format'], '');
                            break;
                        case 4:
                            #$output .= $GLOBALS['messages']['something_missing'];
                            #$output .= '<message> Account status is missing.'.$syntax_message.'</message>';
                            return formatReturn($GLOBALS['error_codes']['something_missing'], 'Account status is missing.' . $syntax_message, $s3ql['format'], '');
                            break;
                        case 5:
                            $output .= $GLOBALS['messages']['something_missing'];
                            $output .= '<message> Password is missing.' . $syntax_message . '</message>';
                            return formatReturn($GLOBALS['error_codes']['something_missing'], 'Password is missing.' . $syntax_message, $s3ql['format'], '');
                            break;
                        case 6:
                            #$output .= $GLOBALS['messages']['something_missing'];
                            return formatReturn($GLOBALS['error_codes']['something_missing'], '', $s3ql['format'], '');
                            break;
                        case 7:
                            #$output .= $GLOBALS['messages']['something_missing'];
                            return formatReturn($GLOBALS['error_codes']['something_missing'], '', $s3ql['format'], '');
                            break;
                        case 8:
                            #$output .=$GLOBALS['messages']['repeating_action'].'<message> User '.$inputs['account_lid'].' already exists</message>';
                            return formatReturn($GLOBALS['error_codes']['something_missing'], 'User ' . $inputs['account_lid'] . ' already exist', $s3ql['format'], '');
                            break;
                    }
                    break;
                case 'group':
                    ##EDIT GROUP
                    $info = $e_info;
                    $group_id = $info['group_id'];
                    $validity = validateInputs(compact('element', 'inputs', 'oldvalues', 'info', 'db', 'action', 'key'));
                    if ($validity[0]) {
                        if (update_group(compact('inputs', 'group_id', 'user_id', 'db'))) {
                            return formatReturn($GLOBALS['error_codes']['success'], 'G' . $group_id . ' successfully updated', $s3ql['format'], '');
                            #return ($GLOBALS['messages']['success'].'<message>G'.$group_id.' successfully updated</message>');
                        } else {
                            return formatReturn($GLOBALS['error_codes']['something_went_wrong'], 'G' . $group_id . ' could not be updated. Reason undetermined.', $s3ql['format'], '');
                            #return ($GLOBALS['messages']['something_went_wrong']);
                        }
                        break;
                    } else {
                        return $validity[1];
                    }
                    break;
                case 'project':
                    ##EDIT PROJECT
                    $project_info = $e_info;
                    $U = compact('project_info', 'db', 'user_id');
                    #$validity = validate_project_inputs($U);
                    $info = $e_info;
                    $validity = validateInputs(compact('element', 'inputs', 'oldvalues', 'info', 'db', 'action', 'key'));
                    if ($validity[0]) {
                        if (update_project($U)) {
                            return formatReturn($GLOBALS['error_codes']['success'], $element . " P" . $element_id . " updated.", $s3ql['format'], '');
                        } else {
                            return formatReturn($GLOBALS['error_codes']['something_went_wrong'], 'Failed to update project!', $s3ql['format'], '');
                        }
                    } else {
                        #break validity in error and message
                        ereg('<error>([0-9]+)</error>(.*)<message>(.*)</message>', $validity[1], $valOut);
                        return formatReturn($valOut[1], $valOut[3], $s3ql['format'], '');
                    }
                    break;
                case 'collection':
                    ##EDIT CLASS
                    $resource_info = $e_info;
                    $editresource = compact('db', 'user_id', 'resource_info', 'action', 'inputs', 'oldvalues');
                    $info = $e_info;
                    $validity = validateInputs(compact('element', 'inputs', 'oldvalues', 'info', 'db', 'action', 'key'));
                    #echo '<pre>';print_r($validity);exit;
                    #echo $validity = validate_resource_inputs($editresource);exit;
                    if ($validity[0]) {
                        if (update_resource($editresource)) {
                            #$validity[1].'<br><message>'.$element.' updated</message>';
                            $output .= formatReturn('0', $element . " C" . $element_id . ' updated', $format, '');
                            return $output;
                            #return ($output);
                        }
                    } else {
                        ereg('<error>([0-9]+)</error>(.*)<message>(.*)</message>', $validity[1], $valOut);
                        return formatReturn($valOut[1], $valOut[3], $s3ql['format'], '');
                        #return ($validity[1]);
                    }
                    break;
                case 'item':
                    ##EDIT INSTANCE
                    #echo '<pre>';print_r($oldvalues);exit;
                    #Does this resource exist?
                    $instance_id = $element_id;
                    $info = $e_info;
                    $notes = $s3ql['set']['notes'];
                    $R = compact('info', 'inputs', 'oldvalues', 'db', 'user_id');
                    $validity = validateInputs(compact('element', 'inputs', 'oldvalues', 'info', 'db', 'action', 'key'));
                    if ($validity[0]) {
                        if (update_resource_instance($R)) {
                            return formatReturn('0', $element . " I" . $element_id . " updated", $s3ql['format'], '');
                            #$action = 'edit';
                            #$statement_info = $info;
                            #return ($output);
                        }
                    } else {
                        ereg('<error>([0-9]+)</error>(.*)<message>(.*)</message>', $validity[1], $valOut);
                        return formatReturn($valOut[1], $valOut[3], $s3ql['format'], '');
                        #return ($validity[1]);
                    }
                    break;
                case 'rule':
                    $rule_id = $element_id;
                    $info = $e_info;
                    if ($info['object'] == 'UID') {
                        if ($s3ql['where']['subject'] != '') {
                            #redirect to change class?
                            $res3ql = array_diff_key($s3ql, array('edit' => '', 'update' => ''));
                            $res3ql['where'] = array_diff_key($res3ql['where'], array('rule_id' => ''));
                            $res3ql = array_merge($res3ql, compact('db', 'user_id'));
                            $res3ql['edit'] = 'class';
                            $res3ql['where']['class_id'] = $info['subject_id'];
                            $done = S3QLaction($res3ql);
                            return $done;
                        } else {
                            return formatReturn($GLOBALS['error_codes']['wrong_input'], 'Rule ' . $element_id . ' cannot be edited. To change the subject of the relation please use edit class', $s3ql['format']);
                        }
                    } else {
                        #permission was verified before switch
                        if ($s3ql['set']['subject_id'] != '') {
                            #for log, need to keep track of old literal as well.
                            $oldvalues['subject'] = $info['subject'];
                            $class_info = s3info('class', $s3ql['set']['subject_id'], $db);
                            if (!is_array($class_info)) {
                                return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], 'Class ' . $s3ql['set']['subject_id'] . ' does not exist', $format, '');
                                #return ($something_does_not_exist.'<message>Class '.$s3ql['set']['subject_id'].' does not exist</message>');
                            }
                            $info['subject_id'] = $s3ql['set']['subject_id'];
                            $info['subject'] = $class_info['entity'];
                        } else {
                            if ($s3ql['set']['subject'] != '') {
                                $oldvalues['subject_id'] = $info['subject_id'];
                                #for log, need to keep track of old literal as well.
                                $info['subject_id'] = fastClassID(array('entity' => $s3ql['set']['subject'], 'project_id' => $project_id, 'db' => $db));
                            }
                        }
                        if ($s3ql['set']['verb_id'] != '') {
                            $oldvalues['verb'] = $info['verb'];
                            #for log, need to keep track of old literal as well.
                            $instance_info = URI('I' . $s3ql['set']['verb_id'], $user_id, $db);
                            if (!is_array($instance_info)) {
                                return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], 'Instance ' . $s3ql['set']['verb_id'] . ' does not exist', $s3ql['format'], '');
                            } else {
                                $info['verb'] = $instance_info['notes'];
                            }
                        } else {
                            #turn a literal verb into an instance of a class
                            #class exists in project? no? create it;else find it's
                            $VerbClass = projectVerbClass(array('project_id' => $info['project_id'], 'db' => $db, 'user_id' => $user_id));
                            if (!$VerbClass) {
                                $to_create = array('project_id' => $info['project_id'], 'entity' => 's3dbVerb', 'notes' => 'Collection created by S3DB for holding Verbs');
                                $inputs = gatherInputs(array('element' => 'collection', 'to_create' => $to_create, 'db' => $db, 'user_id' => $user_id));
                                $inserted = insert_s3db(array('element' => 'collection', 'inputs' => $inputs, 'user_id' => $user_id, 'db' => $db));
                                #try again;
                                $VerbClass = projectVerbClass(array('project_id' => $info['project_id'], 'db' => $db, 'user_id' => $user_id));
                            }
                            #now create the instanceVerb
                            if ($VerbClass == '') {
                                return formatReturn($GLOBALS['error_codes']['something_went_wrong'], 'Rule Could not be updated. No collection was found for the verbs', $s3ql['format'], '');
                            }
                            $inputs = array('resource_class_id' => $VerbClass['resource_id'], 'project_id' => $info['project_id'], 'notes' => $s3ql['where']['verb'] != '' ? $s3ql['where']['verb'] : $info['verb'], 'created_by' => $user_id, 'entity' => $VerbClass['entity'], 'status' => 'A');
                            $inserted = insert_s3db(array('element' => 'instance', 'inputs' => $inputs, 'user_id' => $user_id, 'db' => $db));
                            $info['verb_id'] = $inserted['instance_id'];
                            $info['verb'] = verb4instanceID(array('key' => $s3ql['key'], 'instance_id' => $info['verb_id'], 'db' => $db));
                            #echo '<pre>';print_r($info);exit;
                        }
                        if ($s3ql['set']['object_id'] != '') {
                            $oldvalues['object'] = $info['object'];
                            #for log, need to keep track of old literal as well.
                            $class_info = URI('C' . $s3ql['set']['object_id'], $user_id, $db);
                            if (!is_array($class_info)) {
                                return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], 'Collection ' . $s3ql['set']['object_id'] . ' does not exist', $s3ql['format'], '');
                            }
                            $info['object_id'] = $s3ql['set']['object_id'];
                            $info['object'] = $class_info['entity'];
                        } else {
                            if ($s3ql['set']['object'] != '') {
                                $oldvalues['object_id'] = $info['object_id'];
                                #for log, need to keep track of old literal as well.
                                $info['object_id'] = fastClassID(array('entity' => $s3ql['set']['object'], 'project_id' => $project_id, 'db' => $db));
                            }
                        }
                        $validity = validateInputs(compact('element', 'inputs', 'oldvalues', 'info', 'db', 'user_id', 'action', 'key'));
                        #echo '<pre>';print_r($info);exit;
                        if ($validity[0]) {
                            if (update_rule(compact('info', 'inputs', 'oldvalues', 'db', 'user_id'))) {
                                return formatReturn('0', $element . ' updated', $s3ql['format'], '');
                                #$output .= $validity[1].'<br><message>'.$element.' updated</message>';
                                #return ($output);
                            } else {
                                return formatReturn($validity[1], $validity[2], $format, '');
                            }
                        } else {
                            return formatReturn($validity[1], $validity[2], $format, '');
                        }
                    }
                    break;
                    #This closes edit rules
                case 'statement':
                    $statement_id = $element_id;
                    $value = $s3ql['set']['value'];
                    $notes = $s3ql['set']['notes'];
                    $rule_id = get_entry('statement', 'rule_id', 'statement_id', $statement_id, $db);
                    $object = get_entry('rule', 'object', 'rule_id', $rule_id, $db);
                    $statement_info = $e_info;
                    $project_id = $statement_info['project_id'];
                    $acl = find_final_acl($user_id, $project_id, $db);
                    #When the value is not being updated, use the old value for the update
                    if ($value == '') {
                        $value = $statement_info['value'];
                    }
                    if (!in_array('notes', array_keys($s3ql['set']))) {
                        $notes = $statement_info['notes'];
                    }
                    #Does the user have permission to change this statement?
                    if (!$statement_info['change']) {
                        return formatReturn($GLOBALS['error_codes']['no_permission_message'], "User does not have permission to change this statement", $s3ql['format'], '');
                    } elseif (resourceObject(array('rule_id' => $statement_info['rule_id'], 'project_id' => $project_id, 'db' => $db)) && !resource_found(array('rule_id' => $statement_info['rule_id'], 'user_id' => $user_id, 'project_id' => $project_id, 'value' => $value, 'db' => $db))) {
                        return formatReturn($GLOBALS['error_codes']['wrong_input'], "Value for this statement must be a valid resource_id from class " . $object, $s3ql['format'], '');
                    } elseif ($statement_info['filename'] != '') {
                        return formatReturn($GLOBALS['error_codes']['wrong_input'], "Statements that contain files must be deleted first and the updated version of the file uploaded", $s3ql['format'], '');
                    } elseif (!validate_statement_value($statement_info['rule_id'], $value, $db)) {
                        $rule_info = s3info('rule', $statement_info['rule_id'], $db);
                        return formatReturn($GLOBALS['error_codes']['wrong_input'], 'The rule of this statement requires validation. Please input value in the format: ' . $rule_info['validation'], $s3ql['format'], '');
                    } else {
                        $modified_by = $user_id;
                        #$oldvalues = array_filter($oldvalues);
                        #$inputs = array_filter($inputs);
                        #echo '<pre>';print_r($oldvalues);exit;
                        $S = compact('statement_id', 'statement_info', 'oldvalues', 'inputs', 'value', 'notes', 'modified_by', 'db', 'user_id');
                        $updated = update_statement($S);
                        if ($updated) {
                            return formatReturn($GLOBALS['error_codes']['success'], $element . " updated", $s3ql['format'], '');
                        } else {
                            return formatReturn($GLOBALS['error_codes']['something_went_wrong'], 'Statement update failed.', $s3ql['format'], '');
                        }
                    }
                    break;
            }
            #close switch element
            break;
            #close switch action
        #close switch action
        case 'delete':
            #echo '<pre>';print_r($s3ql);
            if ($s3ql['delete'] == 'class') {
                $s3ql['delete'] = 'collection';
            }
            if ($s3ql['delete'] == 'instance') {
                $s3ql['delete'] = 'item';
            }
            #echo '<pre>';print_r($s3ql);
            #map queries
            if ($s3ql['where']['resource_id'] != '') {
                if ($s3ql['delete'] == 'instance') {
                    $s3ql['where']['item_id'] = $s3ql['where']['resource_id'];
                } elseif ($s3ql['delete'] == 'class') {
                    $s3ql['where']['collection_id'] = $s3ql['where']['resource_id'];
                }
            }
            $element = $s3ql['delete'];
            $letter = letter($element);
            $possible = array('key', 'project', 'collection', 'rule', 'item', 'statement', 'user', 'group', 'permission');
            $D = compact('db', 'user_id', 's3ql');
            if (!in_array($element, array_keys($possible))) {
                #return $not_a_query;
                return formatReturn($GLOBALS['error_codes']['not_a_query'], $element . ' is not a valid s3db element.', $format, '');
            }
            #is there an ID to locate the appropriate resource?
            $element_id = $s3ql['where'][$element . '_id'];
            if ($element_id == '' && $element != 'permission') {
                return formatReturn($GLOBALS['error_codes']['something_missing'], 'Please specify ' . $element . '_id' . ' to delete', $format, '');
            }
            #return ($something_missing.'<message>Please specify '.$element.'_id'.' to delete</message>');
            $uid_info = uid($element_id);
            if (!ereg('^(U|G|P|C|R|I|S)', $uid_info['uid'])) {
                $uid_info['uid'] = strtoupper(substr($element, 0, 1)) . $uid_info['uid'];
            }
            $uid = $uid_info['uid'];
            #$e_info = URIinfo($uid['Did'].'/'.$uid['uid'],$user_id,$key, $db);
            #how many "deleateable" ids are on the query?
            $deleteable = array('group' => 'group_id', 'user' => 'user_id', 'project' => 'project_id', 'rule' => 'rule_id', 'collection' => 'collection_id', 'item' => 'item_id', 'statement' => 'statement_id');
            #scoreTable will allow us to score the elements according to their position in the inheritance model. To chose the correct permission level
            $scoreTable = array_reverse($deleteable, 0);
            $scoreTable = array_combine(array_keys($scoreTable), range(1, count($deleteable)));
            if (ereg('user|project|group', $element) && count(array_filter(array_diff_key($s3ql['where'], array($element . '_id' => '', 'confirm' => '')))) == 0) {
                $s3ql['where']['deployment_id'] = substr($GLOBALS['Did'], 1, strlen($GLOBALS['Did']));
                $info[$GLOBALS['Did']] = URI($GLOBALS['Did'], $user_id, $db);
                $permission2delete[$GLOBALS['Did']] = $info[$GLOBALS['Did']]['delete_data'];
                $core_score[$GLOBALS['Did']] = 8;
                #if(ereg('user|group', $element) && )
                #$s3ql['flag']='resource'; #delete just the resource 'user', 'group' or 'project';
            }
            #echo '<pre>';print_r($s3ql);exit;
            if (ereg('(user|group|project|collection|rule|item|statement|file|permission)', $element)) {
                foreach ($deleteable as $s3element => $id) {
                    #echo $s3element;
                    if ($s3ql['where'][$id] != '') {
                        #for this, this will allow removing 1 permission at a time.
                        $element_name = $s3element;
                        $id_name = $id;
                        $uid4info = uid($s3ql['where'][$id]);
                        #if(!ereg('^(U|G|P|C|I|S|R)', $letter))
                        $uid4info['uid'] = strtoupper(substr($element_name, 0, 1)) . $uid4info['uid'];
                        $uid2check = $uid4info['uid'];
                        $element_info = URIinfo($uid2check, $user_id, $key, $db);
                        $info[strtoupper(substr($element_name, 0, 1)) . $s3ql['where'][$id_name]] = $element_info;
                        $permission2delete[strtoupper(substr($element_name, 0, 1)) . $s3ql['where'][$id_name]] = $element_info['delete_data'];
                        $core_score[strtoupper(substr($element_name, 0, 1)) . $s3ql['where'][$id_name]] = $scoreTable[$element_name];
                        #when deleting a rule on a project, user does not need to be able to change the rule, he only needs to be able to change project.
                        #$core_score =
                        if (!is_array($element_info)) {
                            if ($uid4info['Did'] == $GLOBALS['Did']) {
                                return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], 'Resource ' . strtoupper(substr($element_name, 0, 1)) . $s3ql['where'][$id_name] . ' was not found', $format, '');
                            }
                        }
                    }
                }
                #echo '<pre>';print_r($info);exit;
            }
            #if user is unlinking a resource from another, he needs permission on the upstream one,
            #for example, owner of a porject that is deleting a rule from a project. The owner of the project who does not want to share the rule anymore should instead remove grant permissions from it. Similar as in "insert", but the other way around
            #the simplest case is when a user is "removing himself" from a resource - that is when flag is standard and there is only 1 s3id.
            #echo '<pre>';print_r($core_score);exit;
            if (ereg('(user|group|project|collection|rule|item|statement|file)', $element)) {
                if (count($core_score) == '1' || count($core_score) == '2' && $info[$GLOBALS['Did']] != '') {
                    $s3ql['flag'] = $s3ql['flag'] != '' ? $s3ql['flag'] : 'all';
                    #$uid2delete = key($permission2delete);
                    #when user requests to be removed from a resource, remove resource and all dependencies where user has access.
                    $children = array('deployment' => array('project', 'user', 'group'), 'user' => array(), 'group' => array(), 'project' => array('rule', 'collection'), 'rule' => array('statement'), 'collection' => array('item'), 'item' => array('statement'), 'statement' => array());
                    #even though deleting rule would mean deleting all statements on this class, permission on all statements must be verified as it is downstram
                    #while there are children, build dependencies. Some resources have + 1 child
                    $dependencies = array();
                    foreach ($children[$element] as $child) {
                        $Ds3ql = compact('user_id', 'db');
                        $Ds3ql['from'] = $child;
                        $Ds3ql['where'][$element . '_id'] = $element_id;
                        $tmp = S3QLaction($Ds3ql);
                        if (is_array($tmp)) {
                            $dep_resource[$child] = $tmp;
                        }
                        if (is_array($dep_resource[$child])) {
                            foreach ($dep_resource[$child] as $key => $Dinfo) {
                                $dep_key = strtoupper(substr($child, 0, 1)) . $Dinfo[$GLOBALS['s3ids'][$child]];
                                $info[$dep_key] = $Dinfo;
                                $dependencies[$dep_key] = $Dinfo;
                                #when deleitng any element the parent_id in this case will be the id we are trying to delete
                                if (!empty($children[$child])) {
                                    $Gs3ql = compact('user_id', 'db');
                                    $Gs3ql['from'] = $children[$child][0];
                                    $Gs3ql['where'][$child . '_id'] = $Dinfo[$child . '_id'];
                                    $tmp = S3QLaction($Gs3ql);
                                    if (is_array($tmp)) {
                                        $dep_resource[$children[$child][0]] = $tmp;
                                    }
                                }
                            }
                        }
                    }
                    #to avoid key = 0 on change, push the array 1 element forward.
                    $delete = array();
                    if (is_array($dependencies) && !empty($dependencies)) {
                        $delete = array_map('grab_delete', $dependencies);
                        $delete = array_combine(array_keys($dependencies), $delete);
                    }
                    #echo '<pre>';print_r($dep_resource);exit;
                    switch ($s3ql['flag']) {
                        case 'unlink':
                            #unlink from where?
                            $tounlink = array_filter(array_diff_key($s3ql['where'], array($GLOBALS['COREids'][$element] => '')));
                            if ($s3ql['where']['user_id'] != '') {
                                #remove another user
                                if (max($permission2delete) != '0') {
                                    $user_to_remove = $s3ql['where']['user_id'];
                                } else {
                                    return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User does not have permission to remove user ' . $s3ql['where']['user_id'] . ' from resource ' . key($permission2delete), $format, '');
                                    #return ($no_permission_message.'<message>User does not have permission to remove user '.$s3ql['where']['user_id'].' from resource '.key($permission2delete).'</message>');
                                }
                            } else {
                                $user_to_remove = $user_id;
                            }
                            #remove user from every dependency
                            foreach ($delete as $uid_depend => $allowed) {
                                #being allowed here is only going to affect removing another user that is not "self" from a resource
                                $dep_permission_info = array('uid' => $uid_depend, 'shared_with' => 'U' . $user_to_remove, 'permission_level' => '000');
                                if ($user_to_remove == $user_id && has_permission($dep_permission_info, $db) != '') {
                                    if (delete_permission(array('permission_info' => $dep_permission_info, 'db' => $db, 'info' => $info))) {
                                        #$output .= $success.'<message>User '.$user_to_remove.' removed from resource '.$uid_depend.'.</message><br>';
                                        $output .= formatReturn($GLOBALS['error_codes']['success'], 'User ' . $user_to_remove . ' removed from resource ' . $uid_depend, $format, '');
                                    }
                                } elseif ($user_to_remove != $user_id && $allowed && has_permission($dep_permission_info) != '') {
                                    if (delete_permission(array('permission_info' => $dep_permission_info, 'db' => $db, 'info' => $info))) {
                                        #$output .= $success.'<message>User '.$user_to_remove.' removed from resource '.$uid_depend.'.</message><br>';
                                        $output .= formatReturn($GLOBALS['error_codes']['success'], 'User ' . $user_to_remove . ' removed from resource ' . $uid_depend, $format, '');
                                    }
                                } elseif ($user_to_remove != $user_id && !$allowed) {
                                    #$output .= $success.'<message>User does not have permission to remove'.$user_to_remove.' from resource '.$uid_depend.'.</message><br>';
                                    $output .= formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User does not have permission to remove' . $user_to_remove . ' from resource ' . $uid_depend, $format, '');
                                }
                            }
                            #now remove the resource from user
                            $shared_with = array_search(max($core_score), $core_score);
                            $uid2remove = str_replace($GLOBALS['Did'] . '/', '', $uid);
                            if (ereg('^D', $shared_with)) {
                                #when shared_with is deploymet, we reach the highest level: remove user from tables.
                                deleteCoreResource($uid2remove, $user_id, $db);
                                insertLogs($uid2remove, $info, $user_id, $db);
                            }
                            #$uid = array_search(min($core_score), $core_score);
                            $permission_info = array('uid' => $uid2remove, 'shared_with' => 'U' . $user_to_remove, 'permission_level' => '000', 'info' => $info);
                            $has_permission = has_permission($permission_info, $db);
                            if ($has_permission != '' && $has_permission != '000') {
                                $done = delete_permission(compact('permission_info', 'db', 'user_id', 'info'));
                            } elseif ($has_permission == '') {
                                $done = insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                            }
                            if ($done || $has_permission == '000') {
                                $output .= formatReturn($GLOBALS['error_codes']['success'], 'User ' . $user_to_remove . ' removed from resource ' . key($permission2delete) . '.', $s3ql['format'], '');
                            } else {
                                $output .= formatReturn($GLOBALS['error_codes']['something_went_wrong'], 'User ' . $user_to_remove . ' was NOT removed from resource ' . key($permission2delete), $s3ql['format'], '');
                            }
                            $return_message = $output;
                            break;
                        case 'resource':
                            $uid2remove = str_replace($GLOBALS['Did'] . '/', '', $uid);
                            if (max($permission2delete) == '0') {
                                return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User does not have permission to remove user ' . $s3ql['where']['user_id'] . ' from resource ' . key($permission2delete) . ' If you want to remove this resource from view use flag "unlink"', $format, '');
                            } else {
                                #when user is actually deleting a resource, he must have "change" permission on it. He does not need "change" permission on all dependencies.
                                if (deleteCoreResource($uid2remove, $user_id, $db)) {
                                    $return_message = formatReturn($GLOBALS['error_codes']['success'], 'Resource ' . $uid . ' deleted. Resources that depend on ' . $uid . ' may still exist', $format, '');
                                    #if($s3ql['format']=='')
                                    #$return_message = ('<TABLE><TR><TD>error_code</TD><TD>message</TD></TR><TR><TD>'.ereg_replace('[^(0-9)]', '',$GLOBALS['messages']['success']).'</TD><TD>Resource '.$uid.' deleted. Resources that depend on '.$uid.' may still exist</TD></TR></TABLE>');
                                    #else
                                    #$return_message =  ($success.'<message>Resource '.$uid.' deleted. Resources that depend on '.$uid.' may still exist</message>');#not a hard core delete.
                                    insertLogs($uid, $info, $user_id, $db);
                                }
                            }
                            break;
                        case 'all':
                            if (max($permission2delete) == '0') {
                                return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User does not have permission to delete ' . $s3ql['where']['user_id'] . ' If you intend to remove this resource from your projects use flag "unlink"', $format, '');
                            } else {
                                #echo '<pre>';print_r($delete);exit;
                                #start deleting dependencies
                                foreach ($delete as $uid_depend => $allowed) {
                                    $permission_info = array('uid' => $uid_depend, 'shared_with' => 'U' . $user_id, 'permission_level' => '000');
                                    if ($allowed) {
                                        if (deleteCoreResource($uid_depend, $user_id, $db)) {
                                            $output .= formatReturn($GLOBALS['error_codes']['success'], '' . $uid_depend . ' deleted', $s3ql['format'], '');
                                            #if($s3ql['format']=='')
                                            #$output .= '<TABLE><TR><TD>error_code</TD><TD>message</TD></TR><TR><TD>'.ereg_replace('[^(0-9)]', '',$GLOBALS['messages']['success']).'</TD><TD>'.$uid_depend.' deleted</TD></TR></TABLE>';
                                            #else
                                            #$output .= $success.'<message>'.$uid_depend.' deleted</message><br>';
                                        } elseif (has_permission($permission_info, $db) != '') {
                                            if (delete_permission(compact('permission_info', 'db', 'user_id', 'info'))) {
                                                $output .= $success . '<message>Permission on ' . $uid_depend . ' removed for ' . $user_id . '</message><br>';
                                            }
                                        }
                                    }
                                    #echo '<pre>';print_r($info);exit;
                                    insertLogs($uid_depend, $info, $user_id, $db);
                                }
                                #Now delete everything that shared this collection in permission tables
                                $uid_info = uid($uid);
                                $sql = "delete from s3db_permission where uid = '" . $uid . "' or shared_with = '" . $uid . "'";
                                #echo $sql;exit;
                                $db->query($sql, __LINE__, __FILE__);
                                #and now delete the resource itseld
                                $uid = strtoupper(substr($element, 0, 1)) . $element_id;
                                if (deleteCoreResource($uid, $user_id, $db)) {
                                    $output .= formatReturn($GLOBALS['error_codes']['success'], $uid . ' deleted', $s3ql['format'], '');
                                    insertLogs($uid, $info, $user_id, $db);
                                } else {
                                    $output .= $something_went_wrong . '<message>Could not delete ' . $uid . '</message>';
                                }
                                $return_message = $output;
                            }
                            break;
                    }
                } elseif (count($core_score) > 1) {
                    if (ereg('^G', array_search(max($core_score), $core_score)) && array_search(min($core_score), $core_score) == 'U' . $user_id) {
                        $permission2delete[array_search(max($core_score), $core_score)] = '1';
                    }
                    #if the user is removing himself from group
                    if (max($permission2delete) == '0') {
                        return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User does not have permission to remove user ' . $s3ql['where']['user_id'] . ' from resource ' . key($permission2delete) . ' If you want to remove this resource from view use flag "unlink"', $format, '');
                    }
                    #can only pass if the user has access to remove data from the highest scored
                    $result = array_combine($core_score, $permission2delete);
                    #score as index and permissions as values
                    #a group and a user can be inserted in any one resource... as long as user does have permission on the resource
                    if (ereg('user|group', $element) && $result[min(array_keys($result))]) {
                        $result[max(array_keys($result))] = '1';
                    }
                    $double_permission = array('statement' => array('2', '4'));
                    #2 and 4 are the scores the statement needs in the score: rules and instances
                    if (in_array($element, array_keys($double_permission)) && min(array($result[$double_permission[$element][0]], $result[$double_permission[$element][1]])) == '0') {
                        $result = array_combine(array($double_permission[$element][0], $double_permission[$element][1]), array('0', '0'));
                    }
                    #result only checks upstream permissions, but is idB allowed to insert itself on idA?
                    if ($result[max(array_keys($result))] == '0') {
                        #this means the highest scored element does NOT have permission to delete
                        $ids = array_keys($permission2delete);
                        #some ids can be swapped, that is class is swapped with rule "hasUID" and instance is swapped with statement of rule "hasUID"
                        $swap = array('C' => 'rule_id', 'I' => 'statement_id');
                        foreach ($ids as $to_swap) {
                            if (in_array(substr($to_swap, 0, 1), array_keys($swap))) {
                                $letter = substr($to_swap, 0, 1);
                                $new_id = strtoupper(substr($swap[$letter], 0, 1)) . $info[$to_swap][$swap[$letter]];
                            } else {
                                $new_id = $to_swap;
                            }
                            $ids1[] = $new_id;
                        }
                        $ids = $ids1;
                        $recalc_permission2delete = $permission2delete;
                        $has_permission = has_permission(array('uid' => $ids[0], 'shared_with' => $ids[1]), $db);
                        if (ereg('2$', $has_permission) || ereg('1$', $has_permission) && $element_info['created_by'] == $user_id) {
                        }
                        #does the idB have insert permission on idA? Change the score :-)
                        $recalc_permission2delete[$ids[0]] = substr($has_permission, 2, 1);
                        #check again the result
                        $recalc_result = array_combine($core_score, $recalc_permission2delete);
                        #score as index and permissions as values
                        #echo '<pre>';print_r($recalc_result);exit;
                        if ($recalc_result[max(array_keys($recalc_result))] == '0') {
                            return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'User does not have permission to delete in resource ' . array_search('0', $permission2delete), $format, '');
                        }
                        #return ($GLOBALS['messages']['no_permission_message'].'<message>User does not have permission to delete in resource '.array_search('0', $permission2delete).'</message>');
                    }
                }
                #still there? Ok, we are ready to remove resource from another resource
                $shared_with = array_search(max($core_score), $core_score);
                $uid = array_search(min($core_score), $core_score);
                $return_message = removePermission(compact('uid', 'shared_with', 'db', 'info', 'user_id'));
                insertLogs($uid, $info, $user_id, $db);
                return $return_message;
            }
            #begin cases not considered in "deleteable" and those that need extra operations like rule_log and statement_log insertions
            switch ($element) {
                case 'key':
                    #DELETE KEY
                    #does this key belong to this user?
                    if ($user_id != '1' && $e_info['account_id'] != $user_id) {
                        return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'This key cannot be deleted', $format, '');
                        #return $no_permission_message."<message>This key cannot be deleted</message>";
                    }
                    $D['table'] = 'access_keys';
                    $D['element'] = 'key';
                    $D['element_id'] = $element_id;
                    $deleted = delete_element($D);
                    if ($deleted) {
                        return formatReturn($GLOBALS['error_codes']['success'], $element . " " . $element_id . " deleted", $format, '');
                        #$output .= $success;
                        #$output .= $element." deleted<BR>";
                        #$query = S3QLRestWrapper(array('key'=>$key));
                        #$output .= '<a href =" '.$query['url'].$query['s3ql'].'<select>*</select><from>'.$element.'s</from></S3QL>">List '.$element.'s</a>';
                        #return ($output);
                    } else {
                        return formatReturn($GLOBALS['error_codes']['something_went_wrong'], "Failed to delete key", $format, '');
                    }
                    break;
                case 'permission':
                    #DELETE PERMISSION
                    #permission to delete this permission was checked before switch
                    #it will delete permission from downstream resources via upstream but NOT the other way around.
                    $permission_info['shared_with'] = $s3ql['where']['user_id'] != '' ? 'U' . $s3ql['where']['user_id'] : array_search(max($core_score), $core_score);
                    $permission_info['uid'] = array_search(min($core_score), $core_score);
                    #delete only if user has permission to change.
                    $me = array('uid' => $permission_info['uid'], 'shared_with' => 'U' . $user_id, 'db' => $db, 'user_id' => $user_id);
                    $meOnUid = permission4resource($me);
                    $tmp = permission_level($meOnUid, $permission_info['uid'], $user_id, $db);
                    if (!$tmp['edit']) {
                        return formatReturn($GLOBALS['error_codes']['no_permission_message'], "User does not have permission to change " . $permission_info['uid'], $s3ql['format'], '');
                    }
                    if (delete_permission(compact('permission_info', 'db', 'info', 'user_id'))) {
                        insertLogs($permission_info['uid'], $info, $user_id, $db);
                        return formatReturn($GLOBALS['error_codes']['success'], 'Permission on ' . $permission_info['uid'] . ' removed', $format, '');
                    }
                case 'rule':
                    insert_rule_log(array('action' => 'delete', 'rule_info' => $info['R' . $element_id], 'oldvalues' => $info['R' . $element_id], 'inputs' => array(), 'db' => $db, 'user_id' => $user_id));
                    break;
                case 'statement':
                    break;
                case 'class':
                    break;
            }
            #finish switch eleent
            #finish delete
        #finish delete
        case 'grant':
            $permission_info['permission_level'] = $s3ql['grant'];
            $shareables = array('project' => 'project_id', 'rule' => 'rule_id', 'class' => 'class_id', 'instance' => 'instance_id', 'statement' => 'statement_id');
            $shared_with = array('project' => 'project_id', 'user' => 'user_id', 'group' => 'group_id');
            foreach ($shareables as $name => $id) {
                if ($s3ql['where'][$id] != '') {
                    $element_name = $name;
                    $id_name = $id;
                    $permission_info['uid'] = strtoupper(substr($name, 0, 1)) . $s3ql['where'][$id];
                    $permission_info['id'] = $s3ql['where'][$id];
                }
            }
            foreach ($shared_with as $name1 => $id1) {
                if ($s3ql['where'][$id1] != '') {
                    $element_name1 = $name1;
                    $id_name1 = $id1;
                    $permission_info['shared_with'] = strtoupper(substr($name1, 0, 1)) . $s3ql['where'][$id1];
                }
            }
            $permission_info['uid'] = $s3ql['on'] != '' ? $s3ql['on'] : ($permission_info['uid'] != '' ? $permission_info['uid'] : '');
            $permission_info['shared_with'] = $s3ql['to'] != '' ? $s3ql['to'] : ($permission_info['shared_with'] != '' ? $permission_info['shared_with'] : '');
            $permission_info['id'] = substr($permission_info['uid'], 1, strlen($permission_info['uid']));
            $info[$permission_info['uid']] = URI($permission_info['uid'], $user_id, $db);
            $info[$permission_info['shared_with']] = URI($permission_info['shared_with'], $user_id, $db);
            #validate the inputs
            $validity = validate_permission(compact('permission_info', 'user_id', 'db', 'info'));
            switch ($validity) {
                case 0:
                    #lets insert it
                    if (insert_permission(compact('permission_info', 'db', 'user_id', 'info', 'info'))) {
                        #if this the operation of sharing a rule by the owner of the rule. To remove later
                        if (ereg('^R', $permission_info['uid']) && ereg('^P', $permission_info['shared_with']) && !ereg('^0', $permission_info['permission_level'])) {
                            $res3ql = compact('user_id', 'db');
                            $res3ql['insert'] = 'rule';
                            $res3ql['where']['project_id'] = substr($permission_info['shared_with'], 1, strlen($permission_info['shared_with']));
                            $res3ql['where']['rule_id'] = substr($permission_info['uid'], 1, strlen($permission_info['uid']));
                            #$done = S3QLaction($s3ql);
                        }
                    }
                    return formatReturn($GLOBALS['error_codes']['success'], $permission_info['uid'] . ' was shared with ' . $permission_info['shared_with'] . ' with permission level ' . $permission_info['permission_level'], $format, '');
                    #return ($success.'<message>'.$permission_info['uid'].' was shared with '.$permission_info['shared_with'].' with permission level '.$permission_info['permission_level'].'</message>');
                    break;
                case 1:
                    return formatReturn($GLOBALS['error_codes']['wrong_input'], 'Please provide a 2 or 3 digit (range 0-2) permission_level value for this user:view/update/insert permission.' . $GLOBALS['messages']['syntax_message'], $format, '');
                    #return ($wrong_input.'<message>Please provide a 2 or 3 digit (range 0-2) permission_level value for this user:view/update/insert permission.'.$GLOBALS['messages']['syntax_message'].'</message>');
                    break;
                case 2:
                    #This means an update and not an insert is in order
                    if (update_permission(compact('permission_info', 'db', 'user_id', 'info'))) {
                        #if this the operation of sharing a rule -by the owner of the rule. To remove later
                        if (ereg('^R', $permission_info['uid']) && ereg('^P', $permission_info['shared_with']) && !ereg('^0', $permission_info['permission_level'])) {
                            #insert_rule_remotelly(array('project_id'=>$permission_info, 'rule_id'=>, 'db'=>$db));
                            $res3ql = compact('user_id', 'db');
                            $res3ql['insert'] = 'rule';
                            $res3ql['where']['project_id'] = substr($permission_info['shared_with'], 1, strlen($permission_info['shared_with']));
                            $res3ql['where']['rule_id'] = substr($permission_info['uid'], 1, strlen($permission_info['uid']));
                            #$done = S3QLaction($res3ql);
                        }
                    }
                    return formatReturn($GLOBALS['error_codes']['success'], $permission_info['uid'] . ' was shared with ' . $permission_info['shared_with'] . ' with permission level ' . $permission_info['permission_level'], $format, '');
                    #return ($success.'<message>'.$permission_info['uid'].' was shared with '.$permission_info['shared_with'].' with permission level '.$permission_info['permission_level'].'</message>');
                    break;
                case 3:
                    return formatReturn($GLOBALS['error_codes']['wrong_input'], 'Numeric part of uid must match id', $format, '');
                    #return ($wrong_input.'<message>numeric part of uid must match id</message>');
                    break;
                case 4:
                    return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], $permission_info['shared_with'] . ' was not found', $format, '');
                    break;
                case 5:
                    return formatReturn($GLOBALS['error_codes']['something_does_not_exist'], $permission_info['uid'] . ' was not found', $format, '');
                    break;
                case 6:
                    return formatReturn($GLOBALS['error_codes']['no_permission_message'], 'Please chose a level of permission that is equal or smaller than ' . $element_info['permission_level'] . '.', $format, '');
                    break;
                case 7:
                    return formatReturn($GLOBALS['error_codes']['wrong_input'], 'Permission cannot be specified on collection (C) or item (I)', $format, '');
                    break;
                case 8:
                    return formatReturn($GLOBALS['error_codes']['wrong_input'], 'uid to share or user to share with is empty', $format, '');
                    break;
            }
    }
    #close switch action
}
コード例 #13
0
function check_user_management2($C)
{
    extract($C);
    #Now let's check again if we have every necessary item
    #Project
    #$user_proj=array();
    $s3ql = compact('user_id', 'db');
    $s3ql['from'] = 'project';
    $s3ql['where']['name'] = $project_name;
    $s3ql['order_by'] = 'created_on desc';
    $done = S3QLaction($s3ql);
    if ($user_proj['project_id'] != "" && $user_proj['project_id'] != $done[0]['project_id']) {
        $user_proj = array();
        $user_proj['project_id'] = $done[0]['project_id'];
        unlink($GLOBALS['uploads'] . 'user_proj');
        $file_fill = 1;
        #this means that the project in file is not in sync with the proj on s3db
    } else {
        $user_proj['project_id'] = $done[0]['project_id'];
    }
    if ($done[0]['project_id'] == "") {
        $s3ql = compact('user_id', 'db');
        $s3ql['insert'] = 'project';
        $s3ql['where']['name'] = $project_name;
        $s3ql['format'] = 'php';
        $done = S3QLaction($s3ql);
        $msg = unserialize($done);
        $msg = $msg[0];
        $user_proj['project_id'] = $msg['project_id'];
        ##Make project data public
        $s3ql = compact('user_id', 'db');
        $s3ql['insert'] = 'user';
        $s3ql['where']['project_id'] = $user_proj['project_id'];
        $s3ql['where']['user_id'] = '2';
        $s3ql['where']['permission_level'] = 'nnnynn';
        $s3ql['format'] = 'php';
        $done = S3QLaction($s3ql);
        $msg = unserialize($done);
        $msg = $msg[0];
        if ($msg['project_id']) {
            $user_proj['project_id'] = $msg['project_id'];
        }
    }
    #Collections and Rules
    foreach ($important_collections as $name) {
        ##Now chceck for collections and rule; if there were created as part of the original file project, we don't need to create/check them again
        if ($file_fill || !$user_proj[strtolower($name)]['collection_id']) {
            $done = array();
            $s3ql = compact('user_id', 'db');
            $s3ql['from'] = 'collections';
            $s3ql['where']['project_id'] = $user_proj['project_id'];
            $s3ql['where']['name'] = $name;
            $done = S3QLaction($s3ql);
            if (!$done[0]['collection_id']) {
                $done = array();
                $s3ql = compact('user_id', 'db');
                $s3ql['insert'] = 'collection';
                $s3ql['where']['project_id'] = $user_proj['project_id'];
                $s3ql['where']['name'] = $name;
                $s3ql['format'] = 'php';
                $done = S3QLaction($s3ql);
                $msg = unserialize($done);
                $msg = $msg[0];
                $user_proj[strtolower($name)]['collection_id'] = $msg['collection_id'];
            } else {
                $user_proj[strtolower($name)]['collection_id'] = $done[0]['collection_id'];
            }
        }
    }
    foreach ($important_rules as $subName => $subNameRule) {
        foreach ($subNameRule as $ind => $rule_info) {
            $done = array();
            if ($file_fill || !$user_proj[$rule_info['object']]['rule_id']) {
                $s3ql = compact('user_id', 'db');
                $s3ql['from'] = 'rules';
                $s3ql['where']['project_id'] = $user_proj['project_id'];
                $s3ql['where']['subject'] = $subName;
                $s3ql['where']['verb'] = $rule_info['verb'];
                $s3ql['where']['object'] = $rule_info['object'];
                $done = S3QLaction($s3ql);
            }
            if (!$done[0]['rule_id']) {
                $done = array();
                $s3ql = compact('user_id', 'db');
                $s3ql['insert'] = 'rule';
                $s3ql['where']['project_id'] = $user_proj['project_id'];
                $s3ql['where']['subject_id'] = $user_proj[strtolower($subName)]['collection_id'];
                $s3ql['where']['verb'] = $rule_info['verb'];
                if (in_array($rule_info['object'], $important_collections)) {
                    $s3ql['where']['object_id'] = $user_proj[strtolower($rule_info['object'])]['collection_id'];
                } else {
                    $s3ql['where']['object'] = $rule_info['object'];
                }
                $s3ql['format'] = 'php';
                $done = S3QLaction($s3ql);
                $msg = unserialize($done);
                $msg = $msg[0];
                $user_proj[$rule_info['object']]['rule_id'] = $msg['rule_id'];
                $user_proj[strtolower($subName)]['rules'][$ind] = $msg['rule_id'];
                $user_proj[strtolower($subName)]['rule_objects'][$ind] = $s3ql['where']['object_id'] != '' ? $s3ql['where']['object_id'] : $s3ql['where']['object'];
                $user_proj[strtolower($subName)]['rule_object_is_id'][$ind] = $s3ql['where']['object_id'] != '' ? 1 : 0;
            } else {
                $user_proj[$rule_info['object']]['rule_id'] = $done[0]['rule_id'];
                $user_proj[strtolower($subName)]['rules'][$ind] = $done[0]['rule_id'];
                $user_proj[strtolower($subName)]['rule_objects'][$ind] = $s3ql['where']['object_id'] != '' ? $s3ql['where']['object_id'] : $s3ql['where']['object'];
                $user_proj[strtolower($subName)]['rule_object_is_id'][$ind] = $s3ql['where']['object_id'] != '' ? 1 : 0;
            }
            #Make statements in some authorities rule hidden from public
            if (eregi('serviceAccountPassword|serviceAccountUserName|Template', $rule_info['object'])) {
                $done = array();
                $s3ql = compact('user_id', 'db');
                $s3ql['insert'] = 'user';
                $s3ql['where']['rule_id'] = $user_proj[$rule_info['object']]['rule_id'];
                $s3ql['where']['user_id'] = '2';
                $s3ql['where']['permission_level'] = 'ynnN';
                $s3ql['format'] = 'php';
                $done = S3QLaction($s3ql);
                $msg = unserialize($done);
                $msg = $msg[0];
            }
        }
    }
    ##Items
    foreach ($default_items as $collection_name => $itemData) {
        foreach ($itemData as $itemNotes => $itemStatVals) {
            $done = array();
            if ($file_fill || $user_proj[strtolower($collection_name)]['items'][$itemNotes]['item_id'] == '') {
                $s3ql = compact('user_id', 'db');
                $s3ql['from'] = 'item';
                $s3ql['where']['collection_id'] = $user_proj[strtolower($collection_name)]['collection_id'];
                $s3ql['where']['notes'] = $itemNotes;
                $done = S3QLaction($s3ql);
            }
            if (!$done[0]['item_id']) {
                $s3ql['insert'] = 'item';
                $s3ql['where']['collection_id'] = $user_proj[strtolower($collection_name)]['collection_id'];
                $s3ql['where']['notes'] = $itemNotes;
                $s3ql['format'] = 'php';
                $done = S3QLaction($s3ql);
                $msg = unserialize($done);
                $msg = $msg[0];
                $user_proj[strtolower($collection_name)]['items'][$itemNotes]['item_id'] = $msg['item_id'];
            } else {
                $user_proj[strtolower($collection_name)]['items'][$itemNotes]['item_id'] = $done[0]['item_id'];
            }
            $jin++;
            if (is_array($itemStatVals)) {
                foreach ($itemStatVals as $objectName => $objectValue) {
                    $done = array();
                    if ($file_fill || $user_proj[strtolower($collection_name)][$itemNotes]['statements'][$objectName]['statement_id'] == '') {
                        $s3ql = compact('user_id', 'db');
                        $s3ql['from'] = 'statement';
                        $s3ql['where']['item_id'] = $user_proj[strtolower($collection_name)]['items'][$itemNotes]['item_id'];
                        #find the right rule_id
                        $right_rule_id = array_search($objectName, $user_proj[strtolower($collection_name)]['rule_objects']);
                        $s3ql['where']['rule_id'] = $user_proj[strtolower($collection_name)]['rules'][$right_rule_id];
                        #determine if the object value should be retrieved from another collection's items
                        if ($user_proj[strtolower($collection_name)]['rule_object_is_id'][$right_rule_id]) {
                            $s3ql['where']['value'] = $user_proj[strtolower($objectName)]['items'][$objectValue]['item_id'];
                        } else {
                            $s3ql['where']['value'] = $objectValue;
                        }
                        $done = S3QLaction($s3ql);
                    }
                    if (!$done[0]['statement_id']) {
                        $s3ql = compact('user_id', 'db');
                        $s3ql['insert'] = 'statement';
                        $s3ql['where']['item_id'] = $user_proj[strtolower($collection_name)]['items'][$itemNotes]['item_id'];
                        #find the right rule_id
                        $right_rule_id = array_search($objectName, $user_proj[strtolower($collection_name)]['rule_objects']);
                        $s3ql['where']['rule_id'] = $user_proj[strtolower($collection_name)]['rules'][$right_rule_id];
                        #determine if the object value should be retrieved from another collection's items
                        if ($user_proj[strtolower($collection_name)]['rule_object_is_id'][$right_rule_id]) {
                            $s3ql['where']['value'] = $user_proj[strtolower($objectName)]['items'][$objectValue]['item_id'];
                        } else {
                            $s3ql['where']['value'] = $objectValue;
                        }
                        $s3ql['format'] = 'php';
                        $done = S3QLaction($s3ql);
                        $msg = unserialize($done);
                        $msg = $msg[0];
                        $user_proj[strtolower($collection_name)][$itemNotes]['statements'][$objectName]['statement_id'] = $msg['statement_id'];
                        $user_proj[strtolower($collection_name)][$itemNotes]['statements'][$objectName]['value'] = $objectValue;
                    } else {
                        $user_proj[strtolower($collection_name)][$itemNotes]['statements'][$objectName]['statement_id'] = $done[0]['statement_id'];
                    }
                }
            }
        }
    }
    $user_proj['protocols']['names'] = array_keys($user_proj['protocols']['items']);
    $user_proj['protocols']['item_id'] = array();
    foreach ($user_proj['protocols']['names'] as $nm) {
        $user_proj['protocols']['item_id'][] = $user_proj['protocols']['items'][$nm]['item_id'];
    }
    file_put_contents($GLOBALS['uploads'] . 'user_proj', serialize($user_proj));
    return $user_proj;
}
コード例 #14
0
ファイル: sharerules.php プロジェクト: helenadeus/s3db.map
}
#project rules
$project_rules = array();
$s3ql = compact('user_id', 'db');
$s3ql['from'] = 'rules';
$s3ql['where']['project_id'] = $_REQUEST['project_id'];
$rules = s3list($s3ql);
if (is_array($rules)) {
    $project_rules = array_map('grab_rule_id', $rules);
}
#Get all the requests
$s3ql = compact('user_id', 'db');
$s3ql['select'] = '*';
$s3ql['from'] = 'requests';
#echo '<pre>';print_r($s3ql);
$allRequests = S3QLaction($s3ql);
#echo $allRequests;
$MyPending = $allRequests;
if (is_array($MyPending)) {
    foreach ($MyPending as $key => $user_request) {
        #those requests taht have nothing to do with this project can go
        if ($user_request['project_id'] != $_REQUEST['project_id']) {
            $MyPending = array_diff_key($MyPending, array($key => ''));
            if (in_array($user_request['rule_id'], $project_rules)) {
                $myRules[] = $user_request;
            }
        }
    }
}
##Print a list of pending requests
$columns = array('Requested By', 'Project Name', 'Rule_id', 'Rule', 'Notes', 'Status', 'Requested_on', 'Actions');
コード例 #15
0
ファイル: api.php プロジェクト: helenadeus/s3db.map
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 &lt;authentication_id&gt; or &lt;protocol&gt, &lt;authority&gt and &lt;username&gt', $_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 &lt;authentication_id&gt; 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);
                    }
                }
            }
        }
    }
}
コード例 #16
0
ファイル: insertall.php プロジェクト: helenadeus/s3db.map
function render_inserted_statement_all($I)
{
    extract($I);
    $_SESSION['current_color'] = '0';
    $_SESSION['previous_verb'] = '';
    $instance_id = $instance_info['resource_id'];
    $stats = '';
    if (is_array($rules)) {
        foreach ($rules as $rule_info) {
            $report_msg = '';
            $subject = $rule_info['subject'];
            $verb = $rule_info['verb'];
            $object = $rule_info['object'];
            $rule_id = $rule_info['rule_id'];
            $rule_notes = $rule_info['notes'];
            $notes = $_POST['text_' . $instance_id . '_' . $rule_id];
            $index = $index + 1;
            if (in_array($rule_id, $rule_ids)) {
                #echo 'upload_input_'.$instance_id.'_'.$rule_id.'<BR>';
                #gather data from post
                if ($_FILES['upload_input_' . $instance_id . '_' . $rule_id]['name'] == '') {
                    $value = $_POST['input_' . $instance_id . '_' . $rule_id];
                    if ($value == '') {
                        $value = $_POST['input_' . str_replace('.', '_', $instance_id) . '_' . str_replace('.', '_', $rule_id)];
                    }
                    #insert the statement, run S3QL
                    $s3ql = compact('db', 'user_id');
                    $s3ql['insert'] = 'statement';
                    #$s3ql['where']['project_id'] = $project_id;
                    $s3ql['where']['item_id'] = $instance_id;
                    $s3ql['where']['rule_id'] = $rule_id;
                    $s3ql['where']['value'] = $value;
                    $s3ql['where']['notes'] = $notes;
                    #$s3ql['format']='html';
                    $done = S3QLaction($s3ql);
                    $done = html2cell($done);
                    #ereg('<error>([0-9]+)</error>.*<(message|statement_id)>(.*)</(message|statement_id)>', $done, $s3qlout);
                    $statement_id = $done[2]['statement_id'];
                    $S = compact('user_id', 'rule_info', 'instance_id', 'statement_id', 'value', 'notes', 'db', 'done');
                    if ($done[2]['error_code'] == '0') {
                        $report_msg = render_inserted($s3ql, $statement_id);
                        #$report_msg .= sprintf("%s\n", '		<br /><input type="button" value="Insert Another" onClick="window.location=\''.$action['instanceform'].'\'">');
                        #$report_msg .= sprintf("%s\n", '		<br /><input type="button" value="Close Window" onClick="window.location=\''.$action['instanceform'].'\'">');
                    } else {
                        $report_msg = couldnot_insert_statement($S);
                        #render_statement_already_exists($s3ql);
                    }
                    #elseif($s3qlout[1]=='7')
                    #{
                    #$report_msg = render_resource_doesnot_exist($s3ql);
                    #}
                    #elseif($s3qlout[1]=='3')
                    #{
                    #$report_msg = render_value_cannot_be_null($s3ql);
                    #}
                } else {
                    #project is the same that will go to instance
                    $project_id = $rule_info['project_id'];
                    $value = project_folder_name($project_id, $db);
                    $notes = $_REQUEST['text_' . $instance_id . '_' . $rule_id];
                    $filename = $_FILES['upload_input_' . $instance_id . '_' . $rule_id]['name'];
                    $mimetype = $_FILES['upload_input_' . $instance_id . '_' . $rule_id]['type'];
                    $filesize = filesize($_FILES['upload_input_' . $instance_id . '_' . $rule_id]['tmp_name']);
                    $uploadedfile = $_FILES['upload_input_' . $instance_id . '_' . $rule_id]['tmp_name'];
                    if ($filesize <= 0) {
                        $report_msg = 'Filesize cannot be null';
                    } elseif ($filename == '') {
                        $report_msg = 'Filename cannot be empty';
                    } elseif ($value == '' || $uploadedfile == '') {
                        $report_msg = 'Could not move file, please check with you administrator if file uploads are allowed.';
                    } else {
                        $tmp = fileNameAndExtension($filename);
                        extract($tmp);
                        #write a filekey to send the file by the API
                        $filekey = generateAFilekey(compact('filename', 'extension', 'filesize', 'user_id', 'db'));
                        #move the file like the API would do
                        $file = $uploadedfile;
                        $fileMoved = MoveFile(compact('filekey', 'db', 'file'));
                        #generate a statement_id
                        if ($fileMoved) {
                            $s3ql = compact('db', 'user_id');
                            $s3ql['insert'] = 'file';
                            $s3ql['where']['filekey'] = $filekey;
                            $s3ql['where']['notes'] = $notes;
                            $s3ql['where']['project_id'] = $project_id;
                            $s3ql['where']['rule_id'] = $rule_id;
                            $s3ql['where']['item_id'] = $instance_id;
                            $s3ql['format'] = 'html';
                            $done = S3QLaction($s3ql);
                            $done = html2cell($done);
                            #echo '<pre>';print_r($done);
                            #ereg('<statement_id>([0-9]+)</statement_id>', $done, $s3qlout);
                            $statement_id = $done[2]['file_id'];
                            if ($statement_id != '') {
                                $insert = 'file';
                                $S = compact('rule_id', 'instance_id', 'db', 'insert', 'filename');
                                $report_msg = render_inserted($S, $statement_id);
                            }
                        } else {
                            $report_msg = "<font color='red'>Could not move the file</font>";
                            exit;
                        }
                    }
                }
            } else {
                $report_msg = render_empty_form(compact('index', 'rule_info', 'project_id', 'instance_id', 'db'));
            }
            $finalOutput .= $report_msg;
        }
    }
    //echo $stats;
    return $finalOutput;
}
コード例 #17
0
ファイル: s3db.php プロジェクト: helenadeus/s3db.map
    $format = 'html';
}
$s3ql['format'] = $format;
#these represent all the queries that can be performed on the tables
$table = $GLOBALS['s3tables'][$s3ql['from']];
if ($s3ql['insert'] == 'user' && $s3ql['where']['password'] != '') {
    echo formatReturn('6', 'Password cannot be inserted via the API. Please leave this field empty and a random password will be sent to the user\'s email', $format, '');
}
if (($s3ql['edit'] == 'user' || $s3ql['update'] == 'user') && ($s3ql['set']['password'] != '' || $s3ql['set']['email'] != '')) {
    echo formatReturn('6', 'Password and email cannot be changed via the API.', $format, '');
}
#input the struct into the S3QLaction function
$s3ql['db'] = $db;
$s3ql['user_id'] = $user_id;
#echo 'ola';exit;
$s3qlOut = S3QLaction($s3ql);
#echo '<pre>';print_r($s3ql);
#echo '<pre>';print_r($s3qlOut);
if (!is_array($s3qlOut)) {
    echo $s3qlOut;
    exit;
}
#When the result is an array, rules or any other, run display to give values as tab delimited
#if(is_array($s3qlOut))
#echo '<pre>';print_r($s3qlOut);
$data = $s3qlOut;
$letter = letter($s3ql['from']);
$t = $GLOBALS['s3codes'][$letter];
$t = $GLOBALS['plurals'][$t];
#if($s3ql['select']!='*'){
#$toreplace = array_keys($GLOBALS['s3map'][$t]);
コード例 #18
0
function deleteCoreResource($uid, $user_id, $db)
{
    #function deleteCoreResource performs very simple deleteResource queries - given a uid, it retrieves a table and the correct numeric id to delete.
    $s3codes = $GLOBALS['s3codes'];
    $s3tables = $GLOBALS['s3tables'];
    $s3ids = $GLOBALS['s3ids'];
    $messages = $GLOBALS['message'];
    $uid_info = uid($uid);
    $letter = letter($uid);
    $table = $s3codes[$letter];
    if ($table == '') {
        return substr($uid_info['uid'], 0, strlen($uid_info['uid'])) . ' is not a valid resource identifyer';
    }
    #map resource to the right table
    $table_id = $s3ids[$table];
    $table = $s3tables[$table];
    #numeric id
    $num_id = ltrim(str_replace($GLOBALS['Did'] . '/', '', $uid), $letter);
    #$sql = "delete from s3db_".$table." where ".$table_id." = '".$num_id."'";
    switch ($letter) {
        case 'I':
            #also, for every item there is a "has UID" statement that needs to be deleted. But the rule is being deleted when the collection is deleted (from item). So items and statemnts need to be deleted first
            if ($num_id != '') {
                $SQL = "select statement_id from s3db_statement where rule_id in (select rule_id from s3db_rule where verb = 'has UID' and object = 'UID') and resource_id = '" . $num_id . "'";
                $db->query($SQL);
                if ($db->next_record()) {
                    $stat2delete = $db->f('statement_id');
                    $sql1 = "delete from s3db_statement where statement_id = '" . $stat2delete . "'";
                    $db->query($sql1);
                    $sql2 = "delete from s3db_permission where uid = 'S" . $stat2delete . "' or shared_with = 'S" . $stat2delete . "'";
                    #echo $sql2.'<BR>';
                    $db->query($sql2);
                }
            }
            $instance_info = URI($uid, $user_id, $db);
            $s3ql = compact('user_id', 'db');
            $s3ql['select'] = '*';
            $s3ql['from'] = 'statements';
            $s3ql['where']['value'] = $num_id;
            $stats_to_delete = S3QLaction($s3ql);
            if (is_array($stats_to_delete)) {
                foreach ($stats_to_delete as $sInd => $stat_info) {
                    if ($stat_info['object_id'] == $instance_info['resource_class_id'] && $stat_info['delete']) {
                        $s3ql = compact('user_id', 'db');
                        $s3ql['delete'] = 'statement';
                        $s3ql['where']['statement_id'] = $stat_info['statement_id'];
                        S3QLaction($s3ql);
                    }
                }
            }
            break;
        case 'C':
            #remove also the rule "hasUID"
            if ($num_id != '') {
                $rule_has_UID_sql = "delete from s3db_rule where subject_id = '" . $num_id . "' and object='UID' and verb='has UID'";
                $db->query($rule_has_UID_sql, __LINE__, __FILE__);
            }
            break;
    }
    #after dependencies are deleted, delete the resource
    $sql = "delete from s3db_" . $table . " where " . $table_id . " = '" . $num_id . "'";
    #echo $sql.'<BR>';
    $db->query($sql);
    ##Now delete this id in the permissions table
    #
    if ($uid != '') {
        $deleteSQL = "delete from s3db_permission where uid='" . $uid . "' or shared_with = '" . $uid . "'";
        $db->query($deleteSQL);
    }
    $dbdata = get_object_vars($db);
    if ($dbdata['Errno'] == 0) {
        return True;
    } else {
        return False;
    }
}
コード例 #19
0
ファイル: collection.php プロジェクト: helenadeus/s3db.map
    $s3ql['where']['project_id'] = $_REQUEST['project_id'];
}
if ($_REQUEST['orderBy']) {
    $s3ql['order_by'] = $_REQUEST['orderBy'] . ' ' . $_REQUEST['direction'];
}
#echo '<pre>';print_r($s3ql);
$rules = S3QLaction($s3ql);
if ($resource_info['view']) {
    #include all the javascript functions for the menus...
    include 'S3DBjavascript.php';
    #and the short menu for the resource script
    include 'action.header.php';
    $s3ql = compact('user_id', 'db');
    $s3ql['from'] = 'users';
    $s3ql['where']['class_id'] = $class_id;
    $users = S3QLaction($s3ql);
    ?>

<table  border=0 class="intro" width="100%"  align="center">
	<br /><br />
	<tr bgcolor="#CCFF99"><td colspan="3" align="center" >Collection Details</FONT></td></tr>
	<tr class="">
		<td width="20%">Resource Name: </td>
	<?php 
    echo '<td><b>' . $resource_info['entity'] . '</b>&nbsp;&nbsp;&nbsp;&nbsp;';
    if ($resource_info['change']) {
        if ($uid_info['Did'] == $GLOBALS['Did']) {
            echo '<a href="' . $action['editclass'] . '">Edit</a>&nbsp;&nbsp;&nbsp;&nbsp;';
        }
        echo '<a href="' . $action['deleteclass'] . '">Delete</a></td>';
    }
コード例 #20
0
ファイル: s3ql.header.php プロジェクト: helenadeus/s3db.map
function insert_remote_user($account_info, $url)
{
    $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 will be self created, so to distinguish from the ones admin created, change account_type. To make it faster, i'm using s3qlaction that checks user validity, etc, but it might be safer to just create user directly on the sql
    $user_id = '1';
    $s3ql = compact('user_id', 'db');
    $s3ql['insert'] = 'user';
    $s3ql['where']['login'] = $url . '#' . $account_info['account_lid'];
    $s3ql['where']['email'] = '*****@*****.**';
    $s3ql['where']['username'] = $account_info['account_uname'];
    $s3ql['where']['account_group'] = 'r';
    #r as in remote
    #echo '<pre>';print_r($s3ql);
    $done = S3QLaction($s3ql);
    ereg('<message>(.*)</message><user_id>([0-9]+)</user_id>', $done, $s3qlout);
    $user_id = $s3qlout[2];
    if ($user_id != '') {
        return $user_id;
    } else {
        return $done;
    }
}
コード例 #21
0
ファイル: xlsproject.php プロジェクト: helenadeus/s3db.map
 } else {
     $start = 0;
     $end = count($instances);
 }
 $kk = 0;
 $end = count($instances) < $end ? count($instances) : $end;
 if (is_array($instances)) {
     for ($k = $start; $k < $end; $k++) {
         $st = array_merge($uni, array('resource_id' => $instances[$k]['resource_id'], 'object' => '!=UID'));
         #$all_values = get_all_statements($st);
         if (!is_array($instances[$k]['stats'])) {
             $s3ql = compact('user_id', 'db');
             $s3ql['select'] = '*';
             $s3ql['from'] = 'statements';
             $s3ql['where']['instance_id'] = $instances[$k]['resource_id'];
             $all_values = S3QLaction($s3ql);
             $_SESSION['queryresult'][$k]['stats'] = $all_values;
         } else {
             $all_values = $instances[$k]['stats'];
         }
         #echo '<pre>';print_r($s3ql);
         #echo '<pre>';print_r($all_values);exit;
         #reset rule keys
         $statSum = $statSum + count($all_values);
         #echo '<pre>';print_r($all_values);
         $row = $kk + 3 + $addtoNextRow;
         #resources with statements, put an lines for more than 1 stat per rule
         $n = get_max_num_values($all_values, $rules) == 0 ? 1 : get_max_num_values($all_values, $rules);
         for ($m = 0; $m < $n; $m++) {
             ##Resource_id and notes in the first and seecond col
             $subrow = $row + $m;
コード例 #22
0
ファイル: rdfproject.php プロジェクト: helenadeus/s3db.map
 #for ($i=0;$i<count($coreElements), $i++)
 $s3ql = compact('user_id', 'db');
 foreach ($coreElements as $element) {
     $cols = $dbstruct[$element];
     if ($element != 'project') {
         $cols = array_diff($cols, array('project_id', 'permission'));
     } else {
         if ($element == 'class') {
             $iid = '0';
         } elseif ($element == 'instance') {
             $iid = '1';
         }
     }
     $s3ql['from'] = $element;
     $s3ql['where']['project_id'] = $project_id;
     $D[$element] = S3QLaction($s3ql);
     #$D[$element]= listS3DB(array('user_id'=>$user_id,'db'=>$db,'table'=>$element, 'cols'=>$cols, 'project_id'=>"~ '^".$project_id."$'",'permission'=>"~ '(^|_)".$project_id."_'", 'iid'=>$iid));
     #echo '<pre>';print_r($D[$element]);
     if (is_array($D[$element])) {
         if ($element == 'statements') {
             $D[$element] = array_map('grab_class_instance_id', $D[$element]);
             $D[$element] = array_filter(array_map('delete_empty_statements', $D[$element]));
             #must ignore statements with no value
         } elseif ($element == 'rules') {
             $D[$element] = include_class_id($D[$element], $db);
             #whenever the element is a rule, replace the subject with a class
             $D[$element] = include_object_class_id($D[$element], $project_id, $db);
         } elseif ($element == 'instances') {
             $D[$element] = include_instance_class_id($D[$element], $project_id, $db);
         }
         #whenever the element is a rule, replace the subject with a class
コード例 #23
0
ファイル: accesslog.php プロジェクト: helenadeus/s3db.map
#Helena F Deus (helenadeus@gmail.com)
include 'adminheader.php';
$section_num = '2';
$website_title = $GLOBALS['s3db_info']['server']['site_title'] . ' - access log';
$site_intro = $GLOBALS['s3db_info']['server']['site_intro'];
$manager = 'Access Log';
$content_width = '80%';
$s3ql = compact('user_id', 'db');
$s3ql['select'] = '*';
$s3ql['from'] = 'accesslog';
if ($_REQUEST['orderBy'] != '') {
    $s3ql['order_by'] = $_REQUEST['orderBy'] . ' ' . $_REQUEST['direction'];
} else {
    $s3ql['order_by'] = 'login_timestamp desc';
}
$logs = S3QLaction($s3ql);
#echo '<pre>';print_r($logs);exit;
if (count($logs) > 0) {
    $data_grid = render_elements($logs, '', array('Login ID', 'Login From', 'Login Time'), 'accesslog');
}
include S3DB_SERVER_ROOT . '/s3style.php';
include S3DB_SERVER_ROOT . '/tabs.php';
?>
<!-- BEGIN top -->

<table class="top" align="center">
	<tr><td>
		<table class="insidecontents" align="center" width="<?php 
echo $content_width;
?>
">
コード例 #24
0
ファイル: htmlgen.php プロジェクト: helenadeus/s3db.map
function aclGrid($Z)
{
    #acGid prints the grid with the permission codes
    #input:$Z=compact('user_id', 'db');
    extract($Z);
    #CREATE THE HEADER AND SET THE TPL FILE
    if (!$users) {
        $s3ql = compact('user_id', 'db');
        $s3ql['select'] = '*';
        $s3ql['from'] = 'groups';
        $s3ql['where']['user_id'] = $user_id;
        $done = S3QLaction($s3ql);
        $groups = $done;
        #Got the groups, now figure out the users
        $users = array();
        if (is_array($groups)) {
            foreach ($groups as $group_info) {
                $s3ql = compact('user_id', 'db');
                $s3ql['select'] = '*';
                $s3ql['from'] = 'users';
                $s3ql['where']['group_id'] = $group_info['account_id'];
                if ($_REQUEST['orderBy'] != '') {
                    $s3ql['order_by'] = $_REQUEST['orderBy'] . ' ' . $_REQUEST['direction'];
                }
                $done = S3QLaction($s3ql);
                if (is_array($done)) {
                    foreach ($done as $user) {
                        array_push($users, $user);
                    }
                }
            }
        }
    }
    #replace the 0,1,2... of the array bu the account Id for making sure we get a unique list
    if (is_array($users) && !empty($users)) {
        $how_many = count($users);
        $datagrid = render_elements($users, $acl, array('User ID', 'Login', 'User Name', 'Access Control List'), 'account_acl', $new, $uid, $how_many);
    }
    return $datagrid;
}
コード例 #25
0
ファイル: project.php プロジェクト: helenadeus/s3db.map
    #$project_actions .= '<input type="button" value="Export Project in RDF" size="20" onClick="window.location=\''.$action['rdfexport'].'\'">&nbsp;&nbsp;&nbsp;';
    $project_actions .= '<input type="button" value="RDF" size="20" onClick="window.open(\'' . $action['rdfmenu'] . '\',null,\'height=350,width=400,resizable=1,scrollbars=1\')">&nbsp;&nbsp;&nbsp;';
    $project_actions .= '<BR></TABLE></center>';
    echo '<table  border=0 class="intro" width="100%"  align="center">
		<tr  bgcolor="#99CCFF"><td  colspan="3" align="center"><FONT Face="Arial" SIZE="3" COLOR="navy">Export</td></tr>';
    echo '<tr><td>' . $project_actions . '</tr></td>';
    #Find all the users involved in the project
    #$P = compact('db', 'user_id', 'project_id', 'sortorder', 'direction');
    #$shared_users = list_project_users($P);
    #$shared_users = list_shared_users($uni);
    if (is_array($_SESSION[$user_id]['users'][$project_id])) {
        $shared_users = $_SESSION[$user_id]['users'][$project_id];
    } else {
        $s3ql = compact('user_id', 'db');
        $s3ql['select'] = '*';
        $s3ql['from'] = 'users';
        $s3ql['where']['project_id'] = $project_id;
        if ($_REQUEST['orderBy'] != '') {
            $s3ql['order_by'] = $_REQUEST['orderBy'] . ' ' . $_REQUEST['direction'];
        }
        $shared_users = S3QLaction($s3ql);
        #$_SESSION[$user_id]['users'][$project_id] = $shared_users;
    }
    #increment with the owner and the user that is visualizing the project
    if (is_array($shared_users) && !empty($shared_users)) {
        echo '<table  border=0 class="intro" width="100%"  align="center">
			<tr  bgcolor="#99CCFF"><td  colspan="3" align="center"><FONT Face="Arial" SIZE="3" COLOR="navy">Users</td></tr>';
        echo render_elements($shared_users, $acl, array('Login', 'User Name', 'Permissions'), 'account_acl');
    }
}
include 'footer.php';
コード例 #26
0
ファイル: datamatrix.php プロジェクト: helenadeus/s3db.map
function render_datamatrix_values($vals)
{
    $action = $GLOBALS['webaction'];
    extract($vals);
    $color = $_REQUEST['color'];
    $format = $_REQUEST['format'];
    $parser = get_parser_characters($format);
    $rows = '';
    $items = $instances;
    //		if($_REQUEST['num_per_page']!='' && $_REQUEST['current_page']!='')
    //			{
    //			$start = (($_REQUEST['current_page']-1)*$_REQUEST['num_per_page']);
    //			$end=($_REQUEST['num_per_page']*$_REQUEST['current_page']);
    //			}
    //			else {
    //				$start = 0;
    //				$end= count($items);
    //		}
    #if(is_array($matched_resource))
    for ($i = $start; $i < $end; $i++) {
        $item_id = $items[$i]['item_id'];
        if (!is_array($items[$i]['stats'])) {
            $row = '';
            $s3ql = compact('db', 'user_id');
            $s3ql['select'] = '*';
            $s3ql['from'] = 'statements';
            $s3ql['where']['item_id'] = $item_id;
            $all_values = S3QLaction($s3ql);
        } else {
            $all_values = $items[$i]['stats'];
        }
        #echo '<pre>';print_r($all_values);exit;
        if (is_array($all_values) && !empty($all_values)) {
            #replace values with filelinks and find the notes for the buttons
            $all_values = include_button_notes($all_values, $project_id, $db);
            $all_values = Values2Links($all_values);
        }
        if (count($all_values) == '0') {
            if ($color == 'on') {
                if ($total % 2 == 0) {
                    $row = sprintf("%s\n", '		<tr bgcolor="AliceBlue">');
                } else {
                    $row = sprintf("%s\n", $parser['tr']);
                }
                #$all_values = include_button_notes($all_values, $project_id, $db);
                #In case color is on, it means we are trying to achieve one of the interactive, user-friendly interfaces. Therefore, resource should come in the format of a button. Need to be dealt with care in case
                $resource_id_button = '<input type="button" size="10" value="' . str_pad($item_id, 6, '0', STR_PAD_LEFT) . '" onClick="window.open(\'' . $action['item'] . '&item_id=' . $item_id . '\', \'_blank\', \'width=700, height=600, location=no, titlebar=no, scrollbars=yes, resizable=yes\')">';
            } else {
                $resource_id_button = $item_id;
            }
            $subrow = '';
            $subrow .= sprintf("%s", $parser['td'] . $resource_id_button . $parser['end_td']);
            $subrow .= sprintf("%s", $parser['td'] . $items[$i]['notes'] . $parser['end_td']);
            #Moving on to the data on the rules, since there are no values on this row, print only opening and ending the cell
            if (is_array($rules)) {
                foreach ($rules as $j => $value) {
                    $subrow .= sprintf("%s", $parser['td'] . $parser['end_td']);
                }
            }
            $subrow .= sprintf("%s", $parser['end_tr']);
            $row .= $subrow;
            $total += 1;
        } else {
            $n = get_max_num_values($all_values, $rules) == 0 ? 1 : get_max_num_values($all_values, $rules);
            #$n will determine the number of lines for this item
            $total = 0;
            $row = '';
            for ($m = 0; $m < $n; $m++) {
                //$row ='';
                if ($_REQUEST['color'] == 'on') {
                    #if($total%2==0)
                    #$row .=sprintf("%s\n", '<tr bgcolor="AliceBlue">');}
                    #else
                    #$row .=sprintf("%s\n", $parser['tr']);
                    $resource_id_button = '<input type="button" size="10" value="' . str_pad($item_id, 6, '0', STR_PAD_LEFT) . '" onClick="window.open(\'' . $action['item'] . '&item_id=' . $item_id . '\', \'_blank\', \'width=700, height=600, location=no, titlebar=no, scrollbars=yes, resizable=yes\')">';
                } else {
                    $resource_id_button = $item_id;
                }
                $row .= sprintf("%s", $parser['tr']);
                $subrow = '';
                $subrow .= sprintf("%s", $parser['td'] . $resource_id_button . $parser['end_td']);
                $subrow .= sprintf("%s", $parser['td'] . $items[$i]['notes'] . $parser['end_td']);
                #if($item_id=='3783'){ echo $row ;  exit;}
                //print_r($rules);
                if (is_array($rules)) {
                    foreach ($rules as $j => $value) {
                        $rule_id = $rules[$j]['rule_id'];
                        $values = get_value_by_rule($all_values, $rule_id);
                        if ($format == 'html' && $color == 'on') {
                            $value = viewStatementValue($values[$m]);
                        } else {
                            $value = $values[$m]['value'];
                        }
                        if ($value != '') {
                            $subrow .= sprintf("%s", $parser['td'] . $value . $parser['end_td']);
                        } else {
                            $subrow .= sprintf("%s", $parser['td'] . $parser['end_td']);
                        }
                    }
                }
                $subrow .= sprintf($parser['end_tr']);
                $row .= $subrow;
            }
            $rows .= $row;
        }
    }
    $rows .= sprintf($parser['end_table']);
    return $rows;
}
コード例 #27
0
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');
    $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();
    #do a query on user to find useremail
    $sql = "select account_id,account_email from s3db_account where account_lid='" . $username . "' and account_type " . $GLOBALS['regexp'] . " '^(u|a|r)\$'";
    $db->query($sql, __LINE__, __FILE__);
    if ($db->next_record()) {
        $email = $db->f('account_email');
        $user_id = $db->f('account_id');
    } else {
        header('Location:login.php?error=9&login='******'user_id', 'db');
    $s3ql['insert'] = 'key';
    $s3ql['where']['expires'] = date('Y-m-d H:i:s', time() + 1 * 1 * 60 * 60);
    $s3ql['where']['notes'] = 'Temporary key generated automatically for password recovery';
    $s3ql['format'] = 'php';
    $done = S3QLaction($s3ql);
    $msg = unserialize($done);
    $msg = $msg[0];
    #send an email to user with a link to change profile by using this temporary key
    $key_id = $msg['key_id'];
    if ($key_id != '') {
        if ($_SERVER['HTTP_X_FORWARDED_HOST'] != '') {
            $def = $_SERVER['HTTP_X_FORWARDED_HOST'];
        } else {
            $def = $_SERVER['HTTP_HOST'];
        }
        if ($_SERVER['https'] == 'on') {
            $http = 'https://';
        } else {
            $http = 'http://';
        }
        $url = $action['edituser'] . '&key=' . $key_id . '&id=' . $user_id;
        $message .= sprintf("%s\n\n", 'Dear ' . $username);
        $message .= sprintf("%s\n", 'A password reset was requested for your account');
        $message .= sprintf("%s\n", 'To reset your account go to ' . $url);
        $message .= sprintf("%\n\n", 'This link will expire in 1 hour');
        $message .= sprintf("%s\n", 'The S3DB team.(http://www.s3db.org)');
        $message .= sprintf("%s\n\n", 'Note: Please do not reply to this email, this is an automated message');
        $subject = 'Your S3DB account - lost password request';
        if ($email == '') {
            return False;
        } else {
            $tosent = compact('email', 'subject', 'message');
            send_email($tosent);
        }
        #redirect back to login
        header('Location:' . $action['login'] . '?error=10');
    }
    #once the user logs in delete this temporary key (maybe put a pattern on it, such that a temporary key is always recognized)
}
コード例 #28
0
ファイル: move2s3db.php プロジェクト: helenadeus/s3db.map
function findFileItemId($file, $user_id, $db)
{
    ### => This part to uncomment once queries are made faster
    #Is there an item with this path value on path rule?
    /*
    $s3ql=compact('user_id','db');
    $s3ql['select']='*';
    $s3ql['from']='statements';
    $s3ql['where']['rule_id']=$GLOBALS['update_project']['path']['rule_id'];
    $s3ql['where']['file_name']=$path;
    #$s3ql['where']['value']=base64_encode($file);
    $s3ql['where']['local']=1;
    $s3ql['limit']='1';
    $s3ql['format']='html';
    		
    $stat =S3QLaction($s3ql);
    
    if(!is_array($stat))
    {
    $s3ql=compact('user_id','db');
    $s3ql['insert']='item';
    $s3ql['where']['collection_id']=$GLOBALS['update_project']['collection_id'];
    $s3ql['where']['notes']=base64_encode($file);
    $s3ql['format']='html';
    
    $inserted =S3QLaction($s3ql);
    ereg('<error>([0-9]+)</error>(.*)<(message|item_id)>(.*)</(message|item_id)>', $inserted, $s3qlout);
    
    $item_id = $s3qlout[4];
    
    ###
    #Now fill up the stat - for information retrieval purposes only (this avoids having to create a long list to keep track of the item where the file is
    $s3ql=compact('user_id','db');
    $s3ql['insert']='statement';
    $s3ql['where']['item_id']=$item_id;
    $s3ql['where']['rule_id']=$GLOBALS['update_project']['path']['rule_id'];
    $s3ql['where']['value']=base64_encode($file);
    $s3ql['local']=1;
    
    $inserted =S3QLaction($s3ql);
    
    }
    else{
    
    $stat_info=$stat[0];
    $item_id = $stat_info['item_id'];
    
    }
    */
    $sql = "select resource_id from s3db_statement where rule_id = '" . $GLOBALS['update_project']['file']['rule_id'] . "' and file_name = '" . $file . "' order by created_on desc limit 1";
    $db->query($sql, __LINE__, __FILE__);
    if ($db->next_record()) {
        $item_id = $db->f('resource_id');
    } else {
        $s3ql = compact('user_id', 'db');
        $s3ql['insert'] = 'item';
        $s3ql['where']['collection_id'] = $GLOBALS['update_project']['collection_id'];
        $s3ql['where']['notes'] = urlencode($file);
        $s3ql['format'] = 'html';
        $inserted = S3QLaction($s3ql);
        $msg = html2cell($inserted);
        $msg = $msg[2];
        #ereg('<error>([0-9]+)</error>(.*)<(message|item_id)>(.*)</(message|item_id)>', $inserted, $s3qlout);
        $item_id = $msg['item_id'];
        ###
        #Now fill up the stat - for information retrieval purposes only (this avoids having to create a long list to keep track of the item where the file is
        $s3ql = compact('user_id', 'db');
        $s3ql['insert'] = 'statement';
        $s3ql['where']['item_id'] = $item_id;
        $s3ql['where']['rule_id'] = $GLOBALS['update_project']['path']['rule_id'];
        $s3ql['where']['value'] = urlencode($file);
        $s3ql['local'] = 1;
        $inserted = S3QLaction($s3ql);
    }
    return $item_id;
}
コード例 #29
0
ファイル: remoteproject.php プロジェクト: helenadeus/s3db.map
<?php

#createuser.php is the interface for admins for creating users. Includes tabs.php.
include 'adminheader.php';
if ($_POST['submit']) {
    $permission_level = $_POST['view'] . $_POST['change'] . $_POST['add'];
    #check if login and email inserted
    if (strlen($permission_level) < 3) {
        $message .= "Please select a permission level for view, change and add";
    } else {
        $s3ql = compact('user_id', 'db');
        $s3ql['insert'] = 'user';
        $s3ql['where'] = array('user_id' => $_POST['remote_user_id'], 'permission_level' => $permission_level);
        $done = S3QLaction($s3ql);
        ereg('<error>([0-9]+)</error>.*<(user_id|message)>(.*)</(user_id|message)>', $done, $s3qlout);
        if ($s3qlout[1] == '0') {
            #preg_match('[0-9]', $done, $inserted_user_id);
            $inserted_user_id = $s3qlout[4];
            #insert the user in the specified groups
        } else {
            $message .= $s3qlout[3];
        }
        if ($message == '') {
            header('Location:' . $action['listusers']);
            exit;
        }
    }
    #pass the variables to the form
    $remote_user_id = $_POST['remote_user_id'];
    $view = $remote_user_info['view'];
    $change = $remote_user_info['change'];
コード例 #30
0
ファイル: projectsTree.php プロジェクト: helenadeus/s3db.map
function create_tree_items($tree_items_file, $othervars)
{
    extract($othervars);
    $deployment_info = URIinfo('D' . $GLOBALS['Did'], $user_id, $key, $db);
    #Change the struct for project
    #wait for allprojects.php to retrieve all the projects first and put them on session :-)
    $s3ql['db'] = $db;
    $s3ql['user_id'] = $user_id;
    $s3ql['from'] = 'projects';
    $s3ql['order_by'] = 'project_id asc';
    #echo '<pre>';print_r($s3ql);
    $projects = S3QLaction($s3ql);
    #echo '<pre>';print_r($projects);
    $treeitem .= sprintf("%s\n", "var TREE_ITEMS = [ ['Projects', '" . $action['listprojects'] . "',");
    #print_r ($project_resources);
    if (is_array($projects)) {
        foreach ($projects as $project_info) {
            #$acl = find_final_acl($user_id, $project_info['project_id'], $db);
            $treeitem .= sprintf("%s\n", "['" . addslashes(urldecode($project_info['project_name'])) . "', '" . $action['project'] . "&project_id=" . $project_info['project_id'] . "',");
            #open the project
            #Create the tree node for each shared resource
            if (is_array($_SESSION[$user_id]['resources'][$project_info['project_id']])) {
                $classes = $_SESSION[$user_id]['resources'][$project_info['project_id']];
            } else {
                $s3ql = compact('user_id', 'db');
                $s3ql['select'] = '*';
                $s3ql['from'] = 'collections';
                $s3ql['where']['project_id'] = $project_info['project_id'];
                $classes = S3QLaction($s3ql);
                #echo $project_info['project_id'];echo '<pre>';print_r($classes);
                #$classes = S3QLaction($s3ql);
            }
            #echo '<pre>';print_r($classes);
            if (is_array($classes)) {
                /*$s3ql=compact('user_id','db');
                				$s3ql['select']='*';
                				$s3ql['from'] = 'rules';
                				$s3ql['where']['project_id'] = $project_info['project_id'];
                				#$s3ql['where']['object']="!='UID'";
                
                			
                			$rules = S3QLaction($s3ql);
                			#echo '<pre>';print_r($rules);
                			#separate the rules per subject
                			foreach ($rules as $rule_info) {
                				if($rule_info['object']!='UID')
                				$subject_rules['C'.$rule_info['subject_id']][] = $rule_info;
                			}
                			*/
                #echo '<pre>';print_r($subject_rules);exit;
                foreach ($classes as $resource_info) {
                    #$rule_id = get_rule_id_by_entity_id($resource_info['resource_id'],  $resource_info['project_id'], $db);
                    $treeitem .= sprintf("%s\n", "\t['" . addslashes(urldecode($resource_info['entity'])) . "', '" . $action['resource'] . "&project_id=" . $project_info['project_id'] . "&class_id=" . $resource_info['resource_id'] . "&rule_id=" . $rule_id . "',");
                    #open the resource
                    #List the rules for each shared resource
                    $rules = $subject_rules['C' . $resource_info['class_id']];
                    #Make the node for each rule
                    /*			
                    if (is_array($rules))
                    {foreach ($rules as $rule_info)
                    {$treeitem .= "		['".addslashes(urldecode($rule_info['verb']))."<B>|</B>".addslashes(urldecode($rule_info['object']))."', '".$action['querypage']."&project_id=".$project_info['project_id']."&class_id=".$resource_info['resource_id']."&rule_id=".$rule_info['rule_id']."'";#open the verb|object
                    
                    $treeitem .= sprintf("%s\n", "],"); #close the verb|object
                    
                    }
                    }
                    
                    					#Make a node for new rule
                    */
                    if ($resource_info['view']) {
                        $treeitem .= "\t\t['<I>[Query " . addslashes(urldecode($resource_info['entity'])) . "]</I>', '" . $action['querypage'] . "&class_id=" . $resource_info['resource_id'] . "&project_id=" . $project_info['project_id'] . "'";
                        #query page for class
                        $treeitem .= sprintf("%s\n", "],");
                        $treeitem .= "\t\t['<I>[List all " . addslashes(urldecode($resource_info['entity'])) . "]</I>', '" . $action['querypage'] . "&class_id=" . $resource_info['resource_id'] . "&project_id=" . $project_info['project_id'] . "&listall=yes'";
                        #list instances
                        $treeitem .= sprintf("%s\n", "],");
                    }
                    if ($resource_info['add_data']) {
                        $treeitem .= "\t\t['<I>[Add " . addslashes(urldecode($resource_info['entity'])) . "]</I>', '" . $action['insertinstance'] . "&class_id=" . $resource_info['resource_id'] . "&project_id=" . $project_info['project_id'] . "'";
                        #add instance
                        $treeitem .= sprintf("%s\n", "],");
                        $treeitem .= "\t\t['<I>[Add rule]</I>', '" . $action['createrule'] . "&project_id=" . $project_info['project_id'] . "&class_id=" . $resource_info['resource_id'] . "&rule_id=" . $rule_id . "'";
                        #open the verb|object
                        $treeitem .= sprintf("%s\n", "],");
                        #close the verb|object
                    }
                    $treeitem .= sprintf("%s\n", "\t],");
                    #close the shared resource
                    #Create a node for new resource
                }
            }
            if ($project_info['add_data']) {
                $treeitem .= sprintf("%s\n", "\t['[<I>New Collection</I>]', '" . $action['createclass'] . "&project_id=" . $project_info['project_id'] . "',");
                #open the resource
                $treeitem .= sprintf("%s\n", "\t],");
                #close the shared resource
            }
            $treeitem .= sprintf("%s\n", "],");
            #close the project
        }
    }
    #Create a node for new project
    if ($deployment_info['propagate']) {
        $treeitem .= sprintf("%s\n", "['[<I>New project</I>]', '" . $action['createproject'] . "',");
        #open the project
        $treeitem .= sprintf("%s\n", "],");
        #close the project
    }
    $treeitem .= "] ];";
    #close the tree
    return $treeitem;
}