Example #1
0
 public function interact()
 {
     // Fetch the entity, using provided identifiers...
     $entity = $this->getEntity();
     // ... verify that the password matches
     // @todo: handle the other bits of A1, like rehashing and brute force checks
     $this->authenticator->checkPassword($this->getRequiredIdentifier('password'), $entity->password);
     // ... and return the formatted result.
     return $this->formatter->__invoke($entity);
 }
Example #2
0
 public function interact()
 {
     // Fetch the entity, using provided identifiers...
     $entity = $this->getEntity();
     // Rate limit login attempts
     $this->rateLimiter->limit($entity);
     // ... verify that the password matches
     $this->authenticator->checkPassword($this->getRequiredIdentifier('password'), $entity->password);
     // ... and return the formatted result.
     return $this->formatter->__invoke($entity);
 }
 /**
  * Gets domain and URL authority from SEOmoz.
  *
  * @access		private
  * @link 		http://www.seomoz.org/api		The SEOmoz API
  * @return		array 					Returns array, containing authority data.
  */
 public static function Seomoz_Authority($uri)
 {
     // external helper class
     include_once 'ext/SeoMoz/Authenticator.php';
     $authenticator = new Authenticator();
     $url = urlencode($uri);
     $tmp = SEOstats::cURL('http://lsapi.seomoz.com/linkscape/url-metrics/' . $url . '?' . $authenticator->getAuthenticationStr());
     $data = json_decode($tmp);
     $result = array('Title' => $data->ut, 'URL' => $data->uu, 'External Links' => $data->ueid, 'Links' => $data->uid, 'URL Authority' => $data->upa, 'URL mozRank' => $data->umrp, 'Subdomain mozRank' => $data->fmrp, 'HTTP Status Code' => $data->us, 'Page Authority' => $data->upa, 'Domain Authority' => $data->pda);
     return $result;
 }
Example #4
0
function route($handler, $module, $action)
{
    if ($handler == 'TTAM') {
        if ($module == 'Authenticator') {
            $auth = new Authenticator();
            if ($action = 'getToken') {
                $authCode = $_GET['code'];
                $data = $auth->getToken($authCode);
            }
        }
    }
}
Example #5
0
 private function initController()
 {
     $this->frontController = new FrontController();
     // Create the database interface objects and their proxies and register
     // them with the FrontController.
     $configuration = new Configuration($this->dbConnector);
     $entries = new Entries($this->dbConnector);
     $authenticator = new Authenticator($this->dbConnector);
     $captchaAuth = new CaptchaAuth($this->dbConnector);
     $authenticator->setMethodHandler(AuthMethods::CAPTCHA, new CaptchaAuthHandler($captchaAuth));
     $resolvers = array(new DirectClassResolver('configuration', $configuration, array('getAll' => array(), 'getByName' => array(Types::STRING))), new DirectClassResolver('entries', $entries, array('getEntryCount' => array(), 'getAllIds' => array(Types::STRING), 'getIdsForRange' => array(Types::STRING, Types::INT, Types::INT), 'getEntryById' => array(Types::INT), 'addEntry' => array(Types::STRING, Types::STRING, Types::STRING))), new ClassResolver('auth', new AuthServer($authenticator)), new ClassResolver('captchaAuth', new CaptchaAuthServer($captchaAuth)), new CaptchaImageResolver($captchaAuth));
     foreach ($resolvers as $resolver) {
         $this->frontController->addResolver(new AuthResolverProxy($resolver, $authenticator));
     }
 }
