/**
     * Displays the main form for removing a gift
     * @return HTML output
     */
    function displayForm()
    {
        global $wgUser, $wgOut, $wgUploadPath;
        $rel = new UserGifts($wgUser->getName());
        $gift = $rel->getUserGift($this->gift_id);
        $user = Title::makeTitle(NS_USER, $gift['user_name_from']);
        $gift_image = '<img src="' . $wgUploadPath . '/awards/' . Gifts::getGiftImage($gift['gift_id'], 'l') . '" border="0" alt="gift" />';
        $output = $wgOut->setPageTitle(wfMsg('g-remove-title', $gift['name']));
        $output .= '<div class="back-links">
			<a href="' . $wgUser->getUserPage()->escapeFullURL() . '">' . wfMsg('g-back-link', $gift['user_name_to']) . '</a>
		</div>
		<form action="" method="post" enctype="multipart/form-data" name="form1">
			<div class="g-remove-message">' . wfMsg('g-remove-message', $gift['name']) . '</div>
			<div class="g-container">' . $gift_image . '<div class="g-name">' . $gift['name'] . '</div>
				<div class="g-from">' . wfMsg('g-from', $user->escapeFullURL(), $gift['user_name_from']) . '</div>';
        if ($gift['message']) {
            $output .= '<div class="g-user-message">' . $gift['message'] . '</div>';
        }
        $output .= '</div>
			<div class="cleared"></div>
			<div class="g-buttons">
				<input type="hidden" name="user" value="' . addslashes($gift['user_name_from']) . '">
				<input type="button" class="site-button" value="' . wfMsg('g-remove') . '" size="20" onclick="document.form1.submit()" />
				<input type="button" class="site-button" value="' . wfMsg('g-cancel') . '" size="20" onclick="history.go(-1)" />
			</div>
		</form>';
        return $output;
    }
	/**
	 * Displays the main upload form, optionally with a highlighted
	 * error message up at the top.
	 *
	 * @param string $msg as HTML
	 * @access private
	 */
	function mainUploadForm( $msg = '' ) {
		global $wgOut, $wgUser, $wgUseCopyrightUpload;

		if ( !$this->canUserManage() ) {
			throw new ErrorPageError( 'error', 'badaccess' );
		}

		$cols = intval( $wgUser->getOption( 'cols' ) );
		$ew = $wgUser->getOption( 'editwidth' );
		if ( $ew ) {
			$ew = ' style="width:100%"';
		} else {
			$ew = '';
		}

		if ( '' != $msg ) {
			$sub = wfMsg( 'uploaderror' );
			$wgOut->addHTML( "<h2>{$sub}</h2>\n" .
				"<h4 class='error'>{$msg}</h4>\n" );
		}
		$sk = $wgUser->getSkin();

		$sourcefilename = wfMsg( 'sourcefilename' );
		$destfilename = wfMsg( 'destfilename' );

		$fd = wfMsg( 'filedesc' );
		$ulb = wfMsg( 'uploadbtn' );

		$iw = wfMsg( 'ignorewarning' );

		$titleObj = SpecialPage::getTitleFor( 'Upload' );
		$action = $titleObj->escapeLocalURL();

		$encDestFile = htmlspecialchars( $this->mDestFile );
		$source = null;

		if ( $wgUseCopyrightUpload ) {
			$source = "
	<td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
	<td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
	htmlspecialchars( $this->mUploadCopyStatus ) . "\" size='40' /></td>
	</tr><tr>
	<td align='right'>" . wfMsg ( 'filesource' ) . ":</td>
	<td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
	htmlspecialchars( $this->mUploadSource ) . "\" style='width:100px' /></td>
	";
		}

		$watchChecked = $wgUser->getOption( 'watchdefault' )
			? 'checked="checked"'
			: '';

		global $wgUploadPath;
		$gift_image = Gifts::getGiftImage( $this->gift_id, 'l' );
		if ( $gift_image != '' ) {
			$output = '<table><tr><td style="color:#666666;font-weight:800">' .
				wfMsg( 'g-current-image' ) . '</td></tr>';
			$output .= '<tr><td><img src="' . $wgUploadPath .
				'/images/awards/' . $gift_image . '" border="0" alt="' .
				wfMsg( 'g-gift' ) . '" /></td></tr></table><br />';
		}
		$wgOut->addHTML( $output );

		$wgOut->addHTML( "
	<form id='upload' method='post' enctype='multipart/form-data' action=\"\">
	<table border='0'><tr>

	<td style='color:#666666;font-weight:800'>" . wfMsg( 'g-file-instructions' ) . "<p>" . wfMsg( 'g-choose-file' ) . "<br />
	<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' style='width:100px' />
	</td></tr><tr>
	{$source}
	</tr>
	<tr><td>
	<input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
	</td></tr></table></form>\n" );
	}
	function displayForm( $gift_id ) {
		global $wgUser;

		if ( !$gift_id && !$this->canUserCreateGift() ) {
			return $this->displayGiftList();
		}

		$form = '<div><b><a href="' . $this->getTitle()->escapeFullURL() .
			'">' . wfMsg( 'giftmanager-view' ) . '</a></b></div>';

		if ( $gift_id ) {
			$gift = Gifts::getGift( $gift_id );
			if (
				$wgUser->getID() != $gift['creator_user_id'] &&
				(
					!in_array( 'giftadmin', $wgUser->getGroups() ) &&
					!$wgUser->isAllowed( 'delete' )
				)
			)
			{
				throw new ErrorPageError( 'error', 'badaccess' );
			}
		}

		$form .= '<form action="" method="post" enctype="multipart/form-data" name="gift">';
		$form .= '<table border="0" cellpadding="5" cellspacing="0" width="500">';
		$form .= '<tr>
		<td width="200" class="view-form">' . wfMsg( 'g-gift-name' ) . '</td>
		<td width="695"><input type="text" size="45" class="createbox" name="gift_name" value="' .
			( isset( $gift['gift_name'] ) ? $gift['gift_name'] : '' ) . '"/></td>
		</tr>
		<tr>
		<td width="200" class="view-form" valign="top">' . wfMsg( 'giftmanager-description' ) . '</td>
		<td width="695"><textarea class="createbox" name="gift_description" rows="2" cols="30">' .
			( isset( $gift['gift_description'] ) ? $gift['gift_description'] : '' ) . '</textarea></td>
		</tr>';
		if ( $gift_id ) {
			$creator = Title::makeTitle( NS_USER, $gift['creator_user_name'] );
			$form .= '<tr>
			<td class="view-form">' .
				wfMsgExt( 'g-created-by', 'parsemag', $gift['creator_user_name'] ) .
			'</td>
			<td><a href="' . $creator->escapeFullURL() . '">' .
				$gift['creator_user_name'] . '</a></td>
			</tr>';
		}

		// If the user isn't in the gift admin group, they can only create
		// private gifts
		if ( !$wgUser->isAllowed( 'giftadmin' ) ) {
			$form .= '<input type="hidden" name="access" value="1" />';
		} else {
			$publicSelected = $privateSelected = '';
			if ( isset( $gift['access'] ) && $gift['access'] == 0 ) {
				$publicSelected = ' selected="selected"';
			}
			if ( isset( $gift['access'] ) && $gift['access'] == 1 ) {
				$privateSelected = ' selected="selected"';
			}
			$form .= '<tr>
				<td class="view-form">' . wfMsg( 'giftmanager-access' ) . '</td>
				<td>
				<select name="access">
					<option value="0"' . $publicSelected . '>' .
						wfMsg( 'giftmanager-public' ) .
					'</option>
					<option value="1"' . $privateSelected . '>' .
						wfMsg( 'giftmanager-private' ) .
					'</option>
				</select>
				</td>
			</tr>';
		}

		if ( $gift_id ) {
			global $wgUploadPath;
			$gml = SpecialPage::getTitleFor( 'GiftManagerLogo' );
			$gift_image = '<img src="' . $wgUploadPath . '/awards/' .
				Gifts::getGiftImage( $gift_id, 'l' ) . '" border="0" alt="' .
				wfMsg( 'g-gift' ) . '" />';
			$form .= '<tr>
			<td width="200" class="view-form" valign="top">' . wfMsg( 'giftmanager-giftimage' ) . '</td>
			<td width="695">' . $gift_image .
			'<p>
			<a href="' . $gml->escapeFullURL( 'gift_id=' . $gift_id ) . '">' .
				wfMsg( 'giftmanager-image' ) . '</a>
			</td>
			</tr>';
		}

		if ( isset( $gift['gift_id'] ) ) {
			$button = wfMsg( 'edit' );
		} else {
			$button = wfMsg( 'g-create-gift' );
		}

		$form .= '<tr>
			<td colspan="2">
				<input type="hidden" name="id" value="' . ( isset( $gift['gift_id'] ) ? $gift['gift_id'] : '' ) . '" />
				<input type="button" class="createbox" value="' . $button . '" size="20" onclick="document.gift.submit()" />
				<input type="button" class="createbox" value="' . wfMsg( 'cancel' ) . '" size="20" onclick="history.go(-1)" />
			</td>
		</tr>
		</table>

		</form>';
		return $form;
	}
    /**
     * Show the special page
     *
     * @param $par Mixed: parameter passed to the page or null
     */
    public function execute($par)
    {
        global $wgUploadPath;
        $out = $this->getOutput();
        $request = $this->getRequest();
        $currentUser = $this->getUser();
        // Set the page title, robot policies, etc.
        $this->setHeaders();
        // Add CSS
        $out->addModuleStyles('ext.socialprofile.usergifts.css');
        $user_name = $request->getVal('user');
        $page = $request->getInt('page', 1);
        /**
         * Redirect Non-logged in users to Login Page
         * It will automatically return them to the ViewGifts page
         */
        if ($currentUser->getID() == 0 && $user_name == '') {
            $login = SpecialPage::getTitleFor('Userlogin');
            $out->redirect(htmlspecialchars($login->getFullURL('returnto=Special:ViewGifts')));
            return false;
        }
        /**
         * If no user is set in the URL, we assume it's the current user
         */
        if (!$user_name) {
            $user_name = $currentUser->getName();
        }
        $user_id = User::idFromName($user_name);
        $user = Title::makeTitle(NS_USER, $user_name);
        /**
         * Error message for username that does not exist (from URL)
         */
        if ($user_id == 0) {
            $out->setPageTitle($this->msg('g-error-title')->plain());
            $out->addHTML($this->msg('g-error-message-no-user')->plain());
            return false;
        }
        /**
         * Config for the page
         */
        $per_page = 10;
        $per_row = 2;
        /**
         * Get all gifts for this user into the array
         */
        $rel = new UserGifts($user_name);
        $gifts = $rel->getUserGiftList(0, $per_page, $page);
        $total = $rel->getGiftCountByUsername($user_name);
        /**
         * Show gift count for user
         */
        $out->setPageTitle($this->msg('g-list-title', $rel->user_name)->parse());
        $output = '<div class="back-links">
			<a href="' . $user->getFullURL() . '">' . $this->msg('g-back-link', $rel->user_name)->parse() . '</a>
		</div>
		<div class="g-count">' . $this->msg('g-count', $rel->user_name, $total)->parse() . '</div>';
        if ($gifts) {
            $x = 1;
            // Safe links
            $viewGiftLink = SpecialPage::getTitleFor('ViewGift');
            $giveGiftLink = SpecialPage::getTitleFor('GiveGift');
            $removeGiftLink = SpecialPage::getTitleFor('RemoveGift');
            foreach ($gifts as $gift) {
                $giftname_length = strlen($gift['gift_name']);
                $giftname_space = stripos($gift['gift_name'], ' ');
                if (($giftname_space == false || $giftname_space >= "30") && $giftname_length > 30) {
                    $gift_name_display = substr($gift['gift_name'], 0, 30) . ' ' . substr($gift['gift_name'], 30, 50);
                } else {
                    $gift_name_display = $gift['gift_name'];
                }
                $user_from = Title::makeTitle(NS_USER, $gift['user_name_from']);
                $gift_image = "<img src=\"{$wgUploadPath}/awards/" . Gifts::getGiftImage($gift['gift_id'], 'l') . '" border="0" alt="" />';
                $output .= '<div class="g-item">
					<a href="' . htmlspecialchars($viewGiftLink->getFullURL('gift_id=' . $gift['id'])) . '">' . $gift_image . '</a>
					<div class="g-title">
						<a href="' . htmlspecialchars($viewGiftLink->getFullURL('gift_id=' . $gift['id'])) . '">' . $gift_name_display . '</a>';
                if ($gift['status'] == 1) {
                    if ($user_name == $currentUser->getName()) {
                        $rel->clearUserGiftStatus($gift['id']);
                        $rel->decNewGiftCount($currentUser->getID());
                    }
                    $output .= '<span class="g-new">' . $this->msg('g-new')->plain() . '</span>';
                }
                $output .= '</div>';
                $output .= '<div class="g-from">' . $this->msg('g-from', htmlspecialchars($user_from->getFullURL()), $gift['user_name_from'])->text() . '</div>
					<div class="g-actions">
						<a href="' . htmlspecialchars($giveGiftLink->getFullURL('gift_id=' . $gift['gift_id'])) . '">' . $this->msg('g-to-another')->plain() . '</a>';
                if ($rel->user_name == $currentUser->getName()) {
                    $output .= '&#160;';
                    $output .= $this->msg('pipe-separator')->escaped();
                    $output .= '&#160;';
                    $output .= '<a href="' . htmlspecialchars($removeGiftLink->getFullURL('gift_id=' . $gift['id'])) . '">' . $this->msg('g-remove-gift')->plain() . '</a>';
                }
                $output .= '</div>
					<div class="cleared"></div>';
                $output .= '</div>';
                if ($x == count($gifts) || $x != 1 && $x % $per_row == 0) {
                    $output .= '<div class="cleared"></div>';
                }
                $x++;
            }
        }
        /**
         * Build next/prev nav
         */
        $numofpages = $total / $per_page;
        $pageLink = $this->getPageTitle();
        if ($numofpages > 1) {
            $output .= '<div class="page-nav">';
            if ($page > 1) {
                $output .= Linker::link($pageLink, $this->msg('g-previous')->plain(), array(), array('user' => $user_name, 'page' => $page - 1)) . $this->msg('word-separator')->plain();
            }
            if ($total % $per_page != 0) {
                $numofpages++;
            }
            if ($numofpages >= 9 && $page < $total) {
                $numofpages = 9 + $page;
            }
            if ($numofpages >= $total / $per_page) {
                $numofpages = $total / $per_page + 1;
            }
            for ($i = 1; $i <= $numofpages; $i++) {
                if ($i == $page) {
                    $output .= $i . ' ';
                } else {
                    $output .= Linker::link($pageLink, $i, array(), array('user' => $user_name, 'page' => $i)) . $this->msg('word-separator')->plain();
                }
            }
            if ($total - $per_page * $page > 0) {
                $output .= $this->msg('word-separator')->plain() . Linker::link($pageLink, $this->msg('g-next')->plain(), array(), array('user' => $user_name, 'page' => $page + 1));
            }
            $output .= '</div>';
        }
        $out->addHTML($output);
    }
    function getGifts($user_name)
    {
        global $wgUser, $wgMemc, $wgUserProfileDisplay, $wgUploadPath;
        // If not enabled in site settings, don't display
        if ($wgUserProfileDisplay['gifts'] == false) {
            return '';
        }
        $output = '';
        // User to user gifts
        $g = new UserGifts($user_name);
        $user_safe = urlencode($user_name);
        // Try cache
        $key = wfMemcKey('user', 'profile', 'gifts', "{$g->user_id}");
        $data = $wgMemc->get($key);
        if (!$data) {
            wfDebug("Got profile gifts for user {$user_name} from DB\n");
            $gifts = $g->getUserGiftList(0, 4);
            $wgMemc->set($key, $gifts, 60 * 60 * 4);
        } else {
            wfDebug("Got profile gifts for user {$user_name} from cache\n");
            $gifts = $data;
        }
        $gift_count = $g->getGiftCountByUsername($user_name);
        $gift_link = SpecialPage::getTitleFor('ViewGifts');
        $per_row = 4;
        if ($gifts) {
            $output .= '<div class="user-section-heading">
				<div class="user-section-title">' . wfMsg('user-gifts-title') . '</div>
				<div class="user-section-actions">
					<div class="action-right">';
            if ($gift_count > 4) {
                $output .= '<a href="' . $gift_link->escapeFullURL('user='******'" rel="nofollow">' . wfMsg('user-view-all') . '</a>';
            }
            $output .= '</div>
					<div class="action-left">';
            if ($gift_count > 4) {
                $output .= wfMsg('user-count-separator', '4', $gift_count);
            } else {
                $output .= wfMsg('user-count-separator', $gift_count, $gift_count);
            }
            $output .= '</div>
					<div class="cleared"></div>
				</div>
			</div>
			<div class="cleared"></div>
			<div class="user-gift-container">';
            $x = 1;
            foreach ($gifts as $gift) {
                if ($gift['status'] == 1 && $user_name == $wgUser->getName()) {
                    $g->clearUserGiftStatus($gift['id']);
                    $wgMemc->delete($key);
                    $g->decNewGiftCount($wgUser->getID());
                }
                $user = Title::makeTitle(NS_USER, $gift['user_name_from']);
                $gift_image = '<img src="' . $wgUploadPath . '/awards/' . Gifts::getGiftImage($gift['gift_id'], 'ml') . '" border="0" alt="" />';
                $gift_link = $user = SpecialPage::getTitleFor('ViewGift');
                $class = '';
                if ($gift['status'] == 1) {
                    $class = 'class="user-page-new"';
                }
                $output .= '<a href="' . $gift_link->escapeFullURL('gift_id=' . $gift['id']) . '" ' . $class . " rel=\"nofollow\">{$gift_image}</a>";
                if ($x == count($gifts) || $x != 1 && $x % $per_row == 0) {
                    $output .= '<div class="cleared"></div>';
                }
                $x++;
            }
            $output .= '</div>';
        }
        return $output;
    }
    /**
     * Show the special page
     *
     * @param $par Mixed: parameter passed to the page or null
     */
    public function execute($par)
    {
        global $wgUploadPath;
        $out = $this->getOutput();
        $user = $this->getUser();
        // Set the page title, robot policies, etc.
        $this->setHeaders();
        // Add CSS
        $out->addModuleStyles('ext.socialprofile.usergifts.css');
        $giftId = $this->getRequest()->getInt('gift_id');
        if (!$giftId || !is_numeric($giftId)) {
            $out->setPageTitle($this->msg('g-error-title')->plain());
            $out->addHTML($this->msg('g-error-message-invalid-link')->plain());
            return false;
        }
        $gift = UserGifts::getUserGift($giftId);
        if ($gift) {
            if ($gift['status'] == 1) {
                if ($gift['user_name_to'] == $user->getName()) {
                    $g = new UserGifts($gift['user_name_to']);
                    $g->clearUserGiftStatus($gift['id']);
                    $g->decNewGiftCount($user->getID());
                }
            }
            // DB stuff
            $dbr = wfGetDB(DB_SLAVE);
            $res = $dbr->select('user_gift', array('DISTINCT ug_user_name_to', 'ug_user_id_to', 'ug_date'), array('ug_gift_id' => $gift['gift_id'], 'ug_user_name_to <> ' . $dbr->addQuotes($gift['user_name_to'])), __METHOD__, array('GROUP BY' => 'ug_user_name_to', 'ORDER BY' => 'ug_date DESC', 'LIMIT' => 6));
            $out->setPageTitle($this->msg('g-description-title', $gift['user_name_to'], $gift['name'])->parse());
            $output = '<div class="back-links">
				<a href="' . htmlspecialchars(Title::makeTitle(NS_USER, $gift['user_name_to'])->getFullURL()) . '">' . $this->msg('g-back-link', $gift['user_name_to'])->parse() . '</a>
			</div>';
            $sender = Title::makeTitle(NS_USER, $gift['user_name_from']);
            $removeGiftLink = SpecialPage::getTitleFor('RemoveGift');
            $giveGiftLink = SpecialPage::getTitleFor('GiveGift');
            $giftImage = '<img src="' . $wgUploadPath . '/awards/' . Gifts::getGiftImage($gift['gift_id'], 'l') . '" border="0" alt="" />';
            $message = $out->parse(trim($gift['message']), false);
            $output .= '<div class="g-description-container">';
            $output .= '<div class="g-description">' . $giftImage . '<div class="g-name">' . $gift['name'] . '</div>
					<div class="g-timestamp">(' . $gift['timestamp'] . ')</div>
					<div class="g-from">' . $this->msg('g-from', htmlspecialchars($sender->getFullURL()), $gift['user_name_from'])->text() . '</div>';
            if ($message) {
                $output .= '<div class="g-user-message">' . $message . '</div>';
            }
            $output .= '<div class="cleared"></div>
					<div class="g-describe">' . $gift['description'] . '</div>
					<div class="g-actions">
						<a href="' . htmlspecialchars($giveGiftLink->getFullURL('gift_id=' . $gift['gift_id'])) . '">' . $this->msg('g-to-another')->plain() . '</a>';
            if ($gift['user_name_to'] == $user->getName()) {
                $output .= $this->msg('pipe-separator')->escaped();
                $output .= '<a href="' . htmlspecialchars($removeGiftLink->getFullURL('gift_id=' . $gift['id'])) . '">' . $this->msg('g-remove-gift')->plain() . '</a>';
            }
            $output .= '</div>
				</div>';
            $output .= '<div class="g-recent">
					<div class="g-recent-title">' . $this->msg('g-recent-recipients')->plain() . '</div>
					<div class="g-gift-count">' . $this->msg('g-given', $gift['gift_count'])->parse() . '</div>';
            foreach ($res as $row) {
                $userToId = $row->ug_user_id_to;
                $avatar = new wAvatar($userToId, 'ml');
                $userNameLink = Title::makeTitle(NS_USER, $row->ug_user_name_to);
                $output .= '<a href="' . htmlspecialchars($userNameLink->getFullURL()) . "\">\n\t\t\t\t\t{$avatar->getAvatarURL()}\n\t\t\t\t</a>";
            }
            $output .= '<div class="cleared"></div>
				</div>
			</div>';
            $out->addHTML($output);
        } else {
            $out->setPageTitle($this->msg('g-error-title')->plain());
            $out->addHTML($this->msg('g-error-message-invalid-link')->plain());
        }
    }
    function displayFormAll()
    {
        global $wgUser, $wgOut, $wgRequest, $wgGiveGiftPerRow, $wgUploadPath;
        $user = Title::makeTitle(NS_USER, $this->user_name_to);
        $page = $wgRequest->getInt('page');
        if (!$page || !is_numeric($page)) {
            $page = 1;
        }
        $per_page = 24;
        $per_row = $wgGiveGiftPerRow;
        if (!$per_row) {
            $per_row = 3;
        }
        $total = Gifts::getGiftCount();
        $gifts = Gifts::getGiftList($per_page, $page, 'gift_name');
        $output = '';
        if ($gifts) {
            $wgOut->setPageTitle(wfMsg('g-give-all-title', $this->user_name_to));
            $output .= '<div class="back-links">
				<a href="' . $user->escapeFullURL() . '">' . wfMsg('g-back-link', $this->user_name_to) . '</a>
			</div>
			<div class="g-message">' . wfMsg('g-give-all', $this->user_name_to) . '</div>
			<form action="" method="post" enctype="multipart/form-data" name="gift">';
            $x = 1;
            foreach ($gifts as $gift) {
                $gift_image = "<img id=\"gift_image_{$gift['id']}\" src=\"{$wgUploadPath}/awards/" . Gifts::getGiftImage($gift['id'], 'l') . '" border="0" alt="" />';
                $output .= "<div onclick=\"selectGift({$gift['id']})\" onmouseover=\"highlightGift({$gift['id']})\" onmouseout=\"unHighlightGift({$gift['id']})\" id=\"give_gift_{$gift['id']}\" class=\"g-give-all\">\r\n\t\t\t\t\t{$gift_image}\r\n\t\t\t\t\t<div class=\"g-title g-blue\">{$gift['gift_name']}</div>";
                if ($gift['gift_description']) {
                    $output .= "<div class=\"g-describe\">{$gift['gift_description']}</div>";
                }
                $output .= '<div class="cleared"></div>
				</div>';
                if ($x == count($gifts) || $x != 1 && $x % $per_row == 0) {
                    $output .= '<div class="cleared"></div>';
                }
                $x++;
            }
            /**
             * Build next/prev nav
             */
            $giveGiftLink = SpecialPage::getTitleFor('GiveGift');
            $numofpages = $total / $per_page;
            $user_safe = urlencode($user->getText());
            if ($numofpages > 1) {
                $output .= '<div class="page-nav">';
                if ($page > 1) {
                    $output .= '<a href="' . $giveGiftLink->escapeFullURL('user='******'&page=' . ($page - 1)) . '">' . wfMsg('g-previous') . '</a> ';
                }
                if ($total % $per_page != 0) {
                    $numofpages++;
                }
                if ($numofpages >= 9) {
                    $numofpages = 9 + $page;
                }
                for ($i = 1; $i <= $numofpages; $i++) {
                    if ($i == $page) {
                        $output .= $i . ' ';
                    } else {
                        $output .= '<a href="' . $giveGiftLink->escapeFullURL('user='******'&page=' . $i) . "\">{$i}</a> ";
                    }
                }
                if ($total - $per_page * $page > 0) {
                    $output .= ' <a href="' . $giveGiftLink->escapeFullURL('user='******'&page=' . ($page + 1)) . '">' . wfMsg('g-next') . '</a>';
                }
                $output .= '</div>';
            }
            /**
             * Build next/prev nav
             */
            $output .= '<div class="g-give-all-message-title">' . wfMsg('g-give-all-message-title') . '</div>
				<textarea name="message" id="message" rows="4" cols="50"></textarea>
				<div class="g-buttons">
					<input type="hidden" name="gift_id" value="0" />
					<input type="hidden" name="user_name" value="' . addslashes($this->user_name_to) . '" />
					<input type="button" class="site-button" value="' . wfMsg('g-send-gift') . '" size="20" onclick="sendGift()" />
					<input type="button" class="site-button" value="' . wfMsg('g-cancel') . '" size="20" onclick="history.go(-1)" />
				</div>
			</form>';
        } else {
            $wgOut->setPageTitle(wfMsg('g-error-title'));
            $wgOut->addHTML(wfMsg('g-error-message-invalid-link'));
        }
        return $output;
    }
	/**
	 * Show the special page
	 *
	 * @param $par Mixed: parameter passed to the page or null
	 */
	public function execute( $par ) {
		global $wgUser, $wgOut, $wgRequest, $wgUploadPath, $wgUserGiftsScripts;

		$wgOut->addExtensionStyle( $wgUserGiftsScripts . '/UserGifts.css' );

		$giftId = $wgRequest->getInt( 'gift_id' );
		if ( !$giftId || !is_numeric( $giftId ) ) {
			$wgOut->setPageTitle( wfMsg( 'g-error-title' ) );
			$wgOut->addHTML( wfMsg( 'g-error-message-invalid-link' ) );
			return false;
		}

		$gift = UserGifts::getUserGift( $giftId );

		if ( $gift ) {
			if ( $gift['status'] == 1 ) {
				if ( $gift['user_name_to'] == $wgUser->getName() ) {
					$g = new UserGifts( $gift['user_name_to'] );
					$g->clearUserGiftStatus( $gift['id'] );
					$g->decNewGiftCount( $wgUser->getID() );
				}
			}

			// DB stuff
			$dbr = wfGetDB( DB_SLAVE );
			$res = $dbr->select(
				'user_gift',
				array( 'DISTINCT ug_user_name_to', 'ug_user_id_to', 'ug_date' ),
				array(
					'ug_gift_id' => $gift['gift_id'],
					"ug_user_name_to <> '" . addslashes( $gift['user_name_to'] ) . "'"
				),
				__METHOD__,
				array(
					'GROUP BY' => 'ug_user_name_to',
					'ORDER BY' => 'ug_date DESC',
					'LIMIT' => 6
				)
			);

			$wgOut->setPageTitle( wfMsgExt(
				'g-description-title',
				'parsemag',
				$gift['user_name_to'],
				$gift['name']
			) );

			$output = '<div class="back-links">
				<a href="' . Title::makeTitle( NS_USER, $gift['user_name_to'] )->escapeFullURL() . '">'
				. wfMsg( 'g-back-link', $gift['user_name_to'] ) . '</a>
			</div>';

			$user = Title::makeTitle( NS_USER, $gift['user_name_from'] );
			$removeGiftLink = SpecialPage::getTitleFor( 'RemoveGift' );
			$giveGiftLink = SpecialPage::getTitleFor( 'GiveGift' );

			$giftImage = '<img src="' . $wgUploadPath . '/awards/' .
				Gifts::getGiftImage( $gift['gift_id'], 'l' ) .
				'" border="0" alt="" />';

			$message = $wgOut->parse( trim( $gift['message'] ), false );

			$output .= '<div class="g-description-container">';
			$output .= '<div class="g-description">' .
					$giftImage .
					'<div class="g-name">' . $gift['name'] . '</div>
					<div class="g-timestamp">(' . $gift['timestamp'] . ')</div>
					<div class="g-from">' . wfMsg(
						'g-from',
						$user->escapeFullURL(),
						$gift['user_name_from']
					) . '</div>';
			if ( $message ) {
				$output .= '<div class="g-user-message">' . $message . '</div>';
			}
			$output .= '<div class="cleared"></div>
					<div class="g-describe">' . $gift['description'] . '</div>
					<div class="g-actions">
						<a href="' . $giveGiftLink->escapeFullURL( 'gift_id=' . $gift['gift_id'] ) . '">' .
							wfMsg( 'g-to-another' ) . '</a>';
			if ( $gift['user_name_to'] == $wgUser->getName() ) {
				$output .= wfMsgExt( 'pipe-separator', 'escapenoentities' );
				$output .= '<a href="' . $removeGiftLink->escapeFullURL( 'gift_id=' . $gift['id'] ) . '">' .
					wfMsg( 'g-remove-gift' ) . '</a>';
			}
			$output .= '</div>
				</div>';

			$output .= '<div class="g-recent">
					<div class="g-recent-title">' .
						wfMsg( 'g-recent-recipients' ) .
					'</div>
					<div class="g-gift-count">' .
						wfMsgExt( 'g-given', 'parsemag', $gift['gift_count'] ) .
					'</div>';

			foreach ( $res as $row ) {
				$userToId = $row->ug_user_id_to;
				$avatar = new wAvatar( $userToId, 'ml' );
				$userNameLink = Title::makeTitle( NS_USER, $row->ug_user_name_to );

				$output .= '<a href="' . $userNameLink->escapeFullURL() . "\">
					{$avatar->getAvatarURL()}
				</a>";
			}
			$output .= '<div class="cleared"></div>
				</div>
			</div>';

			$wgOut->addHTML( $output );
		} else {
			$wgOut->setPageTitle( wfMsg( 'g-error-title' ) );
			$wgOut->addHTML( wfMsg( 'g-error-message-invalid-link' ) );
		}
	}
 /**
  * Get recently received user-to-user gifts from the user_gift and gift
  * tables and set them in the appropriate class member variables.
  */
 private function setGiftsRec()
 {
     global $wgLang;
     $dbr = wfGetDB(DB_SLAVE);
     $where = $this->where('ug_user_id_to');
     $option = $this->option('ug_id');
     $res = $dbr->select(array('user_gift', 'gift'), array('ug_id', 'ug_user_id_from', 'ug_user_name_from', 'ug_user_id_to', 'ug_user_name_to', 'UNIX_TIMESTAMP(ug_date) AS item_date', 'gift_name', 'gift_id'), $where, __METHOD__, $option, array('gift' => array('INNER JOIN', 'gift_id = ug_gift_id')));
     foreach ($res as $row) {
         global $wgUploadPath, $wgMemc;
         $key = wfForeignMemcKey('huiji', '', 'setGiftsRec', $row->ug_id);
         $html = $wgMemc->get($key);
         $timeago = HuijiFunctions::getTimeAgo($row->item_date) . '前';
         if ($html != '') {
             $html = $this->updateTime($html, $timeago);
         } else {
             $user_title = Title::makeTitle(NS_USER, $row->ug_user_name_to);
             $user_title_from = Title::makeTitle(NS_USER, $row->ug_user_name_from);
             $gift_image = '<img src="' . $wgUploadPath . '/awards/' . Gifts::getGiftImage($row->gift_id, 'm') . '" border="0" alt="" />';
             $view_gift_link = SpecialPage::getTitleFor('ViewGift');
             $avatar = new wAvatar($row->ug_user_id_to, 'ml');
             $avatarUrl = $avatar->getAvatarURL();
             $user_name_short = $wgLang->truncate($row->ug_user_name_to, 25);
             // $timeago = HuijiFunctions::getTimeAgo($row->item_date);
             /* build html */
             $html = $this->templateParser->processTemplate('user-home-item', array('userAvatar' => $avatarUrl, 'userName' => '<b><a href="' . htmlspecialchars($user_title->getFullURL()) . "\">{$user_name_short}</a></b>", 'timestamp' => $timeago, 'description' => wfMessage('useractivity-gift', '<b><a href="' . htmlspecialchars($user_title->getFullURL()) . "\">{$row->ug_user_name_to}</a></b>", '<a href="' . htmlspecialchars($user_title_from->getFullURL()) . "\">{$user_title_from->getText()}</a>")->text(), 'hasShowcase' => true, 'showcase' => "<a href=\"" . htmlspecialchars($view_gift_link->getFullURL('gift_id=' . $row->ug_id)) . "\" rel=\"nofollow\">\n\t\t\t\t\t\t\t\t\t\t\t{$gift_image}\n\t\t\t\t\t\t\t\t\t\t\t{$row->gift_name}\n\t\t\t\t\t\t\t\t\t\t</a>\n\t\t\t\t\t\t\t\t\t"));
             $wgMemc->set($key, $html);
         }
         $this->activityLines[] = array('type' => 'gift-rec', 'timestamp' => $row->item_date, 'data' => $html);
         // $this->activityLines[] = array(
         // 	'type' => 'gift-rec',
         // 	'timestamp' => $row->item_date,
         // 	'data' => ' ' . $html
         // );
         $this->items[] = array('id' => $row->ug_id, 'type' => 'gift-rec', 'timestamp' => $row->item_date, 'pagetitle' => $row->gift_name, 'namespace' => $row->gift_id, 'username' => $row->ug_user_name_to, 'userid' => $row->ug_user_id_to, 'comment' => $row->ug_user_name_from, 'new' => '0', 'minor' => 0);
     }
 }
    function displayFormAll()
    {
        global $wgGiveGiftPerRow, $wgUploadPath;
        $out = $this->getOutput();
        $user = Title::makeTitle(NS_USER, $this->user_name_to);
        $page = $this->getRequest()->getInt('page');
        if (!$page || !is_numeric($page)) {
            $page = 1;
        }
        $per_page = 24;
        $per_row = $wgGiveGiftPerRow;
        if (!$per_row) {
            $per_row = 3;
        }
        $total = Gifts::getGiftCount();
        $gifts = Gifts::getGiftList($per_page, $page, 'gift_name');
        $output = '';
        if ($gifts) {
            $out->setPageTitle($this->msg('g-give-all-title', $this->user_name_to)->parse());
            $output .= '<div class="back-links">
				<a href="' . htmlspecialchars($user->getFullURL()) . '">' . $this->msg('g-back-link', $this->user_name_to)->parse() . '</a>
			</div>
			<div class="g-message">' . $this->msg('g-give-all', $this->user_name_to)->parse() . '</div>
			<form action="" method="post" enctype="multipart/form-data" name="gift">';
            $x = 1;
            foreach ($gifts as $gift) {
                $gift_image = "<img id=\"gift_image_{$gift['id']}\" src=\"{$wgUploadPath}/awards/" . Gifts::getGiftImage($gift['id'], 'l') . '" border="0" alt="" />';
                $output .= "<div id=\"give_gift_{$gift['id']}\" class=\"g-give-all\">\n\t\t\t\t\t{$gift_image}\n\t\t\t\t\t<div class=\"g-title g-blue\">{$gift['gift_name']}</div>";
                if ($gift['gift_description']) {
                    $output .= "<div class=\"g-describe\">{$gift['gift_description']}</div>";
                }
                $output .= '<div class="cleared"></div>
				</div>';
                if ($x == count($gifts) || $x != 1 && $x % $per_row == 0) {
                    $output .= '<div class="cleared"></div>';
                }
                $x++;
            }
            /**
             * Build next/prev nav
             */
            $giveGiftLink = $this->getPageTitle();
            $numofpages = $total / $per_page;
            $user_name = $user->getText();
            if ($numofpages > 1) {
                $output .= '<div class="page-nav">';
                if ($page > 1) {
                    $output .= Linker::link($giveGiftLink, $this->msg('g-previous')->plain(), array(), array('user' => $user_name, 'page' => $page - 1)) . $this->msg('word-separator')->plain();
                }
                if ($total % $per_page != 0) {
                    $numofpages++;
                }
                if ($numofpages >= 9) {
                    $numofpages = 9 + $page;
                }
                for ($i = 1; $i <= $numofpages; $i++) {
                    if ($i == $page) {
                        $output .= $i . ' ';
                    } else {
                        $output .= Linker::link($giveGiftLink, $i, array(), array('user' => $user_name, 'page' => $i)) . $this->msg('word-separator')->plain();
                    }
                }
                if ($total - $per_page * $page > 0) {
                    $output .= $this->msg('word-separator')->plain() . Linker::link($giveGiftLink, $this->msg('g-next')->plain(), array(), array('user' => $user_name, 'page' => $page + 1));
                }
                $output .= '</div>';
            }
            /**
             * Build the send/cancel buttons and whatnot
             */
            $output .= '<div class="g-give-all-message-title">' . $this->msg('g-give-all-message-title')->plain() . '</div>
				<textarea name="message" id="message" rows="4" cols="50"></textarea>
				<div class="g-buttons">
					<input type="hidden" name="gift_id" value="0" />
					<input type="hidden" name="user_name" value="' . addslashes($this->user_name_to) . '" />
					<input type="button" id="send-gift-button" class="site-button" value="' . $this->msg('g-send-gift')->plain() . '" size="20" />
					<input type="button" class="site-button" value="' . $this->msg('g-cancel')->plain() . '" size="20" onclick="history.go(-1)" />
				</div>
			</form>';
        } else {
            $out->setPageTitle($this->msg('g-error-title')->plain());
            $out->addHTML($this->msg('g-error-message-invalid-link')->plain());
        }
        return $output;
    }
	/**
	 * Displays the main form for removing a gift permanently
	 *
	 * @return String: HTML output
	 */
	function displayForm() {
		global $wgOut, $wgUploadPath;

		$gift = Gifts::getGift( $this->gift_id );

		$gift_image = '<img src="' . $wgUploadPath . '/awards/' .
			Gifts::getGiftImage( $this->gift_id, 'l' ) .
			'" border="0" alt="gift" />';

		$wgOut->setPageTitle( wfMsg( 'g-remove-title', $gift['gift_name'] ) );

		$output = '<div class="back-links">
			<a href="' . SpecialPage::getTitleFor( 'GiftManager' )->escapeFullURL() . '">' .
				wfMsg( 'g-viewgiftlist' ) . '</a>
		</div>
		<form action="" method="post" enctype="multipart/form-data" name="form1">
			<div class="g-remove-message">' .
				wfMsg( 'g-delete-message', $gift['gift_name'] ) .
			'</div>
			<div class="g-container">' .
				$gift_image .
				'<div class="g-name">' . $gift['gift_name'] . '</div>
			</div>
			<div class="cleared"></div>
			<div class="g-buttons">
				<input type="button" class="site-button" value="' . wfMsg( 'g-remove' ) . '" size="20" onclick="document.form1.submit()" />
				<input type="button" class="site-button" value="' . wfMsg( 'g-cancel' ) . '" size="20" onclick="history.go(-1)" />
			</div>
		</form>';

		return $output;
	}
	/**
	 * Get recently received user-to-user gifts from the user_gift and gift
	 * tables and set them in the appropriate class member variables.
	 */
	private function setGiftsRec() {
		$dbr = wfGetDB( DB_SLAVE );

		$where = array();

		if ( !empty( $this->rel_type ) ) {
			$users = $dbr->select(
				'user_relationship',
				'r_user_id_relation',
				array(
					'r_user_id' => $this->user_id,
					'r_type' => $this->rel_type
				),
				__METHOD__
			);
			$userArray = array();
			foreach ( $users as $user ) {
				$userArray[] = $user;
			}
			$userIDs = implode( ',', $userArray );
			if ( !empty( $userIDs ) ) {
				$where[] = "ug_user_id_to IN ($userIDs)";
			}
		}

		if ( !empty( $this->show_current_user ) ) {
			$where['ug_user_id_to'] = $this->user_id;
		}

		$res = $dbr->select(
			array( 'user_gift', 'gift' ),
			array(
				'ug_id', 'ug_user_id_from', 'ug_user_name_from',
				'ug_user_id_to', 'ug_user_name_to',
				'UNIX_TIMESTAMP(ug_date) AS item_date', 'gift_name', 'gift_id'
			),
			$where,
			__METHOD__,
			array(
				'ORDER BY' => 'ug_id DESC',
				'LIMIT' => $this->item_max,
				'OFFSET' => 0
			),
			array( 'gift' => array( 'INNER JOIN', 'gift_id = ug_gift_id' ) )
		);

		foreach ( $res as $row ) {
			global $wgUploadPath;
			$user_title = Title::makeTitle( NS_USER, $row->ug_user_name_to );
			$user_title_from = Title::makeTitle( NS_USER, $row->ug_user_name_from );

			$gift_image = '<img src="' . $wgUploadPath . '/awards/' .
				Gifts::getGiftImage( $row->gift_id, 'm' ) .
				'" border="0" alt="" />';
			$view_gift_link = SpecialPage::getTitleFor( 'ViewGift' );

			$html = wfMsg( 'useractivity-gift',
				"<b><a href=\"{$user_title->escapeFullURL()}\">{$row->ug_user_name_to}</a></b>",
				"<a href=\"{$user_title_from->escapeFullURL()}\">{$user_title_from->getText()}</a>"
			) .
			"<div class=\"item\">
				<a href=\"" . $view_gift_link->escapeFullURL( 'gift_id=' . $row->ug_id ) . "\" rel=\"nofollow\">
					{$gift_image}
					{$row->gift_name}
				</a>
			</div>";

			$this->activityLines[] = array(
				'type' => 'gift-rec',
				'timestamp' => $row->item_date,
				'data' => ' ' . $html
			);

			$this->items[] = array(
				'id' => $row->ug_id,
				'type' => 'gift-rec',
				'timestamp' => $row->item_date,
				'pagetitle' => $row->gift_name,
				'namespace' => $row->gift_id,
				'username' => $row->ug_user_name_to,
				'userid' => $row->ug_user_id_to,
				'comment' => $row->ug_user_name_from,
				'new' => '0',
				'minor' => 0
			);
		}
	}
 /**
  * Displays the main upload form, optionally with a highlighted
  * error message up at the top.
  *
  * @param string $msg as HTML
  * @access private
  */
 function mainUploadForm($msg = '')
 {
     global $wgUseCopyrightUpload;
     if (!$this->canUserManage()) {
         throw new ErrorPageError('error', 'badaccess');
     }
     $out = $this->getOutput();
     if ($msg != '') {
         $sub = $this->msg('uploaderror')->plain();
         $out->addHTML("<h2>{$sub}</h2>\n" . "<h4 class='error'>{$msg}</h4>\n");
     }
     $ulb = $this->msg('uploadbtn')->plain();
     $source = null;
     if ($wgUseCopyrightUpload) {
         $source = "\n\t<td align='right' nowrap='nowrap'>" . $this->msg('filestatus')->plain() . "</td>\n\t<td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" . htmlspecialchars($this->mUploadCopyStatus) . "\" size='40' /></td>\n\t</tr><tr>\n\t<td align='right'>" . $this->msg('filesource')->plain() . "</td>\n\t<td><input tabindex='4' type='text' name='wpUploadSource' value=\"" . htmlspecialchars($this->mUploadSource) . "\" style='width:100px' /></td>\n\t";
     }
     global $wgUploadPath;
     $gift_image = Gifts::getGiftImage($this->gift_id, 'l');
     if ($gift_image != '') {
         $output = '<table><tr><td style="color:#666666;font-weight:800">' . $this->msg('g-current-image')->plain() . '</td></tr>';
         $output .= '<tr><td><img src="' . $wgUploadPath . '/awards/' . $gift_image . '" border="0" alt="' . $this->msg('g-gift')->plain() . '" /></td></tr></table><br />';
     }
     $out->addHTML($output);
     $out->addHTML("\n\t<form id='upload' method='post' enctype='multipart/form-data' action=\"\">\n\t<table border='0'><tr>\n\n\t<td style='color:#666666;font-weight:800'>" . $this->msg('g-file-instructions')->escaped() . '<p>' . $this->msg('g-choose-file')->plain() . "<br />\n\t<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' style='width:100px' />\n\t</td></tr><tr>\n\t{$source}\n\t</tr>\n\t<tr><td>\n\t<input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />\n\t</td></tr></table></form>\n");
 }