public static function createConnection($db) { // get the configuration $config = getConfiguration('db', $db); // create mysqli connection return new mysqli(array_val($config, 'server'), array_val($config, 'username'), array_val($config, 'password'), array_val($config, 'database'), array_val($config, 'port')); }
/** * test the configuration loads correctly for each configuration file */ public function testConfiguration() { // get the database configuration $config = getConfiguration('db'); // check we get the main database configuration $this->assertArrayHasKey('db1', $config); // check the database configuraion has all the required variables $this->assertArrayHasKeys($this->expectedDatabaseFields, $config['db1']); // check use of the second parameter to target specific sections works as intended $config = getConfiguration('db', 'db1'); $this->assertArrayHasKeys($this->expectedDatabaseFields, $config); // get the cache configuration $config = getConfiguration('cache'); // check we get the main database configuration $this->assertArrayCountGreaterThanOrEqual($config, 1); // check we get back a list of servers $server_list = array_val($config, 'servers'); $this->assertArrayCountGreaterThanOrEqual($server_list, 1); // check we get back the host and port variables for each server foreach ($server_list as $server_name) { $server_config = array_val($config, $server_name); $this->assertArrayHasKeys($this->expectedCacheFields, $server_config); } // get the ab test configuration // ab tests are optional, only test the output if we have some if ($config = getConfiguration('ab_test')) { //test names foreach ($config as $test_name => $test_details) { // check the test name is valid $this->assertRegExp('/^[a-zA-Z0-9]{4}$/', $test_name); } } }
/** * this will accept a method and request params and return completed, and signed query strigns for facebook * the optional $combine parameter will combine the result in such a way that it is ready for inclusion in a * method_feed, which is the parameter use for batch calling methods on the facebook API * * @param string $method * @param array $post * @param bool $combine * @return mixed * @author Craig Ulliott */ function build_fb_query_string($method, array $params, $combine = false) { // get the configuration $config = getConfiguration('facebook'); // the extra GET params facebook uses $get = array(); $get['session_key'] = ''; $get['api_key'] = $config['api_key']; $get['v'] = '1.0'; $get['method'] = $method; // the extra POST params facebook uses $params['call_id'] = microtime(true); $params['format'] = 'JSON'; $params_array = array_merge($get, $params); $str = ''; ksort($params_array); foreach ($params_array as $k => $v) { $str .= "{$k}={$v}"; } $str .= $config['api_secret']; $params['sig'] = md5($str); if ($combine) { return http_build_query(array_merge($get, $params)); } return array('get_string' => http_build_query($get), 'post_string' => http_build_query($params)); }
static function getCache() { if (!self::$cache) { $config = getConfiguration('cache'); // apply any overides to the configuration self::$compression = array_val($config, 'compression', self::$compression); self::$default_ttl = array_val($config, 'default_ttl', self::$default_ttl); self::$connect_timeout_msec = array_val($config, 'connect_timeout_msec', self::$connect_timeout_msec); self::$cache_enabled = array_val($config, 'cache_enabled', self::$cache_enabled); self::$local_cache_enabled = array_val($config, 'local_cache_enabled', self::$local_cache_enabled); // apply any overides to the debug mode self::$debug = array_val($config, 'debug', self::$debug); self::$local_cache_debug = array_val($config, 'local_cache_debug', self::$local_cache_debug); // build the cache object and connect the servers self::$cache = new Memcache(); // get the server list out of the configuration foreach (array_val($config, 'servers') as $machine_name) { // load the configuration block for each server $server_config = getConfiguration('cache', $machine_name); // setup this servers connection self::$cache->addServer($server_config['host'], $server_config['port'], false, $server_config['weight'], 1, 1, false, null); //, self::$connect_timeout_msec); } } return self::$cache; }
/** * the constructor takes the folder name containing the images and an optional parameter to change the output file type * * @param string $name * @param string $type * @author Craig Ulliott */ function __construct($name, $type = 'png') { // apply any overides to the configuration $config = getConfiguration('sprite'); $this->base_path = array_val($config, 'base_path', $this->base_path); // is it a relative path or not if (substr($this->base_path, 1, 1) != '/') { $this->base_path = SITE_ROOT . $this->base_path; } $this->extensions = array_val($config, 'extensions', $this->extensions); $this->base_url = array_val($config, 'base_url', $this->base_url); // sanity check the name of the image if (preg_match("/^([a-z])+\$/", $name)) { $this->name = $name; } else { throw new Exception("not a valid folder name, should be a-z, all lower case with no spaces"); } // check this is one of the extensions we are allowing if (in_array($type, $this->extensions)) { $this->type = $type; } else { throw new Exception("not a valid image type"); } // add all images in the given directory $this->addDirectory($this->base_path . '/' . $name); }
function ldap_bind($con, $user, $password) { $ldapDomainName = getConfiguration('auth.ldap.domain.name'); if ($ldapDomainName) { $password = $ldapDomainName . '\\' . $password; } return !Utils::isEmptyString($user) && !Utils::isEmptyString($password) && $user === $password; }
/** * loads the configuration and sets it * * @return void * @author Craig Ulliott */ public static function loadConfiguration() { // load AWS config file $config = getConfiguration('aws'); // cache to this object self::$access_key = $config['access_key']; self::$secret_key = $config['secret_key']; self::$pem_certificate = $config['pem_certificate']; self::$pem_pk = $config['pem_pk']; return true; }
/** * Return the Facebook client object * * @return Facebook */ public static function getClient() { if (!isset(self::$client)) { // lazy load to keep memory low require_once 'facebook.php'; // get the configuration $config = getConfiguration('facebook'); // facebook client self::$client = new No_Cookie_Facebook($config['api_key'], $config['api_secret']); } return self::$client; }
private static function notify($contactId, &$allRides, $potentialRideIds) { debug(__METHOD__ . "({$contactId}, " . json_encode($potentialRideIds) . ")"); $toNotify = array(); foreach ($allRides as $ride) { if (in_array($ride['Id'], $potentialRideIds)) { $toNotify[] = $ride; } } $contact = DatabaseHelper::getInstance()->getContactById($contactId); $mailBody = MailHelper::render(VIEWS_PATH . '/showInterestMail.php', array('rides' => $toNotify), $contact); Utils::sendMail(Utils::buildEmail($contact['Email']), $contact['Email'], getConfiguration('mail.addr'), getConfiguration('mail.display'), 'New rides from carpool', $mailBody); }
function setConfiguration($VAL, $DEFAULT_VAL) { global $username, $password, $database, $dbhost; $db = mysql_connect($dbhost, $username, $password); mysql_select_db($database) or die("Unable to select database"); mysql_query("SET NAMES utf8", $db); mysql_query("SET CHARACTER SET utf8", $db); $val = getConfiguration($VAL, null); if ($val == null) { mysql_query("insert into domain (Pagename,Caption) values('" . $VAL . "','" . $DEFAULT_VAL . "')"); } else { mysql_query("update domain set Caption = '" . $DEFAULT_VAL . "' where Pagename = '" . $VAL . "'"); } }
/** * get the wib client, lazy loading the client library if this is the first call * * @return void * @author Craig Ulliott */ public static function getClient() { if (!self::$wib) { // the wib client has its own database connection $database_configuration = getConfiguration('db', 'db1'); // lazy load the library to keep memory use low require 'whereivebeen.php'; // get the configuration $config = getConfiguration('wib'); // setup the object self::$wib = new WhereIveBeen(array_val_required($config, 'api_key'), array_val_required($config, 'api_secret'), $database_configuration, $use_oauth = true, array_val_required($config, 'server_addr'), array_val_required($config, 'authorize_uri')); } return self::$wib; }
private function __construct() { $dsn = str_replace('%DATAPATH%', DATA_PATH, getConfiguration('database.dsn')); $user = getConfiguration('database.user'); $pass = getConfiguration('database.pass'); info('Connecting to DB: ' . $dsn); $this->_db = new PDO($dsn, $user, $pass); if (!$this->_db) { throw new Exception('DB Connection failed: ' . Utils::errorInfoToString($this->_db->errorCode())); } // Use exceptions as error handling $this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // If required, run DB initialization code (such as setting codepage to use) if (($initCode = getConfiguration('database.init')) !== false) { $this->_db->query($initCode); } }
function authenticate($params) { assert('isset($params["user"]) && isset($params["password"])'); $con = false; if (($domain = getConfiguration('auth.ldap.domain')) !== false) { $port = (int) getConfiguration('auth.ldap.port', self::LDAP_DEFAULT_PORT); $con = ldap_connect($domain, $port); } if ($con === false) { throw new Exception(__METHOD__ . ": Failed to connect to {$domain} in port {$port}"); } $authUser = $user = $this->ldap_escape($params['user']); $pass = $this->ldap_escape($params['password']); $ldapDomainName = getConfiguration('auth.ldap.domain.name'); if ($ldapDomainName) { $authUser = $ldapDomainName . '\\' . $authUser; } debug(__METHOD__ . ": Trying to authenticate {$authUser} against {$domain}"); if (ldap_bind($con, $authUser, $pass)) { // We're assuming that the email used is as the user name $email = $email = Utils::buildEmail($user); // Close the connection - we don't need it any more ldap_unbind($con); // Fetch contact $contact = DatabaseHelper::getInstance()->getContactByEmail($email); if ($contact !== false) { return array('Id' => $contact['Id'], 'Role' => $contact['Role']); } else { // Contact is not in the database - we better create it // TODO: Put the option to read data return array('Id' => DatabaseHelper::getInstance()->addContact('', '', $email, ROLE_IDENTIFIED), 'Role' => ROLE_IDENTIFIED); } } else { $errCode = ldap_errno($con); if ($errCode == self::LDAP_INAPPROPRIATE_AUTH || $errCode == self::LDAP_INVALID_CREDENTIALS) { // Invalid credentials - simply fail return false; } // Internal error throw new Exception(__METHOD__ . " : LDAP error: " . ldap_err2str($errCode)); } }
public function initInternal() { $this->_regions = DatabaseHelper::getInstance()->getRegions(); if (isset($_GET['regionSelector']) && array_key_exists($_GET['regionSelector'], $this->_regions)) { $this->_currentRegion = $this->_regions[$_GET['regionSelector']]; // Set the cookie for 14 days if (!setcookie('region', $_GET['regionSelector'], time() + TWO_WEEKS, getConfiguration('public.path') . '/')) { warn(__METHOD__ . ': Could not set cookie for user! Output already exists.'); } unset($_GET['region']); } else { if (isset($_COOKIE['region']) && array_key_exists($_COOKIE['region'], $this->_regions)) { $this->_currentRegion = $this->_regions[$_COOKIE['region']]; // Update cookie expiry time setcookie('region', $_COOKIE['region'], time() + TWO_WEEKS, getConfiguration('public.path') . '/'); } else { $this->_currentRegion = $this->_regions[self::getDefaultRegion()]; } } info(__METHOD__ . ' region selected: ' . $this->_currentRegion['Id'] . ' (' . $this->_currentRegion['Name'] . ')'); }
static function buildNavbar() { $html = ''; $role = AuthHandler::getRole(); $acl = $GLOBALS['acl']; $logged = $role !== ROLE_GUEST; // Put branding bar if we want one if (getConfiguration('branding.enable')) { $html .= ViewRenderer::renderToString('views/branding.php'); } $html .= '<div id="navbar">'; if ($logged) { $pages =& self::$pagesMember; // Put the right ref on the logout link $pages[4]['params'] = array('ref' => Utils::getRunningScript()); // If we have no ride yet, the name of join.php is still "Join" if (!AuthHandler::isRideRegistered()) { $pages[1]['name'] = 'Join'; } } else { $pages =& self::$pagesGuest; } $str = '<ol>'; foreach ($pages as $page) { if ($acl->isAllowed($role, $page['href'])) { $str .= '<li><a href="' . Utils::buildLocalUrl($page['href'], isset($page['params']) ? $page['params'] : null) . '" '; if ($page['href'] == Utils::getRunningScript()) { $str .= 'class="selected"'; } $str .= '>' . _($page['name']) . '</a></li>'; } } $str .= '</ol>'; $html .= $str; $html .= self::buildLanguageSelector(); $html .= self::buildRegionSelector(); $html .= '<div class="clearFloat"></div></div>'; return $html; }
function setSystem() { $system = array(); echo "Do the Hard thing ...<br/>"; $system = array_merge($system, loadJSONintoArray("system/defs/settings.json")); // ########## if (isset($_SERVER["HTTPS"]) && strtolower($_SERVER["HTTPS"]) == "on") { $protocol = "https"; } else { $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"], 0, strpos($_SERVER["SERVER_PROTOCOL"], "/"))); } $basePath = substr($_SERVER["SCRIPT_FILENAME"], 0, strrpos($_SERVER["SCRIPT_FILENAME"], "/")) . "/"; $baseUrl = $protocol . "://" . $_SERVER["HTTP_HOST"] . substr($_SERVER["SCRIPT_NAME"], 0, strrpos($_SERVER["SCRIPT_NAME"], "/")) . "/"; $system["baseUrl"] = $baseUrl; $system["basePath"] = $basePath; $config = getConfiguration($system["baseUrl"], $system["basePath"] . "system/defs/config.json"); if (!$config) { $this->error = "Configuration fault!"; } $config["dbPassword"] = base64_encode($config["dbPassword"]); $system = array_merge($system, $config); return $system; }
private function initInternal() { $this->locales = DatabaseHelper::getInstance()->getLocales(); if (isset($_GET['lang']) && array_key_exists($_GET['lang'], $this->locales)) { $this->locale = $this->locales[$_GET['lang']]; // Set the cookie for 14 days if (!setcookie('lang', $_GET['lang'], time() + TWO_WEEKS, getConfiguration('public.path') . '/')) { warn(__METHOD__ . ': Could not set cookie for user! Output already exists.'); } unset($_GET['lang']); } else { if (isset($_COOKIE['lang']) && array_key_exists($_COOKIE['lang'], $this->locales)) { $this->locale = $this->locales[$_COOKIE['lang']]; // Update cookie expiry time setcookie('lang', $_COOKIE['lang'], time() + TWO_WEEKS, getConfiguration('public.path') . '/'); } else { $this->locale = $this->locales[self::getDefaultLocale()]; } } info(__METHOD__ . ' locale selected: ' . $this->locale['Name'] . ' (' . $this->locale['Locale'] . ')'); setlocale(LC_ALL, $this->locale['Locale']); putenv('LC_ALL=' . $this->locale['Locale']); }
} if ($BASEPATH == "") { $BASEPATH = "/"; } if ($MASTER_PASSWORD == "") { $MASTER_PASSWORD = "******"; } if ($lang == "") { $lang = "en"; } $sitename = getConfiguration("sitename", $_POST["sitename"] != "" ? $_POST["sitename"] : "My push2press app"); $url = getConfiguration("url", "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME']); $url = str_replace("setup.php", "", $url); $bgc1 = getConfiguration("bgc1", $_POST["bgc1"] != "" ? $_POST["bgc1"] : "#000000"); $bgc2 = getConfiguration("bgc2", $_POST["bgc2"] != "" ? $_POST["bgc2"] : "#ffffff"); $adminemail = getConfiguration("adminemail", $_POST["adminemail"] != "" ? $_POST["adminemail"] : ""); echo $htop; echo "<br>"; echo "<br>"; echo "<style>\n\tlegend, h1 {\n\t\tpadding-top:10px;\n\t\tpadding-left:180px;\n\t}\n\tinput, textarea {\n\t width: 280px;\n\t}\n\t</style>"; echo "<div class='continer'>\n\t<div class='row-fluid'>\n\t\t<div class='span4'>\n\t\t\t<br>\n\t\t\t<h1> </h1>\n\t\t\t<br>\n\t\t\t<img src='http://www.push2press.com/p2p/images/MainImage.jpg'>\n\t\t</div>\n\t\t<div class='span8'>"; echo "<br>"; if ($hosted == "y") { echo "<h1>Setup - Step 2 of 2</h1>"; } else { echo "<h1>Setup - Step 1 of 2s</h1>"; } echo "<br>"; echo "<div>{$setuperror}</div>"; echo "<br>"; echo "<form action='setup.php' method='POST'>";
font-weight: bold; padding: 5px 3px; text-align: left; } tr.even { background: #E6E6FA; } </style> <body> <h1><?php echo _('New Potential Rides From'); ?> <?php echo getConfiguration('app.name'); ?> </h1> <p><?php echo sprintf(_('%d new potential rides, matching the source and destination towns you specified, were found for you:'), count($this->rides)); ?> </p> <table id="rides"> <tr> <th id="resultsFrom"><?php echo _('From'); ?> </th> <th id="resultsTo"><?php echo _('To'); ?>
// This is a post - form submitted if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (!AuthHandler::isSessionExisting()) { // Try to discard bots by dropping requests with no session die; } extract($_POST); if (!Utils::isEmptyString($feedback)) { $mailHelper = new MailHelper(); $wantToStr = isset($wantTo) && isset($feedbackOptions[$wantTo]) ? $feedbackOptions[$wantTo] : _("Other"); $params = array('wantTo' => $wantToStr, 'feedback' => $feedback, 'email' => $email); $body = $mailHelper->render('views/feedbackMail.php', $params); $to = getConfiguration('feedback.mail'); $toName = getConfiguration('feedback.to.name'); $from = getConfiguration('feedback.from'); $fromName = getConfiguration('feedback.from.name'); $replyTo = Utils::isEmptyString($email) ? null : Utils::buildEmail($email); Utils::sendMail($to, $toName, $from, 'Carpool feedback', 'New carpool feedback', $body, $replyTo, $replyTo); GlobalMessage::setGlobalMessage(_('Thanks for the feedback!')); } else { GlobalMessage::setGlobalMessage(_('Please write something.'), GlobalMessage::ERROR); } // Get after post Utils::redirect('feedback.php'); } else { AuthHandler::putUserToken(); ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
?> <th id="resultsCommunication"><?php echo _('Contact Details'); ?> </th> <th id="resultsComment"><?php echo _('Comment'); ?> </th> </tr> </table> <p id="resultsMessage"></p> </div> </div> </div> <?php View_Php_To_Js::putVariable('cities', $db->getCities($currentRegion)); View_Php_To_Js::putConstant('DEFAULT_DOMAIN', getConfiguration('default.domain')); View_Php_To_Js::putConstant('APP_NAME', _(getConfiguration('app.name'))); View_Php_To_Js::putConstant('DISPLAY_DEST', $displayDest ? '1' : '0'); View_Php_To_Js::putTranslations(array('Sorry, no results found.', 'Sorry, something went wrong. Request could not be completed.', 'Show interest', 'Loading...', 'Could not add ride', 'Thanks for showing interest! You will notified about new rides.', 'Providing', 'Looking', 'Email', 'Phone', 'Would like to join a ride', 'Offers a ride', 'Would like to share a ride', 'Arrival ride is not relevant', 'Usually leaves home at', 'Home ride is not relevant', 'Usually leaves work at', 'Last updated')); echo View_Php_To_Js::render(); ?> <script type="text/javascript" src="lib/jquery-1.8.1.min.js"></script> <script type="text/javascript" src="lib/bootstrap/js/bootstrap.custom.min.js"></script> <script type="text/javascript" src="lib/form/jquery.form.min.js"></script> <script type="text/javascript" src="js/utils.js"></script> <script type="text/javascript" src="js/filter.js"></script> <script type="text/javascript" src="js/index.js"></script> </body> </html>
public static function login() { $username = null; $password = null; $valid = false; if (isset($_SESSION['username']) && isset($_SESSION['password'])) { // a session is active $username = $_SESSION['username']; $password = $_SESSION['password']; $valid = true; } else { if (isset($_POST['username']) && isset($_POST['password'])) { // a login is requested via HTTP POST $username = $_POST['username']; $password = $_POST['password']; } else { if (isset($_GET['username']) && isset($_GET['password'])) { // a login is requested via HTTP GET $username = $_GET['username']; $password = $_GET['password']; } } } // validate the credentials if (!$valid) { $user_id = UserC::login($username, $password); } else { return true; } if ($user_id == -1) { // invalid credentials return false; } // valid credentials // so store everything as part of the session $_SESSION['username'] = strtolower($username); $_SESSION['password'] = $password; $_SESSION['userid'] = $user_id; $_SESSION['userconf'] = getConfiguration(); $_SESSION['feed_new'] = '00.00'; $_SESSION['feed_old'] = microtime(true); return true; }
/** * this is the main feature of the view, in the MVC paradigm the controller sends updates to the view, this is * the method which captures the updates. * * The uri is essentially the part of the system which we are updating so different output will be negotiated * depending on the value of the uri. * * The data are the things which have changed due to the controller. * * The message is optional, it is for notes, debug information or with json sending messages back alongside the data * * @param string $uri * @param array $data * @return void * @author Craig Ulliott */ public static function update($uri, $data = NULL) { // extract the base from the url, we use this to determine the type of output $uri_r = explode('/', trim($uri, '/'), 2); $base = array_val($uri_r, 0); $path = array_val($uri_r, 1); // for an error we try and determine the best format to send back the message if ($base == 'error') { // if the original request came from AJAX if (array_val($_SERVER, 'HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest') { // rewrite and use the json handler for this error $base = 'json'; $path = 'fail'; $data = array_val($data, 'message', 'Unknown Error'); } else { // pass back the appropriate http code for this error $code = array_val($data, 'code'); switch ($code) { case '404': header("HTTP/1.0 404 Not Found"); break; case '500': header("HTTP/1.0 500 Internal Server Error"); break; default: die('unknown error code "' . $code . '"'); } // use the page handler to display this error $base = 'page'; $path = 'error/' . $code; } } // for an error, we try to determine if we are // we handle the update differently depending on the base of the uri switch ($base) { // these are the different layout files, we are loading a whole page template and passing the result into these layouts case 'page': // we are preparing a full html page $tpl_vars = array(); // the part of the page being updated from teh controller (aka the page contents) $tpl_vars['page_content'] = Template::loadTemplate($path, $data); // script and css clien side includes $tpl_vars['css_url'] = ENV == 'dev' ? '/css/generate' : STATIC_BASE_URL . 'css/style.css'; $tpl_vars['js_url'] = ENV == 'dev' ? '/js/generate' : STATIC_BASE_URL . 'js/script.js'; // todo:: $tpl_vars['css_url'] = '/css/generate'; $tpl_vars['js_url'] = '/js/generate'; // the facebook API key $tpl_vars['fb_api_key'] = getConfiguration('facebook', 'api_key'); // user values $tpl_vars['current_uid'] = CURRENT_UID; $tpl_vars['current_session_key'] = CURRENT_SESSION_KEY; // the parts of the path $path_r = explode('/', $path); // the active section is the first part of the path $active_section = reset($path_r); // used to set an active class on the main tab $tpl_vars['active'] = $active_section; // we build body classes to target css more accurately, one whole class for each parent section $body_classes = array(); while ($path_r) { $body_classes[] = implode('-', $path_r); array_pop($path_r); } // the current login state if (CURRENT_UID) { $body_classes[] = 'logged-in'; } // the current browser (TODO:) if (true == false) { $body_classes[] = 'ie-7'; } // the body classes, used to determine the browser and login state $tpl_vars['body_class'] = implode(' ', $body_classes); // render the full page in either the base or admin layout file $output = Template::loadLayout($base, $tpl_vars); // complete the translations Translator::translate('en'); $output = Translator::parse($output); // useful headers for debugging self::outputDebugHeaders(); // output to the browser die($output); // partial means we are rendering a template (usualy html) but not passing it back into the page template // this is usually for partial page updates preformed by javascript // partial means we are rendering a template (usualy html) but not passing it back into the page template // this is usually for partial page updates preformed by javascript case 'partial': // render the template and output to the browser $output = Template::loadTemplate($path, $data); // complete the translations Translator::translate('en'); $translated_output = Translator::parse($output); // useful headers for debugging self::outputDebugHeaders(); // to hold the output $r = array(); // the rest of the params go into the data key $r['page'] = $translated_output; // the correct content type header('Content-type: application/json'); // build and send the json back to the browser $encoded_output = json_encode($r); die($encoded_output); // json is used by javascript for various AJAX functionality // json is used by javascript for various AJAX functionality case 'json': $r = array(); switch ($path) { // ouput raw json data case 'data': // the content type header('Content-type: application/json'); // build and send the json back to the browser $encoded_output = json_encode($data); die($encoded_output); // success means we simply set the success key to 1, javascript will capture this // success means we simply set the success key to 1, javascript will capture this case 'success': $r['success'] = 1; break; // fail means we simply set the success key to 0, javascript will capture this and handle is as a fail // fail means we simply set the success key to 0, javascript will capture this and handle is as a fail case 'fail': $r['success'] = 0; break; default: throw new exception($path . ' is not a valid path for json output'); } // the data variable is used for sending back a message // it is sent as a blank string if one wasnt provided $r['message'] = (string) $data; // the correct content type header('Content-type: application/json'); // build and send the json back to the browser $encoded_output = json_encode($r); die($encoded_output); // content pass through, with the uri as a content type // content pass through, with the uri as a content type case 'content': // the different content types we accept switch ($path) { // common image types case 'image/png': case 'image/gif': case 'image/jpeg': // css and js // css and js case 'text/css': case 'text/javascript': case 'text/html': // data // data case 'text/csv': // the content type header('Content-type: ' . $path); // other useful headers for debugging self::outputDebugHeaders(); // send to the browser die($data); default: throw new exception($path . ' is not a known safe content type'); } default: throw new exception($base . ' is not a valid base for updating this view'); } }
LocaleManager::init(); RegionManager::init(); // Start session AuthHandler::init(); // Initialize the ACL $acl = new SimpleAcl(); $acl->addRole(ROLE_GUEST); $acl->addRole(ROLE_AUTHORIZED_ACCESS, ROLE_GUEST); $acl->addRole(ROLE_IDENTIFIED, ROLE_GUEST); $acl->addRole(ROLE_IDENTIFIED_REGISTERED, ROLE_IDENTIFIED); $acl->addRole(ROLE_ADMINISTRATOR, ROLE_IDENTIFIED_REGISTERED); if (ENV === ENV_DEVELOPMENT) { $acl->addResource(ROLE_GUEST, array('webres.php', 'test.php')); } $acl->addResource(ROLE_GUEST, array('auth.php', 'optout.php')); if (getConfiguration('auth.mode') == AuthHandler::AUTH_MODE_PASS) { $acl->addResource(ROLE_GUEST, array('join.php', 'help.php', 'AddRideAll.php', 'GetRegionConfiguration.php')); } else { if (AuthHandler::getAuthMode() == AuthHandler::AUTH_MODE_TOKEN) { $acl->addResource(ROLE_GUEST, array('join.php', 'help.php', 'index.php', 'AddRideAll.php', 'feedback.php', 'SearchRides.php', 'GetRegionConfiguration.php')); } } $acl->addResource(ROLE_IDENTIFIED, array('join.php', 'help.php', 'index.php', 'feedback.php', 'logout.php', 'thanks.php', 'SearchRides.php', 'AddRideAll.php', 'GetRegionConfiguration.php')); $acl->addResource(ROLE_IDENTIFIED_REGISTERED, array('ActivateToggle.php', 'DeleteRide.php', 'ShowInterest.php')); // Content management $acl->addResource(ROLE_ADMINISTRATOR, array('translations.php')); // Enfore access control $role = AuthHandler::getRole(); $resource = Utils::getRunningScript(); if (!$acl->isAllowed($role, $resource)) { if ($role == ROLE_GUEST && $acl->isAllowed($role, 'auth.php')) {
function test_writeConfigFile() { appendTestMessage(NEW_LINE_LOG . " >> Tests writing of config file..." . NEW_LINE_LOG); appendTestMessage("No config: User = admin, key = timezone_offset_minutes"); $ret = getConfiguration(ADMIN_NAME, CONFIG_KEY_TIMEZONE_OFFSET_MINUTES, true); if (isNullOrEmptyString($ret)) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("No config: User = cUser, key = timezone_offset_minutes"); $ret = getConfiguration('cUser', CONFIG_KEY_TIMEZONE_OFFSET_MINUTES, true); if (isNullOrEmptyString($ret)) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Delete missing config file: User = cUser"); $ret = resetConfig('cUser'); if ($ret) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Delete missing config file: User = admin"); $ret = resetConfig(ADMIN_NAME); if ($ret) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Set config: User = admin, , key = timezone_offset_minutes (set server)"); $ret = setConfiguration(ADMIN_NAME, CONFIG_KEY_TIMEZONE_OFFSET_MINUTES, '10'); if ($ret) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = admin, key = timezone_offset_minutes"); $ret = getConfiguration(ADMIN_NAME, CONFIG_KEY_TIMEZONE_OFFSET_MINUTES, true); if ($ret == '10') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = cUser, key = timezone_offset_minutes"); $ret = getConfiguration('cUser', CONFIG_KEY_TIMEZONE_OFFSET_MINUTES, false); if ($ret == '') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = cUser, key = timezone_offset_minutes"); $ret = getConfiguration('cUser', CONFIG_KEY_TIMEZONE_OFFSET_MINUTES, true); if ($ret == '10') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Set config: User = dUser, key = track_expiration_days (set user and server)"); $ret = setConfiguration('dUser', CONFIG_KEY_TRACK_EXPIRATION_DAYS, 'aa'); if ($ret) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = admin, key = timezone_offset_minutes"); $ret = getConfiguration(ADMIN_NAME, CONFIG_KEY_TIMEZONE_OFFSET_MINUTES, true); if ($ret == '10') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = admin, key = track_expiration_days"); $ret = getConfiguration(ADMIN_NAME, CONFIG_KEY_TRACK_EXPIRATION_DAYS, true); if ($ret == 'aa') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = dUser, key = timezone_offset_minutes"); $ret = getConfiguration('dUser', CONFIG_KEY_TIMEZONE_OFFSET_MINUTES, true); if ($ret == '10') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = dUser, key = track_expiration_days"); $ret = getConfiguration('dUser', CONFIG_KEY_TRACK_EXPIRATION_DAYS, true); if ($ret == 'aa') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Set config: User = admin, , key = track_expiration_days (set server only)"); $ret = setConfiguration(ADMIN_NAME, CONFIG_KEY_TRACK_EXPIRATION_DAYS, '15'); if ($ret) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Set config: User = dUser, , key = track_expiration_days (set user only)"); $ret = setConfiguration('dUser', CONFIG_KEY_TRACK_EXPIRATION_DAYS, 'dd'); if ($ret) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = admin, key = timezone_offset_minutes"); $ret = getConfiguration(ADMIN_NAME, CONFIG_KEY_TIMEZONE_OFFSET_MINUTES, true); if ($ret == '10') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = admin, key = track_expiration_days"); $ret = getConfiguration(ADMIN_NAME, CONFIG_KEY_TRACK_EXPIRATION_DAYS, true); if ($ret == '15') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = dUser, key = timezone_offset_minutes"); $ret = getConfiguration('dUser', CONFIG_KEY_TIMEZONE_OFFSET_MINUTES, true); if ($ret == '10') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = dUser, key = track_expiration_days"); $ret = getConfiguration('dUser', CONFIG_KEY_TRACK_EXPIRATION_DAYS, true); if ($ret == 'dd') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Set config en bloc: User = dUser, track_expiration_days=0, timezone_offset_minutes=-60"); $param = CONFIG_KEY_TRACK_EXPIRATION_DAYS . '=0' . PHP_EOL . CONFIG_KEY_TIMEZONE_OFFSET_MINUTES . '=-60'; $ret = setConfigurationEnBloc('dUser', $param); if (ret) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = dUser, key = track_expiration_days = 0"); $ret = getConfiguration('dUser', CONFIG_KEY_TRACK_EXPIRATION_DAYS, true); if ($ret == '0') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Get config: User = dUser, key = timezone_offset_minutes = -60"); $ret = getConfiguration('dUser', CONFIG_KEY_TIMEZONE_OFFSET_MINUTES, true); if ($ret == '-60') { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } //--------- // Test the cleanup cleanUp('eUser'); appendTestMessage("User dir 'eUser' is there after clean up for 'eUser' that has an expiration time of 15 days"); $dirToOld = USER_DIR . DIRECTORY_SEPARATOR . 'eUser'; if (is_dir($dirToOld)) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("User dir 'dUser' was removed by the clean up for 'dUser' that has an expiration time of 0 days."); $dirToOld = USER_DIR . DIRECTORY_SEPARATOR . 'dUser'; if (!is_dir($dirToOld)) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } appendTestMessage("Remove test users"); $ret = removeTestUsers(); if ($ret) { appendTestMessage("- ok"); } else { appendTestMessage("- failed"); return false; } resetConfig(ADMIN_NAME); return true; }
echo htmlspecialchars($authUrl); ?> </a></p> <p><?php echo _('To use it, just paste the exact link to your browser address bar and hit "Enter".'); ?> </p> <?php } else { ?> <p><?php printf(_('You can always use "<a href="%s">My Profile</a>" page to update or delete your account any time in the future.'), Utils::buildLocalUrl('join.php')); ?> </p> <?php } ?> <p><?php echo _('Unless you ask for it, you will never get any more emails from this site.'); ?> </p> <br /> <p><?php echo _('Thanks'); ?> ,<br/><b><?php printf('The %s team', _(getConfiguration('app.name'))); ?> </b></p> </div>
<?php // get the main configuration from the core.ini file $config = getConfiguration('core'); // this is used to set up the URIs below and help catch dev vs production environments define('ROOT_DOMAIN', array_val_required($config, 'root_domain')); define('IMG_BASE_URL', array_val_required($config, 'img_base_url')); define('STATIC_BASE_URL', array_val_required($config, 'static_base_url')); define('MEMCACHED_PREFIX', array_val_required($config, 'memcached_prefix')); define('PAGINATION_HARD_LIMIT', array_val_required($config, 'pagination_hard_limit')); define('SESSION_DB', array_val_required($config, 'session_db')); // mvc default controller (essentially the default page) define('DEFAULT_CONTROLLER', array_val_required($config, 'default_controller')); define('DEFAULT_METHOD', array_val_required($config, 'default_method')); // constants define('MYSQL_DATETIME', 'Y-m-d H:i:s'); define('MYSQL_DATE', 'Y-m-d'); // if this is a *.dev.* host, we're in dev if (isset($_SERVER['HTTP_HOST']) && strstr($_SERVER['HTTP_HOST'], '.dev.')) { define('ENV', 'dev'); //get the dev name from a URI like : http://www.developers-name.dev.ROOT_DOMAIN if (preg_match('/\\.([a-z]*)\\.dev\\.' . ROOT_DOMAIN . '/', $_SERVER['HTTP_HOST'], $matches)) { define('DEV_NAME', $matches[1]); } else { die('could not determine environment dev_name'); } } else { define('ENV', 'production'); }
<label for="email"><?php echo _('Email'); ?> </label> <input class="textInput" id="email" name="email" type="text" size=20 value="<?php echo isset($contact_Email) ? $contact_Email : ''; ?> " <?php if (!$canUpdateEmail) { echo 'readonly'; } ?> /> <?php if ($domainUsersMode) { echo '@' . getConfiguration('default.domain'); } if (!$canUpdateEmail) { echo '<p class="description">' . _('Authentication policy does not allow you to change email account.') . '</p>'; } else { if ($domainUsersMode) { echo '<p class="description">' . _('Please use your company email, without the domain suffix.') . '</p>'; } } ?> </dd> <?php if (AuthHandler::getAuthMode() == AuthHandler::AUTH_MODE_PASS) { ?> <dd class="mandatory"> <label for="passw1"><?php
public static function render($contact) { $authUrl = Utils::buildLocalUrl('auth.php', array('c' => $contact['Id'], 'i' => $contact['Identifier'])); $html = '<html>' . '<head><title></title></head>' . '<style>' . 'h1 { font-size: xx-large; } ' . '#content p { font-size: large } ' . '</style>' . '<body>' . '<h1>' . sprintf(_('Thanks, %s'), htmlspecialchars($contact['Name'])) . '!</h1>' . '<div id="content">' . '<p>' . _('You sucssfully joined the carpool.') . '</p>' . '<p>' . sprintf(_('You can always update or delete your account by browsing to %s'), '<a href="' . htmlspecialchars($authUrl) . '">' . htmlspecialchars($authUrl) . '</a>') . '.</p>' . '<p>' . _('Unless you ask for it, you will never get any more emails from this site.') . '</p>' . '<p>' . _('Thanks') . ',<br/>' . sprintf('The %s team', _(getConfiguration('app.name'))) . '</div>' . '</body>' . '</html>'; return $html; }
// Register Session $app->register(new Silex\Provider\SessionServiceProvider()); // Register Monolog (log service) $app->register(new Silex\Provider\MonologServiceProvider(), array('monolog.logfile' => __DIR__ . '/development.log')); // Register Translation Service $app->register(new Silex\Provider\TranslationServiceProvider()); $app['translator'] = $app->share($app->extend('translator', function ($translator, $app) { $translator->addLoader('yaml', new YamlFileLoader()); $translator->addResource('yaml', __DIR__ . '/locales/en.yml', 'en'); $translator->addResource('yaml', __DIR__ . '/locales/es.yml', 'es'); return $translator; })); // Register Twig (templates service) $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views')); // Register Doctrine (mySql provider) $configuration = getConfiguration(); $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_mysql', 'host' => $configuration['host'], 'dbname' => $configuration['dbname'], 'user' => $configuration['user'], 'password' => $configuration['password'], 'charset' => 'utf8', 'driverOptions' => array(1002 => 'SET NAMES utf8')))); // Register Security Provider $app->register(new Silex\Provider\SecurityServiceProvider(), array('security.firewalls' => array('account' => array('pattern' => '^/account/', 'form' => array('login_path' => '/login', 'check_path' => '/account/login_check'), 'logout' => array('logout_path' => '/account/logout'), 'users' => $app->share(function () use($app) { return new UserProvider($app['db']); }))))); // Managers declaration $app['accountManager'] = function ($app) { return new AccountManager($app['db'], $app["monolog"]); }; // Before all actions $app->before(function (Request $request) use($app) { $language = getHeaderLanguage($request); $app["monolog"]->addInfo("Locate to: " . $language); $app["translator"]->setLocale($language); });