/** * Forward the user to a specified url * * @param string $url The URL to forward to * @param integer $code [optional] HTTP status code */ public function forward($url, $code = 200) { if (Context::getRequest()->isAjaxCall() || Context::getRequest()->getRequestedFormat() == 'json') { $this->getResponse()->ajaxResponseText($code, Context::getMessageAndClear('forward')); } Logging::log("Forwarding to url {$url}"); Logging::log('Triggering header redirect function'); $this->getResponse()->headerRedirect($url, $code); }
public static function add($key, $value) { if (!self::isInMemorycacheEnabled()) { Logging::log('Key "' . $key . '" not cached (cache disabled)', 'cache'); return false; } apc_store($key, $value); Logging::log('Caching value for key "' . $key . '"', 'cache'); return true; }
public function manufacture($classname, $id, $row = null) { // Check that the id is valid if ((int) $id == 0) { throw new \Exception('Invalid id'); } // Set up the name for the factory array $factory_array_name = "_{$classname}s"; $item = null; // Set up the manufactured array if it doesn't exist if (!isset($this->{$factory_array_name})) { Logging::log("Setting up manufactured array for {$classname}"); $this->{$factory_array_name} = array(); } // If the current id doesn't exist in the manufactured array, manufacture it if (!array_key_exists($id, $this->{$factory_array_name})) { // Initialize a position for the item in the manufactured array $this->{$factory_array_name}[$id] = null; try { // Check if the class is cacheable as well $cacheable = in_array($classname, array('TBGProject', 'TBGStatus', 'TBGPriority', 'TBGCategory', 'TBGUserstate')); $item = null; // If the class is cacheable, check if it exists in the cache if ($cacheable) { if ($item = Cache::get("TBGFactory_cache{$factory_array_name}_{$id}")) { Logging::log("Using cached {$classname} with id {$id}"); } } // If we didn't get an item from the cache, manufacture it if (!$cacheable || !is_object($item)) { $item = new $classname($id, $row); Logging::log("Manufacturing {$classname} with id {$id}"); // Add the item to the cache if it's cacheable if ($cacheable) { Cache::add("TBGFactory_cache{$factory_array_name}_{$id}", $item); } } // Add the manufactured item to the manufactured array $this->{$factory_array_name}[$id] = $item; } catch (Exception $e) { throw $e; } } else { Logging::log("Using previously manufactured {$classname} with id {$id}"); } // Return the item at that id in the manufactured array return $this->{$factory_array_name}[$id]; }
public function write($q) { global $conf; try { $db = new PDO('sqlite:' . $this->dbLocation); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $results = $db->exec($q); $db = NULL; } catch (Exception $e) { echo "Can't write in SQLite database. Please check you have granted write permissions to <tt>meta/</tt> and <tt>meta/db.sqlite</tt>.<br/>Also you can check a list of <a href='https://github.com/alangrafu/lodspeakr/wiki/CommonErrors'>common errors</a> and how to <a href='https://github.com/alangrafu/lodspeakr/wiki/Wipe-out-the-database'>wipe out the database</a>'"; if ($conf['debug']) { Logging::log('Exception exec: ' . $e->getMessage(), E_USER_ERROR); } exit(1); } return $results; }
public function execute($file) { global $conf; global $localUri; global $uri; global $acceptContentType; global $endpoints; global $lodspk; $extension = array_pop(explode(".", $file)); $ct = $this->getContentType($extension); header("Content-type: " . $ct); $uri = $localUri; if ($conf['debug']) { Logging::log("In " . $conf['static']['directory'] . " static file {$file}"); } $htmlExtension = 'html'; if ($conf['static']['haanga'] && substr_compare($file, $htmlExtension, -strlen($htmlExtension), strlen($htmlExtension)) === 0) { $lodspk['home'] = $conf['basedir']; $lodspk['baseUrl'] = $conf['basedir']; $lodspk['module'] = 'static'; $lodspk['root'] = $conf['root']; $lodspk['contentType'] = $acceptContentType; $lodspk['ns'] = $conf['ns']; $lodspk['this']['value'] = $localUri; $lodspk['this']['curie'] = Utils::uri2curie($localUri); $lodspk['local']['value'] = $localUri; $lodspk['local']['curie'] = Utils::uri2curie($localUri); $lodspk['contentType'] = $acceptContentType; $lodspk['endpoint'] = $conf['endpoint']; $lodspk['type'] = $modelFile; $lodspk['header'] = $prefixHeader; $lodspk['baseUrl'] = $conf['basedir']; Utils::processDocument($conf['static']['directory'] . $file, $lodspk, null); } else { echo file_get_contents($conf['static']['directory'] . $file); } }
public function execute($service) { global $conf; global $localUri; global $uri; global $acceptContentType; global $endpoints; global $lodspk; global $firstResults; global $results; $context = array(); $context['contentType'] = $acceptContentType; $context['endpoints'] = $endpoints; //$f = $this->getFunction($localUri); $params = array(); $params = $this->getParams($localUri); //$params[] = $context; //$acceptContentType = Utils::getBestContentType($_SERVER['HTTP_ACCEPT']); $extension = Utils::getExtension($acceptContentType); $args = array(); list($modelFile, $viewFile) = $service; try { $prefixHeader = array(); for ($i = 0; $i < sizeof($params); $i++) { if ($conf['mirror_external_uris'] != false) { $altUri = Utils::curie2uri($params[$i]); $altUri = preg_replace("|^" . $conf['basedir'] . "|", $conf['ns']['local'], $altUri); $params[$i] = Utils::uri2curie($altUri); } } $segmentConnector = ""; for ($i = 0; $i < sizeof($params); $i++) { Utils::curie2uri($params[$i]); //echo $params[$i]." ".Utils::curie2uri($params[$i]);exit(0); $auxPrefix = Utils::getPrefix($params[$i]); if ($auxPrefix['ns'] != NULL) { $prefixHeader[] = $auxPrefix; } $args["arg" . $i] = $params[$i]; $args["all"] .= $segmentConnector . $params[$i]; if ($segmentConnector == "") { $segmentConnector = "/"; } } $results['params'] = $params; $lodspk['home'] = $conf['basedir']; $lodspk['baseUrl'] = $conf['basedir']; $lodspk['module'] = 'service'; $lodspk['root'] = $conf['root']; $lodspk['contentType'] = $acceptContentType; $lodspk['ns'] = $conf['ns']; $lodspk['this']['value'] = $uri; $lodspk['this']['curie'] = Utils::uri2curie($uri); $lodspk['local']['value'] = $localUri; $lodspk['local']['curie'] = Utils::uri2curie($localUri); $lodspk['contentType'] = $acceptContentType; $lodspk['endpoint'] = $conf['endpoint']; $lodspk['type'] = $modelFile; $lodspk['header'] = $prefixHeader; $lodspk['args'] = $args; $lodspk['add_mirrored_uris'] = false; $lodspk['baseUrl'] = $conf['basedir']; $lodspk['this']['value'] = $uri; if ($viewFile == null) { $lodspk['transform_select_query'] = true; } // chdir($lodspk['model']); Utils::queryFile($modelFile, $endpoints['local'], $results, $firstResults); if (!$lodspk['resultRdf']) { $results = Utils::internalize($results); $firstAux = Utils::getfirstResults($results); // chdir($conf['home']); if (is_array($results)) { $resultsObj = Convert::array_to_object($results); $results = $resultsObj; } else { $resultsObj = $results; } $lodspk['firstResults'] = Convert::array_to_object($firstAux); } else { $resultsObj = $results; } //Need to redefine viewFile as 'local' i.e., inside service.foo/ so I can load files with the relative path correctly //$viewFile = $extension.".template"; //chdir($conf['home']); Utils::processDocument($viewFile, $lodspk, $results); } catch (Exception $ex) { echo $ex->getMessage(); if ($conf['debug']) { Logging::log($ex->getMessage(), E_ERROR); } HTTPStatus::send500($uri); } }
public static function activate($code) { $RS = database::Query('SELECT id FROM users WHERE accesscode=:var1 AND status=0', array('var1' => $code), $stats); if ($stats == 1) { $user = new self($RS[0]['id']); $user->set('status', 1); $user->save(); Logging::log(2, $user); } else { $user = new self(); $user->errmsg = Texter::get('user|activationFail'); } return $user; }
/** * Forward the user to a different URL * * @param string $url the url to forward to * @param integer $code HTTP status code */ public function headerRedirect($url, $code = 302) { Logging::log('Running header redirect function'); $this->clearHeaders(); $this->setHttpStatus($code); if (Caspar::getRequest()->isAjaxCall() || Caspar::getRequest()->getRequestedFormat() == 'json') { $this->renderHeaders(); } else { $this->addHeader("Location: {$url}"); $this->renderHeaders(); } exit; }
<?php include_once '/var/www/html/Lux/Core/Helper.php'; $db = new Db("Scoreboard"); $OUTPUT = new Output(); $REQUEST = new Request(); $collection = $db->selectCollection("Users"); $RULES = new Rules(1, "scoreboard"); $REQUEST = new Request(); $quantity = intval($REQUEST->get("quantity", "1")); $asset_id = $REQUEST->get("asset_id"); $document = $collection->findAndModify(array("user_id" => $RULES->getId()), array('$inc' => array("assets." . $asset_id . ".quantity" => $quantity))); $LOG = new Logging("Scoreboard.asset"); $LOG->log($RULES->getId(), 61, $REQUEST->get("asset_id"), $quantity, "User added item to scoreboard Possessions"); $OUTPUT->success(0, $document, null);
<?php // Helper functions and includs include_once '/var/www/html/Lux/Core/Helper.php'; $db = new Db("Inventory"); $OUTPUT = new Output(); $REQUEST = new Request(); $collection = $db->selectCollection("Cart"); $RULES = new Rules(1, "cart"); $REQUEST = new Request(); // get the asset, push it into the cart that is selected $collectionName = $REQUEST->get("collection", "Standard"); $cartName = $REQUEST->get("wishlist", "Default"); $document = $collection->findAndModify(array("user_id" => $RULES->getId()), array('$push' => array("wishlist." . $cartName => MongoDBRef::create($collectionName, $REQUEST->get("id"), "Assets")))); // Used for analytics $LOG = new Logging("Cart.order"); $LOG->log($RULES->getId(), 43, $REQUEST->get("id"), 100, "User Wished for item"); $OUTPUT->success(0, $document, null);
<?php /* Reformatted 12.11.2015 */ // helpers nad includes include_once '/var/www/html/Lux/Core/Helper.php'; // Create Database Connection $db = new Db("SocialNetwork"); $OUTPUT = new Output(); // Get Request Data $REQUEST = new Request(); // No privleges Required $RULES = new Rules(0, "profile"); // Selects collection from Database Connection $collectionName = Helper::getCollectionName($REQUEST, "Groups"); $collection = $db->selectCollection($collectionName); // Format Query $query = Helper::formatQuery($REQUEST, "group_id"); // Used for anayltics $LOG = new Logging("Groups.query"); $LOG->log($RULES->getId(), 72, $query, 100, "Groups Queried"); // Find Documents in Collection $documents = $collection->find($query); // Output $OUTPUT->success(1, $documents); ?>
private static function getModelandView($t, $extension) { global $conf; global $results; global $rPointer; global $lodspk; $objResult = array('modelFile' => null, 'viewFile' => null); //Defining default views and models $curieType = ""; //Get the firstResults type available $typesAndValues = array('rdfs:Resource' => -1, 'rdfs__Resource' => -1); if (!isset($conf['disableComponents']) || $conf['disableComponents'] != true) { foreach ($t as $v) { $curie = Utils::uri2curie($v); $typesAndValues[$curie] = 0; $typesAndValues[str_replace(":", "__", $curie)] = 0; if (isset($conf['type']['priority'][$curie]) && $conf['type']['priority'][$curie] >= 0) { $typesAndValues[$curie] = $conf['type']['priority'][$curie]; $typesAndValues[str_replace(":", "__", $curie)] = $conf['type']['priority'][$curie]; } } } arsort($typesAndValues); $extensionView = $extension . "."; $extensionModel = ''; if ($extension != 'html') { $extensionModel = $extension . '.'; } foreach ($typesAndValues as $v => $w) { $auxViewFile = $conf['home'] . $conf['view']['directory'] . '/' . $conf['type']['prefix'] . '/' . $v . '/' . $extension . '.template'; $auxModelFile = $conf['home'] . $conf['model']['directory'] . '/' . $conf['type']['prefix'] . '/' . $v . '/' . $extension . '.queries'; if ($v == null) { continue; } $lodspk['componentName'] = $v; if (file_exists($auxModelFile)) { $objResult['modelFile'] = $auxModelFile; //$conf['type']['prefix'].'/'.$v.'/'.$extensionModel.'queries'; if (file_exists($auxViewFile)) { $objResult['viewFile'] = $auxViewFile; //$conf['type']['prefix'].'/'.$v.'/'.$extensionView.'template'; } elseif ($extension != 'html') { //View doesn't exists (and is not HTML) $objResult['viewFile'] = null; } break; //return $objResult; } elseif (file_exists($conf['home'] . $conf['model']['directory'] . '/' . $conf['type']['prefix'] . '/' . $v . '/queries')) { $objResult['modelFile'] = $conf['home'] . $conf['model']['directory'] . '/' . $conf['type']['prefix'] . '/' . $v . '/queries'; if (file_exists($auxViewFile)) { $objResult['viewFile'] = $auxViewFile; } else { $lodspk['transform_select_query'] = true; $objResult['viewFile'] = null; } if ($conf['debug']) { Logging::log("LODSPeaKr can't find the proper query. Using HTML query instead.", E_USER_NOTICE); } break; } else { $found = false; if (sizeof($conf['components']['types']) > 0) { foreach ($conf['components']['types'] as $type) { $typeArray = explode("/", $type); $typeName = end($typeArray); if ($v == $typeName && file_exists($type)) { array_pop($typeArray); $conf['type']['prefix'] = array_pop($typeArray); $conf['model']['directory'] = join("/", $typeArray); $conf['view']['directory'] = $conf['model']['directory']; $lodspk['model'] = $conf['model']['directory'] . '/' . $conf['type']['prefix'] . '/' . $typeName . '/queries'; $lodspk['view'] = $conf['view']['directory'] . '/' . $conf['type']['prefix'] . '/' . $typeName . '/' . $extension . '.template'; $objResult['viewFile'] = $lodspk['view']; $objResult['modelFile'] = $lodspk['model']; $found = true; if (!file_exists($objResult['viewFile'])) { $lodspk['transform_select_query'] = true; $objResult['viewFile'] = null; } return $objResult; } } } if ($found) { break; } } /*if($objResult['viewFile'] == null && $extensionView == 'html'){ $objResult['viewFile'] = 'html.template'; }*/ } return $objResult; }
public function processIncomingEmailAccount(IncomingEmailAccount $account) { $count = 0; if ($emails = $account->getUnprocessedEmails()) { try { $current_user = framework\Context::getUser(); foreach ($emails as $email) { $user = $this->getOrCreateUserFromEmailString($email->from); if ($user instanceof User) { if (framework\Context::getUser()->getID() != $user->getID()) { framework\Context::switchUserContext($user); } $message = $account->getMessage($email); $data = $message->getBodyPlain() ? $message->getBodyPlain() : strip_tags($message->getBodyHTML()); if ($data) { if (mb_detect_encoding($data, 'UTF-8', true) === false) { $data = utf8_encode($data); } $new_data = ''; foreach (explode("\n", $data) as $line) { $line = trim($line); if ($line) { $line = preg_replace('/^(_{2,}|-{2,})$/', "<hr>", $line); $new_data .= $line . "\n"; } else { $new_data .= "\n"; } } $data = nl2br($new_data, false); } // Parse the subject, and obtain the issues. $parsed_commit = Issue::getIssuesFromTextByRegex(mb_decode_mimeheader($email->subject)); $issues = $parsed_commit["issues"]; // If any issues were found, add new comment to each issue. if ($issues) { foreach ($issues as $issue) { $text = preg_replace('#(^\\w.+:\\n)?(^>.*(\\n|$))+#mi', "", $data); $text = trim($text); if (!$this->processIncomingEmailCommand($text, $issue) && $user->canPostComments()) { $comment = new Comment(); $comment->setContent($text); $comment->setPostedBy($user); $comment->setTargetID($issue->getID()); $comment->setTargetType(Comment::TYPE_ISSUE); $comment->save(); } } } else { if ($user->canReportIssues($account->getProject())) { $issue = new Issue(); $issue->setProject($account->getProject()); $issue->setTitle(mb_decode_mimeheader($email->subject)); $issue->setDescription($data); $issue->setPostedBy($user); $issue->setIssuetype($account->getIssuetype()); $issue->save(); // Append the new issue to the list of affected issues. This // is necessary in order to process the attachments properly. $issues[] = $issue; } } // If there was at least a single affected issue, and mail // contains attachments, add those attachments to related issues. if ($issues && $message->hasAttachments()) { foreach ($message->getAttachments() as $attachment_no => $attachment) { echo 'saving attachment ' . $attachment_no; $name = $attachment['filename']; $new_filename = framework\Context::getUser()->getID() . '_' . NOW . '_' . basename($name); if (framework\Settings::getUploadStorage() == 'files') { $files_dir = framework\Settings::getUploadsLocalpath(); $filename = $files_dir . $new_filename; } else { $filename = $name; } Logging::log('Creating issue attachment ' . $filename . ' from attachment ' . $attachment_no); echo 'Creating issue attachment ' . $filename . ' from attachment ' . $attachment_no; $content_type = $attachment['type'] . '/' . $attachment['subtype']; $file = new File(); $file->setRealFilename($new_filename); $file->setOriginalFilename(basename($name)); $file->setContentType($content_type); $file->setDescription($name); $file->setUploadedBy(framework\Context::getUser()); if (framework\Settings::getUploadStorage() == 'database') { $file->setContent($attachment['data']); } else { Logging::log('Saving file ' . $new_filename . ' with content from attachment ' . $attachment_no); file_put_contents($new_filename, $attachment['data']); } $file->save(); // Attach file to each related issue. foreach ($issues as $issue) { $issue->attachFile($file); } } } $count++; } } } catch (\Exception $e) { } if (framework\Context::getUser()->getID() != $current_user->getID()) { framework\Context::switchUserContext($current_user); } } $account->setTimeLastFetched(time()); $account->setNumberOfEmailsLastFetched($count); $account->save(); return $count; }
<?php /* Reformatted 12.11.2015 */ // Helper functions adn includes include_once '/var/www/html/Lux/Core/Helper.php'; // Create Database Connection $DB = new Db("Auth"); $OUTPUT = new Output(); // Get Request Data $REQUEST = new Request(); // Admin Privleges required $RULES = new Rules(5, "providers"); // Selects Collection From Database Connection $collectionName = Helper::getCollectionName($REQUEST, "Providers"); $collection = $DB->selectCollection($collectionName); // provider name required for specific query (otherwise all will be returned) $query = Helper::formatQuery($REQUEST, "provider_name", null, array("protocol" => "OAuth2")); // Used for analytics $LOG = new Logging("Auth2.query"); $LOG->log($RULES->getId(), 112, $query, 100, "User viewed items in cart/wishlist"); // Find Documents in Collection $documents = $collection->find($query); // Output $OUTPUT->success(1, $documents);
/* Reformatted 12.11.2015 */ // helper functions and includes include_once '/var/www/html/Lux/Core/Helper.php'; // Create Database Connection $DB = new Db("Auth"); $OUTPUT = new Output(); // Get Request Variables $REQUEST = new Request(); // Admin privleges needed $RULES = new Rules(5, "providers"); // Select Collection From Database $collectionName = Helper::getCollectionName($REQUEST, "Providers"); $collection = $DB->selectCollection($collectionName); // Format Query $query = Helper::formatQuery($REQUEST, "provider_name"); // Values which are accepted by the adjustment Script $permitted = array("provider_name", "base1", "base2", "base3", "client_id", "client_secret", "default_scope"); // Used for Analytics $LOG = new Logging("Auth1.adjust"); $LOG->log($RULES->getId(), 111, $query, 100, "User Modified Asset"); // Format Update and Options $update = Helper::updatePermitted($REQUEST, $permitted); $update["protocol"] = "OAuth2"; $options = Helper::formatOptions($REQUEST); // Find and Modify Documents in Collection $documents = $collection->findAndModify($query, $update, $options); $OUTPUT->success(0, $documents); ?>
$return = $this->user->createPassword($_POST['values']['password_new1'], $this->user->get('id')); if ($return['success'] == 1) { if (isset($_COOKIE['authCookie'])) { $this->user->verifyPassword($this->user->get('mail'), $_POST['values']['password_new1'], 1); } else { $this->user->verifyPassword($this->user->get('mail'), $_POST['values']['password_new1'], 0); } } else { $errmsg[] = $return['errmsg']; } } if ($return['success'] == 0 && count($errmsg) > 0) { echo json_encode(array('success' => 0, 'errmsg' => $errmsg)); } else { echo json_encode(array('success' => 1)); Logging::log(7, $this->user); } break; case 'sendNewPassword': $user = new user($_POST['values']['clientId']); $newPassword = $user->generateRandomPassword(); $loginCredentials = $user->createPassword($newPassword); if ($loginCredentials['success'] === 1) { $result = mailer::sendNewPasswordMail($user, $newPassword); if ($result === true) { $user->set('salt', $loginCredentials['salt']); $user->set('password', $loginCredentials['password']); $user->save(); echo json_encode(array('status' => 'correct', 'msg' => Texter::get('client|sendNewPassword'))); } else { echo json_encode(array('status' => Texter::get('client|sendNewPasswordfail')));
<?php /* Reformatted 12.11.2015 */ // Helper script and includes include_once '/var/www/html/Lux/Core/Helper.php'; // Create Database Connection $DB = new Db("System"); $OUTPUT = new Output(); // Get Request Data $REQUEST = new Request(); // Admin privleges needed $RULES = new Rules(5, "accounts"); // Selects Collection from Databse Connection $collectionName = Helper::getCollectionName($REQUEST, "Accounts", false); $collection = $DB->selectCollection($collectionName); // Format Query $query = Helper::formatQuery($REQUEST, "user", "system_info.user"); // Used for Analytics $LOG = new Logging("Accounts.query"); $LOG->log($RULES->getId(), 2, $RULES->getId(), 100, "User Account Queried"); // Find Documents in Collection $documents = $collection->find($query); // Output $OUTPUT->success(0, $documents); ?>
// Selects Collection From Database Connection $collectionName = Helper::getCollectionName($REQUEST, "Accounts"); $collection = $DB->selectCollection($collectionName); // Format Query $query = Helper::formatQuery($REQUEST, "user", "system_info.user"); // Value's which are accepted by the adjustment script $permitted = array("user", "email", "role", "permissions[]"); // Format update and options $update = Helper::updatePermitted($REQUEST, $permitted); $update = Helper::subDocUpdate($update, "system_info"); $options = Helper::formatOptions($REQUEST); // Get Old Document $document_old = $collection->findOne($query); // Used in Analytics $LOG = new Logging("Accounts.adjust"); $LOG->log($RULES->getId(), 1, $RULES->getId(), 100, "User Modified Account"); // Find and Modify Documents in Collection $results = $collection->findAndModify($query, $update, $options); $document = $collection->findOne($query); // Handle if an Admin is creating an account. Email is needed to notify Account Holder (with password). if (is_null($document_old) && isset($document["system_info"]["email"])) { $password = bin2hex(openssl_random_pseudo_bytes(8)); $hash = password_hash($password, PASSWORD_DEFAULT); // TODO: Change to $setOnInsert $collection->update($document["_id"], array('$set' => array("system_info.hash" => $hash))); // Send new Account holder an Email $user = $document["system_info"]["user"]; $to = $document["system_info"]["email"]; $subject = 'Email Verification'; $message = "An account was created for you by an admistrator. Your user name is \n\n {$user} and password is \n\n {$password}"; $headers = 'From: no-reply@' . $_SERVER["HTTP_HOST"] . "\r\n" . 'X-Mailer: PHP/' . phpversion();
/** * Sends a new random password to a user * * @param object $user The user object to send to. * @param string $newPassword The raw new password (use user->generateRandomPassword()). * * @return integer Returns number of sent mails (1 or 0) */ public static function sendNewPasswordMail($user, $newPassword) { if (self::$_me === null) { self::$_me = new self(); } $substituteEntities = array('newPassword' => $newPassword); self::$_me->set('subject', Texter::get('newPasswordMail|subject')); self::$_me->set('to', $user->get('mail')); self::$_me->set('body', self::$_me->processHTMLTemplate('newPassword.mail', $substituteEntities), 'text/html'); self::$_me->send(); if (self::$_me->result == 1) { Logging::log(101, $user); } return self::$_me->result; }
<?php include_once '/var/www/html/Lux/Core/Helper.php'; $db = new Db("Scoreboard"); $OUTPUT = new Output(); $REQUEST = new Request(); $collection = $db->selectCollection("Users"); $RULES = new Rules(1, "scoreboard"); $REQUEST = new Request(); $level_id = $REQUEST->get("level_id"); $sub_level_id = $REQUEST->get("level_id"); $quantity = $REQUEST->get("change", false) ? $REQUEST->get("change") : $REQUEST->get("value"); $operator = $REQUEST->get("change", false) ? '$inc' : '$set'; $metric = $REQUEST->get("metric"); $document = $collection->findAndModify(array("user_id" => $RULES->getId()), array($operator => array("Levels." . $REQUEST->get("level_id") . ".sub_levels." . $REQUEST->get("sub_level_id") . ".Metrics." . $metric => $quantity))); $LOG = new Logging("Scoreboard.metric"); $LOG->log($RULES->getId(), 63, $REQUEST->get("metric"), $quantity, "User adjusted metric"); $OUTPUT->success(0, $document, null);
public function __($text, $replacements = array(), $html_decode = false) { if (isset($this->_strings[$text])) { $retstring = $this->_strings[$text]; } else { $retstring = $text; Logging::log('The text "' . $text . '" does not exist in list of translated strings.', 'i18n'); $this->_missing_strings[$text] = true; } if (!empty($replacements)) { $tmp = array(); foreach ($replacements as $key => $value) { $tmp[$key] = $value; $retstring = str_replace(array_keys($tmp), array_values($tmp), $retstring); } } if ($html_decode) { $retstring = html_entity_decode($retstring); } return $retstring; }
/** * Present a template * @param string $template_file * @param array $params */ public static function presentTemplate($template_file, $params = array()) { Logging::log("configuring template variables for template {$template_file}"); if (!file_exists($template_file)) { throw new exceptions\TemplateNotFoundException("The template file <b>{$template_file}</b> cannot be found."); } foreach ($params as $key => $val) { ${$key} = $val; } if (array_key_exists('key', $params)) { $key = $params['key']; } if (array_key_exists('val', $params)) { $val = $params['val']; } /** * @global \thebuggenie\core\framework\Request The request object */ $tbg_request = Context::getRequest(); /** * @global \thebuggenie\core\framework\Response The response object */ $tbg_response = Context::getResponse(); /** * @global \thebuggenie\core\framework\Request The request object */ $tbg_routing = Context::getRouting(); /** * @global \thebuggenie\core\entities\User The user object */ $tbg_user = Context::getUser(); Context::loadLibrary('common'); Context::loadLibrary('ui'); Logging::log("rendering template '{$template_file}'"); require $template_file; }
<?php /* Reformatted 12.11.2015 */ // Helpers and includes include_once '/var/www/html/Lux/Core/Helper.php'; // Create Database Connection $DB = new Db("Inventory"); $OUTPUT = new Output(); // Get Request Data $REQUEST = new Request(); // User needs to be logged in for access $RULES = new Rules(1, "cart"); // Select Collection from Connection $collectionName = Helper::getCollectionName($REQUEST, "Cart"); $collection = $DB->selectCollection($collectionName); // Format Query $query = array("user_id" => $RULES->getId()); // Used for anayltics $LOG = new Logging("OAuth.query"); $LOG->log($RULES->getId(), 72, $query, 100, "OAuth Providers Queried"); // Format Limits (Skip, Limit) $options = Helper::formatLimits($REQUEST); // Find Documents $documents = $collection->find($query, $options); // Output $OUTPUT->success(0, $documents); ?>
/* Reformatted 12.11.2015 */ // Helper and includes include_once '/var/www/html/Lux/Core/Helper.php'; // Create Database Connection $DB = new Db("System"); $OUTPUT = new Output(); // Get Request Variables $REQUEST = new Request(); // Admin Privleges needed $RULES = new Rules(5, "cms"); // Select Collection From Database Connection $collectionName = Helper::getCollectionName($REQUEST, "Content"); $collection = $DB->selectCollection($collectionName); // Format Query $query = Helper::formatQuery($REQUEST, "field_name"); // Values which are permitted by the Adjustment Script $permitted = array("field_name", "content.full", "content.short", "header.text", "header.sub", "header.url_safe", "picture.banner", "picture.other[]", "picture.slideshow[]"); // Format Update and options $update = Helper::updatePermitted($REQUEST, $permitted); $options = Helper::formatOptions($REQUEST); // Used for analytics $LOG = new Logging("CMS.adjust"); $LOG->log($RULES->getId(), 51, $query, 100, "Content Updated"); // Find And Modify Documents in Collection $document = $collection->findAndModify($query, $update, $options); // Output $OUTPUT->success(0, $document); ?>
<?php // Helper functions and includes include_once '/var/www/html/Lux/Core/Helper.php'; $db = new Db("Inventory"); $OUTPUT = new Output(); $REQUEST = new Request(); $cart = $db->selectCollection("Cart"); $orders = $db->selectCollection("Orders"); // Must be logged in to place an order $RULES = new Rules(1, "cart"); $REQUEST = new Request(); // get the asset, push it into the cart that is selected $collectionName = $REQUEST->get("collection", "Standard"); $cartName = $REQUEST->get("cart", "Default"); $old = $cart->findAndModify(array("user_id" => $RULES->getId()), array("cart." . $cartName => []), array('new' => false)); // Criteria for an order $document = $orders->insert(array("user_id" => $RULES->getId(), "items" => $old["cart"][$cartName], "status.shipped" => false, "status.recieved" => false, "status.paid" => false, "status.modified" => false, "status.processed" => false, "status.finalized" => false)); // Used for anayltics $LOG = new Logging("Cart.order"); $LOG->log($RULES->getId(), 42, 2, 100, "User Ordered item"); $OUTPUT->success(0, $document, null);
<?php // Helper functions and includes include_once '/var/www/html/Lux/Core/Helper.php'; $db = new Db("Inventory"); $OUTPUT = new Output(); $REQUEST = new Request(); $collection = $db->selectCollection("Cart"); $RULES = new Rules(1, "cart"); $REQUEST = new Request(); // get the asset, push it into the cart that is selected $collectionName = $REQUEST->get("collection", "Standard"); $cartName = $REQUEST->get("cart", "Default"); $document = $collection->findAndModify(array("user_id" => $RULES->getId()), array('$push' => array("carts." . $cartName => MongoDBRef::create($collectionName, $REQUEST->get("id"), "Assets")))); // Used for analytics $LOG = new Logging("Cart.add"); $LOG->log($RULES->getId(), 41, $REQUEST->get("id"), 100, "User added item to cart"); $OUTPUT->success(0, $document, null);
public function getUploadStatus($id) { Logging::log('sanitizing id'); // sanitize the ID value $id = preg_replace('/[^a-z0-9]/i', '', $id); if (mb_strlen($id) == 0) { Logging::log('oops, invalid id ' . $id); return; } // ensure the uploaded status data exists in the session if (!array_key_exists($id, $_SESSION['__upload_status'])) { Logging::log('upload with this id ' . $id . ' is not in progress yet'); $_SESSION['__upload_status'][$id] = array('id' => $id, 'finished' => false, 'percent' => 0, 'total' => 0, 'complete' => 0); } // retrieve the data from the session so it can be updated and returned $ret = $_SESSION['__upload_status'][$id]; // if we can't retrieve the status or the upload has finished just return if (!self::CanGetUploadStatus() || $ret['finished']) { Logging::log('upload either finished or we cant track it'); // $ret['finished'] = true; // $ret['percent'] = 100; // $ret['complete'] = 100; return $ret; } // retrieve the upload data from APC $status = apc_fetch('upload_' . $id); // false is returned if the data isn't found if ($status) { $ret['finished'] = (bool) $status['done']; $ret['total'] = $status['total']; $ret['complete'] = $status['current']; if (array_key_exists('file_id', $ret)) { $status['file_id'] = $ret['file_id']; } elseif (array_key_exists('error', $ret)) { $status['failed'] = true; $status['error'] = $ret['error']; } // calculate the completed percentage if ($ret['total'] > 0) { $ret['percent'] = $ret['complete'] / $ret['total'] * 100; } // write the changed data back to the session $_SESSION['__upload_status'][$id] = $ret; } return $ret; }
require_once "resources/classes/logging.php"; if (permission_exists('dialplan_add') || permission_exists('inbound_route_add') || permission_exists('outbound_route_add') || permission_exists('fifo_add') || permission_exists('time_condition_add')) { //access granted } else { echo "access denied"; exit; } //add multi-lingual support $language = new text(); $text = $language->get(); //logger $log = new Logging(); //set the http get/post variable(s) to a php variable if (isset($_REQUEST["id"])) { $dialplan_uuid = check_str($_REQUEST["id"]); $log->log("debug", "isset id."); $log->log("debug", $dialplan_uuid); } //get the dialplan data $dialplan_uuid = $_GET["id"]; $sql = "select * from v_dialplans "; $sql .= "where dialplan_uuid = '{$dialplan_uuid}' "; $log->log("debug", check_sql($sql)); $prep_statement = $db->prepare(check_sql($sql)); $prep_statement->execute(); $result = $prep_statement->fetchAll(PDO::FETCH_NAMED); $log->log("debug", $result); foreach ($result as &$row) { $domain_uuid = $row["domain_uuid"]; $database_dialplan_uuid = $row["dialplan_uuid"]; $app_uuid = $row["app_uuid"];
public function query($q, $output = 'json') { global $conf; $auxoutput = $this->params['output']; $accept = 'application/sparql-results+json'; if ($output != null) { $this->params['output'] = $output; } if ($output == 'xml') { $accept = 'application/sparql-results+xml'; } elseif ($output == 'rdf') { $accept = 'application/rdf+xml'; } $aux = ""; $modified = 0; $now = time(); $cacheFile = ""; if (is_int($conf['cache']['global']) && $conf['cache']['global'] > 0) { $cacheFile = $conf['home'] . "cache/query" . md5($this->sparqlUrl . $q); if (file_exists($cacheFile)) { $modified = filemtime($cacheFile); } } if (is_int($conf['cache']['global']) && $conf['cache']['global'] > 0 && $modified + $conf['cache']['global'] > $now) { if ($conf['debug']) { $msg = "Taking data from cache ({$cacheFile}). Renewal in " . ($modified + $conf['cache']['global'] - $now) . " seconds\n"; Logging::log($msg); echo $msg; } $aux = file_get_contents($cacheFile); } else { $c = curl_init(); $context = array(); $context[0] = 'Connection: close'; $context[1] = 'Accept: ' . $accept; $params = $this->params; $params['query'] = $q; $url = $this->sparqlUrl . '?' . http_build_query($params, '', '&'); curl_setopt($c, CURLOPT_URL, $url); curl_setopt($c, CURLOPT_HTTPHEADER, $context); curl_setopt($c, CURLOPT_USERAGENT, "LODSPeaKr version " . $conf['version']); curl_setopt($c, CURLOPT_RETURNTRANSFER, true); $aux = curl_exec($c); // execute the curl command if ($conf['debug']) { if ($aux == false) { Logging::log("Error executing SPARQL query (" . $this->sparqlUrl . "): " . curl_error($c), E_USER_ERROR); echo "Error executing SPARQL query (" . $this->sparqlUrl . "): " . curl_error($c); } } $http_status = intval(curl_getinfo($c, CURLINFO_HTTP_CODE)); curl_close($c); $this->params['output'] = $auxoutput; if (is_int($conf['cache']['global']) && $conf['cache']['global'] > 0 && $http_status == 200) { file_put_contents($cacheFile, $aux, LOCK_EX); if ($conf['debug']) { $msg = "Notice: Writing results in " . $cacheFile . "\n"; Logging::log($msg, E_USER_NOTICE); echo $msg; } } } if (preg_match("/select/i", $q)) { $r = json_decode($aux, true); if ($conf['debug']) { if ($r == false) { Logging::log("Warning: Results from a SELECT sparql query couldn't get parsed", E_USER_WARNING); echo "Warning: Results from a SELECT sparql query couldn't get parsed"; } } return $r; } if (preg_match("/describe/i", $q)) { return $aux; } if (preg_match("/construct/i", $q)) { return $aux; } if (preg_match("/ask/i", $q)) { $r = json_decode($aux, true); return $r; } }
public static function queryFile($modelFile, $e, &$rPointer, &$fPointer) { global $conf; global $lodspk; global $results; global $firstResults; global $uri; $data = array(); $strippedModelFile = str_replace('endpoint.', '', str_replace('.query', '', $modelFile)); if (!is_dir($modelFile)) { require_once $conf['home'] . 'lib/Haanga/lib/Haanga.php'; Haanga::configure(array('cache_dir' => $conf['home'] . 'cache/', 'autoescape' => FALSE)); //Haanga supports the dot (.) convention only for objects if (is_array($lodspk)) { $lodspkObj = Convert::array_to_object($lodspk); $lodspk = $lodspkObj; } $r2 = Convert::array_copy($results); $models = Convert::array_to_object($r2); $f2 = Convert::array_copy($firstResults); $first = Convert::array_to_object($f2); $vars = compact('uri', 'lodspk', 'conf', 'models', 'first'); $q = file_get_contents($modelFile); if ($q == false) { HTTPStatus::send500("<br/>I can't load " . $modelFile . " in " . getcwd()); } $fnc = Haanga::compile($q); $query = $fnc($vars, TRUE); if (is_object($lodspk)) { $lodspkObj = Convert::object_to_array($lodspk); $lodspk = $lodspkObj; } $query = Utils::addPrefixes($query); if ($lodspk['transform_select_query'] == true) { include_once $conf['home'] . 'lib/arc2/ARC2.php'; $parser = ARC2::getSPARQLParser(); $parser->parse($query); $sparqlConstruct = array(); if (!$parser->getErrors()) { $resultVars = array(); $q_infos = $parser->getQueryInfos(); foreach ($q_infos['query']['result_vars'] as $v) { if ($v['type'] == 'var') { $resultVars[$v['value']] = 1; } } $x = Utils::extractObj($q_infos['query']['pattern']); foreach ($x as $v) { if ($resultVars[$v['s']] && $v['s_type'] == 'var' || $resultVars[$v['p']] && $v['p_type'] == 'var' || $resultVars[$v['o']] && $v['o_type'] == 'var') { array_push($sparqlConstruct, $v); } } $construct = ""; foreach ($sparqlConstruct as $v) { if ($v['s_type'] == 'uri') { $construct .= "<" . $v['s'] . "> "; } elseif ($v['s_type'] == 'var') { $construct .= '?' . $v['s'] . ' '; } else { $construct .= $v['s'] . " "; } if ($v['p_type'] == 'uri') { $construct .= "<" . $v['p'] . "> "; } elseif ($v['p_type'] == 'var') { $construct .= '?' . $v['p'] . ' '; } else { $construct .= $v['p'] . " "; } if ($v['o_type'] == 'uri') { $construct .= "<" . $v['o'] . "> "; } elseif ($v['o_type'] == 'literal') { $construct .= '"' . $v['o'] . '" '; } elseif ($v['o_type'] == 'var') { $construct .= '?' . $v['o'] . ' '; } else { $construct .= $v['o'] . " "; } $construct .= ".\n"; } if ($construct == "") { if (sizeof($q_infos['query']['result_vars']) > 0) { //For now, assuming variables are in the GRAPH ?g $query = "CONSTRUCT {?g ?x ?y} WHERE{GRAPH ?g{?g ?x ?y}}"; } else { if (!preg_match('/construct/i', $query)) { HTTPStatus::send500(); } } } else { $query = preg_replace('/select\\s*[^{]*\\s*(where)?\\s*{/i', 'CONSTRUCT {' . $construct . '} WHERE{', $query); } } else { return; //HTTPStatus::send500("invalid query: " . var_export($parser->getErrors(), true)."\n\nQUERY:\n".$query); } } if ($conf['debug']) { Logging::log($modelFile . " against " . $e->getSparqlUrl()); Logging::log($query); Logging::log("Running query from " . $modelFile . " on endpoint " . $e->getSparqlURL(), E_USER_NOTICE); } $lodspk['queryText'][$strippedModelFile] = $query; $initTime = microtime(true); $aux = $e->query($query, Utils::getResultsType($query)); $endTime = microtime(true); if ($conf['debug']) { Logging::log("Execution time: " . ($endTime - $initTime) . " seconds"); } $timeObj = new stdClass(); $timeObj->query = new stdClass(); $timeObj->query->value = $strippedModelFile; $timeObj->time = new stdClass(); $timeObj->time->value = $endTime - $initTime; $lodspk['queryTimes'][$strippedModelFile] = $timeObj; if ($modelFile != $lodspk['type']) { if (!isset($rPointer[$strippedModelFile])) { $rPointer[$strippedModelFile] = array(); $firstResults[$strippedModelFile] = array(); } if (Utils::getResultsType($query) == $conf['output']['select']) { $rPointer[$strippedModelFile] = Utils::sparqlResult2Obj($aux); $fPointer[$strippedModelFile] = $rPointer[$strippedModelFile][0]; } else { $lodspk['resultRdf'] = true; $rPointer[$strippedModelFile] = $aux; } } else { if (Utils::getResultsType($query) == $conf['output']['select']) { $rPointer = Utils::sparqlResult2Obj($aux); $fPointer[$strippedModelFile] = $rPointer[0]; } else { $lodspk['resultRdf'] = true; $rPointer = $aux; } } } else { if (strpos('endpoint.', $modelFile) == 0) { if ($conf['debug']) { Logging::log("{$modelFile} is a directory, will process it later", E_USER_NOTICE); } if ($modelFile != $lodspk['type']) { if (!isset($rPointer[$strippedModelFile])) { $rPointer[$strippedModelFile] = array(); } Utils::queryDir($modelFile, $rPointer[$strippedModelFile], $fPointer[$strippedModelFile]); } else { Utils::queryDir($modelFile, $rPointer, $fPointer); } } } }