Beispiel #1
0
 protected function parse($iri)
 {
     if (!is_array($iri)) {
         if ($iri == null) {
             $iri = array();
         } else {
             if (!($iri = URL::parse($iri))) {
                 return null;
             }
             if (!isset($iri['host'])) {
                 $iri['host'] = $this->clusterName;
             }
         }
     }
     if (!isset($iri['scheme']) || !strlen($iri['scheme'])) {
         $iri['scheme'] = 'cluster';
     }
     if (!isset($iri['host']) || !strlen($iri['host'])) {
         $iri['host'] = $this->clusterName;
     }
     if (!isset($iri['path'])) {
         $iri['path'] = '/';
     }
     if (!isset($iri['pathcomp'])) {
         $iri['pathcomp'] = array();
         $x = explode('/', $iri['path']);
         foreach ($x as $p) {
             if (!strlen($p)) {
                 continue;
             }
             $iri['pathcomp'][] = $p;
         }
     }
     return $iri;
 }
Beispiel #2
0
 public function __construct($reqUrl, $params)
 {
     if ($reqUrl instanceof URL) {
         $this->reqUrl = $reqUrl;
     } else {
         $this->reqUrl = URL::parse($reqUrl);
     }
     $this->params = $params;
 }
/**
 * Providing the standard PHP interface.
 *
 * Mostly compatible to {@link http://php.net/manual/en/function.parse-url.php \parse_url()}
 *
 * The 2nd parameter which can be provided in the original php function can't
 * be supported here, because there are no constants for the additional values.
 *
 * As this function wants to be compatible to {@link http://php.net/manual/en/function.parse-url.php \parse_url()}
 * it returns <tt>false</tt> (instead of throwing exceptions) in case of
 * failiures.
 *
 * @return array|boolean
 * @param $url string
 * @author akrys
 */
function parse_url($url)
{
    try {
        $obj = new URL($url);
        return $obj->parse();
    } catch (\Exception $e) {
        //some error handling one could think of.
        //for simple dev purposes, a simple var_dump should be enough
        //		print $e->getMessage();
        //		var_dump($e->getTraceAsString());
    }
    return false;
}
Beispiel #4
0
 /**
  * 执行路由
  *
  * @param string $controller 控制器
  * @param string $action 方法
  */
 public function execute($controller = null, $action = null)
 {
     #解析链接
     if (is_null($controller)) {
         $url = URL::parse();
     } else {
         if (is_null($action)) {
             $action = 'index';
         }
         $url = URL::parseController($controller, $action);
     }
     App::setController($url->getController());
     App::setAction($url->getAction());
     $this->invoke($url);
 }
 public function save_mainmenu($form)
 {
     $base_url = Site::get_url('habari', true);
     $start_url = $form->mainmenus->value;
     /* Strip out the base URL from the requested URL */
     /* but only if the base URL isn't / */
     if ('/' != $base_url) {
         $start_url = str_replace($base_url, '', $start_url);
     }
     /* Trim off any leading or trailing slashes */
     $start_url = trim($start_url, '/');
     /* Remove the querystring from the URL */
     if (strpos($start_url, '?') !== FALSE) {
         list($start_url, $query_string) = explode('?', $start_url);
     }
     /* Allow plugins to rewrite the stub before it's passed through the rules */
     $start_url = Plugins::filter('rewrite_request', $start_url);
     $stub = $start_url;
     /* Grab the URL filtering rules from DB */
     $matched_rule = URL::parse($stub);
     if ($matched_rule === FALSE) {
         print 'error, cant find rule';
         // error!!!!
     }
     /* Return $_GET values to their proper place */
     $args = array();
     if (!empty($query_string)) {
         parse_str($query_string, $args);
     }
     $rule = $matched_rule->name;
     $args = array_merge($matched_rule->named_arg_values, $args);
     if (User::identify()->can('super_user') && $form->affect_all->value == true) {
         foreach (Users::get_all() as $user) {
             $user->info->admindetour_real = array('rule' => $rule, 'args' => $args);
             $user->update();
         }
     } else {
         User::identify()->info->admindetour_real = array('rule' => $rule, 'args' => $args);
     }
     $_POST[$form->mainmenus->field] = URL::get($rule, $args);
     $form->save();
 }
Beispiel #6
0
function Groups()
{
    global $context, $txt, $scripturl, $sourcedir, $user_info, $modSettings;
    // The sub-actions that we can do. Format "Function Name, Mod Bar Index if appropriate".
    $subActions = array('index' => array('GroupList', 'view_groups'), 'members' => array('MembergroupMembers', 'view_groups'), 'requests' => array('GroupRequests', 'group_requests'));
    if (!isset($modSettings['groupColorsInline'])) {
        require_once $sourcedir . '/lib/Subs-Membergroups.php';
        regenerateColorStyle();
    }
    // Default to sub action 'index' or 'settings' depending on permissions.
    $_REQUEST['sa'] = isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]) ? $_REQUEST['sa'] : 'index';
    // Get the template stuff up and running.
    loadLanguage('ManageMembers');
    loadLanguage('ModerationCenter');
    if (isset($_REQUEST['action']) && $_REQUEST['action'] === 'admin' || $_REQUEST['action'] === 'groups') {
        loadAdminTemplate('ManageMembergroups');
    }
    // If we can see the moderation center, and this has a mod bar entry, add the mod center bar.
    if ($_REQUEST['action'] != 'moderate' && (allowedTo('access_mod_center') || $user_info['mod_cache']['bq'] != '0=1' || $user_info['mod_cache']['gq'] != '0=1' || allowedTo('manage_membergroups'))) {
        if (isset($_REQUEST['group'])) {
            redirectexit(URL::parse('?action=moderate;area=viewgroups;sa=members;group=' . $_REQUEST['group']));
        } else {
            if (isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'requests' && isset($_POST[$context['session_var']])) {
                require_once $sourcedir . '/ModerationCenter.php';
                $_GET['area'] = $_REQUEST['sa'] == 'requests' ? 'groups' : 'viewgroups';
                ModerationMain(true);
            } else {
                redirectexit(URL::parse('?action=moderate;area=viewgroups'));
            }
        }
        //require_once($sourcedir . '/ModerationCenter.php');
        //$_GET['area'] = $_REQUEST['sa'] == 'requests' ? 'groups' : 'viewgroups';
        //ModerationMain(true);
    } else {
        isAllowedTo('view_mlist');
        $context['linktree'][] = array('url' => $scripturl . '?action=groups', 'name' => $txt['groups']);
    }
    // Call the actual function.
    $subActions[$_REQUEST['sa']][0]();
}
 public static function processRequest()
 {
     // Make sure that a proper table and lookup key have been provided.
     // If they aren't, this request can be ended.
     if (!static::$table or !static::$lookupKey) {
         return json_encode(["ERROR" => "This API does not have the proper lookup configurations set."]);
     }
     // Get Important Values
     $request = ['method' => $_SERVER['REQUEST_METHOD'], 'class' => get_called_class(), 'url' => URL::parse(), 'headers' => getallheaders(), 'input' => file_get_contents('php://input')];
     $requestMethod = $request['method'];
     $resourcePath = substr($request['url']['path'], strpos($request['url']['path'] . "/", $request['class'] . "/") + strlen($request['class']) + 1);
     // Get the lookup ID to see which record we're attempting to match
     if (!($lookupID = static::extractLookupID($resourcePath))) {
         // This request has no specific resource to point to. There's a good chance that we're attempting
         // to GET data using an advanced search for multiple results. If this is the case, track that behavior.
         if ($requestMethod == "GET") {
             $requestMethod = "GET_SEARCH";
         }
     }
     // Make sure the API Request has proper handling set up
     if (!isset(static::$allowRequests[$requestMethod])) {
         return json_encode(["ERROR" => "The handling of this request method is not set properly."]);
     }
     // Make sure this API is allowed
     if (static::$allowRequests[$requestMethod] == self::CLOSED) {
         return json_encode(["ERROR" => "This API is not accessible using the " . strtoupper($requestMethod) . " method."]);
     }
     // Check if this API requires authentication
     if (static::$allowRequests[$requestMethod] >= self::AUTHENTICATED) {
         // Make sure that the appropriate authentication procedures have been passed
         if (!static::authenticateRequest($request)) {
             return json_encode(["ERROR" => "Unable to access this API: improper authentication used."]);
         }
     }
     // Prepare an empty response
     $response = array();
     // Handle the request
     switch ($requestMethod) {
         case "GET":
             $response = static::getRequest($lookupID, $request);
             break;
         case "GET_SEARCH":
             $response = static::getSearchRequest($request);
             break;
         case "POST":
             $response = static::postRequest($request);
             break;
         case "PUT":
             $response = static::putRequest($lookupID, $request);
             break;
         case "PATCH":
             $response = static::patchRequest($lookupID, $request);
             break;
         case "DELETE":
             $response = static::deleteRequest($lookupID, $request);
             break;
     }
     // Return a serialized response
     return json_encode($response);
 }