Example #6
0
 public function test11RetrieveConceptFiletrStatus()
 {
     // Use API to search for concept and filter on status
     // todo: test additionele zoek parameters
     print "\n" . "Test: get concept via filters";
     $client = Authenticator::authenticate();
     //prepare and send request
     $uri = BASE_URI_ . '/public/api/find-concepts?q=prefLabel:' . CONCEPT_prefLabel . '&status:' . CONCEPT_status_forfilter . '&tenant:' . TENANT . '&inScheme:' . CONCEPT_schema_forfilter;
     print "\n fileterd request's uri: " . $uri;
     $client->setUri($uri);
     $client->setConfig(array('maxredirects' => 0, 'timeout' => 30));
     $client->SetHeaders(array('Accept' => 'text/html,application/xhtml+xml,application/xml', 'Content-Type' => 'application/xml', 'Accept-Language' => 'nl,en-US,en', 'Accept-Encoding' => 'gzip, deflate', 'Connection' => 'keep-alive'));
     $response = $client->request(Zend_Http_Client::GET);
     // analyse respond
     if ($response->getStatus() != 200) {
         print "\n " . $response->getMessage();
     }
     print "\n Response Headers: ";
     var_dump($response->getHeaders());
     $this->AssertEquals(200, $response->getStatus());
     $namespaces = array("rdf" => "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "skos" => "http://www.w3.org/2004/02/skos/core#", "openskos" => "http://openskos.org/xmlns/openskos.xsd");
     print "\n\n\n Response Body: ";
     var_dump($response->getBody());
     $dom = new Zend_Dom_Query();
     $dom->setDocumentXML($response->getBody());
     $dom->registerXpathNamespaces($namespaces);
     $elem = $dom->queryXpath('/rdf:RDF');
     $this->assertEquals($elem->current()->nodeType, XML_ELEMENT_NODE, 'The root node of the response is not an element');
     $resDescr = $dom->queryXpath('/rdf:RDF/rdf:Description');
     $resStatus = $dom->queryXpath('/rdf:RDF/rdf:Description/openskos:status');
     $this->assertEquals(1, $resDescr->count());
     $this->assertEquals($resDescr->count(), $resStatus->count(), "Not all result concepts have status field. ");
 }
Example #7
0
 /**
  * check if $passFromForm is same as $passFromDb
  * @param string $passFromDb
  * @param string $passFromForm
  * @return boolean
  */
 public static function checkPassword($passFromDb, $passFromForm)
 {
     if ($passFromDb === \Authenticator::calculateHash($passFromForm, $passFromDb)) {
         return TRUE;
     }
     return FALSE;
 }
 /**
  * Will redirect the user directly to the IdP login endpoint if:
  *
  * 1) the 'SAMLAuthenticator' is the default authenticator
  * 2) there isn't a GET param showloginform set to 1
  * 3) the member is not currently logged in
  * 4) there are no form messages (errors or notices)
  *
  * @return void
  */
 public function onBeforeSecurityLogin()
 {
     if (Authenticator::get_default_authenticator() != 'SAMLAuthenticator') {
         return;
     }
     // by going to the URL Security/login?showloginform=1 we bypass the auto sign on
     if ($this->owner->request->getVar('showloginform') == 1) {
         return;
     }
     // if member is already logged in, don't auto-sign-on, this is most likely because
     // of unsufficient permissions.
     $member = Member::currentUser();
     if ($member && $member->exists()) {
         return;
     }
     // if there are form messages, don't auto-sign-on, this is most likely because of
     // login errors / failures or other notices.
     if (Session::get('FormInfo')) {
         // since FormInfo can be a "nulled" array, we have to check
         foreach (Session::get('FormInfo') as $form => $info) {
             foreach ($info as $name => $value) {
                 if ($value !== null) {
                     return;
                 }
             }
         }
     }
     $backURL = Session::get('BackURL');
     if ($this->owner->request->getVar('BackURL')) {
         $backURL = $this->owner->request->getVar('BackURL');
     }
     $authenticator = Injector::inst()->create('SAMLAuthenticator');
     $authenticator->authenticate(array("BackURL" => $backURL));
 }
function create_topic($request)
{
    Authenticator::assert_manager_or_professor($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale']);
    try {
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die('', 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data)) {
            Util::output_errors_and_die('', 400);
        }
        $model = new Model();
        if (!isset($input_data['name'])) {
            $input_data['name'] = '';
        }
        $topic_id = $model->create_topic($input_data['name']);
        if ($topic_id) {
            http_response_code(201);
            header('Content-Type: text/plain');
            echo '/topics/' . $topic_id;
            die;
        } else {
            Util::output_errors_and_die('', 400);
        }
    } catch (ConflictException $e) {
        Util::output_errors_and_die($e->getMessage(), 409);
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
function update_programming_language($pl_id, $request)
{
    Authenticator::assert_manager($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale']);
    try {
        $model = new Model();
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die('', 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data)) {
            Util::output_errors_and_die('', 400);
        }
        $result = $model->edit_programming_language($pl_id, $input_data);
        header('Content-Type: text/plain');
        http_response_code($result ? 200 : 404);
        die;
    } catch (ConflictException $e) {
        Util::output_errors_and_die($e->getMessage(), 409);
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
function test_auto_marking_sc($request)
{
    Authenticator::assert_manager_or_professor($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale'], '/new-question/errors');
    try {
        $model = new Model();
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die($msg->_('invalid-format'), 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data) || !isset($input_data['question']) || !isset($input_data['source-code']) || !is_string($input_data['source-code'])) {
            Util::output_errors_and_die($msg->_('invalid-format'), 400);
        }
        $extra = !empty($input_data['extra']) ? $input_data['extra'] : [];
        $qd = $input_data['question'];
        set_empty_if_undefined($qd['type']);
        if ($qd['type'] != 'source-code') {
            Util::output_errors_and_die('', 400);
        }
        $q = new QuestionSC($qd, Question::FROM_USER, $extra);
        $q->mark_automatically(array('source-code' => $input_data['source-code']), $log, $result);
        http_response_code(200);
        header('Content-Type: application/json');
        echo my_json_encode($result);
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
 public function sendMail($id)
 {
     /* $destinatari = '*****@*****.**';
        $email = "*****@*****.**";
        $cc_address = "*****@*****.**";
        $cc_address2 = "*****@*****.**";
        $subject = 'Ordine numero ' . $_SESSION['idordine'] . ' Ricevuto';
        //mando prima una mail a info@caisse.it e poi una al cliente
        $message = $mail; */
     $stati = $this->stato->where('cancellato', '=', false)->orderby('id', 'asc')->lists('descrizione', 'id')->all();
     $ordine = $this->ordine->with('prodotti', 'utenti.clienti', 'pagamenti.scontiTipoPagamento', 'stati')->find($id);
     if ($this->auth->check() && ($ordine->utente == $this->auth->user()->id || $this->utente->find($this->auth->user()->id)->ruolo == 1)) {
         $tempTot = $ordine->costo;
         $sconto = $ordine->sconto;
         $speseSpedizione = $ordine->costospedizione;
         $totale = number_format(round($tempTot - $sconto + $speseSpedizione, 2), 2);
         $destination = $this->auth->user()->username;
         Mail::send('email.order', compact('ordine', 'totale', 'stati', 'cartcount', 'sconto'), function ($message) use($ordine, $destination) {
             $message->from('*****@*****.**', 'Holistic Remedies');
             $message->to($destination)->subject('Conferma Ordine ' . $ordine['id']);
         });
         Mail::send('email.order', compact('ordine', 'totale', 'stati', 'cartcount', 'sconto'), function ($message) use($ordine) {
             $message->from('*****@*****.**', 'Holistic Remedies');
             $message->to('*****@*****.**')->cc('*****@*****.**')->cc('*****@*****.**')->subject('Conferma Ordine ' . $ordine['id']);
         });
     } else {
         return Response::json(array('code' => '401', 'msg' => 'KO', 'error' => "unauthorized"));
     }
 }
Example #13
0
/**
 * Try to perform a user login request.
 */
function tryLogin()
{
    global $req, $session, $msg, $nc;
    global $status;
    global $serverUri;
    if ($status === "unknown" && $req->check("action")) {
        $action = $req->getString("action");
        switch ($action) {
            case "login":
                if ($req->getSubmitButton("cancel")) {
                    $status = "unknown";
                    return;
                }
                assert($req->getSubmitButton("login"));
                $identity = $req->getString("identity");
                $signature = $req->getString("signature");
                $version = $req->getInteger("version");
                if ($version !== 1) {
                    throw new RuntimeException("Unsupported signature" . " version: {$version}");
                }
                /* Redirect to loginForm in case an exception is thrown
                   below (i. e., authentication fails).  */
                $status = "loginForm";
                $auth = new Authenticator($nc, $serverUri);
                try {
                    $res = $auth->login($identity, $signature, $session->getNonce());
                    assert($res === TRUE);
                    $session->setUser($identity);
                } catch (LoginFailure $err) {
                    throw new UIError($err->getMessage());
                }
                /* No exception thrown means success.  */
                $msg->addMessage("You have logged in successfully.");
                $status = "unknown";
                break;
            case "logout":
                $session->setUser(NULL);
                $msg->addMessage("You have been logged out successfully.");
                $status = "unknown";
                break;
            default:
                // Ignore unknown action request.
                break;
        }
    }
}
Example #14
0
 /**
  * Forcibly clear all _SESSION variables and destroys the session
  *
  * @param string $guid The GUID of this user
  */
 public static function ClearAuthentication($guid = "CURRENT_USER")
 {
     self::Init();
     self::$user = null;
     unset($_SESSION[$guid]);
     self::UnsetAllSessionVars();
     @session_destroy();
 }
function test_auto_marking($request)
{
    Authenticator::assert_manager_or_professor($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale'], '/new-question/errors');
    try {
        $model = new Model();
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die($msg->_('invalid-format'), 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data) || !isset($input_data['question']) || !isset($input_data['studentAnswer'])) {
            Util::output_errors_and_die($msg->_('invalid-format'), 400);
        }
        $extra = !empty($input_data['extra']) ? $input_data['extra'] : [];
        $qd = $input_data['question'];
        set_empty_if_undefined($qd['type']);
        if (!Validator::validate_question_type($qd['type'])) {
            Util::output_errors_and_die($msg->_('invalid-type'), 400);
        }
        switch ($qd['type']) {
            case 'short-answer':
                $q = new QuestionSA($qd, Question::FROM_USER, $extra);
                break;
            case 'essay':
                $q = new QuestionES($qd, Question::FROM_USER, $extra);
                break;
            case 'multiple-choice':
                $q = new QuestionMC($qd, Question::FROM_USER, $extra);
                break;
            case 'matching':
                $q = new QuestionMA($qd, Question::FROM_USER, $extra);
                break;
            case 'fitb-type':
                $q = new QuestionFT($qd, Question::FROM_USER, $extra);
                break;
            case 'fitb-select':
                $q = new QuestionFS($qd, Question::FROM_USER, $extra);
                break;
            case 'source-code':
                $q = new QuestionSC($qd, Question::FROM_USER, $extra);
                break;
        }
        http_response_code(200);
        header('Content-Type: application/json');
        $mark = $q->mark_automatically($input_data['studentAnswer'], $log);
        foreach ($log as $i => $line) {
            $log[$i] = $msg->_('/auto-marking/' . $line[0], $line[1]);
        }
        $log = implode('<br/>', $log);
        echo my_json_encode(array('log' => $log, 'mark' => $mark));
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
 /**
  * 
  * This method returns the metrics about a URL or set of URLs.  
  * 
  * @param objectURL
  * @param col This field filters the data to get only specific columns
  * 			  col = 0 fetches all the data
  * @return
  */
 public function getUrlMetrics($objectURL, $col = 0)
 {
     $urlToFetch = "http://lsapi.seomoz.com/linkscape/url-metrics/" . urlencode($objectURL) . "?" . Authenticator::getInstance()->getAuthenticationStr();
     if ($col > 0) {
         $urlToFetch = $urlToFetch . "&Cols=" . $col;
     }
     $response = ConnectionUtil::makeRequest($urlToFetch);
     return $response;
 }
Example #17
0
 function tearDown()
 {
     // Restore selected authenticator
     // MemberAuthenticator might not actually be present
     if (!in_array('MemberAuthenticator', $this->priorAuthenticators)) {
         Authenticator::unregister('MemberAuthenticator');
     }
     Authenticator::set_default_authenticator($this->priorDefaultAuthenticator);
     parent::tearDown();
 }
function create_question($request, $assignment_id = null)
{
    Authenticator::assert_manager_or_professor($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale']);
    try {
        $model = new Model();
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die('', 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data)) {
            Util::output_errors_and_die('', 400);
        }
        set_empty_if_undefined($input_data['type']);
        if (!Validator::validate_question_type($input_data['type'])) {
            Util::output_errors_and_die($msg->_('invalid-type'), 400);
        }
        switch ($input_data['type']) {
            case 'short-answer':
                $q = new QuestionSA($input_data, Question::FROM_USER);
                break;
            case 'essay':
                $q = new QuestionES($input_data, Question::FROM_USER);
                break;
            case 'multiple-choice':
                $q = new QuestionMC($input_data, Question::FROM_USER);
                break;
            case 'matching':
                $q = new QuestionMA($input_data, Question::FROM_USER);
                break;
            case 'fitb-type':
                $q = new QuestionFT($input_data, Question::FROM_USER);
                break;
            case 'fitb-select':
                $q = new QuestionFS($input_data, Question::FROM_USER);
                break;
            case 'source-code':
                $q = new QuestionSC($input_data, Question::FROM_USER);
                break;
        }
        $qid = $model->create_question($q);
        header('Content-Type: text/plain');
        echo '/question_bank/questions/' . $qid;
        http_response_code(201);
        die;
    } catch (ConflictException $e) {
        Util::output_errors_and_die($e->getMessage(), 409);
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
Example #19
0
 function tearDown()
 {
     // Restore selected authenticator
     // MemberAuthenticator might not actually be present
     if (!in_array('MemberAuthenticator', $this->priorAuthenticators)) {
         Authenticator::unregister('MemberAuthenticator');
     }
     Authenticator::set_default_authenticator($this->priorDefaultAuthenticator);
     // Restore unique identifier field
     Member::set_unique_identifier_field($this->priorUniqueIdentifierField);
     parent::tearDown();
 }
Example #20
0
 /**
  * @param Form $form
  */
 public function userCredentialsSubmitted($form)
 {
     $values = $form->getValues();
     $user = $this->userRepo->findById($this->user->id)->fetch();
     if (Authenticator::checkPassword($user->password, $values->oldpass)) {
         $this->userRepo->setPassword($this->user->id, $values->newpass);
         $this->flashMessage('Heslo nastaveno', 'success');
     } else {
         $this->flashMessage('Staré heslo bylo zadáno nesprávně', 'error');
     }
     $this->redirect('this');
 }
Example #21
0
function update_user($username, $request)
{
    $user_data = Authenticator::assert_manager($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale']);
    try {
        $model = new Model();
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        switch ($content_type) {
            case 'application/json':
                $input_data = json_decode($raw_input, true);
                break;
            case 'application/x-www-form-urlencoded':
                $input_data = array();
                parse_str($raw_input, $input_data);
                break;
            default:
                Util::output_errors_and_die('', 415);
        }
        if (empty($input_data)) {
            Util::output_errors_and_die('', 400);
        }
        $changes = array();
        foreach ($input_data as $f => $v) {
            if (is_string($input_data[$f])) {
                $changes[$f] = trim($input_data[$f]);
            } else {
                Util::output_errors_and_die('', 400);
            }
        }
        if (isset($input_data['password'])) {
            // don't trim
            if (is_string($input_data['password'])) {
                $changes['password'] = $input_data['password'];
            } else {
                Util::output_errors_and_die('', 400);
            }
        }
        if ($model->update_user($username, $changes)) {
            echo $user_data['username'] . ' -> ' . $username;
            $model->insert_approvedby($user_data['username'], $username);
            http_response_code(204);
            die;
        } else {
            Util::output_errors_and_die('', 404);
        }
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
Example #22
0
 public function test11RetrieveConceptFiletrStatus()
 {
     // Use API to search for concept and filter on status
     // todo: test additionele zoek parameters
     print "\n" . "Test: get concept via filters";
     $client = Authenticator::authenticate();
     //prepare and send request
     $uri = BASE_URI_ . '/public/api/find-concepts?q=prefLabel:' . CONCEPT_prefLabel . '&status:' . CONCEPT_status_forfilter . '&tenant:' . TENANT . '&inScheme:' . CONCEPT_schema_forfilter;
     print "\n filtered request's uri: " . $uri . "\n";
     $client->setUri($uri);
     $client->setConfig(array('maxredirects' => 0, 'timeout' => 30));
     $client->SetHeaders(array('Accept' => 'text/html,application/xhtml+xml,application/xml', 'Content-Type' => 'application/xml', 'Accept-Language' => 'nl,en-US,en', 'Accept-Encoding' => 'gzip, deflate', 'Connection' => 'keep-alive'));
     $response = $client->request(Zend_Http_Client::GET);
     // analyse respond
     print "\n get status: " . $response->getMessage() . "\n";
     $this->AssertEquals(200, $response->getStatus());
     $namespaces = array("rdf" => "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "skos" => "http://www.w3.org/2004/02/skos/core#", "openskos" => "http://openskos.org/xmlns/openskos.xsd");
     $dom = new Zend_Dom_Query();
     $dom->setDocumentXML($response->getBody());
     $dom->registerXpathNamespaces($namespaces);
     $elem = $dom->queryXpath('/rdf:RDF');
     $this->assertEquals(XML_ELEMENT_NODE, $elem->current()->nodeType, 'The root node of the response is not an element');
     $this->assertEquals(1, $elem->current()->getAttribute("openskos:numFound"));
     $resDescr = $dom->queryXpath('/rdf:RDF/rdf:Description');
     $i = 0;
     $l = $resDescr->count();
     $resDescr->rewind();
     while ($i < $l) {
         $labels = $resDescr->current()->getElementsByTagName("altLabel");
         //print "\n val:" . $labels ->item(0) ->textContent;
         $randomn = rand(0, 4096);
         $labels->item(0)->nodeValue = "test-1-" . $randomn;
         $doc = $resDescr->current()->ownerDocument;
         $xml = $doc->saveXML();
         var_dump($xml);
         // try $newdom isntead of $dom, which can be corrupted
         //$dom = new DOMDocument('1.0', 'utf-8');
         //$rdf = $dom -> createElement("rdf:RDF");
         //$dom ->importNode($newDescr, TRUE);// appendChild($rdf);
         //$rdf ->appendChild($newDescr);
         //$xml = $dom->saveXML();
         //var_dump($xml);
         $client->setUri(BASE_URI_ . "/public/api/concept?");
         $client->setConfig(array('maxredirects' => 0, 'timeout' => 30));
         $response = $client->setEncType('text/xml')->setRawData($xml)->setParameterGet('tenant', TENANT)->setParameterGet('collection', COLLECTION_1_code)->setParameterGet('key', API_KEY)->request(Zend_Http_Client::PUT);
         print "\n Update response message: " . $response->getMessage();
         $this->AssertEquals(200, $response->getStatus(), 'Update request returned worng status code');
         $resDescr->next();
         $i++;
     }
 }
function test_question($request)
{
    Authenticator::assert_manager_or_professor($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale'], '/new-question/errors');
    try {
        $model = new Model();
        $raw_input = $request->getBody();
        $content_type = explode(';', $request->type)[0];
        if ($content_type !== 'application/json') {
            Util::output_errors_and_die($msg->_('invalid-format'), 415);
        }
        $input_data = json_decode($raw_input, true);
        if (empty($input_data)) {
            Util::output_errors_and_die($msg->_('invalid-format'), 400);
        }
        set_empty_if_undefined($input_data['type']);
        if (!Validator::validate_question_type($input_data['type'])) {
            Util::output_errors_and_die($msg->_('invalid-type'), 400);
        }
        switch ($input_data['type']) {
            case 'short-answer':
                $q = new QuestionSA($input_data, Question::FROM_USER);
                break;
            case 'essay':
                $q = new QuestionES($input_data, Question::FROM_USER);
                break;
            case 'multiple-choice':
                $q = new QuestionMC($input_data, Question::FROM_USER);
                break;
            case 'matching':
                $q = new QuestionMA($input_data, Question::FROM_USER);
                break;
            case 'fitb-type':
                $q = new QuestionFT($input_data, Question::FROM_USER);
                break;
            case 'fitb-select':
                $q = new QuestionFS($input_data, Question::FROM_USER);
                break;
            case 'source-code':
                $q = new QuestionSC($input_data, Question::FROM_USER);
                break;
        }
        http_response_code(200);
        header('Content-Type: application/json');
        echo my_json_encode($q->to_auto_marking_test(true, true));
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
Example #24
0
 public function tearDown()
 {
     // Restore selected authenticator
     // MemberAuthenticator might not actually be present
     if (!in_array('MemberAuthenticator', $this->priorAuthenticators)) {
         Authenticator::unregister('MemberAuthenticator');
     }
     foreach ($this->priorAuthenticators as $authenticator) {
         Authenticator::register($authenticator);
     }
     Authenticator::set_default_authenticator($this->priorDefaultAuthenticator);
     // Restore unique identifier field
     Member::config()->unique_identifier_field = $this->priorUniqueIdentifierField;
     Security::config()->remember_username = $this->priorRememberUsername;
     parent::tearDown();
 }
 /**
  * The authenticate function
  *
  * Takes the basic auth details and attempts to log a user in from the DB
  *
  * @return Member|false The Member object, or false if no member
  */
 public static function authenticate()
 {
     //if there is no username or password, break
     if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
         return false;
     }
     //Attempt to authenticate with the default authenticator for the site
     $authClass = Authenticator::get_default_authenticator();
     $member = $authClass::authenticate(array('Email' => $_SERVER['PHP_AUTH_USER'], 'Password' => $_SERVER['PHP_AUTH_PW']));
     //Log the member in and return the member, if they were found
     if ($member) {
         $member->LogIn(false);
         return $member;
     }
     return false;
 }
 public static function setUpBeforeClass()
 {
     self::$client = Authenticator::authenticate();
     // create a test concept
     $randomn = rand(0, 2048);
     self::$prefLabel = 'testPrefLable_' . $randomn;
     self::$altLabel = 'testAltLable_' . $randomn;
     self::$hiddenLabel = 'testHiddenLable_' . $randomn;
     self::$notation = 'test-xxx-' . $randomn;
     self::$uuid = uniqid();
     self::$about = BASE_URI_ . CONCEPT_collection . "/" . self::$notation;
     $xml = '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:skos="http://www.w3.org/2004/02/skos/core#" xmlns:openskos="http://openskos.org/xmlns#" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dcmi="http://dublincore.org/documents/dcmi-terms/#">' . '<rdf:Description rdf:about="' . self::$about . '">' . '<rdf:type rdf:resource="http://www.w3.org/2004/02/skos/core#Concept"/>' . '<skos:prefLabel xml:lang="nl">' . self::$prefLabel . '</skos:prefLabel>' . '<skos:altLabel xml:lang="nl">' . self::$altLabel . '</skos:altLabel>' . '<skos:hiddenLabel xml:lang="nl">' . self::$hiddenLabel . '</skos:hiddenLabel>' . '<openskos:set rdf:resource="' . BASE_URI_ . CONCEPT_collection . '"/>' . '<openskos:uuid>' . self::$uuid . '</openskos:uuid>' . '<skos:notation>' . self::$notation . '</skos:notation>' . '<skos:inScheme  rdf:resource="http://data.beeldengeluid.nl/gtaa/Onderwerpen"/>' . '<skos:topConceptOf rdf:resource="http://data.beeldengeluid.nl/gtaa/Onderwerpen"/>' . '<skos:definition xml:lang="nl">testje (voor def ingevoegd)</skos:definition>' . '</rdf:Description>' . '</rdf:RDF>';
     self::$response0 = RequestResponse::CreateConceptRequest(self::$client, $xml, "false");
     //var_dump(self::$response0->getBody());
     print "\n Creation status: " . self::$response0->getStatus() . "\n";
 }
 public function testCollectionsRDFXML()
 {
     print "\n" . "Test: get collection. ";
     $client = Authenticator::authenticate();
     //prepare and send request
     $client->setUri(BASE_URI_ . '/public/api/collections/' . COLLECTION_1_tenant . ":" . COLLECTION_1_code . '.rdf');
     $client->setConfig(array('maxredirects' => 0, 'timeout' => 30));
     $client->SetHeaders(array('Accept' => 'text/html,application/xhtml+xml,application/xml', 'Content-Type' => 'text/xml', 'Accept-Language' => 'nl,en-US,en', 'Accept-Encoding' => 'gzip, deflate', 'Connection' => 'keep-alive'));
     $response = $client->request(Zend_Http_Client::GET);
     // analyse respond
     if ($response->getStatus() != 200) {
         print "\n " . $response->getMessage();
     }
     $this->AssertEquals(200, $response->getStatus());
     $this->assertionsForXMLRDFCollection($response);
 }
    public static function setUpBeforeClass()
    {
        self::$client = Authenticator::authenticate();
        // create a test concept
        $randomn = rand(0, 2048);
        self::$prefLabel = 'testImportPrefLable_' . $randomn;
        self::$notation = 'test-import-' . $randomn;
        print "\n " . self::$notation . "\n";
        self::$uuid = uniqid();
        self::$about = BASE_URI_ . CONCEPT_collection . "/" . self::$notation;
        self::$creator = CREATOR;
        $xml = '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:skos="http://www.w3.org/2004/02/skos/core#" xmlns:openskos="http://openskos.org/xmlns#" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:ns0="http://dublincore.org/documents/dcmi-terms/#">' . '<rdf:Description rdf:about="' . self::$about . '">' . '<rdf:type rdf:resource="http://www.w3.org/2004/02/skos/core#Concept"/>' . '<skos:notation>' . self::$notation . '</skos:notation>' . '<skos:inScheme rdf:resource="http://hdl.handle.net/11148/CCR_P-DialogueActs_1bb8b49f-7260-6731-6479-408c29cead73"/>' . '<skos:inScheme rdf:resource="http://hdl.handle.net/11148/CCR_P-LexicalSemantics_0d519a3c-85a6-ea17-d93c-8b89339ffc88"/>' . '<skos:inScheme rdf:resource="http://hdl.handle.net/11148/CCR_P-Metadata_deedbe7e-9a1d-4388-2857-ad0daaf06793"/>' . '<skos:inScheme rdf:resource="http://hdl.handle.net/11148/CCR_P-Morphosyntax_c99c78ee-1425-c8f3-33e3-fe2a4b2ec7ca"/>' . '<skos:inScheme rdf:resource="http://hdl.handle.net/11148/CCR_P-SemanticContentRepresentation_37ab80c4-cf9f-18dd-c319-e6554b1d9462"/>' . '<skos:inScheme rdf:resource="http://hdl.handle.net/11148/CCR_P-Syntax_ba63dab1-103c-f8ee-81c3-f32a101e5c96"/>' . '<skos:inScheme rdf:resource="http://hdl.handle.net/11148/CCR_P-Terminology_bf8fdd3f-0075-bca2-ae35-1070be98f856"/>' . '<skos:inScheme rdf:resource="http://hdl.handle.net/11148/CCR_P-Translation_d8214c27-7c8f-9d05-e6ca-ea8fdc922a1c"/>' . '<skos:topConceptOf rdf:resource="http://hdl.handle.net/11148/CCR_P-Metadata_deedbe7e-9a1d-4388-2857-ad0daaf06793"/>' . '<skos:topConceptOf rdf:resource="http://hdl.handle.net/11148/CCR_P-Terminology_bf8fdd3f-0075-bca2-ae35-1070be98f856"/>' . '<skos:topConceptOf rdf:resource="http://hdl.handle.net/11148/CCR_P-Morphosyntax_c99c78ee-1425-c8f3-33e3-fe2a4b2ec7ca"/>' . '<skos:topConceptOf rdf:resource="http://hdl.handle.net/11148/CCR_P-SemanticContentRepresentation_37ab80c4-cf9f-18dd-c319-e6554b1d9462"/>' . '<skos:topConceptOf rdf:resource="http://hdl.handle.net/11148/CCR_P-Syntax_ba63dab1-103c-f8ee-81c3-f32a101e5c96"/>' . '<skos:topConceptOf rdf:resource="http://hdl.handle.net/11148/CCR_P-LexicalSemantics_0d519a3c-85a6-ea17-d93c-8b89339ffc88"/>' . '<skos:topConceptOf rdf:resource="http://hdl.handle.net/11148/CCR_P-DialogueActs_1bb8b49f-7260-6731-6479-408c29cead73"/>' . '<skos:topConceptOf rdf:resource="http://hdl.handle.net/11148/CCR_P-Translation_d8214c27-7c8f-9d05-e6ca-ea8fdc922a1c"/>' . '<skos:prefLabel xml:lang="nl">' . self::$prefLabel . '</skos:prefLabel>' . '<openskos:uuid>' . self::$uuid . '</openskos:uuid>' . '<skos:scopeNote xml:lang="nl">A text corpus may be limited according to aspects of subject fields, size or time, e.g. mathematical texts, certain periodicals from 1986 onwards. It is used as source material for further linguistic analysis or terminology work. (source: ISO 1087-2, 2.7)</skos:scopeNote>' . '<skos:definition xml:lang="nl">A systematic collection of machine-readable texts or parts of text prepared, coded and stored according to predefined rules. (source: ISO 1087-2, 2.7)</skos:definition>' . '</rdf:Description>' . '</rdf:RDF>';
        self::$boundaryNumeric = '36374246216810994721943965972';
        $part1 = 'Content-Disposition: form-data; name="MAX_FILE_SIZE"
           

10485760';
        $part2 = 'Content-Disposition: form-data; name="xml"; filename="tttt.xml"
Content-Type: text/xml

' . $xml;
        $part3 = 'Content-Disposition: form-data; name="status"

candidate';
        $part4 = 'Content-Disposition: form-data; name="ignoreIncomingStatus"

0';
        $part5 = 'Content-Disposition: form-data; name="lang"

en';
        $part6 = 'Content-Disposition: form-data; name="toBeChecked"

0';
        $part7 = 'Content-Disposition: form-data; name="purge"

0';
        $part8 = 'Content-Disposition: form-data; name="onlyNewConcepts"

0';
        $part9 = 'Content-Disposition: form-data; name="submit"

Submit';
        $boundary = "--" . self::$boundaryNumeric;
        $boundaryLn = $boundary . "\n";
        $lnBoundaryLn = "\n" . $boundaryLn;
        self::$postData = $boundaryLn . $part1 . $lnBoundaryLn . $part2 . $lnBoundaryLn . $part3 . $lnBoundaryLn . $part4 . $lnBoundaryLn . $part5 . $lnBoundaryLn . $part6 . $lnBoundaryLn . $part7 . $lnBoundaryLn . $part8 . $lnBoundaryLn . $part9 . "\n" . $boundary . "--";
    }
function get_programming_languages($request)
{
    Authenticator::assert_manager_or_professor($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale']);
    try {
        $model = new Model();
        $result = $model->get_programming_languages();
        http_response_code(200);
        header('Content-Type: application/json');
        echo my_json_encode($result);
        die;
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}
Example #30
0
function delete_user($username, $request)
{
    Authenticator::assert_manager($request->cookies['authToken']);
    $msg = new Messages($GLOBALS['locale']);
    try {
        $model = new Model();
        if ($model->delete_user($username)) {
            http_response_code(204);
        } else {
            http_response_code(404);
        }
        die;
    } catch (DatabaseException $e) {
        Util::output_errors_and_die($e->getMessage(), 503);
    } catch (Exception $e) {
        Util::output_errors_and_die($e->getMessage(), 400);
    }
}