Пример #1
0
function insert_s3db($D)
{
    #insert_s3db(compact('element', 'inputs', 'user_id', 'db'));
    #this is meant to be a general function for every insert, froum user to group. It create the entry, based on information on array $info and adds an entry on permissions
    #There will be 2 special cases: creating a class also creates the rule "has UID" and creating an instance also creates the statament where reosurce_id is instance_id and rule is "hasUID"
    extract($D);
    $table = $GLOBALS['s3tables'][$element];
    #echo '<pre>';print_r($D);
    $cols_for_entry = $GLOBALS['dbstruct'][$element];
    $letter = strtoupper(substr($element, 0, 1));
    #some special restrictions apply
    switch ($letter) {
        case 'U':
            $cols_for_entry = array_diff($cols_for_entry, array('addr1', 'addr2', 'city', 'state', 'postal_code', 'country'));
            array_push($cols_for_entry, 'account_pwd');
            $inputs['account_addr_id'] = insert_address($D);
            break;
        case 'G':
            $cols_for_entry = array_merge($cols_for_entry, array('account_pwd', 'account_group'));
            $inputs['account_type'] = 'g';
            $inputs['account_group'] = $inputs['account_type'];
            $inputs['account_uname'] = $inputs['account_lid'];
            break;
        case 'C':
            $inputs['iid'] = '0';
            break;
        case 'I':
            $inputs['iid'] = '1';
            $inputs['resource_class_id'] = $inputs['resource_class_id'] == '' ? $inputs['class_id'] : $inputs['resource_class_id'];
            $inputs['resource_id'] = $inputs['resource_id'] != '' ? $inputs['resource_id'] : $inputs['instance_id'];
            break;
        case 'F':
            $element = 'statement';
            $cols_for_entry = $GLOBALS['dbstruct']['statements'];
            $table = $GLOBALS['s3tables']['statements'];
            $inputs['statement_id'] = s3id();
            #now need to move file from tmp folder into final folder
            $moved = tmpfile2folder(array('inputs' => $inputs, 'db' => $db, 'user_id' => $user_id));
            if (!$moved[0]) {
                return $moved[1];
            } else {
                $inputs = $moved[1];
            }
            break;
    }
    #remove ''_id from cols for entry if that field is empty;
    if ($inputs[$GLOBALS['s3ids'][$element]] == '') {
        #never levae the primary key input empty
        #$inputs[$GLOBALS['s3ids'][$element]] = find_latest_UID($table, $db)+1;
        $inputs[$GLOBALS['s3ids'][$element]] = s3id();
    }
    $sql = buildInsertString($cols_for_entry, $inputs, $table);
    #echo $sql;exit;
    $db->query($sql, __LINE__, __FILE__);
    if ($db->Errno == 1) {
        $inputs[$GLOBALS['s3ids'][$element]] = s3id();
        $sql = buildInsertString($cols_for_entry, $inputs, $table);
        $db->query($sql, __LINE__, __FILE__);
    }
    $dbdata = get_object_vars($db);
    #$dbdata['Errno']='0';
    #echo '<pre>';print_r($dbdata);exit;
    if ($dbdata['Errno'] != '0') {
        if ($table == 'account') {
            $sql = "update s3db_" . $table . " set account_status = 'A' where account_id = '" . $inputs['account_id'] . "'";
            $db->query($sql, __LINE__, __FILE__);
            $dbdata = get_object_vars($db);
        }
        if ($dbdata['Errno'] != 0) {
            return array(False, $GLOBALS['error_codes']['something_went_wrong'] . '<message>' . str_replace('key', $GLOBALS['COREids'][$element], $dbdata['Error']) . '</message>', $GLOBALS['error_codes']['something_went_wrong'], $dbdata['Error']);
        }
    } else {
        #$element_id = $db->get_last_insert_id($table, $GLOBALS['s3ids'][$element]);
        #$element_id = find_latest_UID($table, $db);
        $element_id = $inputs[$GLOBALS['s3ids'][$element]];
        $info[$letter . $element_id] = $inputs;
        #special restrictions apply after create:
        switch ($letter) {
            case 'P':
                $project_id = $element_id;
                #if project_id is remote, need to change it's name a bit because / and # are not allowed in project_name;
                #$project_id = urlencode($project_id);
                #create the folder on the extras for the files of this project
                $folder_code_name = random_string(15) . '.project' . urlencode($project_id);
                $maindir = $GLOBALS['s3db_info']['server']['db']['uploads_folder'] . $GLOBALS['s3db_info']['server']['db']['uploads_file'];
                $destinationfolder = $maindir . '/' . $folder_code_name;
                #create the folder for the project
                if (mkdir($destinationfolder, 0777)) {
                    $indexfile = $destinationfolder . '/index.php';
                    if (file_exists($destinationfolder)) {
                        file_put_contents($indexfile, 'This folder cannot be accessed');
                        chmod($indexfile, 0777);
                    }
                    $sql = "update s3db_project set project_folder = '" . $folder_code_name . "' where project_id = '" . $project_id . "'";
                    $db->query($sql, __LINE__, __FILE__);
                } else {
                    echo "Could not create directory for this project. You might not be able to upload files to this project.";
                }
                break;
            case 'I':
                $class_id = $inputs['resource_class_id'];
                $statement_info = $inputs;
                $statement_info['rule_id'] = fastRuleID4class(compact('class_id', 'db', 'user_id'));
                $statement_info['value'] = $element_id;
                $statement_info['resource_id'] = $element_id;
                #$stat_inserted = insert_s3db(array('element'=>'statement', 'inputs'=>$statement_info, 'db'=>$db, 'user_id'=>$user_id));
                #echo '<pre>';print_r($statement_info);exit;
                $stat_inserted = insert_statement(compact('statement_info', 'db', 'user_id'));
                $action = 'create';
                insert_statement_log(compact('oldvalues', 'inputs', 'action', 'statement_info', 'user_id', 'db'));
                #echo '<pre>';print_r($stat_inserted);
                if ($stat_inserted[0]) {
                    ereg('<statement_id>([0-9]+)</statement_id>', $stat_inserted[1], $s3qlout);
                    $statement_info['statement_id'] = $stat_inserted[1];
                }
                $info['S' . $statement_info['statement_id']] = $statement_info;
                break;
            case 'C':
                $rule_info = $inputs;
                $rule_info['subject'] = $inputs['entity'];
                $rule_info['subject_id'] = $element_id;
                $rule_info['verb_id'] = '0';
                $rule_info['verb'] = 'has UID';
                $rule_info['object'] = 'UID';
                #echo '<pre>';print_r($inputs);
                #echo '<pre>';print_r($rule_info);exit;
                $rule_inserted = insert_rule(compact('rule_info', 'db', 'user_id'));
                break;
            case 'R':
                $rule_info = $inputs;
                $rule_info['rule_id'] = $element_id;
                #echo '<pre>';print_r($rule_info);exit;
                $action = 'create';
                $rule_inserted = insert_rule_log(compact('rule_info', 'action', 'db', 'user_id'));
                break;
            case 'S':
                $statement_info = $inputs;
                $action = 'create';
                insert_statement_log(compact('oldvalues', 'action', 'statement_info', 'user_id', 'db'));
            case 'F':
                $statement_info = $inputs;
                $action = 'create';
                insert_statement_log(compact('oldvalues', 'action', 'statement_info', 'user_id', 'db'));
        }
        #now add an entry that specifies user "creator' with permission level on 222 this entry (because someone has to have it)
        #some resources need to be mirrored, or swapped:
        if (ereg('^(U|G)$', $letter)) {
            #owner of groups is automatically created within it with PL 222
            if (ereg('^G$', $letter)) {
                $permission_info = array('uid' => 'U' . $user_id, 'shared_with' => strtoupper(substr($element, 0, 1)) . $element_id, 'permission_level' => '222');
                #echo '<pre>';print_r($permission_info);
                insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
            } elseif (ereg('^U$', $letter)) {
                ##also, for each user insertions, create an item_id for this user in the userManagement project. This will only create it if it does not yet exist
                include_once S3DB_SERVER_ROOT . '/s3dbcore/authentication.php';
                $user_proj = create_authentication_proj($db, $user_id);
                #now, create an item in the userManagement project for this user
                $user2add = $element_id;
                $c = compact('user2add', 'user_proj', 'user_id', 'db');
                $user_proj = insert_authentication_tuple($c);
                if ($inputs['permission_level'] != "") {
                    ##creator has specified that his own permissions can propagate
                    $permission_info = array('uid' => 'U' . $user_id, 'shared_with' => 'U' . $user2add, 'permission_level' => $inputs['permission_level']);
                    insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                }
            }
            #and then insert them i deployment
            $permission_info = array('uid' => 'D' . $GLOBALS['Did'], 'shared_with' => strtoupper(substr($element, 0, 1)) . $element_id);
            $permission_info['permission_level'] = $inputs['permission_level'] != '' ? $inputs['permission_level'] : '200';
        } else {
            if (ereg('^P$', $letter)) {
                #project has a special treatment, creators of project get to have permission level 222 on it.
                $permission_info['shared_with'] = 'U' . $user_id;
                $permission_info['shared_with'] = 'U' . $user_id;
                $permission_info['uid'] = $letter . $element_id;
                $permission_info['permission_level'] = 'YYY';
                ##This assures that it will migrate to child resources
                insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
            } elseif (ereg('^R$', $letter)) {
                #Rule require permission to be inserted also for subject_id, verb_id and, if exists, object-id
                ##For SUBJECT
                $permission_info = array('uid' => 'R' . $rule_info['rule_id'], 'shared_with' => 'C' . $rule_info['subject_id'], 'permission_level' => '222', 'info' => $info);
                #insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                ##For VERB
                $permission_info = array('uid' => 'R' . $rule_info['rule_id'], 'shared_with' => 'I' . $rule_info['verb_id'], 'permission_level' => '222', 'info' => $info);
                #insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                #FOR OBJECT
                if ($rule_info['object_id']) {
                    $permission_info = array('uid' => 'R' . $rule_info['rule_id'], 'shared_with' => 'C' . $rule_info['object_id'], 'permission_level' => '222', 'info' => $info);
                    #insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                }
                $permission_info['shared_with'] = 'P' . $inputs['project_id'];
            } elseif (ereg('^C$', $letter)) {
                $permission_info['shared_with'] = 'P' . $inputs['project_id'];
            } elseif (ereg('^I$', $letter)) {
                #insert for statement too
                $permission_info = array('uid' => 'S' . $statement_info['statement_id'], 'shared_with' => 'R' . $statement_info['rule_id'], 'permission_level' => '222', 'info' => $info);
                #insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                #and then for instance
                $permission_info['shared_with'] = 'C' . $inputs['resource_class_id'];
            } elseif (ereg('^S|F$', $letter)) {
                if ($letter == 'F') {
                    $element_id = $statement_info['statement_id'];
                    $element = 'file';
                    $letter = 'S';
                }
                $permission_info = array('uid' => $letter . $statement_info['statement_id'], 'shared_with' => 'I' . $statement_info['resource_id'], 'permission_level' => '222', 'info' => $info);
                #insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                ##If there is an object_id, insert one for that too
                if ($statement_info['object_id']) {
                    $permission_info = array('uid' => $letter . $statement_info['statement_id'], 'shared_with' => 'I' . $statement_info['object_id'], 'permission_level' => '222', 'info' => $info);
                    #insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
                }
                #And add one for the rule
                $permission_info['shared_with'] = 'R' . $inputs['rule_id'];
            }
            #and not these are global
            $permission_info['permission_level'] = $inputs['permission_level'] != '' ? $inputs['permission_level'] : '222';
            $permission_info['uid'] = $letter . $element_id;
            $info[$permission_info['uid']] = URI($permission_info['uid'], $user_id, $db);
        }
        #echo '<pre>';print_r($permission_info);
        #insert_permission(compact('permission_info', 'db', 'user_id', 'info'));
        return array(TRUE, $GLOBALS['error_codes']['success'] . "; " . $element . '_id' . ': <' . $element . '_id' . '>' . $element_id . '</' . $element . '_id' . '>' . '<a href =" ' . $query['url'] . '?key=' . $D['key'] . '&query=<S3QL><select>*</select><from>' . $GLOBALS['plurals'][$element] . '</from><where><' . $element . '_id>' . $element_id . '</' . $element . '_id></where></S3QL>">View ' . $element . '</a>', $element, $element . '_id' => $element_id, $GLOBALS['messages']['success'], strtoupper($element) . ' inserted');
    }
}
Пример #2
0
function auth($username, $password, $format = 'html', $createkey = true, $authorities = '')
{
    if ($username != '' && $password != '') {
        #connect to the db
        $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();
        list($valid, $user_info, $message) = auth_user_api($username, $user_id, $password, $db);
        if (!$valid) {
            #does this user have another account? try it remotelly
            #in case an authority has been endorsed: if authority is complex, build the username taking that into account
            if ($authorities) {
                $create_account = false;
                foreach ($GLOBALS['endorsed'] as $ord => $end) {
                    if ($end == $authorities) {
                        $email = $username . (substr($end, 0, 1) == '@' ? '' : '@') . $end;
                        $userLabel = $end . ':' . $username;
                        $protocol = $GLOBALS['s3db_info']['deployment']['endorsed_protocol'][$ord];
                        $auth = $GLOBALS['s3db_info']['deployment']['endorsed_server'][$ord];
                        $userComplexId = $protocol . ':' . $authorities . ':' . $username;
                        #$email = $username.((substr($end,0,1)=='@')?'':'@').$end;
                        #$protocol = $GLOBALS['s3db_info']['deployment']['endorsed_protocol'][$ord];
                        #$userLabel = $protocol.':'.$end.':'.$username;
                        #$auth=$GLOBALS['s3db_info']['deployment']['endorsed_server'][$ord];
                        if ($protocol == 'ldap') {
                            $userComplexName = $protocol . ':' . $auth . ':' . ereg_replace('cn=email', 'cn=' . $username, $GLOBALS['s3db_info']['deployment']['endorsed_ldap_rns'][$ord]);
                            $create_account = $GLOBALS['s3db_info']['deployment']['endorsed_automated'][$ord];
                        } elseif ($protocol == 'http') {
                            $userComplexName = $protocol . ':' . $auth . ':' . ereg_replace('email', $username, $GLOBALS['s3db_info']['deployment']['endorsed_ldap_rns'][$ord]);
                        }
                    }
                }
            }
            if ($userComplexName == '') {
                $userComplexName = $username;
            }
            #
            list($valid, $token, $expires) = univ_authenticate($userComplexName, $password, $serv_account);
            #if user was validated remotelly, user_info will correspond to the remote user. Also, a key has been generated; that is what will be used for the remainder of this session.
            if ($valid) {
                #even if user was authenticated remotelly, he still needs to have been created as user of this deployment
                if ($email == '') {
                    $email = $username;
                }
                if ($userComplexId != '') {
                    $username = $userComplexId;
                    $account_id = s3id();
                }
                #else {$account_id=$username;}
                $sql = "select * from s3db_account where (account_id='" . $account_id . "' or account_email='" . $email . "') and account_status='A'";
                #$sql = "select * from s3db_account where (account_id='".$username."' or account_email='".$username."') and account_status='A'";
                $db->query($sql);
                if (!$db->next_record()) {
                    ##If these account have been endorsed as trustworthy, we can, at this point, create an account for the user
                    if ($create_account) {
                        #$adminUser=1;
                        /*$s3ql=array('user_id'=>$adminUser,'db'=>$db);
                        		$s3ql['insert']='user';
                        		$s3ql['where']['user_id']=$email;
                        		$s3ql['where']['email']=$email;
                        		$done = S3QLaction($s3ql);
                        		*/
                        $sql = "insert into s3db_account (account_id, account_lid,account_pwd,account_uname,account_email,account_addr_id,created_on,created_by,account_status,account_type) values ('" . $account_id . "','" . $userLabel . "','" . random_string(15) . "','" . $email . "','" . $email . "','0','now()','1','A','u')";
                        $db->query($sql);
                        $user_info = array('account_id' => $account_id, 'account_lid' => $userLabel, 'account_type' => 'r');
                    } elseif (is_file($GLOBALS['uploads'] . '/userManage.s3db')) {
                        $user_proj = unserialize(file_get_contents($GLOBALS['uploads'] . '/userManage.s3db'));
                        if (!$user_proj) {
                            return array(false, "User project does not exist");
                            exit;
                        }
                        $sql = "select * from s3db_statement where rule_id = '" . $user_proj['email']['rule_id'] . "' and value = '" . $username . "'";
                        $db->query($sql);
                        if ($db->next_record()) {
                            $item_id = $db->f('resource_id');
                            if ($item_id) {
                                $sql = "select * from s3db_statement where resource_id = '" . $item_id . "' and rule_id = '" . $user_proj['user_id']['rule_id'] . "'";
                                $db->query($sql);
                                if ($db->next_record()) {
                                    $sql = "select * from s3db_account where account_status = 'A' and account_id = '" . ereg_replace('^U', '', $db->f('value')) . "'";
                                    $db->query($sql);
                                    if ($db->next_record()) {
                                        $user_info = array('account_id' => ereg_replace('^U', '', $db->f('value')), 'account_type' => 'u');
                                    }
                                } else {
                                    return array(false, '');
                                }
                            } else {
                                return array(false, '');
                            }
                        } else {
                            return array(false, '');
                        }
                    } else {
                        return array(false, formatReturn($GLOBALS['error_codes']['wrong_input'], 'User ' . $username . ' does not have permission in this deployment. If you think you should have permission, please inform the administrator of this deployment.', $format, ''));
                        $valid = 0;
                        exit;
                    }
                } else {
                    $key = $token;
                    $user_info = array('account_id' => $account_id, 'account_lid' => $username, 'account_type' => 'r');
                    # $user_info = array('account_id'=>$username, 'account_type'=>'r');
                    if (strtotime($expires) > strtotime(date('Y-m-d', time() + 1 * 24 * 60 * 60))) {
                        return array(false, formatReturn($GLOBALS['error_codes']['wrong_input'], 'S3DB received a key which expires after 24h. For security reasons, a key must be valid for 24h or less', $format, ''), $user_info);
                        exit;
                    }
                }
            } else {
                return array(false, formatReturn($GLOBALS['error_codes']['wrong_input'], $token, $format, ''));
            }
        } else {
            #local user was validated
            $key = random_string(15);
            $expires = date('Y-m-d', time() + 1 * 24 * 60 * 60);
        }
        if ($valid) {
            $user_id = $user_info['account_id'];
            create_log($user_id, $db);
            if ($createkey) {
                if (!$key) {
                    $key = random_string(15);
                }
                if (!$expires) {
                    $expires = date('Y-m-d', time() + 1 * 24 * 60 * 60);
                }
                $inputs = array('key_id' => $key, 'expires' => $expires, 'notes' => 'Key generated automatically via API', 'account_id' => $user_id);
                $added = add_entry('access_keys', $inputs, $db);
                $data[0] = $inputs;
                $letter = 'E';
                $pack = compact('data', 'user_id', 'db', 'letter', 't', 'format');
                if ($added) {
                    return array(true, completeDisplay($pack), $user_info);
                    exit;
                } else {
                    return array(false, formatReturn('2', 'Your authentication was valid but a key could not be created.', $format, ''));
                    exit;
                }
            } else {
                $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();
                $_SESSION['db'] = $db;
                $_SESSION['user'] = $user_info;
                return array(true, formatReturn('0', 'User validated.', $format, ''), $user_info);
                exit;
            }
        } else {
            return array(false, formatReturn($GLOBALS['error_codes']['wrong_input'], 'Please provide a valid username and password', $format, ''));
            exit;
        }
    } elseif ($username != '') {
        return array(false, formatReturn($GLOBALS['error_codes']['wrong_input'], 'Please provide a valid password', $format, ''));
        exit;
    } elseif ($password != '') {
        return array(false, formatReturn($GLOBALS['error_codes']['wrong_input'], 'Please provide a valid username', $format, ''));
        exit;
    } else {
        return array(false, formatReturn($GLOBALS['error_codes']['something_missing'], 'Please provide a valid username and password', $format, ''));
        exit;
    }
}
Пример #3
0
function registerURL($U)
{
    #this function call the db but it should NOT leave this one function
    extract($U);
    include_once 'config.inc.php';
    $key = $GLOBALS['deployment_project']['key'];
    include 'core.header.php';
    #include (S3DB_SERVER_ROOT.'/webActions.php');
    #require_once(S3DB_SERVER_ROOT.'/s3dbcore/class.db.inc.php');
    #include_once(S3DB_SERVER_ROOT.'/s3dbcore/common_functions.inc.php');
    #include_once(S3DB_SERVER_ROOT.'/s3dbcore/callback.php');
    #Generate Did, and,  since we're on it, name if empty
    if (!$Did && $case == 'registernewURL') {
        $Did = s3id();
    }
    if (!$name && $case == 'registernewURL') {
        $name = 'D' . $Did;
        $U['name'] = $name;
    }
    $db = CreateObject('s3dbapi.db');
    $db->Halt_On_Error = 'no';
    $db->Host = $GLOBALS['s3db_info']['server']['db']['db_host'];
    $db->Type = $GLOBALS['s3db_info']['server']['db']['db_type'];
    $db->Database = $GLOBALS['s3db_info']['server']['db']['db_name'];
    $db->User = $GLOBALS['s3db_info']['server']['db']['db_user'];
    $db->Password = $GLOBALS['s3db_info']['server']['db']['db_pass'];
    $db->connect();
    $U['db'] = $db;
    list($inputValid, $errMessage) = validate_register_inputs($U);
    if ($inputValid) {
        switch ($case) {
            case 'registernewURL':
                $protocol = $_SERVER['HTTPS'] != '' ? 'https://' : 'http://';
                $url = ereg('localhost', $url) ? $protocol . getClientIP() . str_replace($protocol . 'localhost', '', $url) : $url;
                #echo $sql;exit;
                #echo $s3rl;exit;
                if ($Did != '') {
                    $sql = "select * from s3db_deployment where deployment_id = '" . $Did . "'";
                    $db->query($sql, __LINE__, __FILE__);
                    if ($db->next_record()) {
                        return array(False, 'Did already exists. Please provide another one or leave that field blank for an arbitrary value');
                    }
                }
                #if($Did!=''){
                $sql = "insert into s3db_deployment (deployment_id, url, publickey, message, created_on) values ('" . $Did . "', '" . $url . "', '" . $publicKey . "', '" . random_string(20) . "', now())";
                #echo $sql;
                $db->query($sql, __LINE__, __FILE__);
                $s3rl = $Did;
                #}
                #else{
                #include('s3id.php');
                #$sql = "insert into s3db_deployment (deployment_id, url, publickey, message, created_on) values ('".$Did."', '".$url."', '".$publicKey."', '".random_string(20)."', now())";
                #echo $sql;exit;
                #$db->query($sql, __LINE__, __FILE__);
                if ($db->Errno == 0) {
                    ##Now create an entry in the project of deployemnts;
                    #create a remote user to access this entry
                    $s3ql = compact('user_id', 'db');
                    $s3ql['insert'] = 'user';
                    $s3ql['where']['user_id'] = $url . (substr($url, strlen($url) - 1, 1) == '/' ? '' : '/') . 'U1';
                    $s3ql['where']['permission_level'] = '111';
                    $s3ql['format'] = 'php';
                    $done = unserialize(S3QLaction($s3ql));
                    //$msg=html2cell($done);
                    $msg = $done[0];
                    if (ereg('^(4|9|0)$', $msg['error_code'])) {
                        $remoteUser = $s3ql['where']['user_id'];
                        $user_id = '1';
                        $s3ql = compact('user_id', 'db');
                        $s3ql['insert'] = 'item';
                        $s3ql['where']['collection_id'] = $GLOBALS['deployment_project']['collection_id'];
                        $s3ql['where']['item_id'] = $Did;
                        $s3ql['where']['notes'] = $name == '' ? urlencode('Deployment ' . $Did) : $name;
                        $s3ql['format'] = 'php';
                        $done = unserialize(S3QLaction($s3ql));
                        $msg = $done[0];
                        if ($msg['error_code'] == '0' || $msg['error_code'] == '4') {
                            $s3ql = compact('user_id', 'db');
                            $s3ql['insert'] = 'user';
                            $s3ql['where']['item_id'] = $msg['item_id'];
                            $s3ql['where']['user_id'] = $remoteUser;
                            $s3ql['where']['permission_level'] = '222';
                            $done = S3QLaction($s3ql);
                            $item_id = $msg['item_id'];
                            $msg = html2cell($done);
                            $msg = $msg[2];
                            #find the collectiont rules
                            $s3ql = compact('user_id', 'db');
                            $s3ql['from'] = 'rules';
                            $s3ql['where']['subject_id'] = $GLOBALS['deployment_project']['collection_id'];
                            $rules = S3QLaction($s3ql);
                            if (!empty($rules)) {
                                $s3ql = compact('user_id', 'db');
                                $s3ql['insert'] = 'statement';
                                $s3ql['where']['item_id'] = $item_id;
                                foreach ($rules as $key => $rule_info) {
                                    if (in_array($rule_info['object'], array_keys($_GET))) {
                                        $s3ql['where']['rule_id'] = $rule_info['rule_id'];
                                        if ($rule_info['object'] == 'keywords') {
                                            $keywords = explode(',', $_GET['keywords']);
                                            foreach ($keywords as $word) {
                                                if (is_base64_encoded($word)) {
                                                    $word = base64_decode($word);
                                                }
                                                $s3ql['where']['value'] = $word;
                                                $done = S3QLaction($s3ql);
                                            }
                                        } elseif ($rule_info['object'] == 'url') {
                                            $s3ql['where']['value'] = $url;
                                            $done = S3QLaction($s3ql);
                                        } elseif ($rule_info['object'] == 'description') {
                                            $v = $_GET[$rule_info['object']];
                                            if (is_base64_encoded($v)) {
                                                $v = base64_decode($v);
                                            }
                                            $s3ql['where']['value'] = $v;
                                            $done = S3QLaction($s3ql);
                                        } elseif ($rule_info['object'] == 'name') {
                                            $s3ql['where']['value'] = $name;
                                            $done = S3QLaction($s3ql);
                                        } else {
                                            $v = $_GET[$rule_info['object']];
                                            $s3ql['where']['value'] = $v;
                                            $done = S3QLaction($s3ql);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                #After registering url, return Did
                if ($Did != '') {
                    return array(True, array('deployment_id' => $Did, 'name' => $name));
                } else {
                    return array(False, '');
                }
                break;
            case 'findURL':
                ##Let's first check if there is already a deployment in this URL
                if ($url != '') {
                    $sql = "select * from s3db_deployment where url = '" . $url . "'";
                    $db->query($sql, __LINE__, __FILE__);
                    if ($db->next_record()) {
                        $reg = array('deployment_id' => $db->f('deployment_id'), 'url' => $db->f('url'), 'modified_on' => $db->f('modified_on'));
                        return array(True, $reg);
                    }
                } elseif ($Did != '') {
                    $sql = "select * from s3db_deployment where deployment_id = '" . str_replace('D', '', $Did) . "'";
                    $db->query($sql, __LINE__, __FILE__);
                    if ($db->next_record()) {
                        $reg = array('url' => $db->f('url'), 'publicKey' => $db->f('publickey'), 'modified_on' => $db->f('modified_on'));
                        return array(True, $reg);
                    } else {
                        return array(False, 'Did not found');
                    }
                }
                break;
            case 'updateURL':
                #did the user send the decripted message already? Validate and change the message
                if ($message != '') {
                    $sql = "select * from s3db_deployment where deployment_id = '" . str_replace('D', '', $Did) . "'";
                    $db->query($sql, __LINE__, __FILE__);
                    if ($db->next_record()) {
                        $oldUrl = $db->f('url');
                        $storedMessage = $db->f('message');
                        #do messages match?
                        if ($storedMessage != $message) {
                            #$sql = "update s3db_register set message= '".random_string(20)."' where deployment_id = '".str_replace('D', '', $Did)."'";
                            return array(False, 'Error code:<error>3</error><description> Decripted Message does not match the request</description>');
                        } else {
                            #echo 'ahaa, you found it :-)';
                            #update key
                            $sql = "update s3db_deployment set url = '" . $newUrl . "', message= '" . random_string(20) . "', modified_on = now() where deployment_id = '" . str_replace('D', '', $Did) . "'";
                            $db->query($sql, __LINE__, __FILE__);
                            ##Now update the entry on s3db
                            $sql = "update s3db_statement set url='" . $newUrl . "' where rule_id='' and item_id=''";
                            $dbdata = get_object_vars($db);
                            if ($dbdata['Errno'] == '0') {
                                return array(True, 'Error code:<error>0</error><description>  URL updated</description>');
                            } else {
                                return array(False, 'Error code:<error>1</error><description>  Could not update URL</description>');
                            }
                        }
                    } else {
                        return array(False, 'Error code:<error>2</error> Could not find Did');
                    }
                } else {
                    #send a message to the url to make sure he is who he says he is
                    $sql = "select * from s3db_deployment where deployment_id = '" . ereg_replace('^D', '', $Did) . "'";
                    $db->query($sql);
                    if ($db->next_record()) {
                        $publicKey = $db->f('publickey');
                        $message = $db->f('message');
                    } else {
                        return array(False, 'Could not find URL');
                    }
                    #encript it
                    require_once 'pearlib/RSACrypt/RSA.php';
                    $encripted = encrypt($message, $publicKey);
                    if ($encripted == '') {
                        $encripted = encrypt($message, urlencode($publicKey));
                    }
                    $ErrMessage = "For authentication, please decript this message using your private key: <message>" . rawurlencode($encripted) . "</message><br />(Note: you might need to remove url encoding that your browser might have added before decoding. Plase refer to http://www.asciitable.com/ for the correct characters.)";
                    echo formatReturn($GLOBALS['error_codes']['success'], $ErrMessage, $format, array('encripted' => $encripted));
                    exit;
                    #echo "For authentication, please decript this message using your private key: <message>".rawurlencode($encripted)."</message>";
                    #echo "<br />(Note: you might need to remove url encoding that your browser might have added before decoding. Plase refer to http://www.asciitable.com/ for the correct characters.)";
                    #	exit;
                }
        }
    } else {
        echo formatReturn($GLOBALS['error_codes']['wrong_input'], $errMessage, $format, '');
    }
}