Beispiel #8
0
 /**
  * Receive a Pingback via XMLRPC
  * @param array $params An array of XMLRPC parameters from the remote call
  * @return string The success state of the pingback
  */
 public function xmlrpc_pingback__ping($params)
 {
     try {
         list($source_uri, $target_uri) = $params;
         // This should really be done by an Habari core function
         $target_parse = InputFilter::parse_url($target_uri);
         $target_stub = $target_parse['path'];
         $base_url = Site::get_path('base', TRUE);
         if ('/' != $base_url) {
             $target_stub = str_replace($base_url, '', $target_stub);
         }
         $target_stub = trim($target_stub, '/');
         if (strpos($target_stub, '?') !== FALSE) {
             list($target_stub, $query_string) = explode('?', $target_stub);
         }
         // Can this be used as a target?
         $target_slug = URL::parse($target_stub)->named_arg_values['slug'];
         if ($target_slug === FALSE) {
             throw new XMLRPCException(33);
         }
         // Does the target exist?
         $target_post = Post::get(array('slug' => $target_slug));
         if ($target_post === FALSE) {
             throw new XMLRPCException(32);
         }
         // Is comment allowed?
         if ($target_post->info->comments_disabled) {
             throw new XMLRPCException(33);
         }
         // Is this Pingback already registered?
         if (Comments::get(array('post_id' => $target_post->id, 'url' => $source_uri, 'type' => Comment::PINGBACK))->count() > 0) {
             throw new XMLRPCException(48);
         }
         // Retrieve source contents
         $rr = new RemoteRequest($source_uri);
         $rr->execute();
         if (!$rr->executed()) {
             throw new XMLRPCException(16);
         }
         $source_contents = $rr->get_response_body();
         // encoding is converted into internal encoding.
         // @todo check BOM at beginning of file before checking for a charset attribute
         $habari_encoding = MultiByte::hab_encoding();
         if (preg_match("/<meta[^>]+charset=([A-Za-z0-9\\-\\_]+)/i", $source_contents, $matches) !== FALSE && strtolower($habari_encoding) != strtolower($matches[1])) {
             $ret = MultiByte::convert_encoding($source_contents, $habari_encoding, $matches[1]);
             if ($ret !== FALSE) {
                 $source_contents = $ret;
             }
         }
         // Find the page's title
         preg_match('/<title>(.*)<\\/title>/is', $source_contents, $matches);
         $source_title = $matches[1];
         // Find the reciprocal links and their context
         preg_match('/<body[^>]*>(.+)<\\/body>/is', $source_contents, $matches);
         $source_contents_filtered = preg_replace('/\\s{2,}/is', ' ', strip_tags($matches[1], '<a>'));
         if (!preg_match('%.{0,100}?<a[^>]*?href\\s*=\\s*("|\'|)' . $target_uri . '\\1[^>]*?' . '>(.+?)</a>.{0,100}%s', $source_contents_filtered, $source_excerpt)) {
             throw new XMLRPCException(17);
         }
         /** Sanitize Data */
         $source_excerpt = '...' . InputFilter::filter($source_excerpt[0]) . '...';
         $source_title = InputFilter::filter($source_title);
         $source_uri = InputFilter::filter($source_uri);
         /* Sanitize the URL */
         if (!empty($source_uri)) {
             $parsed = InputFilter::parse_url($source_uri);
             if ($parsed['is_relative']) {
                 // guess if they meant to use an absolute link
                 $parsed = InputFilter::parse_url('http://' . $source_uri);
                 if (!$parsed['is_error']) {
                     $source_uri = InputFilter::glue_url($parsed);
                 } else {
                     // disallow relative URLs
                     $source_uri = '';
                 }
             }
             if ($parsed['is_pseudo'] || $parsed['scheme'] !== 'http' && $parsed['scheme'] !== 'https') {
                 // allow only http(s) URLs
                 $source_uri = '';
             } else {
                 // reconstruct the URL from the error-tolerant parsing
                 // http:moeffju.net/blog/ -> http://moeffju.net/blog/
                 $source_uri = InputFilter::glue_url($parsed);
             }
         }
         // Add a new pingback comment
         $pingback = new Comment(array('post_id' => $target_post->id, 'name' => $source_title, 'email' => '', 'url' => $source_uri, 'ip' => sprintf("%u", ip2long($_SERVER['REMOTE_ADDR'])), 'content' => $source_excerpt, 'status' => Comment::STATUS_UNAPPROVED, 'date' => HabariDateTime::date_create(), 'type' => Comment::PINGBACK));
         $pingback->insert();
         // Respond to the Pingback
         return 'The pingback has been registered';
     } catch (XMLRPCException $e) {
         $e->output_fault_xml();
     }
 }
Beispiel #9
0
assert('URL::join_ext(array("/file", ".txt")) == "/file.txt"');
assert('URL::join_ext("some", "path", "to", "/file", ".tar.gz") == "some/path/to/file.tar.gz"');
assert('URL::join_ext("file/", ".txt") == "file/.txt"');
/* Test URL::parse and URL::unparse */
$url = 'http://www.example.com/some/page?foo=3&foo=bar&baz=foo;';
$x = URL::parse($url);
list($base, $args) = $x;
assert('$base === "http://www.example.com/some/page"');
assert('is_assoc_array($args)');
assert('count($args) == 2');
assert('array_has_key($args, "foo")');
assert('$args["foo"] === "bar"');
$url = 'page.php?foo=3&bar=123';
$x = URL::parse($url);
list($base, $args) = $x;
assert('is_assoc_array($args)');
assert('count($args) == 2');
assert('array_has_key($args, "foo")');
assert('$args["foo"] === "3"');
assert('array_has_key($args, "bar")');
assert('$args["bar"] === "123"');
$url = 'http://example.com/some/page.php?foo=3&bar=123';
$x = URL::parse($url);
list($base, $args) = $x;
$y = URL::unparse($base, $args);
assert('$y === $url');
$url = '/some/page.php';
$x = URL::parse($url);
list($base, $args) = $x;
$y = URL::unparse($base, $args);
assert('$y === $url');
Beispiel #10
0
 static function getScheme($url)
 {
     $components = URL::parse($url);
     return $components[2];
 }
