public function actionGenerate($id) { $station = $this->loadModel($id); $election = Elections::model()->findAll(); $oldtokens = Tokens::model()->findAll('station_id=:station_id', array(':station_id' => $id)); foreach ($oldtokens as $oldtoken) { Votes::model()->deleteAll('token_id=:token_id', array(':token_id' => $oldtoken->id)); } Tokens::model()->deleteAll('station_id=:station_id', array(':station_id' => $id)); $tokens = array(); for ($i = 0; $i < $station->voters_count; $i++) { $token = new Tokens(); $token->election_id = $election[0]->id; $token->station_id = $id; $token->token = $this->generatePassword(); $prevtoken = Tokens::model()->findAll('token=:token', array(':token' => $token->token)); while ($prevtoken) { $token->token = $this->generatePassword(); $prevtoken = Tokens::model()->findAll('token=:token', array(':token' => $token->token)); } $token->done_vote = 0; $token->save(); $tokens[] = $token; } $this->render('generate', array('election' => $election[0], 'tokens' => $tokens, 'station' => $station)); }
/** * Return class name from token * * @param int $staticCall * @return string */ protected function getClassByStaticCall($staticCall) { $step = 1; $staticClassParts = []; while ($this->tokens->getTokenCodeByKey($staticCall - $step) == T_STRING || $this->tokens->getTokenCodeByKey($staticCall - $step) == T_NS_SEPARATOR) { $staticClassParts[] = $this->tokens->getTokenValueByKey($staticCall - $step); $step++; } return implode(array_reverse($staticClassParts)); }
/** * @inheritdoc */ public function getDependencies(Uses $uses) { foreach ($this->throws as $throw) { $class = ''; if ($this->tokens->getTokenCodeByKey($throw + 2) == T_NEW) { $step = 4; while ($this->tokens->getTokenCodeByKey($throw + $step) == T_STRING || $this->tokens->getTokenCodeByKey($throw + $step) == T_NS_SEPARATOR) { $class .= trim($this->tokens->getTokenValueByKey($throw + $step)); $step++; } if ($uses->hasUses()) { $class = $uses->getClassNameWithNamespace($class); } $this->dependencies[] = $class; } } return $this->dependencies; }
public function newAction($id, Request $request) { $em = $this->getDoctrine()->getManager(); $customer = $em->getRepository('OrthIndexBundle:Customers')->findOneBy(array('id' => $id)); $user = new Users(); $form = $this->createForm(new UserType(), $user); $form->handleRequest($request); if ($form->isValid()) { $formData = $form->getData(); function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } $randomPassword = generateRandomString(); $encoderFactory = $this->get('security.encoder_factory'); $encoder = $encoderFactory->getEncoder($user); $salt = '$2a$12$uWepESKverBsrLAuOPY'; $passkeyHash = $encoder->encodePassword($randomPassword, $salt); $user->setPassKey($passkeyHash); $user->setCustomer($customer); $token = new Tokens(); $datetime = new \DateTime('tomorrow'); $datetime->format('Y-m-d H:i:s'); $token->setToken(md5(uniqid())); $token->setExpDate($datetime); $token->setUser($user); $em->persist($token); $em->persist($user); $em->flush(); $message = \Swift_Message::newInstance()->setSubject('Registrierung im OrthShop')->setFrom('*****@*****.**')->setTo($formData->getEmail())->setContentType("text/html")->setBody($this->renderView('OrthIndexBundle:Mail:adminregistrationMail.html.twig', array('user' => $user, 'token' => $token, 'passkey' => $randomPassword), 'text/html')); $this->get('mailer')->send($message); $this->get('session')->getFlashBag()->add('success', 'Der Benutzer wurde erfolgreich gespeichert!'); return $this->redirectToRoute('orth_admin_customer', array('id' => $customer->getId()), 301); } return $this->render('OrthAdminBundle:Users:new.html.twig', array('form' => $form->createView())); }
public function generate(&$user) { if (!is_object($user)) { return false; } //delete all existing tokens $user->tokens->delete(); $secret = openssl_random_pseudo_bytes(32); //generate new token $token = new Tokens(); $token->users_id = $user->id; $token->secret_key = $this->crypt->encryptBase64($secret); $token->created = date('Y-m-d H:i:s'); $token->hmac = hash_hmac('sha256', strtolower($user->username) . '|' . $token->created, $secret, false); //save token information if ($token->save()) { //return encrypted token return $this->crypt->encryptBase64($this->crypt->encrypt($user->username . '|' . $token->created . '|' . $token->hmac)); } return false; }
static function pull() { $tokenGen = new TokenPregen(); $tokens = $tokenGen->getWords(); if (count($tokens) < 2) { $tokens = $tokenGen->regenerate(); $tokens = $tokenGen->save(); $tokens = $tokenGen->getWords(); } //if all fails get them manually if (count($tokens) < 2) { $tokens = Tokens::getList(); } return $tokens; }
public function actionThanks() { $this->layout = "vote"; if (isset($_POST['election_id'])) { $chosen = Yii::app()->session['chosenones']; $donevote = true; if (isset($_POST['token_id'])) { $token = Tokens::model()->find('id=:token', array(':token' => $_POST['token_id'])); if (!$token->done_vote) { $token->done_vote = 1; $token->date_vote = date('Y-m-d H:i'); $token->save(); $donevote = false; } } if (!$donevote) { $seats = Seats::model()->findAll(array("condition" => "election_id=" . $_POST['election_id'], "order" => "priority asc")); foreach ($seats as $seat) { foreach ($chosen[$seat->id] as $candidate_id) { $vote = new Votes(); $vote->token_id = $token->id; $vote->candidate_id = $candidate_id; $vote->save(); } } } $this->render('thanks', array('election' => Elections::model()->find('id=:election_id', array(':election_id' => $_POST['election_id'])))); } }
function parse_pattern($source, \ArrayIterator $options) { $tokens = Tokens::fromPattern($source); $result = parse_expr($tokens, $options); if ($tokens->current() != null) { $tokens->raiseException('unexpected ending: ' . implode(' ', $tokens->left())); } return new Required($result); }
public static function rawValue($value) { if ($tokenType = Tokens::test($value)) { if ($tokenType == 'u') { $value = Crush::$process->tokens->get($value)->value; } elseif ($tokenType == 's') { $value = Crush::$process->tokens->get($value); } } return $value; }
/** * @param $index * @param Tokens $tokens */ public function replace($index, Tokens $tokens) { $this->tokens = array_merge(array_slice($this->tokens, 0, $index), $tokens->getTokens(), array_slice($this->tokens, $index + 1)); }
<input type="submit" value="Continue" /> </div> </div> <br /><br /> </form> </div> </div>'; } else { //check if the key is set if ($key) { //load the Tokens module $CORE->load_CoreModule('tokens'); //construct $token = new Tokens(); //Set the application string so the token is only valid for this app $token->setApplication('PRECOVER'); //set and validate the token $TokenValidation = $token->set_decodedToken($key); //make sure the token checks out if ($TokenValidation === true) { //the token is valid, save the token for the execute $_SESSION['P_Recovery_Token'] = $key; echo ' <div class="page-desc-holder"> This is the final step of the password recovery process, all you have to do is to enter your new password. </div> <div class="container_3 account-wide" align="center">
function storeParsedTokens($xmlString) { // $xmlString is the lemnatized XML result from the Edina Geoparser $sentencesPerPage = $this->sentencesPerPage(); $output = false; $gazSourceRefs = array(); $gazRbIDs = array(); $tokensObj = new Tokens(); //class for manipulating tokens in the database $documentIn = $tokensObj->checkDocumentDone($this->docID); if (!$documentIn) { @($xml = simplexml_load_string($xmlString)); unset($xmlString); if ($xml) { $output = array(); $pageNumber = 1; $sentPage = array(); foreach ($xml->xpath("//s") as $sentence) { $sentID = false; foreach ($sentence->xpath("@id") as $xres) { $sentID = (string) $xres; } //echo "<h2>Sentence: ".$sentID."</h2>"; $sentPage[] = $sentID; if (count($sentPage) >= $sentencesPerPage) { unset($sentPage); $sentPage = array(); $pageNumber++; } foreach ($sentence->xpath("w") as $word) { $tokenID = false; $pws = null; $token = false; $location = false; $gazRbID = false; $gazSource = false; $gazRef = false; foreach ($word->xpath("@id") as $xres) { $tokenID = (string) $xres; } foreach ($word->xpath("text()") as $xres) { $token = (string) $xres; } foreach ($word->xpath("@pws") as $xres) { $pws = (string) $xres; if ($pws == "yes") { $pws = true; } else { $pws = false; } } foreach ($word->xpath("@locname") as $xres) { $location = (string) $xres; } if ($location != false) { //echo "<p><strong>Token: $token (".$tokenID.") ($location)</strong></p>"; foreach ($xml->xpath("//ent[parts/part/@ew = '{$tokenID}']") as $ent) { foreach ($ent->xpath("@id") as $xres) { $gazRbID = (string) $xres; } foreach ($ent->xpath("@gazref") as $xres) { $gazRef = (string) $xres; } foreach ($ent->xpath("@source-gazref") as $xres) { $gazSource = (string) $xres; if (!in_array($gazSource, $gazSourceRefs)) { $gazSourceRefs[] = $gazSource; $this->gazSourceRefs = $gazSourceRefs; } } } if (!$gazRbID) { $location = "[place]"; //we couldn't find an entity for this token, but we want to note it is a place } else { $location = $gazRbID; } } //end case of a place reference $data = array("docID" => $this->docID, "batchID" => $this->batchID, "pageID" => $pageNumber, "sentID" => $sentID, "tokenID" => $tokenID, "pws" => $pws, "gazRef" => $location, "token" => $token); $DBtokenID = $tokensObj->addRecord($data); if ($gazRbID != false && $DBtokenID != false) { if (!array_key_exists($gazRbID, $gazRbIDs)) { $gazRbIDs[$gazRbID] = $DBtokenID; //associate the place identification with the database token id $this->gazRbIDs = $gazRbIDs; } } $output[] = $DBtokenID; } //end loop through tokens in a sentence } //end loop through sentences } //end case of valid XML } //end case where the document is not yet done return $output; }
public function actionResultform($id) { $this->layout = 'blankback'; $seats = Seats::model()->with(array('candidates.votes' => array('order' => 'candidates.votescount desc')))->findAll(array('condition' => 't.election_id=' . $id, 'order' => 'priority asc')); $election = Elections::model()->with('tokens')->findByPk($id); $usedtokens = Tokens::model()->used($id)->findAll(); $mPDF1 = Yii::app()->ePdf->mpdf(); $mPDF1->WriteHTML($this->render('resultform', array('seats' => $seats, 'election' => $election, 'usedtokens' => $usedtokens), true)); $mPDF1->Output('results-' . $election->name . '.pdf', 'I'); }
protected function captureCommentAndString($str) { $process = $this->process; $callback = function ($m) use($process) { $fullMatch = $m[0]; if (strpos($fullMatch, '/*') === 0) { // Bail without storing comment if output is minified or a private comment. if ($process->minifyOutput || strpos($fullMatch, '/*$') === 0) { $label = ''; } else { // Fix broken comments as they will break any subsquent // imported files that are inlined. if (!preg_match('~\\*/$~', $fullMatch)) { $fullMatch .= '*/'; } $label = $process->tokens->add($fullMatch, 'c'); } } else { // Fix broken strings as they will break any subsquent // imported files that are inlined. if ($fullMatch[0] !== $fullMatch[strlen($fullMatch) - 1]) { $fullMatch .= $fullMatch[0]; } $label = $process->tokens->add($fullMatch, 's'); } return $process->generateMap ? Tokens::pad($label, $fullMatch) : $label; }; return preg_replace_callback(Regex::$patt->commentAndString, $callback, $str); }
<?php if (!defined('init_executes')) { header('HTTP/1.0 404 not found'); exit; } //Load the Tokens Module $CORE->load_CoreModule('tokens'); //setup new instance of multiple errors $ERRORS->NewInstance('password_recovery'); //Define the variables $password = isset($_POST['password']) ? $_POST['password'] : false; $password2 = isset($_POST['password2']) ? $_POST['password2'] : false; $key = isset($_SESSION['P_Recovery_Token']) ? $_SESSION['P_Recovery_Token'] : false; //construct $token = new Tokens(); //Set the application string so the token is only valid for this app $token->setApplication('PRECOVER'); ###################################### ###### NEW PASSWORD CHECK ############ if (!$password) { //no new password $ERRORS->Add('Please enter new password.'); } else { if (!$password2) { //password not confirmed $ERRORS->Add('Please confirm your new password.'); } else { if ($password != $password2) { //password do not match $ERRORS->Add('You\'ve failed to confirm your new password.');
public static function registerDefaults() { Tokens::register(array("theme_dir" => Themes::$curr_theme->getPublicPath(), "public_root" => TH_PUB_ROOT, "root" => TH_ROOT, "public_content_dir" => TH_PUB_ROOT . TH_CONTENT, "content_dir" => TH_ROOT . TH_CONTENT, "uploads_dir" => TH_ROOT . TH_UPLOADS, "public_uploads_dir" => TH_PUB_ROOT . TH_UPLOADS)); }
public function bookpagejsonAction() { $this->_helper->viewRenderer->setNoRender(); $requestParams = $this->_request->getParams(); $data = false; if (isset($requestParams['docID']) && isset($requestParams['pageID'])) { $docID = $requestParams['docID']; $pageID = $requestParams['pageID']; Zend_Loader::loadClass("Document"); Zend_Loader::loadClass("Tokens"); Zend_Loader::loadClass("Issues"); $docObj = new Document(); $translated = $docObj->getTranslatedVersions($docID); $tokObj = new Tokens(); if ($docID == 2) { //$tokObj->tokenStructure($docID); } $text = $tokObj->getGapVisDocPage($docID, $pageID); $textAdded = false; if ($text != false) { foreach ($translated as $row) { $lang = $row["lang"]; $transDocID = $row["documentID"]; if ($transDocID == $docID) { $data["text@" . $lang] = $text; $textAdded = true; } else { $data["text@" . $lang] = $tokObj->getGapVisDocPage($transDocID, $pageID); } } if (!$textAdded) { $data["text"] = $text; } $data["section"] = $tokObj->sectionID; $data["image"] = false; } } if (!$data) { $this->view->requestURI = $this->_request->getRequestUri(); return $this->render('404error'); } else { $output = Zend_Json::encode($data); $output = preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U\$1')))", json_encode($data)); //$output = json_encode($data, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE); } //$output["memory"] = memory_get_usage(true); header('Content-Type: application/json; charset=utf8'); header("Access-Control-Allow-Origin: *"); echo $output; }
function svg_preprocess($element) { if (isset($element->data['margin'])) { $margin =& $element->data['margin']; $parts = svg_parselist($margin); $count = count($parts); if ($count === 1) { $margin = array($parts[0], $parts[0], $parts[0], $parts[0]); } elseif ($count === 2) { $margin = array($parts[0], $parts[1], $parts[0], $parts[1]); } elseif ($count === 3) { $margin = array($parts[0], $parts[1], $parts[2], $parts[1]); } else { $margin = $parts; } } else { $element->data['margin'] = array(0, 0, 0, 0); } // 'Unzip' string tokens on data attributes. foreach (array('points', 'd') as $point_data_attr) { if (isset($element->attrs[$point_data_attr])) { $value = $element->attrs[$point_data_attr]; if (Tokens::is($value, 's')) { $element->attrs[$point_data_attr] = trim(Crush::$process->tokens->get($value), '"\''); } } } if (isset($element->data['width'])) { $element->svg_attrs['width'] = $element->data['width']; } if (isset($element->data['height'])) { $element->svg_attrs['height'] = $element->data['height']; } }
public function searchAction() { $requestParams = $this->_request->getParams(); Zend_Loader::loadClass("Issues"); Zend_Loader::loadClass("Tokens"); Zend_Loader::loadClass("Document"); Zend_Loader::loadClass("GazetteerRefs"); Zend_Loader::loadClass("GazetteerURIs"); $docID = 1; //default to the first doc $relatedPlaceTokens = false; $placeURIs = false; $foundTokens = false; if (isset($requestParams["uri"])) { $this->view->searchTerm = $requestParams["uri"]; $this->view->searchType = "Place URI"; $tokensObj = new Tokens(); //$tokensObj->tokenStructure($docID); $relatedPlaceTokens = $tokensObj->getUniqueTokensFromPlaceURI($requestParams["uri"]); if (isset($requestParams["docID"])) { if (strlen($requestParams["docID"]) > 0) { $docID = $requestParams["docID"]; } } $gazRefObj = new GazetteerRefs(); $placeURIs = $gazRefObj->getListofURIs($docID); } elseif (isset($requestParams["q"])) { $searchTerm = $requestParams["q"]; $this->view->searchTerm = $searchTerm; $this->view->searchType = "Token String"; $startPage = false; $endPage = false; $structure = false; $page = 1; //default for paging through requests if (isset($requestParams["docID"])) { if (strlen($requestParams["docID"]) > 0) { $docID = $requestParams["docID"]; } } if (isset($requestParams["startPage"])) { if (strlen($requestParams["startPage"]) > 0) { $startPage = $requestParams["startPage"]; } } if (isset($requestParams["endPage"])) { if (strlen($requestParams["endPage"]) > 0) { $endPage = $requestParams["endPage"]; } } if (isset($requestParams["endPage"])) { if (strlen($requestParams["endPage"]) > 0) { $endPage = $requestParams["endPage"]; } } if (isset($requestParams["page"])) { if (strlen($requestParams["page"]) > 0) { $page = $requestParams["page"]; } } $tokensObj = new Tokens(); $foundTokens = $tokensObj->getTokensByToken($searchTerm, $docID, $page, $startPage, $endPage, $structure); } $this->view->docID = $docID; $this->view->requestParams = $requestParams; $this->view->relatedPlaceTokens = $relatedPlaceTokens; $this->view->placeURIs = $placeURIs; $this->view->foundTokens = $foundTokens; }
public function captureUrls($str, $add_padding = false) { $count = preg_match_all(Regex::make('~@import \\s+ (?<import>{{s_token}}) | {{LB}} (?<func>url|data-uri) {{parens}}~ixS'), $str, $m, PREG_OFFSET_CAPTURE); while ($count--) { list($full_text, $full_offset) = $m[0][$count]; list($import_text, $import_offset) = $m['import'][$count]; // @import directive. if ($import_offset !== -1) { $label = $this->add(new Url(trim($import_text))); $str = str_replace($import_text, $add_padding ? str_pad($label, strlen($import_text)) : $label, $str); } else { $func_name = strtolower($m['func'][$count][0]); $url = new Url(trim($m['parens_content'][$count][0])); $url->convertToData = 'data-uri' === $func_name; $label = $this->add($url); $str = substr_replace($str, $add_padding ? Tokens::pad($label, $full_text) : $label, $full_offset, strlen($full_text)); } } return $str; }
function scan($path) { global $aScanItems, $db, $id, $exts; if (is_dir($path)) { if ($dh = opendir($path)) { while (($item = readdir($dh)) !== false) { if (in_array($item, array(".", ".."))) { continue; } $newPath = "{$path}/{$item}"; scan($newPath); } closedir($dh); } } else { if (!in_array(substr($path, strrpos($path, ".") + 1), $exts)) { return; } $code = $line = array(); $source = file_get_contents($path); $tokens = token_get_all($source); $oTokens = new Tokens(); $totalItems = count($aScanItems); while ($token = array_shift($tokens)) { for ($i = 0; $i < $totalItems; $i++) { $itemId = $aScanItems[$i]['id']; $itemName = $aScanItems[$i]['name']; $totalTokens = count($aScanItems[$i]['scanTokens']); if ($oTokens->compareValues($aScanItems[$i]['scanTokens'][0], $token) && !(key($aScanItems[$i]['scanTokens']) == $totalTokens - 1)) { reset($aScanItems[$i]['scanTokens']); unset($code[$itemId], $line[$itemId]); } $aToken = current($aScanItems[$i]['scanTokens']); if (isset($code[$itemId])) { $t = $oTokens->parseToken($token); $code[$itemId] .= $t['value']; } $result = $oTokens->compareValues($aToken, $token); if ($result) { if (!isset($line[$itemId]) && isset($token[2])) { $line[$itemId] = $token[2]; } if (!isset($code[$itemId])) { $t = $oTokens->parseToken($token); $code[$itemId] = $t['value']; } if (key($aScanItems[$i]['scanTokens']) == $totalTokens - 1) { if (!isset($line[$itemId])) { if (!isset($offset)) { $offset = 0; } $pos = strpos($source, $code[$itemId], $offset); $line[$itemId] = substr_count($source, "\n", null, $pos) + 1; $offset = $pos + strlen($code[$itemId]); } $db->query('INSERT INTO scanresults (parentid, file, item, line, code) VALUES(?d, ?, ?, ?d, ?)', $id, $path, $itemName, $line[$itemId], $code[$itemId]); reset($aScanItems[$i]['scanTokens']); unset($code[$itemId], $line[$itemId]); continue; } next($aScanItems[$i]['scanTokens']); } else { if ($oTokens->compareValues($aScanItems[$i]['scanTokens'][$totalTokens - 1], $token)) { reset($aScanItems[$i]['scanTokens']); unset($code[$itemId], $line[$itemId]); } if ($aToken[2] == TOKEN_JUSTAFTER && !$oTokens->compareCodes($token, T_TERMINAL)) { reset($aScanItems[$i]['scanTokens']); unset($code[$itemId], $line[$itemId]); } } } } } }
function alterTokenPlace($tokenID, $placeURI, $note) { $output = false; $db = $this->startDB(); $tokensObj = new Tokens(); $tokenData = $tokensObj->getTokenByID($tokenID); if (is_array($tokenData)) { $token = $tokenData["token"]; $paraID = $tokenData["paraID"]; $pageID = $tokenData["pageID"]; $docID = $tokenData["docID"]; $data = array("active" => false, "issueType" => "Place URI change", "oldID" => 0, "docID" => $docID, "pageID" => $pageID, "placeID" => 0, "tokenID" => $tokenID, "note" => $note); $gazRefObj = new GazetteerRefs(); $ok = $gazRefObj->updatePlaceReference($tokenID, $docID, $placeURI); if (!$ok) { $data["active"] = true; $data["note"] .= " Errors: " . implode(" ", $gazRefObs->errors); } try { $db->insert("gap_issues", $data); $this->lastIssueID = $db->lastInsertId(); $output = true; } catch (Exception $e) { } } }
private function getTokens($active = true, $revoked = false) { $ret_val = null; //First of all does this user exist? $user = $this->hasOne(User::className(), ['user_id' => 'user_id']); switch ($user instanceof User) { case true: $cond = ['active' => 1, 'revoked' => 0]; switch ($active) { case false: $cond['active'] = 0; break; } switch ($revoked) { case true: $cond['revoked'] = 1; break; } //Ok let's get their tokens $ret_val = $this->hasMany(Tokens::className(), ['user_id' => 'user_id'])->where($cond)->asArray()->all(); break; } return $ret_val; }
if ($res->rowCount() > 0) { $row = $res->fetch(PDO::FETCH_ASSOC); } else { if ($email) { $ERRORS->Add('Incorrent E-Mail address. Please make sure you enter the correct E-Mail address of the account.'); } } unset($res); //Check for errors $ERRORS->Check('/index.php?page=password_recovery'); #################################################################### ## The actual script begins here //assume failure $success = false; //Let's setup our token $token = new Tokens(); //Set the account ID to be included as salt $token->setIdentifier($row[$columns['id']]); //Set the application string so the token is only valid for this app $token->setApplication('PRECOVER'); //Set the token expiration time $token->setExpiration($emailTokenLifetime); //Save the user ID under the token $token->setExternalData($row); //Generate a key for the token $token->generateKey(); //get the encoded key $key = $token->get_encodedToken(); //register the token $tokenReg = $token->registerToken(); //continue only if the key was successfully registered
/** * Check if the array at index is multiline. * * This only checks the root-level of the array. * * @param int $index * * @return bool */ public function isArrayMultiLine($index) { if (!$this->isArray($index)) { throw new \InvalidArgumentException('Not an array at given index'); } $tokens = $this->tokens; // Skip only when its an array, for short arrays we need the brace for correct // level counting if ($tokens[$index]->isGivenKind(T_ARRAY)) { $index = $tokens->getNextMeaningfulToken($index); } $endIndex = $tokens[$index]->equals('(') ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index) : $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); for (++$index; $index < $endIndex; ++$index) { $token = $tokens[$index]; $blockType = Tokens::detectBlockType($token); if ($blockType && $blockType['isStart']) { $index = $tokens->findBlockEnd($blockType['type'], $index); continue; } if ($token->isWhitespace() && !$tokens[$index - 1]->isGivenKind(T_END_HEREDOC) && false !== strpos($token->getContent(), "\n")) { return true; } } return false; }
// NIVs date_default_timezone_set('UTC'); // Classes, vendor require './vendor/autoload.php'; require './classes/autoinclude.php'; // Router follows... $router = new AltoRouter(); // Index $router->map('GET', '/', function () { $tmpPresentation = new tmpPresentation(); echo $tmpPresentation->generatePage("TfEL Maths Pedagogy", "<h3>TfEL Maths Pedagogy <small>Shared Reflection API</small></h3> <p>Expects arguments on <code>/s/</code> or <code>/a/</code>.</p><p><strong>Here by accident?</strong><br>You probably followed a broken link to someone's shared observation. Ask them to send you the link again.</p><p><strong>Still totally lost?</strong><br>We can help you figure out where you need to go, email <code>DECD.TfEL@sa.gov.au</code>.")->page; }); // Addition $router->map('POST|PUT', '/a/v[i:version]/[:token]', function ($version, $token) { header("Content-Type: application/json"); $tokens = new Tokens(); if ($tokens->verifyToken($token) && $version == 1) { $shareData = new shareData(); $return = $shareData->createShare(file_get_contents('php://input')); if (!$return) { echo json_encode("Failed to create share URL."); } else { echo json_encode($return); } } else { echo json_encode("Invalid token, or outdated app."); } }); // Get $router->map('GET', '/s/[i:shareid]', function ($shareid) { $shareData = new shareData();
private static $operators = ["STRING_NEQ" => ["!=", "not", "is not"], "NUMERIC_NEQ" => ["!=", "not", "is not"], "DATETIME_NEQ" => ["!=", "<>", "not", "is not"], "NUMERIC_LTE" => ["<="], "DATETIME_LTE" => ["<="], "NUMERIC_GTE" => [">="], "DATETIME_GTE" => [">="], "NUMERIC_LT" => ["<", "less than"], "DATETIME_LT" => ["<", "before"], "NUMERIC_GT" => [">", "more than"], "DATETIME_GT" => [">", "after"], "STRING_LIKE" => ["~", "like"], "STRING_EQ" => ["=", "equals", "is"], "NUMERIC_EQ" => ["=", "equals", "is"], "DATETIME_EQ" => ["=", "on", "is", "at"], "IN" => ["in"]]; private static $operatorTokenAssociations = ["T_OP_NEQ" => ["STRING_NEQ", "NUMERIC_NEQ", "DATETIME_NEQ"], "T_OP_EQ" => ["STRING_EQ", "NUMERIC_EQ", "DATETIME_EQ"], "T_OP_GTE" => ["NUMERIC_GTE", "DATETIME_GTE"], "T_OP_GT" => ["NUMERIC_GT", "DATETIME_GT"], "T_OP_LTE" => ["NUMERIC_LTE", "DATETIME_LTE"], "T_OP_LT" => ["NUMERIC_LT", "DATETIME_LT"], "T_OP_LIKE" => ["STRING_LIKE"], "T_OP_IN" => ["IN"]]; /** * @var bool */ private static $initialised = false; public static function initialize() { if (self::$initialised) { return; } $tokens = []; foreach (self::$operatorTokenAssociations as $token => $operators) { $strings = []; foreach ($operators as $operator) { $strings = array_merge($strings, self::$operators[$operator]); } $strings = array_unique($strings); usort($strings, function ($a, $b) { return strlen($a) - strlen($b); }); $regex = "/^(" . implode("|", $strings) . ")(\\s|\$)/i"; $tokens[$regex] = $token; } self::$terminalTokens = array_merge($tokens, self::$baseTokens); self::$initialised = true; } } // Initialise the static class Tokens::initialize();
/** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { $model = Tokens::model()->findByPk($id); if ($model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } return $model; }