$randSalt = str_replace('$', '', $randSalt);
// Prepare POST Values: make sure that every $_POST value has a default value provided.
$_POST['site-salt'] = isset($_POST['site-salt']) ? Sanitize::text($_POST['site-salt']) : $randSalt;
$_POST['site-handle'] = isset($_POST['site-handle']) ? Sanitize::variable($_POST['site-handle']) : "";
$_POST['site-url'] = isset($_POST['site-url']) ? Sanitize::variable($_POST['site-url'], ":/.") : $_SERVER['SERVER_NAME'];
$_POST['site-name'] = isset($_POST['site-name']) ? Sanitize::text($_POST['site-name']) : "";
$_POST['site-domain'] = isset($_POST['site-domain']) ? Sanitize::variable($_POST['site-domain'], ":/.") : "";
$_POST['site-database-name'] = isset($_POST['site-database-name']) ? Sanitize::variable($_POST['site-database-name']) : "";
// Run the Form
if (Form::submitted("install-app-config")) {
    // Check if all of the input you sent is valid:
    Validate::variable("Site Handle", $_POST['site-handle'], 3, 22);
    Validate::safeword("Site Name", $_POST['site-name'], 3, 42);
    Validate::url("URL", $_POST['site-url'], 3, 64);
    // Parse the URL input
    $siteURL = URL::parse($_POST['site-url']);
    if (Validate::pass()) {
        // Make sure the site handle isn't taken
        $packet = array("site-handle" => $_POST['site-handle'], "uni-handle" => $ownerHandle, "site-name" => $_POST['site-name'], "site-url" => $siteURL['full']);
        // Call UniFaction's API to register a site with the system
        // If the site fails to register, it will provide an alert explaining why
        $response = API_Connect::call(URL::unifaction_com() . "/api/RegisterSiteHandle", $packet);
        if ($response) {
            // If the database users are provided and there is a database name that we can create, build config settings
            $siteTheme = "default";
            $siteThemeStyle = "default";
            $buildApp = '<?php

// Site-Wide Salt
define("SITE_SALT", "' . $_POST['site-salt'] . '");
Beispiel #12
0
	/**
	 * Receive a Pingback via XMLRPC
	 * @param array $params An array of XMLRPC parameters from the remote call
	 * @return string The success state of the pingback
	 */
	public function xmlrpc_pingback__ping( $params )
	{
		try {
			list( $source_uri, $target_uri )= $params;

			// This should really be done by an Habari core function
			$target_parse = InputFilter::parse_url( $target_uri );
			$target_stub = $target_parse['path'];
			$base_url = Site::get_path( 'base', true );

			if ( '/' != $base_url) {
				$target_stub = str_replace( $base_url, '', $target_stub );
			}

			$target_stub = trim( $target_stub, '/' );

			if ( strpos( $target_stub, '?' ) !== false ) {
				list( $target_stub, $query_string )= explode( '?', $target_stub );
			}

			// Can this be used as a target?
			$target_slug = URL::parse( $target_stub )->named_arg_values['slug'];

			if ( $target_slug === false ) {
				throw new XMLRPCException( 33 );
			}

			// Does the target exist?
			$target_post = Post::get( array( 'slug' => $target_slug ) );

			if ( $target_post === false ) {
				throw new XMLRPCException( 32 );
			}

			// Is comment allowed?
			if ( $target_post->info->comments_disabled ) {
				throw new XMLRPCException( 33 );
			}

			// Is this Pingback already registered?
			if ( Comments::get( array( 'post_id' => $target_post->id, 'url' => $source_uri, 'type' => Comment::PINGBACK ) )->count() > 0 ) {
				throw new XMLRPCException( 48 );
			}

			// Retrieve source contents
			try {
				$rr = new RemoteRequest( $source_uri );
				$rr->execute();
				if ( ! $rr->executed() ) {
					throw new XMLRPCException( 16 );
				}
				$source_contents = $rr->get_response_body();
				$headers = $rr->get_response_headers();
			}
			catch ( XMLRPCException $e ) {
				// catch our special type of exception and re-throw it
				throw $e;
			}
			catch ( Exception $e ) {
				throw new XMLRPCException( -32300 );
			}

			// Encoding is converted into internal encoding.
			// First, detect the source string's encoding
			$habari_encoding = strtoupper( MultiByte::hab_encoding() );
			$source_encoding = 'Windows-1252';
			// Is the charset in the headers?
			if ( isset( $headers['Content-Type'] ) && strpos( $headers['Content-Type'], 'charset' ) !== false ) {
				// This regex should be changed to meet the HTTP spec at some point
				if ( preg_match("/charset[\x09\x0A\x0C\x0D\x20]*=[\x09\x0A\x0C\x0D\x20]*('?)([A-Za-z0-9\-\_]+)\1/i", $headers['Content-Type'], $matches ) ) {
					$source_encoding = strtoupper( $matches[2] );
				}
			}
			// Can we tell the charset from the stream itself?
			else if ( ( $enc = MultiByte::detect_bom_encoding( $source_contents ) ) !== false ) {
				$source_encoding = $enc;
			}
			// Is the charset in a meta tag?
			else if ( preg_match( "/<meta[^>]+charset[\x09\x0A\x0C\x0D\x20]*=[\x09\x0A\x0C\x0D\x20]*([\"']?)([A-Za-z0-9\-\_]+)\1/i", $source_contents, $matches ) ) {
				$source_encoding = strtoupper( $matches[2] );
				if (in_array($source_encoding, array("UTF-16", "UTF-16BE", "UTF-16LE"))) {
					$source_encoding = "UTF-8";
				}
			}
			// Then, convert the string
			$ret = MultiByte::convert_encoding( $source_contents, $habari_encoding, $source_encoding );
			if ( $ret !== false ) {
				$source_contents = $ret;
			}

			// Find the page's title
			preg_match( '/<title>(.*)<\/title>/is', $source_contents, $matches );
			$source_title = $matches[1];

			// Find the reciprocal links and their context
			preg_match( '/<body[^>]*>(.+)<\/body>/is', $source_contents, $matches );
			$source_contents_filtered = preg_replace( '/\s{2,}/is', ' ', strip_tags( $matches[1], '<a>' ) );

			// Get rid of all the non-recriprocal links
			$ht = new HTMLTokenizer( trim( $source_contents_filtered ) );
			$set = $ht->parse();
			$all_links = $set->slice( 'a', array() );
			$keep_links = $set->slice( 'a', array( 'href' => $target_uri ) );
			$bad_links = array_diff( $all_links, $keep_links );
			foreach( $bad_links as $link ) {
				$link->tokenize_replace( '' );
				$set->replace_slice( $link );
			}
			$source_contents_filtered = (string)$set;

			// Get the excerpt
			if ( !preg_match( '%.{0,100}?<a[^>]*?href\\s*=\\s*("|\'|)' . $target_uri . '\\1[^>]*?'.'>(.+?)</a>.{0,100}%s', $source_contents_filtered, $source_excerpt ) ) {
				throw new XMLRPCException( 17 );
			}

			/** Sanitize Data */
			$source_excerpt = '&hellip;' . InputFilter::filter( $source_excerpt[0] ) . '&hellip;';
			$source_title = InputFilter::filter($source_title);
			$source_uri = InputFilter::filter($source_uri);

			/* Sanitize the URL */
			if (!empty($source_uri)) {
				$parsed = InputFilter::parse_url( $source_uri );
				if ( $parsed['is_relative'] ) {
					// guess if they meant to use an absolute link
					$parsed = InputFilter::parse_url( 'http://' . $source_uri );
					if ( ! $parsed['is_error'] ) {
						$source_uri = InputFilter::glue_url( $parsed );
					}
					else {
						// disallow relative URLs
						$source_uri = '';
					}
				}
				if ( $parsed['is_pseudo'] || ( $parsed['scheme'] !== 'http' && $parsed['scheme'] !== 'https' ) ) {
					// allow only http(s) URLs
					$source_uri = '';
				}
				else {
					// reconstruct the URL from the error-tolerant parsing
					// http:moeffju.net/blog/ -> http://moeffju.net/blog/
					$source_uri = InputFilter::glue_url( $parsed );
				}
			}

			// Add a new pingback comment
			$pingback = new Comment( array(
				'post_id'	=>	$target_post->id,
				'name'		=>	$source_title,
				'email'		=>	'',
				'url'		=>	$source_uri,
				'ip'		=>	Utils::get_ip(),
				'content'	=>	$source_excerpt,
				'status'	=>	Comment::STATUS_UNAPPROVED,
				'date'		=>	HabariDateTime::date_create(),
				'type' 		=> 	Comment::PINGBACK,
				) );

			$pingback->insert();

			// Respond to the Pingback
			return 'The pingback has been registered';
		}
		catch ( XMLRPCException $e ) {
			$e->output_fault_xml();
		}
	}
Beispiel #13
0
 public static function query($url = null)
 {
     $URL = new URL($url);
     $URL->parse();
     return $URL->query;
 }
Beispiel #14
0
function GetMcard()
{
    global $memberContext, $context, $txt, $user_info;
    $is_xmlreq = $_REQUEST['action'] == 'xmlhttp' ? true : false;
    if (!$is_xmlreq) {
        redirectexit();
    }
    // this isn't supposed to be called normally
    if (!isset($_REQUEST['u'])) {
        AjaxErrorMsg($txt['no_access'], $txt['error_occured']);
    }
    $uid = intval($_REQUEST['u']);
    if (allowedTo('profile_view_any') && $uid) {
        //loadTemplate('MemberCard');
        EoS_Smarty::loadTemplate('membercard');
        loadMemberData($uid, false, 'profile');
        loadMemberContext($uid);
        loadLanguage('Profile');
        loadLanguage('Ratings');
        $context['member'] = $memberContext[$uid];
        if (!empty($context['member']['gender']['name'])) {
            $context['member']['loc'][0] = $context['member']['gender']['image'] . $context['member']['gender']['name'];
        }
        if (isset($context['member']['birth_date']) && !empty($context['member']['birth_date'])) {
            list($birth_year, $birth_month, $birth_day) = sscanf($context['member']['birth_date'], '%d-%d-%d');
            $datearray = getdate(forum_time());
            if ($birth_year > 5) {
                $context['member']['loc'][1] = $datearray['year'] - $birth_year - ($datearray['mon'] > $birth_month || $datearray['mon'] == $birth_month && $datearray['mday'] >= $birth_day ? 0 : 1);
            }
        }
        if (!empty($context['member']['location'])) {
            $context['member']['loc'][2] = 'from ' . $context['member']['location'];
        }
        $context['can_send_pm'] = allowedTo('pm_send') && $uid != $user_info['id'];
        $context['pm_contact_link'] = $context['can_send_pm'] ? URL::parse('?action=pm;sa=send;u=' . $context['member']['id']) : '';
    } else {
        AjaxErrorMsg($txt['no_access'], $txt['error_occured']);
    }
}
Beispiel #15
0
 /**
  * Parses the requested URL.  Automatically
  * translates URLs coming in from mod_rewrite and parses
  * out any action and parameters in the slug.
  */
 public static function parse_request()
 {
     /* Local scope variable caching */
     $controller = Controller::instance();
     /* Grab the base URL from the Site class */
     $controller->base_url = Site::get_path('base', true);
     /* Start with the entire URL coming from web server... */
     $start_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $_SERVER['SCRIPT_NAME'] . (isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '') . (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != '' ? '?' . $_SERVER['QUERY_STRING'] : '');
     /* Strip out the base URL from the requested URL */
     /* but only if the base URL isn't / */
     if ('/' != $controller->base_url) {
         $start_url = str_replace($controller->base_url, '', $start_url);
     }
     // undo &amp;s
     $start_url = str_replace('&amp;', '&', $start_url);
     /* Trim off any leading or trailing slashes */
     $start_url = trim($start_url, '/');
     /* Allow plugins to rewrite the stub before it's passed through the rules */
     $start_url = Plugins::filter('rewrite_request', $start_url);
     $controller->stub = $start_url;
     /* Grab the URL filtering rules from DB */
     $matched_rule = URL::parse($controller->stub);
     if ($matched_rule === FALSE) {
         $matched_rule = URL::set_404();
     }
     /* OK, we have a matching rule.  Set the action and create a handler */
     $controller->action = $matched_rule->action;
     $controller->handler = new $matched_rule->handler();
     /* Insert the regexed submatches as the named parameters */
     $controller->handler->handler_vars['entire_match'] = $matched_rule->entire_match;
     // The entire matched string is returned at index 0
     foreach ($matched_rule->named_arg_values as $named_arg_key => $named_arg_value) {
         $controller->handler->handler_vars[$named_arg_key] = $named_arg_value;
     }
     /* Also, we musn't forget to add the GET and POST vars into the action's settings array */
     $handler_vars = new SuperGlobal($controller->handler->handler_vars);
     $handler_vars = $handler_vars->merge($_GET, $_POST);
     $controller->handler->handler_vars = $handler_vars;
     return true;
 }
Beispiel #16
0
/**
 * fetch new threads (all of them, read status doesn't matter)
 *
 * todo: respect ignored boards
 */
function WhatsNew()
{
    global $context, $modSettings, $txt, $user_info, $scripturl;
    $cutoff_days = !empty($modSettings['whatsNewCutoffDays']) ? $modSettings['whatsNewCutoffDays'] : 30;
    $context['current_action'] = 'whatsnew';
    $start = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
    $context['topics_per_page'] = empty($modSettings['disableCustomPerPage']) && !empty($options['topics_per_page']) ? $options['topics_per_page'] : $modSettings['defaultMaxTopics'];
    // find the first post that is newer than our cutoff time...
    $request = smf_db_query('SELECT m.id_msg from {db_prefix}messages AS m 
			LEFT JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic) 
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board) 
			WHERE {query_wanna_see_board} AND m.approved = 1 AND m.poster_time > unix_timestamp(now()) - ({int:days_cutoff} * 86400) limit 1', array('days_cutoff' => $cutoff_days));
    EoS_Smarty::loadTemplate('recent');
    $context['template_functions'] = 'unread_topics';
    $context['can_approve_posts'] = allowedTo('approve_posts');
    $context['page_title'] = $context['page_header'] = sprintf($txt['whatsnew_title'], $cutoff_days);
    $context['subject_sort_header'] = $txt['subject'];
    $context['views_sort_header'] = $txt['views'];
    $context['lastpost_sort_header'] = $txt['last_post'];
    $context['querystring_board_limits'] = '';
    $context['linktree'][] = array('url' => URL::parse($scripturl . '?action=whatsnew'), 'name' => $context['page_title']);
    if (0 == mysql_num_rows($request)) {
        mysql_free_result($request);
        return;
    }
    list($first_msg) = mysql_fetch_row($request);
    mysql_free_result($request);
    $request = smf_db_query('SELECT DISTINCT(t.id_topic), COUNT(t.id_topic) FROM {db_prefix}topics AS t 
			LEFT JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
			WHERE {query_wanna_see_board} AND t.id_last_msg >= {int:first_msg} limit 1', array('first_msg' => $first_msg));
    list($id, $count) = mysql_fetch_row($request);
    mysql_free_result($request);
    $total = $count;
    $base_url = URL::parse($scripturl . '?action=whatsnew');
    $context['page_index'] = constructPageIndex($base_url . ';start=%1$d', $start, $total, $context['topics_per_page'], true);
    $topic_ids = array();
    $request = smf_db_query('SELECT DISTINCT t.id_topic FROM {db_prefix}topics AS t
			LEFT JOIN {db_prefix}boards AS b ON(b.id_board = t.id_board)
			WHERE {query_wanna_see_board} AND t.id_last_msg >= {int:first_msg} ORDER BY t.id_last_msg DESC LIMIT {int:start}, {int:perpage}', array('first_msg' => $first_msg, 'start' => $start, 'perpage' => $context['topics_per_page']));
    while ($row = mysql_fetch_assoc($request)) {
        $topic_ids[] = $row['id_topic'];
    }
    mysql_free_result($request);
    $request = smf_db_query('SELECT	t.id_topic, IFNULL(lt.id_msg, IFNULL(lmr.id_msg, -1)) + 1 AS new_from, b.id_board, b.name AS board_name, t.num_replies, t.locked, t.num_views, t.is_sticky, t.approved, t.unapproved_posts, t.id_first_msg, t.id_last_msg,
				ms.subject, ml.subject AS last_subject, ms.id_member, IFNULL(mem.real_name, ms.poster_name) AS first_member_name, ms.poster_time AS first_poster_time, ms.icon AS first_icon,
				ml.id_msg_modified, ml.poster_time, ml.id_member AS id_member_updated,
				IFNULL(mem2.real_name, ml.poster_name) AS last_real_name, ml.poster_time AS last_post_time
				FROM {db_prefix}topics AS t 
				INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
				INNER JOIN {db_prefix}messages AS ml ON (ml.id_msg = t.id_last_msg)
				LEFT JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ms.id_member)
				LEFT JOIN {db_prefix}members AS mem2 ON (mem2.id_member = ml.id_member)
				LEFT JOIN {db_prefix}log_topics AS lt ON (lt.id_topic = t.id_topic AND lt.id_member = {int:current_member})
				LEFT JOIN {db_prefix}log_mark_read AS lmr ON (lmr.id_board = t.id_board AND lmr.id_member = {int:current_member})
				LEFT JOIN {db_prefix}prefixes AS p ON (p.id_prefix = t.id_prefix)
				WHERE t.id_topic IN({array_int:topic_ids}) ORDER BY t.id_last_msg DESC', array('start' => $start, 'perpage' => $context['topics_per_page'], 'first_msg' => $first_msg, 'current_member' => $user_info['id'], 'topic_ids' => $topic_ids));
    $topiclist = new Topiclist($request, $total, true);
    mysql_free_result($request);
    $context['showing_all_topics'] = true;
    $context['topics'] = $topiclist->getResult();
}
Beispiel #17
0
function cache_getMembergroupList()
{
    global $scripturl, $smcFunc;
    $request = smf_db_query('
		SELECT id_group, group_name, online_color
		FROM {db_prefix}membergroups
		WHERE min_posts = {int:min_posts}
			AND hidden = {int:not_hidden}
			AND id_group != {int:mod_group}
			AND online_color != {string:blank_string}
		ORDER BY group_name', array('min_posts' => -1, 'not_hidden' => 0, 'mod_group' => 3, 'blank_string' => ''));
    $groupCache = array();
    while ($row = mysql_fetch_assoc($request)) {
        $groupCache[] = '<a class="member group_' . $row['id_group'] . '" href="' . URL::parse('?action=groups;sa=members;group=' . $row['id_group']) . '">' . $row['group_name'] . '</a>';
    }
    mysql_free_result($request);
    return array('data' => $groupCache, 'expires' => time() + 3600, 'refresh_eval' => 'return $GLOBALS[\'modSettings\'][\'settings_updated\'] > ' . time() . ';');
}
Beispiel #18
0
 function getHost($url)
 {
     $components = URL::parse($url);
     return $components[4];
 }
Beispiel #19
0
 /**
  *
  * @param URL $url
  * @return MenuItem
  */
 public function setUrl($url)
 {
     $this->url = URL::parse($url);
     return $this;
 }
Beispiel #20
0
 /**
  * {@inheritdoc}
  * @return URLImmutable
  */
 public function parse($url, $cleanup = true)
 {
     if ($this->isLocked()) {
         return $this->getObj()->parse($url, $cleanup)->setLocked();
     } else {
         return parent::parse($url, $cleanup);
     }
 }
Beispiel #21
0
function aStreamGet($b = 0, $xml = false, $global = false)
{
    global $board, $context, $user_info, $modSettings, $options, $scripturl;
    if (!isset($board) || !$board) {
        $board = $b;
    }
    $start = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;
    $context['xml'] = $xml;
    $context['act_global'] = false;
    $total = 0;
    $context['sef_full_rewrite'] = true;
    $perpage = $xml ? 15 : (empty($modSettings['disableCustomPerPage']) && !empty($options['topics_per_page']) ? $options['topics_per_page'] : $modSettings['defaultMaxTopics']);
    if ($user_info['is_admin']) {
        $pquery = ' AND (a.is_private <= ' . ACT_PLEVEL_ADMIN . ' OR a.id_member = {int:id_user} OR a.id_owner = {int:id_user}) ';
    } else {
        $pquery = ' AND (a.is_private = 0 OR a.id_member = {int:id_user} OR a.id_owner = {int:id_user}) ';
    }
    $filterby = '';
    if (isset($_REQUEST['filter'])) {
        $filterby = normalizeCommaDelimitedList($_REQUEST['filter']);
        if (strlen($filterby)) {
            $pquery .= ' AND a.id_type IN({string:filter})';
        }
    }
    $uquery = '';
    if (isset($_REQUEST['u']) && (int) $_REQUEST['u'] > 0) {
        $uquery .= 'a.id_member = {int:id_user} AND ';
    } else {
        $uquery = !empty($user_info['ignoreusers']) ? 'a.id_member NOT IN({array_int:ignoredusers}) AND ' : '';
    }
    if ($global) {
        if (!$xml) {
            $result = smf_db_query('SELECT COUNT(a.id_act) FROM {db_prefix}log_activities AS a
				LEFT JOIN {db_prefix}boards AS b ON(b.id_board = a.id_board)
				WHERE ' . $uquery . ' ({query_wanna_see_board} OR a.id_board = 0)' . $pquery, array('start' => 0, 'id_user' => $user_info['id'], 'filter' => $filterby, 'perpage' => $perpage, 'ignoredusers' => $user_info['ignoreusers']));
            list($total) = mysql_fetch_row($result);
            mysql_free_result($result);
        }
        $result = smf_db_query('SELECT a.*, t.*, b.name AS board_name FROM {db_prefix}log_activities AS a
			LEFT JOIN {db_prefix}activity_types AS t ON (t.id_type = a.id_type)
			LEFT JOIN {db_prefix}boards AS b ON(b.id_board = a.id_board)
			WHERE ' . $uquery . ' ({query_wanna_see_board} OR a.id_board = 0)' . $pquery . ' ORDER BY a.id_act DESC LIMIT {int:start}, {int:perpage}', array('start' => $start, 'id_user' => $user_info['id'], 'filter' => $filterby, 'perpage' => $perpage, 'ignoredusers' => $user_info['ignoreusers']));
        $context['act_global'] = true;
        $context['viewall_url'] = URL::parse($scripturl . '?action=astream;sa=get;all');
    } else {
        if (!$xml) {
            $result = smf_db_query('SELECT COUNT(a.id_act) FROM {db_prefix}log_activities AS a
				LEFT JOIN {db_prefix}boards AS b ON(b.id_board = a.id_board)
				WHERE ' . $uquery . ' a.id_board = {int:id_board} AND {query_wanna_see_board} ' . $pquery, array('id_board' => $board, 'start' => 0, 'id_user' => $user_info['id'], 'filter' => $filterby, 'perpage' => $perpage, 'ignoredusers' => $user_info['ignoreusers']));
            list($total) = mysql_fetch_row($result);
            mysql_free_result($result);
        }
        $result = smf_db_query('SELECT a.*, t.*, b.name AS board_name FROM {db_prefix}log_activities AS a
			LEFT JOIN {db_prefix}activity_types AS t ON (t.id_type = a.id_type)
			LEFT JOIN {db_prefix}boards AS b ON(b.id_board = a.id_board)
			WHERE ' . $uquery . ' a.id_board = {int:id_board} AND {query_wanna_see_board}' . $pquery . ' ORDER BY a.id_act DESC LIMIT {int:start}, {int:perpage}', array('id_board' => $board, 'start' => $start, 'id_user' => $user_info['id'], 'filter' => $filterby, 'perpage' => $perpage, 'ignoredusers' => $user_info['ignoreusers']));
        $context['viewall_url'] = URL::parse($scripturl . '?action=astream;sa=get;b=' . $board);
    }
    $pages_base = URL::parse($scripturl . '?action=astream;sa=get;all;');
    $pages_base = URL::addParam($pages_base, 'start=%1$d', true);
    $context['pages'] = $total ? constructPageIndex($pages_base, $start, $total, $perpage, true) : '';
    if ($xml) {
        header('Content-Type: text/xml; charset=UTF-8');
    }
    aStreamOutput($result);
}
Beispiel #22
0
<?php

error_reporting(E_ALL);
require_once '../anewt.lib.php';
define('ANEWT_TEXTILE_DEVELOPMENT', 1);
anewt_include('gpc');
anewt_include('page');
$p = new AnewtPage();
$p->set('title', 'Textile formatting test');
if (AnewtGPC::get_bool('debug')) {
    header('Content-type: text/plain');
    $p->set('content_type', 'text/plain');
} else {
    list($base_url, $params) = URL::parse(Request::url());
    $params['debug'] = true;
    $debug_url = URL::unparse($base_url, $params);
    $p->append(ax_p(ax_a_href('(Page source for debugging)', $debug_url)));
}
anewt_include('textformatting');
anewt_include('textile');
$text = file_get_contents('sample-text.txt');
$formatted_text = TextFormatter::format($text, 'textile');
$p->append(ax_raw($formatted_text));
$p->flush();
Beispiel #23
0
 /**
  * Url redirection.
  *
  * @param string $url the url
  * @param string $http_response_code http response code
  * @return void
  */
 public function redirect($url = null, $http_response_code = null)
 {
     if (!empty($url)) {
         $url = URL::parse($url);
         $this->header("Location: {$url}", false, $http_response_code);
     }
     $this->outputHeaders();
     exit;
 }
Beispiel #24
0
function prepareDisplayContext($reset = false)
{
    global $txt, $modSettings, $options, $user_info, $output;
    global $memberContext, $context, $messages_request;
    static $counter = null;
    static $seqnr = 0;
    // If the query returned false, bail.
    if ($messages_request == false) {
        return false;
    }
    // Remember which message this is.  (ie. reply #83)
    if ($counter === null || $reset) {
        $counter = empty($options['view_newest_first']) ? $context['start'] : $context['total_visible_posts'] - $context['start'];
    }
    // Start from the beginning...
    if ($reset) {
        return @mysql_data_seek($messages_request, 0);
    }
    // Attempt to get the next message.
    $message = mysql_fetch_assoc($messages_request);
    if (!$message) {
        mysql_free_result($messages_request);
        return false;
    }
    // If you're a lazy bum, you probably didn't give a subject...
    $message['subject'] = $message['subject'] != '' ? $message['subject'] : $txt['no_subject'];
    // Are you allowed to remove at least a single reply?
    $context['can_remove_post'] |= $context['can_delete_own'] && (empty($modSettings['edit_disable_time']) || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 >= time()) && $message['id_member'] == $user_info['id'];
    // If it couldn't load, or the user was a guest.... someday may be done with a guest table.
    if (!loadMemberContext($message['id_member'], true)) {
        // Notice this information isn't used anywhere else....
        $memberContext[$message['id_member']]['name'] = $message['poster_name'];
        $memberContext[$message['id_member']]['id'] = 0;
        $memberContext[$message['id_member']]['group'] = $txt['guest_title'];
        $memberContext[$message['id_member']]['link'] = $message['poster_name'];
        $memberContext[$message['id_member']]['email'] = $message['poster_email'];
        $memberContext[$message['id_member']]['show_email'] = showEmailAddress(true, 0);
        $memberContext[$message['id_member']]['is_guest'] = true;
        $memberContext[$message['id_member']]['is_banned_from_topic'] = $memberContext[$message['id_member']]['can_see_warning'] = false;
    } else {
        $memberContext[$message['id_member']]['can_view_profile'] = $context['can_profile_view_any'] || $message['id_member'] == $user_info['id'] && $context['can_profile_view_own'];
        $memberContext[$message['id_member']]['is_topic_starter'] = $message['id_member'] == $context['topic_starter_id'];
        $memberContext[$message['id_member']]['can_see_warning'] = !isset($context['disabled_fields']['warning_status']) && $memberContext[$message['id_member']]['warning_status'] && ($context['user']['can_mod'] || !$user_info['is_guest'] && !empty($modSettings['warning_show']) && ($modSettings['warning_show'] > 1 || $message['id_member'] == $user_info['id']));
        $memberContext[$message['id_member']]['is_banned_from_topic'] = !empty($context['topic_banned_members']) ? in_array($message['id_member'], $context['topic_banned_members']) : false;
    }
    $memberContext[$message['id_member']]['ip'] = $message['poster_ip'];
    // Do the censor thang.
    censorText($message['subject']);
    // create a cached (= parsed) version of the post on the fly
    // but only if it's not older than the cutoff time.
    // and do not cache more than PCACHE_UPDATE_PER_VIEW posts per thread view to reduce load spikes
    $dateline = max($message['modified_time'], $message['poster_time']);
    if ($context['pcache_update_counter'] < PCACHE_UPDATE_PER_VIEW && $context['time_cutoff_ref'] - $dateline < $modSettings['post_cache_cutoff'] * 86400) {
        if (empty($message['cached_body'])) {
            $context['pcache_update_counter']++;
            $message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], '');
            // don't cache bbc when we pre-parse the post anyway...
            smf_db_insert('replace', '{db_prefix}messages_cache', array('id_msg' => 'int', 'body' => 'string', 'style' => 'string', 'lang' => 'string', 'updated' => 'int'), array($message['id_msg'], $message['body'], $user_info['smiley_set_id'], $user_info['language_id'], $dateline), array('id_msg', 'body', 'style', 'lang', 'updated'));
            parse_bbc_stage2($message['body'], $message['id_msg']);
        } else {
            $message['body'] =& $message['cached_body'];
            parse_bbc_stage2($message['body'], $message['id_msg']);
        }
    } else {
        $message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg'] . '|' . $message['modified_time']);
        parse_bbc_stage2($message['body'], $message['id_msg']);
    }
    censorText($message['body']);
    // Compose the memory eat- I mean message array.
    //$t_href = URL::topic($topic, $message['subject'], 0, false, '.msg' . $message['id_msg'] . '#msg'.$message['id_msg']);
    $output = array('attachment' => loadAttachmentContext($message['id_msg']), 'id' => $message['id_msg'], 'permahref' => URL::parse('?msg=' . $message['id_msg'] . (isset($_REQUEST['perma']) ? '' : ';perma')), 'member' => &$memberContext[$message['id_member']], 'icon' => $message['icon'], 'icon_url' => getPostIcon($message['icon']), 'subject' => $message['subject'], 'time' => timeformat($message['poster_time']), 'timestamp' => $message['poster_time'], 'counter' => $counter, 'permalink' => isset($_REQUEST['perma']) ? $txt['view_in_thread'] : ' #' . ($counter + 1), 'modified' => array('time' => timeformat($message['modified_time']), 'name' => $message['modified_name']), 'body' => &$message['body'], 'new' => empty($message['is_read']), 'approved' => $message['approved'], 'first_new' => isset($context['start_from']) && $context['start_from'] == $counter, 'is_ignored' => !empty($modSettings['enable_buddylist']) && !empty($options['posts_apply_ignore_list']) && in_array($message['id_member'], $context['user']['ignoreusers']), 'can_approve' => !$message['approved'] && $context['can_approve'], 'can_unapprove' => $message['approved'] && $context['can_unapprove'], 'can_modify' => (!$message['locked'] || $context['can_moderate_board']) && ((!$context['is_locked'] || $context['can_moderate_board']) && ($context['can_modify_any'] || $context['can_modify_replies'] && $context['user']['started'] || $context['can_modify_own'] && $message['id_member'] == $user_info['id'] && (empty($modSettings['edit_disable_time']) || !$message['approved'] || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 > time()))), 'can_remove' => (!$message['locked'] || $context['can_moderate_board']) && ($context['can_delete_any'] || $context['can_delete_replies'] && $context['user']['started'] || $context['can_delete_own'] && $message['id_member'] == $user_info['id'] && (empty($modSettings['edit_disable_time']) || $message['poster_time'] + $modSettings['edit_disable_time'] * 60 > time())), 'can_see_ip' => $context['can_moderate_forum'] || $message['id_member'] == $user_info['id'] && !empty($user_info['id']), 'likes_count' => $message['likes_count'], 'like_status' => $message['like_status'], 'liked' => $message['liked'], 'like_updated' => $message['like_updated'], 'id_member' => $message['id_member'], 'postbit_callback' => $message['approved'] ? $message['id_msg'] == $context['first_message'] ? $context['postbit_callbacks']['firstpost'] : $context['postbit_callbacks']['post'] : 'template_postbit_comment', 'postbit_template_class' => $message['approved'] ? $message['id_msg'] == $context['first_message'] ? $context['postbit_template_class']['firstpost'] : $context['postbit_template_class']['post'] : 'c', 'mq_marked' => in_array($message['id_msg'], $context['multiquote_posts']), 'header_class' => $context['can_moderate_member'] && ($memberContext[$message['id_member']]['is_banned_from_topic'] || $memberContext[$message['id_member']]['can_see_warning']) ? ' watched' : '');
    if ($context['can_see_like']) {
        Ratings::addContent($output, $context['can_give_like'], $context['time_cutoff_ref']);
    } else {
        $output['likes_count'] = 0;
    }
    // Is this user the message author?
    $output['is_message_author'] = $message['id_member'] == $user_info['id'];
    $counter += empty($options['view_newest_first']) ? 1 : -1;
    // hooks can populate these fields with additional content
    $output['template_hook'] = array('before_sig' => '', 'after_sig' => '', 'postbit_below' => '', 'poster_details' => '');
    HookAPI::callHook('display_postbit', array(&$output));
    if (isset($output['member']['can_see_warning']) && !empty($output['member']['can_see_warning'])) {
        $output['member']['warning_status_desc'] = isset($output['member']['warning_status']) ? $txt['user_warn_' . $output['member']['warning_status']] : '';
        $output['member']['warning_status_desc1'] = isset($output['member']['warning_status']) ? $txt['warn_' . $output['member']['warning_status']] : '';
    }
    $output['member']['allow_show_email'] = $output['member']['is_guest'] ? !empty($output['member']['email']) && in_array($output['member']['show_email'], array('yes', 'yes_permission_override', 'no_through_forum')) : false;
    //$context['current_message'] = &$output;
    if ($output['can_remove']) {
        $context['removableMessageIDs'][] = $output['id'];
    }
    //return $output;
}
function customErrorHandler($errorNumber, $errorString, $errorFile, $errorLine)
{
    // Prepare Values
    $errorType = "Error";
    switch ($errorNumber) {
        case E_USER_NOTICE:
            $errorType = "Notice";
            $importance = 0;
            break;
        case E_USER_WARNING:
            $errorType = "Warning";
            $importance = 2;
            break;
        case E_USER_ERROR:
            $errorType = "Fatal Error";
            $importance = 4;
            break;
        default:
            $errorType = "Unknown Error";
            $importance = 8;
            break;
    }
    // Run the Backtrace
    $backtrace = debug_backtrace();
    if (isset($backtrace[1])) {
        // Prepare Backtrace Values
        $origin = $backtrace[1];
        $behind = $backtrace[0];
        // Identify the current URL
        $urlData = URL::parse($_SERVER['SERVER_NAME'] . "/" . $_SERVER['REQUEST_URI']);
        // If the error was triggered with trigger_error(), simplify the logging
        if ($origin['function'] == "trigger_error") {
            // Prepare Logging Values
            $class = "";
            $function = "trigger_error";
            $argString = $origin['args'][0];
            $filePath = str_replace(SYS_PATH, "", $origin['file']);
            $fileLine = (int) $origin['line'];
            // Local Environment
            if (ENVIRONMENT == "local") {
                $cons = get_defined_constants(true);
                $debugData = array("Backtrace" => array_splice($backtrace, 1), "URL" => $urlData, "Constants" => $cons['user'], "_GET" => $_GET, "_POST" => $_POST, "_COOKIE" => $_COOKIE, "_SESSION" => $_SESSION, "_SERVER" => $_SERVER);
            }
        } else {
            // Prepare Logging Values
            $class = isset($origin['class']) ? $origin['class'] : "";
            $function = isset($origin['function']) ? $origin['function'] : "";
            $argString = isset($origin['args']) ? Data_Utilities::convertArrayToArgumentString($origin['args']) : "";
            $filePath = isset($behind['file']) ? str_replace(dirname(SYS_PATH), "", $behind['file']) : '';
            $fileLine = isset($behind['line']) ? $behind['line'] : 0;
            // Skip instances of the autoloader
            if ($errorType == "Unknown Error" and strpos($function, "spl_autoload") !== false) {
                return false;
            }
        }
        // Debug files in the local environment
        if (ENVIRONMENT == "local") {
            if (!isset($urlData['path'])) {
                $urlData['path'] = "home";
            }
            // Add an entry to the debug timeline
            File::write(SYS_PATH . "/debug/" . microtime(true) . "-" . str_replace("/", "_", $urlData['path']) . ".php", print_r(isset($debugData) ? $debugData : $backtrace, true));
            // Add an entry to the primary debug page
            File::prepend(SYS_PATH . "/debug/_primaryDebug.php", print_r(array("Domain" => FULL_DOMAIN, "URL" => $urlData['full'], "Error" => $errorType . ": " . $argString, "File" => "[Line " . $fileLine . "] " . $filePath, "Timestamp" => microtime(true)), true));
            // Add an entry to the debugging page
            File::prepend(SYS_PATH . "/debug/by-site/" . FULL_DOMAIN . "/" . $urlData['path'] . ".php", print_r(array("URL" => $urlData['full'], "Error" => $errorType . ": " . $behind['args'][1], "File" => "[Line " . $fileLine . "] " . $filePath, "Timestamp" => microtime(true)), true));
            // Prune the debug pages so that they don't get overloaded
            File::prune(SYS_PATH . "/debug/_primaryDebug.php", 300);
            File::prune(SYS_PATH . "/debug/by-site/" . FULL_DOMAIN . "/" . $urlData['path'] . ".php", 120);
            // Prune the timeline debug files so that they don't exhaust the system
            if (mt_rand(0, 25) == 22) {
                $debugFiles = Dir::getFiles(SYS_PATH . "/debug");
                foreach ($debugFiles as $dbf) {
                    if ($dbf[0] != "_") {
                        $exp = explode(".", $dbf);
                        if ($exp[0] < time() + 86400) {
                            File::delete(SYS_PATH . "/debug/" . $dbf);
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        // Log this error in the database
        // Debug::logError($importance, $errorType, $class, $function, $argString, $filePath, $fileLine, $urlData['full'], Me::$id);
        // End the Error Handler
        return false;
        // TRUE to run standard error logging afterward
        /*
        if(ENVIRONMENT != "production")
        {
        	Debug::$verbose = true;
        	
        	Debug::scriptError($errorString, $class, $function, $argString, $filePath, $fileLine, $filePathNext, $fileLineNext);
        }
        else
        {
        	return false;
        }
        */
    }
    // Returning FALSE will activate the default PHP Handler after ours runs.
    // Returning TRUE will prevent the default PHP Handler from running.
    return true;
}
<?php

/*
----------------------------------
------ About the Login Form ------
----------------------------------
This page provides a login form for manually logging in. It will send the handle and password to Auth, at which point Auth will process the login and return.
*/
// Determine the Return URL (if not already set)
if (!isset($_SESSION['login']['return_url'])) {
    // If this page was referred by a previous URL
    if (isset($_SERVER['HTTP_REFERER'])) {
        $refURL = URL::parse($_SERVER['HTTP_REFERER']);
        $_SESSION['login']['return_url'] = '/' . (isset($refURL['path']) ? $refURL['path'] : '') . (isset($refURL['query']) ? '?' . $refURL['query'] : '');
    } else {
        $_SESSION['login']['return_url'] = '/';
    }
}
// If you're already logged in, return to the Return URL
if (Me::$id) {
    unset($_SESSION['login']);
    header("Location: /" . $_SESSION['login']['return_url']);
    exit;
}
/****** Form Submission ******/
if (Form::submitted(SITE_HANDLE . "-login-form")) {
    // Validate the Inputs
    Validate::variable("Username", $_POST['handle'], 1, 20);
    Validate::password($_POST['password']);
    // If the Form Validation Passed
    if (Validate::pass()) {
Beispiel #27
0
 public function url_parse($uri)
 {
     return URL::parse($uri);
 }
Beispiel #28
0
function TopicBans()
{
    global $context, $board_info, $topic, $txt, $memberContext, $user_info;
    EoS_Smarty::loadTemplate('modcenter/modcenter_base');
    if (isset($_REQUEST['sa']) && ($_REQUEST['sa'] === 'unban' || $_REQUEST['sa'] === 'ban')) {
        $is_ban = $_REQUEST['sa'] === 'ban' ? 1 : 0;
        $context['page_title'] = $is_ban ? $txt['mc_issue_topic_ban'] : $txt['mc_lift_topic_ban'];
        EoS_Smarty::getConfigInstance()->registerHookTemplate('modcenter_content_area', 'modcenter/topicban_issue_or_lift');
        $context['op_errors'] = array();
        $member = isset($_REQUEST['m']) ? (int) $_REQUEST['m'] : 0;
        if (!isset($topic) || empty($topic) || !isset($board_info) || empty($board_info) || 0 == $member) {
            $context['op_errors'][] = $txt['mc_lift_topic_ban_missing_data'];
        }
        if (!allowedTo('moderate_board')) {
            $context['op_errors'][] = $txt['mc_lift_topic_ban_not_allowed'];
        }
        if (loadMemberData($member) != false) {
            loadMemberContext($member);
            $context['banned_member'] =& $memberContext[$member];
        } else {
            $context['op_errors'][] = $txt['mc_lift_topic_ban_invalid_member'];
        }
        // defaults
        $context['ban_data'] = array('expire' => 0, 'reason' => '');
        if (isset($_REQUEST['save'])) {
            $context['ban_data']['expire'] = !empty($_POST['mc_expire']) ? (int) $_POST['mc_expire'] : 0;
            $context['ban_data']['reason'] = !empty($_POST['mc_reason']) ? htmlspecialchars($_POST['mc_reason']) : '';
        }
        $context['ban_row'] = array();
        // do not check this for admins - they can do whatever they want and even ban a moderator in his own board. Yes, admins are >> all :)
        if ($is_ban && !$user_info['is_admin']) {
            if (isUserAllowedTo('moderate_forum', 0, $member) || isUserAllowedTo('moderate_board', $board_info['id'], $member)) {
                $context['op_errors'][] = $txt['mc_topicban_not_bannable'];
            }
        }
        $request = smf_db_query('SELECT t.id_topic, ba.id_member, ba.updated, ba.reason, m.subject FROM {db_prefix}topics AS t
			LEFT JOIN {db_prefix}topicbans AS ba ON (ba.id_topic = t.id_topic AND ba.id_member = {int:member}) 
			LEFT JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
			WHERE t.id_topic = {int:topic}', array('topic' => $topic, 'member' => $member));
        if (mysql_num_rows($request) > 0) {
            $row = mysql_fetch_assoc($request);
            if (!empty($row['reason']) && strpos($row['reason'], '|')) {
                list($msg, $reason) = explode('|', $row['reason']);
            } else {
                $msg = 0;
                $reason = '';
            }
            $context['ban_row'] = array('id_member' => $row['id_member'], 'id_topic' => $row['id_topic'], 'subject' => $row['subject'], 'ban_time' => timeformat($row['updated']), 'href' => URL::topic($topic, $row['subject']), 'is_banned' => $row['id_member'], 'msg' => $msg, 'reason' => $reason);
            if ($_REQUEST['sa'] == 'ban' && $context['ban_row']['is_banned']) {
                $context['op_errors'][] = $txt['mc_topicban_duplicate'];
            } elseif ($_REQUEST['sa'] == 'unban' && $context['ban_row']['is_banned'] == 0) {
                $context['op_errors'][] = $txt['mc_lift_ban_not_found'];
            }
        } else {
            $context['op_errors'][] = $txt['mc_lift_ban_not_found'];
        }
        mysql_free_result($request);
        $mid = isset($_REQUEST['mid']) ? (int) $_REQUEST['mid'] : 0;
        // save it
        $back_to_topic = URL::topic($topic, $context['ban_row']['subject'], 0, false, '.msg' . (int) $_REQUEST['mid'], '#msg' . (int) $_REQUEST['mid']);
        if (empty($context['op_errors'])) {
            if (isset($_REQUEST['save']) && $is_ban && empty($_POST['mc_reason'])) {
                $context['op_errors'][] = $txt['mc_topicban_missing_reason'];
            }
            if (isset($_REQUEST['save']) && empty($context['op_errors'])) {
                checkSession();
                $context['success'] = 'Success';
                $context['back_url'] = $back_to_topic;
                $context['back_label'] = $txt['mc_lift_ban_backtotopic'];
                if ($is_ban) {
                    $ban_expire = isset($_REQUEST['mc_expire']) && !empty($_REQUEST['mc_expire']) ? (int) $_REQUEST['mc_expire'] * 86400 : 0;
                    $ban_reason = (isset($_REQUEST['mid']) && !empty($_REQUEST['mid']) ? (int) $_REQUEST['mid'] : 0) . '|' . htmlspecialchars($_POST['mc_reason']);
                    smf_db_insert('', '{db_prefix}topicbans', array('id_topic' => 'int', 'id_member' => 'int', 'updated' => 'int', 'expires' => 'int', 'reason' => 'string-255'), array($topic, $member, $context['time_now'], $ban_expire ? $context['time_now'] + $ban_expire : 0, $ban_reason), array('id'));
                } else {
                    smf_db_query('DELETE FROM {db_prefix}topicbans WHERE id_topic = {int:topic} AND id_member = {int:member}', array('topic' => $topic, 'member' => $member));
                }
            } else {
                $context['submit_url'] = URL::parse('?action=moderate;area=topicbans;sa=' . ($is_ban ? 'ban' : 'unban') . ';topic=' . $topic . ';m=' . $member . ';save' . ';mid=' . $mid);
                $context['back_url'] = $back_to_topic;
                $context['back_label'] = $txt['mc_lift_ban_backtotopic'];
                $context['submit_label'] = $is_ban ? $txt['mc_issue_ban'] : $txt['mc_lift_ban'];
                $context['topicban_message'] = $is_ban ? sprintf($txt['mc_topicban_message'], $context['banned_member']['link'], $context['ban_row']['href'], $context['ban_row']['subject']) : sprintf($txt['mc_lift_ban_message'], $context['banned_member']['link'], $context['ban_row']['href'], $context['ban_row']['subject'], $context['ban_row']['ban_time']);
                $context['submit'] = true;
                $context['is_ban'] = $is_ban;
            }
        } else {
            $context['back_url'] = $back_to_topic;
            $context['back_label'] = $txt['mc_lift_ban_backtotopic'];
        }
    } else {
        global $user_info, $context;
        $boards = array();
        if ($user_info['is_admin'] || allowedTo('moderate_forum')) {
            // admins and global moderator can see all topic bans
            $board_query = '1=1';
        } else {
            $boards = boardsAllowedTo('moderate_board');
            if (empty($boards)) {
                fatal_lang_error('no_access', true);
            }
            // we cannot moderate any board, so we have no business in being here
            $board_query = 'b.id_board IN ({array_int:boards})';
        }
        $member = isset($_REQUEST['m']) ? (int) $_REQUEST['m'] : 0;
        $topic = isset($_REQUEST['t']) ? (int) $_REQUEST['t'] : 0;
        $start = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;
        $mode = isset($_REQUEST['sa']) ? $_REQUEST['sa'] : 'all';
        $perpage = 25;
        if ($mode !== 'bymember' && $mode !== 'bytopic' && $mode !== 'all') {
            $mode = 'all';
        }
        $base_query = '1=1';
        if ($mode === 'bymember') {
            $base_query = $member ? 'ba.id_member = {int:member}' : $base_query;
        } else {
            $base_query = $topic ? 'ba.id_topic = {int:topic}' : $base_query;
        }
        EoS_Smarty::getConfigInstance()->registerHookTemplate('modcenter_content_area', 'modcenter/topicbans_list');
        $context['page_title'] = $txt['mc_topicbans_view'];
        $context[$context['moderation_menu_name']]['tab_data'] = array('title' => $txt['mc_topicbans_view'], 'description' => $txt['mc_topicbans_view_desc']);
        $context['topicban_view_desc'] = $txt['mc_view_topicbans_all'];
        if ($mode === 'bytopic' && $topic == 0) {
            $context['error'] = $txt['mc_topicbans_notopic'];
            return;
        } else {
            if ($mode === 'bymember' && $member == 0) {
                $context['error'] = $txt['mc_topicbans_nomember'];
                return;
            }
        }
        $request = smf_db_query('SELECT COUNT(ba.id_topic) FROM {db_prefix}topicbans AS ba
				LEFT JOIN {db_prefix}topics AS t ON(t.id_topic = ba.id_topic)
				LEFT JOIN {db_prefix}boards AS b ON(b.id_board = t.id_board)
				WHERE ' . $base_query . ' AND ' . $board_query, array('member' => $member, 'topic' => $topic, 'boards' => $boards));
        list($context['total_items']) = mysql_fetch_row($request);
        mysql_free_result($request);
        $pages_base = URL::parse('?action=moderate;area=topicbans;sa=' . $mode);
        $pages_base = URL::addParam($pages_base, 'start=%1$d', true);
        $context['pages'] = $context['total_items'] ? constructPageIndex($pages_base, $start, $context['total_items'], $perpage, true) : '';
        $request = smf_db_query('SELECT ba.*, mem.real_name, m.subject FROM {db_prefix}topicbans AS ba
				LEFT JOIN {db_prefix}topics AS t ON(t.id_topic = ba.id_topic)
				LEFT JOIN {db_prefix}members AS mem ON (mem.id_member = ba.id_member)
				LEFT JOIN {db_prefix}messages AS m ON(m.id_msg = t.id_first_msg)
				LEFT JOIN {db_prefix}boards AS b ON(b.id_board = t.id_board)
				WHERE ' . $base_query . ' AND ' . $board_query . ' LIMIT {int:start}, {int:perpage}', array('member' => $member, 'topic' => $topic, 'boards' => $boards, 'start' => $start, 'perpage' => $perpage));
        $desc_done = 0;
        while ($row = mysql_fetch_assoc($request)) {
            if (!$desc_done) {
                switch ($mode) {
                    case 'bymember':
                        $link = '<a href="' . URL::user($member, $row['real_name']) . '" onclick="getMcard(' . $member . ');return(false)">' . $row['real_name'] . '</a>';
                        $context['topicban_view_desc'] = sprintf($txt['mc_view_topicbans_bymember'], $link);
                        break;
                    case 'bytopic':
                        $link = '<a href="' . URL::topic($topic, $row['subject'], 0, false) . '">' . $row['subject'] . '</a>';
                        $context['topicban_view_desc'] = sprintf($txt['mc_view_topicbans_bytopic'], $link);
                        break;
                }
                $desc_done = true;
            }
            $m_href = URL::user($row['id_member'], $row['real_name']);
            $t_href = URL::topic($row['id_topic'], $row['subject'], 0, false);
            if (!empty($row['reason']) && strpos($row['reason'], '|')) {
                list($msg, $reason) = explode('|', $row['reason']);
            } else {
                $reason = '';
            }
            $timediff = $row['expires'] - $context['time_now'];
            $context['topicbans'][] = array('id' => $row['id'], 'id_member' => $row['id_member'], 'member' => array('id' => $row['id_member'], 'name' => $row['real_name'], 'href' => $m_href, 'link' => '<a href="' . $m_href . '" onclick="getMcard(' . $row['id_member'] . ');return(false)">' . $row['real_name'] . '</a>'), 'topic' => array('href' => $t_href, 'subject' => $row['subject'], 'id' => $row['id_topic'], 'link' => '<a href="' . $t_href . '">' . $row['subject'] . '</a>'), 'reason' => $txt['mc_topicban_reason'] . ': ' . $reason . ' (<a href="' . URL::parse('?msg=' . trim($msg) . ';perma') . '">' . $txt['mc_topicban_reason_see'] . '</a>)', 'issue_time' => timeformat($row['updated']), 'expires' => empty($row['expires']) ? $txt['mc_topicban_is_perma'] : ($timediff > 0 ? (int) ($timediff / 3600) . ' ' . $txt['mc_topicban_hours_left'] : $txt['mc_topicban_expires']));
        }
        mysql_free_result($request);
    }
}
Beispiel #29
0
/**
 * @param $memID 		int id_member
 *
 * fetch all likes received by the given user and display them
 * part of the profile -> show content area.
 */
function LikesByUser($memID)
{
    global $context, $user_info, $scripturl, $memberContext, $txt, $modSettings, $options;
    if ($memID != $user_info['id']) {
        isAllowedTo('can_view_ratings');
    }
    // let us use the same value as for topics per page here.
    $perpage = empty($modSettings['disableCustomPerPage']) && !empty($options['topics_per_page']) ? $options['topics_per_page'] : $modSettings['defaultMaxTopics'];
    $out = $_GET['sa'] === 'likesout';
    // display likes *given* instead of received ones
    $is_owner = $user_info['id'] == $memID;
    // we are the owner of this profile, this is important for proper formatting (you/yours etc.)
    $boards_like_see = boardsAllowedTo('like_see');
    // respect permissions
    $start = isset($_REQUEST['start']) ? (int) $_REQUEST['start'] : 0;
    if (!($user_info['is_admin'] || allowedTo('moderate_forum'))) {
        // admins and global mods can see everything
        $bq = ' AND b.id_board IN({array_int:boards})';
    } else {
        $bq = '';
    }
    $q = $out ? 'l.id_user = {int:id_user}' : 'l.id_receiver = {int:id_user}';
    $request = smf_db_query('SELECT count(l.id_msg) FROM {db_prefix}likes AS l
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = l.id_msg)
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
			WHERE ' . $q . ' AND {query_see_board}' . $bq, array('id_user' => $memID, 'boards' => $boards_like_see));
    list($context['total_likes']) = mysql_fetch_row($request);
    mysql_free_result($request);
    $request = smf_db_query('SELECT m.subject, m.id_topic, l.id_user, l.id_receiver, l.updated, l.id_msg, l.rtype, mfirst.subject AS first_subject, SUBSTRING(m.body, 1, 150) AS body FROM {db_prefix}likes AS l
			INNER JOIN {db_prefix}messages AS m ON (m.id_msg = l.id_msg)
			INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
			INNER JOIN {db_prefix}messages AS mfirst ON (mfirst.id_msg = t.id_first_msg)
			INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
			WHERE ' . $q . ' AND {query_see_board} ' . $bq . ' ORDER BY l.id_like DESC LIMIT {int:startwith}, {int:perpage}', array('id_user' => $memID, 'startwith' => $start, 'perpage' => $perpage, 'boards' => $boards_like_see));
    $context['results_count'] = 0;
    $context['likes'] = array();
    $context['displaymode'] = $out ? true : false;
    $context['pages'] = '';
    if ($context['total_likes'] > $perpage) {
        $context['pages'] = constructPageIndex($scripturl . '?action=profile;area=showposts;sa=' . $_GET['sa'] . ';u=' . trim($memID), $start, $context['total_likes'], $perpage);
    }
    $users = array();
    while ($row = mysql_fetch_assoc($request)) {
        $context['results_count']++;
        $thref = URL::topic($row['id_topic'], $row['first_subject'], 0);
        $phref = URL::topic($row['id_topic'], $row['subject'], 0, false, '.msg' . $row['id_msg'], '#msg' . $row['id_msg']);
        $users[] = $out ? $row['id_receiver'] : $row['id_user'];
        $context['likes'][] = array('id_user' => $out ? $row['id_receiver'] : $row['id_user'], 'time' => timeformat($row['updated']), 'topic' => array('href' => $thref, 'link' => '<a href="' . $thref . '">' . $row['first_subject'] . '</a>', 'subject' => $row['first_subject']), 'post' => array('href' => $phref, 'link' => '<a href="' . $phref . '">' . $row['subject'] . '</a>', 'subject' => $row['subject'], 'id' => $row['id_msg']), 'rtype' => $row['rtype'], 'teaser' => strip_tags(preg_replace('~[[\\/\\!]*?[^\\[\\]]*?]~si', '', $row['body'])) . '...', 'morelink' => URL::parse('?msg=' . $row['id_msg'] . ';perma'));
    }
    loadMemberData(array_unique($users));
    foreach ($context['likes'] as &$like) {
        loadMemberContext($like['id_user']);
        $like['member'] =& $memberContext[$like['id_user']];
        $like['text'] = $out ? $is_owner ? sprintf($txt['liked_a_post'], $is_owner ? $txt['you_liker'] : $memberContext[$memID]['name'], $memberContext[$like['id_user']]['link'], $like['post']['href'], $like['topic']['link'], $modSettings['ratings'][$like['rtype']]['text']) : sprintf($txt['liked_a_post'], $is_owner ? $txt['you_liker'] : $memberContext[$memID]['name'], $memberContext[$like['id_user']]['link'], $like['post']['href'], $like['topic']['link'], $modSettings['ratings'][$like['rtype']]['text']) : ($is_owner ? sprintf($txt['liked_your_post'], $like['id_user'] == $user_info['id'] ? $txt['you_liker'] : $like['member']['link'], $like['post']['href'], $like['topic']['link'], $modSettings['ratings'][$like['rtype']]['text']) : sprintf($txt['liked_a_post'], $like['id_user'] == $user_info['id'] ? $txt['you_liker'] : $like['member']['link'], $memberContext[$memID]['name'], $like['post']['href'], $like['topic']['link'], $modSettings['ratings'][$like['rtype']]['text']));
    }
    mysql_free_result($request);
    EoS_Smarty::getConfigInstance()->registerHookTemplate('profile_content_area', 'ratings/profile_display');
}
Beispiel #30
0
function setupMenuContext()
{
    global $context, $modSettings, $user_info, $txt, $scripturl;
    // Set up the menu privileges.
    $context['allow_search'] = !empty($modSettings['allow_guestAccess']) ? allowedTo('search_posts') : !$user_info['is_guest'] && allowedTo('search_posts');
    $context['allow_admin'] = allowedTo(array('admin_forum', 'manage_boards', 'manage_permissions', 'moderate_forum', 'manage_membergroups', 'manage_bans', 'send_mail', 'edit_news', 'manage_attachments', 'manage_smileys'));
    $context['allow_edit_profile'] = !$user_info['is_guest'] && allowedTo(array('profile_view_own', 'profile_view_any', 'profile_identity_own', 'profile_identity_any', 'profile_extra_own', 'profile_extra_any', 'profile_remove_own', 'profile_remove_any', 'moderate_forum', 'manage_membergroups', 'profile_title_own', 'profile_title_any'));
    $context['allow_memberlist'] = allowedTo('view_mlist');
    $context['allow_calendar'] = allowedTo('calendar_view') && !empty($modSettings['cal_enabled']);
    $context['allow_moderation_center'] = $context['user']['can_mod'];
    $context['allow_pm'] = allowedTo('pm_read');
    $cacheTime = $modSettings['lastActive'] * 60;
    // All the buttons we can possible want and then some, try pulling the final list of buttons from cache first.
    if (($menu_buttons = CacheAPI::getCache('menu_buttons-' . implode('_', $user_info['groups']) . '-' . $user_info['language'], $cacheTime)) === null || time() - $cacheTime <= $modSettings['settings_updated'] || URL::haveSID()) {
        $buttons = array('home' => array('title' => $txt['home'], 'href' => URL::home(), 'show' => true, 'is_last' => $context['right_to_left']), 'help' => array('title' => $txt['help'], 'href' => URL::parse('?action=help'), 'show' => true, 'sub_buttons' => array()), 'search' => array('title' => $txt['search'], 'href' => URL::parse('?action=search'), 'show' => $context['allow_search'], 'sub_buttons' => array()), 'admin' => array('title' => $txt['admin'], 'href' => $scripturl . '?action=admin', 'show' => $context['allow_admin'], 'sub_buttons' => array('featuresettings' => array('title' => $txt['modSettings_title'], 'href' => $scripturl . '?action=admin;area=featuresettings', 'show' => allowedTo('admin_forum')), 'packages' => array('title' => $txt['package'], 'href' => $scripturl . '?action=admin;area=packages', 'show' => allowedTo('admin_forum')), 'errorlog' => array('title' => $txt['errlog'], 'href' => $scripturl . '?action=admin;area=logs;sa=errorlog;desc', 'show' => allowedTo('admin_forum') && !empty($modSettings['enableErrorLogging'])), 'permissions' => array('title' => $txt['edit_permissions'], 'href' => $scripturl . '?action=admin;area=permissions', 'show' => allowedTo('manage_permissions'), 'is_last' => true))), 'moderate' => array('title' => $txt['moderate'], 'href' => $scripturl . '?action=moderate', 'show' => $context['allow_moderation_center'], 'sub_buttons' => array('modlog' => array('title' => $txt['modlog_view'], 'href' => $scripturl . '?action=moderate;area=modlog', 'show' => !empty($modSettings['modlog_enabled']) && !empty($user_info['mod_cache']) && $user_info['mod_cache']['bq'] != '0=1'), 'poststopics' => array('title' => $txt['mc_unapproved_poststopics'], 'href' => $scripturl . '?action=moderate;area=postmod;sa=posts', 'show' => $modSettings['postmod_active'] && !empty($user_info['mod_cache']['ap'])), 'attachments' => array('title' => $txt['mc_unapproved_attachments'], 'href' => $scripturl . '?action=moderate;area=attachmod;sa=attachments', 'show' => $modSettings['postmod_active'] && !empty($user_info['mod_cache']['ap'])), 'reports' => array('title' => $txt['mc_reported_posts'], 'href' => $scripturl . '?action=moderate;area=reports', 'show' => !empty($user_info['mod_cache']) && $user_info['mod_cache']['bq'] != '0=1', 'is_last' => true))), 'tags' => array('title' => $txt['smftags_menu'], 'href' => URL::parse('?action=tags'), 'show' => !empty($modSettings['tags_active']), 'sub_buttons' => array()), 'calendar' => array('title' => $txt['calendar'], 'href' => URL::parse('?action=calendar'), 'show' => $context['allow_calendar'], 'sub_buttons' => array('view' => array('title' => $txt['calendar_menu'], 'href' => URL::parse('?action=calendar'), 'show' => allowedTo('calendar_post')), 'post' => array('title' => $txt['calendar_post_event'], 'href' => URL::parse('?action=calendar;sa=post'), 'show' => allowedTo('calendar_post'), 'is_last' => true))), 'mlist' => array('title' => $txt['members_title'], 'href' => URL::parse('?action=mlist'), 'show' => $context['allow_memberlist'], 'sub_buttons' => array('mlist_view' => array('title' => $txt['mlist_menu_view'], 'href' => URL::parse('?action=mlist'), 'show' => true), 'mlist_search' => array('title' => $txt['mlist_search'], 'href' => URL::parse('?action=mlist;sa=search'), 'show' => true, 'is_last' => true))), 'login' => array('title' => $txt['login'], 'href' => $scripturl . '?action=login', 'show' => $user_info['is_guest'], 'sub_buttons' => array()), 'register' => array('title' => $txt['register'], 'href' => $scripturl . '?action=register', 'show' => $user_info['is_guest'] && !(!empty($modSettings['registration_method']) && $modSettings['registration_method'] == 3) ? true : false, 'sub_buttons' => array(), 'is_last' => !$context['right_to_left']));
        // Now we put the buttons in the context so the theme can use them.
        $menu_buttons = array();
        foreach ($buttons as $act => $button) {
            if (!empty($button['show'])) {
                $button['active_button'] = false;
                // Make sure the last button truely is the last button.
                if (!empty($button['is_last'])) {
                    if (isset($last_button)) {
                        unset($menu_buttons[$last_button]['is_last']);
                    }
                    $last_button = $act;
                }
                // Go through the sub buttons if there are any.
                if (!empty($button['sub_buttons'])) {
                    foreach ($button['sub_buttons'] as $key => $subbutton) {
                        if (empty($subbutton['show'])) {
                            unset($button['sub_buttons'][$key]);
                        }
                        // 2nd level sub buttons next...
                        if (!empty($subbutton['sub_buttons'])) {
                            foreach ($subbutton['sub_buttons'] as $key2 => $sub_button2) {
                                if (empty($sub_button2['show'])) {
                                    unset($button['sub_buttons'][$key]['sub_buttons'][$key2]);
                                }
                            }
                        }
                    }
                }
                $menu_buttons[$act] = $button;
            }
        }
        if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2 && !URL::haveSID()) {
            CacheAPI::putCache('menu_buttons-' . implode('_', $user_info['groups']) . '-' . $user_info['language'], $menu_buttons, $cacheTime);
        }
    }
    if (isset($context['current_board'])) {
        $astream_link = '<a onclick="getAStream($(this));return(false);" rel="nofollow" data-board="' . $context['current_board'] . '" href="' . $scripturl . '?action=astream;sa=get;all"><span>View recent activity</span></a>';
    } else {
        $astream_link = '<a onclick="getAStream($(this));return(false);" rel="nofollow" data-board="all" href="' . $scripturl . '?action=astream;sa=get;all"><span>View recent activity</span></a>';
    }
    if (($context['usermenu_buttons'] = CacheAPI::getCache('usermenu_buttons-' . implode('_', $user_info['groups']) . '-' . $user_info['language'], $cacheTime)) === null || time() - $cacheTime <= $modSettings['settings_updated'] || URL::haveSID()) {
        if (!$user_info['is_guest']) {
            $context['usermenu_buttons']['profile'] = array('title' => $txt['your_profile'], 'href' => URL::parse('?action=profile'), 'sub_buttons' => array('forumprofile' => array('href' => URL::parse('?action=profile;area=forumprofile'), 'title' => $txt['forumprofile']), 'account' => array('href' => URL::parse('?action=profile;area=account'), 'title' => $txt['account'])));
            $context['usermenu_buttons']['inbox'] = array('title' => $txt['inbox'], 'href' => URL::parse('?action=pm'), 'sub_buttons' => array('pm_send' => array('href' => URL::parse('?action=pm;sa=send'), 'title' => $txt['pm_menu_send'])));
        }
        $context['usermenu_buttons']['whatsnew'] = array('title' => $txt['whatsnew_menu'], 'href' => URL::parse('?action=whatsnew'));
        if ($modSettings['astream_active']) {
            $context['usermenu_buttons']['whatsnew']['sub_buttons']['getastream'] = array('title' => $txt['view_recent_activity'], 'link' => $astream_link);
        }
        if (!$user_info['is_guest']) {
            $context['usermenu_buttons']['whatsnew']['sub_buttons']['unread'] = array('title' => $txt['unread_since_visit'], 'href' => URL::parse('?action=unread'));
            $context['usermenu_buttons']['whatsnew']['sub_buttons']['unread_replies'] = array('title' => $txt['show_unread_replies'], 'href' => URL::parse('?action=unreadreplies'));
            $context['usermenu_buttons']['whatsnew']['sub_buttons']['subscriptions'] = array('title' => $txt['show_my_subscriptions'], 'href' => URL::parse('?action=profile;area=notification'));
            if ($modSettings['astream_active']) {
                $context['usermenu_buttons']['notifications'] = array('title' => 'Your notifications', 'link' => '<a class="firstlevel compact" rel="nofollow" onclick="getNotifications($(this));return(false);" href="' . URL::parse($scripturl . '?action=astream;sa=notifications;view=all') . '">Your notifications</a>');
            }
        }
        if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2 && !URL::haveSID()) {
            CacheAPI::putCache('usermenu_buttons-' . implode('_', $user_info['groups']) . '-' . $user_info['language'], $context['usermenu_buttons'], $cacheTime);
        }
    }
    $context['menu_buttons'] = $menu_buttons;
    if ($modSettings['astream_active']) {
        $context['usermenu_buttons']['whatsnew']['sub_buttons']['getastream'] = array('title' => $txt['view_recent_activity'], 'link' => $astream_link);
    }
    // Allow editing menu buttons easily.
    HookAPI::callHook('menu_buttons', array(&$context['menu_buttons'], &$context['usermenu_buttons']));
    // Logging out requires the session id in the url.
    if (isset($context['menu_buttons']['logout'])) {
        $context['menu_buttons']['logout']['href'] = sprintf($context['menu_buttons']['logout']['href'], $context['session_var'], $context['session_id']);
    }
    // Figure out which action we are doing so we can set the active menu button in either the main or the user menu
    // Default to home.
    $current_action = 'home';
    if (isset($context['menu_buttons'][$context['current_action']]) || isset($context['usermenu_buttons'][$context['current_action']])) {
        $current_action = $context['current_action'];
    } elseif ($context['current_action'] == 'search2') {
        $current_action = 'search';
    } elseif ($context['current_action'] == 'theme') {
        $current_action = isset($_REQUEST['sa']) && $_REQUEST['sa'] == 'pick' ? 'profile' : 'admin';
    } elseif ($context['current_action'] == 'register2') {
        $current_action = 'register';
    } elseif ($context['current_action'] == 'login2' || $user_info['is_guest'] && $context['current_action'] == 'reminder') {
        $current_action = 'login';
    } elseif ($context['current_action'] == 'groups' && $context['allow_moderation_center']) {
        $current_action = 'moderate';
    } elseif (stristr($context['current_action'], 'unread')) {
        $current_action = 'whatsnew';
    } elseif ($context['current_action'] == 'pm') {
        $current_action = 'inbox';
    }
    if (isset($context['usermenu_buttons'][$current_action])) {
        $context['usermenu_buttons'][$current_action]['active_button'] = true;
    } else {
        $context['menu_buttons'][$current_action]['active_button'] = true;
    }
    if (!$user_info['is_guest'] && $context['user']['unread_messages'] > 0 && isset($context['menu_buttons']['pm'])) {
        $context['menu_buttons']['pm']['alttitle'] = $context['menu_buttons']['pm']['title'] . ' [' . $context['user']['unread_messages'] . ']';
        $context['menu_buttons']['pm']['title'] .= ' [<strong>' . $context['user']['unread_messages'] . '</strong>]';
    }
}