Exemplo n.º 1
0
 protected function view($nome_pagina, $vars = null)
 {
     if (is_array($vars) && count($vars) > 0) {
         extract($vars);
     }
     //instancia a classe
     $tp = new TemplateParser(LAYOUT . $this->_layout . ".phtml");
     //verifica qual a pasta que estará a view
     $act = explode("-", current(explode("/", isset($_GET['url']) ? $_GET['url'] : $this->_Index . "/index_action")));
     foreach ($act as $key => $value) {
         $act[$key] = ucfirst($value);
     }
     //verifica qual a pasta que estará a view
     $pasta = implode("", $act);
     ob_start();
     include VIEWS . "{$pasta}/{$nome_pagina}.phtml";
     //O conteúdo deste buffer interno é copiado na variável $contento
     $conteudo = ob_get_contents();
     ob_end_clean();
     //define os parâmetros da classe
     $tags = array('conteudo' => $conteudo);
     //faz a substituição
     $tp->parseTemplate($tags);
     // exibe a page
     echo $tp->display();
 }
Exemplo n.º 2
0
 /**
  * initialize various variables and generate the template
  * @return QuickTemplate
  */
 protected function prepareQuickTemplate()
 {
     $appleTouchIcon = $this->getConfig()->get('AppleTouchIcon');
     $out = $this->getOutput();
     // add head items
     if ($appleTouchIcon !== false) {
         $out->addHeadItem('touchicon', Html::element('link', array('rel' => 'apple-touch-icon', 'href' => $appleTouchIcon)));
     }
     $out->addHeadItem('viewport', Html::element('meta', array('name' => 'viewport', 'content' => 'initial-scale=1.0, user-scalable=yes, minimum-scale=0.25, ' . 'maximum-scale=5.0, width=device-width')));
     // Generate skin template
     $tpl = parent::prepareQuickTemplate();
     // Set whether or not the page content should be wrapped in div.content (for
     // example, on a special page)
     $tpl->set('unstyledContent', $out->getProperty('unstyledContent'));
     // Set the links for the main menu
     $tpl->set('menu_data', $this->getMenuData());
     // Set the links for page secondary actions
     $tpl->set('secondary_actions', $this->getSecondaryActions($tpl));
     // Construct various Minerva-specific interface elements
     $this->preparePageContent($tpl);
     $this->prepareHeaderAndFooter($tpl);
     $this->prepareMenuButton($tpl);
     $this->prepareBanners($tpl);
     $this->prepareWarnings($tpl);
     $this->preparePageActions($tpl);
     $this->prepareUserButton($tpl);
     $this->prepareLanguages($tpl);
     if ($this->isMenuEnabled) {
         $templateParser = new TemplateParser(__DIR__ . '/../../resources/skins.minerva.scripts/');
         $tpl->set('menuhtml', $templateParser->processTemplate('menu', $tpl->data['menu_data']));
     } else {
         $tpl->set('menuhtml', '');
     }
     return $tpl;
 }
 /**
  * Show the special page
  *
  * @param $par Mixed: parameter passed to the page or null
  */
 public function execute($par)
 {
     global $wgUploadPath, $wgUser, $wgHuijiPrefix;
     $templateParser = new TemplateParser(__DIR__ . '/pages');
     $out = $this->getOutput();
     $user = $this->getUser();
     if (!$user->isAllowed('AdminDashboard')) {
         $out->permissionRequired('AdminDashboard');
         return;
     }
     // Set the page title, robot policies, etc.
     $this->setHeaders();
     // Add CSS
     $out->addModules('ext.socialprofile.userprofile.css');
     $out->addModules('ext.socialprofile.admindashboard.css');
     // Add js and message
     // $out->addModules( 'skin.bootstrapmediawiki.huiji.getRecordsInterface.js' );
     $out->addModules('ext.socialprofile.admindashboard.js');
     $out->addModules('ext.socialprofile.userprofile.js');
     $output = '';
     // Prevent E_NOTICE
     $yesterday = date("Y-m-d", strtotime("-1 day"));
     $totaledit = SiteStats::edits();
     $ueb = new UserEditBox();
     $rankInfo = AllSitesInfo::getAllSitesRankData($wgHuijiPrefix, $yesterday);
     $usf = new UserSiteFollow();
     $follows = $usf->getSiteFollowers('', $wgHuijiPrefix);
     // print_r($follows);
     $followCount = count($follows);
     if ($followCount >= 8) {
         $follows = array_slice($follows, 0, 8);
         $display = '';
     } else {
         $display = 'none';
     }
     $newFollow = array();
     foreach ($follows as $value) {
         $arr['user_name'] = $value['user_name'];
         $userPage = Title::makeTitle(NS_USER, $value['user_name']);
         $arr['user_url'] = htmlspecialchars($userPage->getFullURL());
         $arr['follow_date'] = wfMessage('comments-time-ago', HuijiFunctions::getTimeAgo(strtotime($value['follow_date'])))->text();
         $newFollow[] = $arr;
     }
     $sentToAll = SpecialPage::getTitleFor('SendToFollowers')->getFullURL();
     $showMore = SpecialPage::getTitleFor('EditRank')->getFullURL();
     $rightsManage = SpecialPage::getTitleFor('用户权限')->getFullURL();
     $blockUsers = SpecialPage::getTitleFor('封禁')->getFullURL();
     $freezeUsers = SpecialPage::getTitleFor('解除封禁')->getFullURL();
     $replaceText = SpecialPage::getTitleFor('替换文本')->getFullURL();
     $siteRankPage = SpecialPage::getTitleFor('SiteRank')->getFullURL();
     $allSpecial = SpecialPage::getTitleFor('特殊页面')->getFullURL();
     $siteAvatar = (new wSiteAvatar($wgHuijiPrefix, 'l'))->getAvatarHtml();
     $token = $user->getEditToken();
     if (is_null($newFollow)) {
         $newFollow = false;
     }
     $output .= $templateParser->processTemplate('admin_index', array('siteRank' => isset($rankInfo[0]['site_rank']) ? $rankInfo[0]['site_rank'] : '暂无', 'siteScore' => isset($rankInfo[0]['site_score']) ? $rankInfo[0]['site_score'] : '暂无', 'yesterdayCount' => UserSiteFollow::getFollowerCountOneday($wgHuijiPrefix, $yesterday), 'totalCount' => UserSiteFollow::getFollowerCount($wgHuijiPrefix), 'yesterdayEdit' => $ueb->getSiteEditCount('', $wgHuijiPrefix, $yesterday, $yesterday), 'totalEdit' => $totaledit, 'totalView' => $ueb->getSiteViewCount(-1, $wgHuijiPrefix, '', ''), 'yesterdayView' => $ueb->getSiteViewCount(-1, $wgHuijiPrefix, $yesterday, $yesterday), 'newFollow' => $newFollow, 'sendToAll' => $sentToAll, 'showMore' => $showMore, 'display' => $display, 'rightsManage' => $rightsManage, 'blockUsers' => $blockUsers, 'freezeUsers' => $freezeUsers, 'replaceText' => $replaceText, 'siteRankPage' => $siteRankPage, 'allSpecial' => $allSpecial, 'siteAvatar' => $siteAvatar, 'token' => $token));
     $out->addHtml($output);
 }
 /**
  * @dataProvider provideProcessTemplate
  * @covers TemplateParser::processTemplate
  * @covers TemplateParser::getTemplate
  * @covers TemplateParser::getTemplateFilename
  */
 public function testProcessTemplate($name, $args, $result, $exception = false)
 {
     if ($exception) {
         $this->setExpectedException($exception);
     }
     $tp = new TemplateParser($this->templateDir);
     $this->assertEquals($result, $tp->processTemplate($name, $args));
 }
Exemplo n.º 5
0
 /**
  * Get a common dropdown for all ranking pages
  */
 public static function getRankingDropdown($activeList)
 {
     global $wgUser;
     $templateParser = new TemplateParser(__DIR__);
     $followed = UserSiteFollow::getTopFollowedSitesWithDetails($wgUser->getId(), $wgUser->getId());
     $output = $templateParser->processTemplate('dropdown', array('activeList' => $activeList, 'followed' => $followed, 'hasFollowed' => count($followed) > 0));
     return $output;
 }
Exemplo n.º 6
0
 /**
  * @param string $template e.g. "@YourBundle/Some/someTemplate.twig"
  * @return array [name=> "template name", source => "template source"]
  */
 public function find($template)
 {
     $sources = $this->parser->parse($template);
     $result = [];
     foreach ($sources as $name => $source) {
         $result[] = ['name' => $name, 'source' => $source];
     }
     return $result;
 }
Exemplo n.º 7
0
 public function getHtml()
 {
     $parser = new TemplateParser();
     $parser->setContextProperty('text', $this->text);
     $time = $this->getTime();
     if ($time) {
         $parser->setContextProperty('time', $time->format('H:i:s'));
     }
     return $parser->parseTemplate($this::TEMPLATE_FILENAME);
 }
 /**
  * @inheritdoc
  * Renders a search link and branding.
  */
 protected function makeChromeHeaderContent($data)
 {
     $templateParser = new TemplateParser(__DIR__ . '/../../templates');
     $args = array('siteName' => SkinMinerva::getSitename(), 'showSearchForm' => $this->isSpecialMobileMenuPage, 'showTitle' => !$this->isSpecialMobileMenuPage);
     if ($this->isSpecialMobileMenuPage) {
         $args += array('mobileMenuClass' => 'js-only back ' . MobileUI::iconClass('back'), 'mobileMenuLink' => '#back', 'mobileMenuTitle' => wfMessage('mobile-frontend-main-menu-back')->parse(), 'searchForm' => $this->makeSearchForm($data));
     } else {
         $args += array('mobileMenuClass' => MobileUI::iconClass('search'), 'mobileMenuLink' => SpecialPage::getTitleFor('MobileMenu')->getLocalUrl(), 'mobileMenuTitle' => wfMessage('mobile-frontend-main-menu')->parse(), 'searchInputClass' => 'hidden');
     }
     echo $templateParser->processTemplate('header', $args);
 }
 /**
  * Generate user page content for non-existent user pages
  *
  * @param OutputPage $output
  * @param User $pageUser owner of the user page
  * @return string
  */
 public static function getUserPageContent($output, $pageUser)
 {
     $context = MobileContext::singleton();
     $pageUsername = $pageUser->getName();
     // Is the current user viewing their own page?
     $isCurrentUser = $output->getUser()->getName() === $pageUsername;
     $data['ctaHeading'] = $isCurrentUser ? $context->msg('mobile-frontend-user-page-no-owner-page-yet')->text() : $context->msg('mobile-frontend-user-page-no-page-yet', $pageUsername)->parse();
     $data['ctaDescription'] = $isCurrentUser ? $context->msg('mobile-frontend-user-page-describe-yourself', $context->msg('mobile-frontend-user-page-describe-yourself-editors')->text())->text() : $context->msg('mobile-frontend-user-page-desired-action', $pageUsername)->parse();
     $data['createPageLinkLabel'] = $isCurrentUser ? $context->msg('mobile-frontend-user-page-create-owner-page-link-label')->text() : $context->msg('mobile-frontend-user-page-create-user-page-link-label', $pageUser->getUserPage()->getBaseTitle())->parse();
     $data['createPageLinkAdditionalClasses'] = $isCurrentUser ? 'mw-ui-button' : '';
     $templateParser = new TemplateParser(__DIR__);
     return $templateParser->processTemplate('user_page_cta', $data);
 }
Exemplo n.º 10
0
 static function parseTemplate($template)
 {
     $tp = new TemplateParser();
     $tp->parser = xml_parser_create();
     $tp->setFile($template);
     if (!file_exists($tp->filename)) {
         return self::$FILE_NOT_EXISTS;
     }
     if (xml_parse_into_struct($tp->parser, file_get_contents($tp->filename), $tp->template)) {
         //echo serialize($tp->template); //DEBUG
         return $tp;
     }
     return self::$PARSE_ERROR;
 }
Exemplo n.º 11
0
 public function display()
 {
     //将变量放入到该方法中,进而可以在数组中进行展现..
     //其他没有通过exportVariables () 函数导入的变量将不会显示在模板中.
     $this->sendHeader();
     $mode = strtolower($this->mode);
     if ($mode == 'html') {
         //加载模板页面..
         extract($this->variables);
         $template = $this->findTemplate();
         if (file_exists($template)) {
             //这里需要进行模板的解析操作..
             $file_path = TemplateParser::parse($template, $this->request->module, $this->request->action);
             require $file_path;
             //这里还有很多要做的事情..
         } else {
             throw new VException("Sorry, file:" . $template . " doesn't exists!!", 400);
         }
     } else {
         if ($mode == 'json') {
             $this->echoJson();
         } else {
             if ($mode == 'xml') {
                 //这里缺少一个将PHP数组转化xml的类型转化器.
                 header("Content-type: text/xml");
                 echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
                 echo "<users><user><name>小小菜鸟</name><age>24</age><sex>男</sex></user>";
                 echo "<user><name>艳艳</name><age>23</age><sex>女</sex></user></users>";
             } else {
                 throw new VException("不支持的数据输出格式!", 1);
             }
         }
     }
 }
Exemplo n.º 12
0
 /**
  *
  * @returns TemplateParser
  * @return TemplateParser
  */
 public static function getInstance()
 {
     if (!isset(self::$instance))
     {
         self::$instance = new TemplateParser();
     }
     return self::$instance;
 }
Exemplo n.º 13
0
 function parse_template()
 {
     $data = TemplateParser::parse($this->data, $this->template_file);
     # post-parse JSON
     if (strtolower($this->template_type) == 'json') {
         $data = $this->clean_json($data);
     }
     return $data;
 }
Exemplo n.º 14
0
 function parse_template($string, &$bean_arr)
 {
     global $beanFiles, $beanList;
     foreach ($bean_arr as $bean_name => $bean_id) {
         require_once $beanFiles[$beanList[$bean_name]];
         $focus = new $beanList[$bean_name]();
         $focus->retrieve($bean_id);
         $string = TemplateParser::parse_template_bean($string, $bean_name, $focus);
     }
     return $string;
 }
Exemplo n.º 15
0
 function parse_template()
 {
     $data = TemplateParser::parse($this->data, file_get_contents($this->template_file));
     # post-parse JSON
     if (strtolower($this->template_type) == 'json') {
         # minfy it
         $data = json_minify($data);
         # strip any trailing commas
         # (run it twice to get partial matches)
         $data = preg_replace('/([}\\]"]),([}\\]])/', '$1$2', $data);
         $data = preg_replace('/([}\\]"]),([}\\]])/', '$1$2', $data);
     }
     return $data;
 }
Exemplo n.º 16
0
 /**
  * Show the special page
  *
  * @param $par Mixed: parameter passed to the page or null
  */
 public function execute($par)
 {
     global $wgUploadPath, $wgUser, $wgHuijiPrefix;
     $templateParser = new TemplateParser(__DIR__ . '/pages');
     $out = $this->getOutput();
     $user = $this->getUser();
     // Set the page title, robot policies, etc.
     $this->setHeaders();
     // Add Less
     $out->addModuleStyles('ext.socialprofile.admindashboard.less');
     // Add CSS
     $out->addModuleStyles('ext.socialprofile.admindashboard.css');
     // Add js and messages
     $out->addModules('ext.socialprofile.admindashboard.js');
     $output = '';
     // Prevent E_NOTICE
     $yesterday = date("Y-m-d", strtotime("-1 day"));
     $dbr = wfGetDB(DB_SLAVE);
     $counter = new SiteStatsInit($dbr);
     $totaledit = $counter->edits();
     $ueb = new UserEditBox();
     $output .= $templateParser->processTemplate('admin_index', array('yesterdayCount' => UserSiteFollow::getSiteCountOnedayDB($wgHuijiPrefix, $yesterday), 'totalCount' => UserSiteFollow::getSiteCount($wgHuijiPrefix), 'yesterdayEdit' => $ueb->getSiteEditCountOneday($wgHuijiPrefix, $yesterday), 'totalEdit' => $totaledit, 'totalView' => $ueb->getSiteViewCountTotal($wgHuijiPrefix), 'yesterdayView' => $ueb->getSiteViewCountOneday($wgHuijiPrefix, $yesterday)));
     $out->addHtml($output);
 }
Exemplo n.º 17
0
 static function get_partial_template($name)
 {
     # return contents of partial file, or return 'not found' error (as text)
     if (!self::$partials) {
         self::$partials = Helpers::rglob('./templates/partials*/*.*');
     }
     foreach (self::$partials as $partial) {
         if (preg_match('/([^\\/]+?)\\.[\\w]+?$/', $partial, $file_name)) {
             if ($file_name[1] == $name) {
                 return file_get_contents($partial);
             }
         }
     }
     return 'Partial \'' . $name . '\' not found';
 }
Exemplo n.º 18
0
 public function generateField($field)
 {
     $field = $this->makeVarsFromArray($field);
     switch ($field['type'])
     {
         case 'varchar':
         case 'int':
         case 'float':
             return TemplateParser::getInstance()->parseTemplate($field, 'textInput.html', PATH . 'lib/Bootstrap/');
             break;
         case 'submit':
             return TemplateParser::getInstance()->parseTemplate($field, 'submit.html', PATH . 'lib/Bootstrap/');
             break;
         default:
             return false;
     }
 }
 public function postPrint()
 {
     Session::reflash();
     $result = NULL;
     $tpl_id = Input::get('template', 0);
     $count = Input::get('count', 1);
     $type = Input::get('type');
     $voucher_ids = Session::get('vouchers', ['0']);
     $parser = new TemplateParser();
     $template = VoucherTemplate::find($tpl_id);
     switch ($type) {
         case 'prepaid_voucher':
             $vouchers = Voucher::variables($voucher_ids);
             break;
         case 'refill_coupon':
             $vouchers = refillcoupons::variables($voucher_ids);
             break;
         default:
             throw new Exception("Could not determine form type. Could not proceed.");
             break;
     }
     $i = 1;
     foreach ($vouchers as $voucher) {
         $parser->initData((array) $voucher);
         $result .= $parser->parseTemplateData($template->body);
         if ($i % $count == 0) {
             $result .= "<br />";
         } else {
             $result .= "&nbsp;";
         }
         $i++;
     }
     if ($i > 1) {
         $result .= "<br />" . Form::button('Print This Page', ['onclick' => 'window.print()', 'class' => 'btn btn-primary col-lg-offset-1']);
     } else {
         $result = "Please select atleast one voucher";
     }
     return View::make('admin.vouchers.print')->with('vouchers', $result);
 }
Exemplo n.º 20
0
 public function parseTemplateContent($content, $template = "")
 {
     return $this->parser->compileString($content, $template, Director::isDev() && Config::inst()->get('SSViewer', 'source_file_comments'));
 }
Exemplo n.º 21
0
 function parse_template()
 {
     return TemplateParser::parse($this->data, file_get_contents($this->template_file));
 }
Exemplo n.º 22
0
//Converting Text
$parts = explode('$aos_products_quotes_name', $text);
$text = $parts[0];
$parts = explode('$aos_products_quotes_product_total_price', $parts[1]);
$linePart = '$aos_products_quotes_name' . $parts[0] . '$aos_products_quotes_product_total_price';
//Converting Line Items
$obb = array();
$sep = '';
foreach ($lineItems as $id => $productId) {
    $obb['AOS_Products_Quotes'] = $id;
    $obb['AOS_Products'] = $productId;
    $text .= $sep . TemplateParser::parse_template($linePart, $obb);
    $sep = '</td></tr><tr><td>';
}
$text .= $parts[1];
$converted = TemplateParser::parse_template($text, $object_arr);
$printable = str_replace("\$", "", $converted);
require_once 'modules/Emails/Email.php';
//First Create e-mail draft
$email = new Email();
// set the id for relationships
$email->id = create_guid();
$email->new_with_id = true;
//subject
$email->name = "Quote For " . $quote->name . "";
//body
$email->description_html = $printable;
//type is draft
$email->type = "draft";
$email->status = "draft";
if (!empty($quote->billing_contact_id) && $quote->billing_contact_id != "") {
 /**
  * Add talk, contributions, and uploads links at the top of the user page.
  *
  * @inheritdoc
  * @param BaseTemplate $tpl
  */
 protected function prepareHeaderAndFooter(BaseTemplate $tpl)
 {
     parent::prepareHeaderAndFooter($tpl);
     if ($this->isUserPage) {
         $talkPage = $this->pageUser->getTalkPage();
         $data = array('talkPageTitle' => $talkPage->getPrefixedURL(), 'talkPageLink' => $talkPage->getLocalUrl(), 'talkPageLinkTitle' => $this->msg('mobile-frontend-user-page-talk')->escaped(), 'contributionsPageLink' => SpecialPage::getTitleFor('Contributions', $this->pageUser)->getLocalURL(), 'contributionsPageTitle' => $this->msg('mobile-frontend-user-page-contributions')->escaped(), 'uploadsPageLink' => SpecialPage::getTitleFor('Uploads', $this->pageUser)->getLocalURL(), 'uploadsPageTitle' => $this->msg('mobile-frontend-user-page-uploads')->escaped());
         $templateParser = new TemplateParser(__DIR__);
         $tpl->set('postheadinghtml', $templateParser->processTemplate('user_page_links', $data));
     }
 }
 /**
  * Renders the tags assigned to the page as part of the Browse experiment.
  *
  * @param array $data The data used to build the page
  * @return string The HTML representing the tags section
  */
 protected function renderBrowseTags($data)
 {
     if (!isset($data['browse_tags']) || !$data['browse_tags']) {
         return '';
     }
     $browseTags = $this->getSkin()->getMFConfig()->get('MFBrowseTags');
     $baseLink = SpecialPage::getTitleFor('TopicTag')->getLinkURL();
     // TODO: Create tag entity and view.
     $tags = array_map(function ($rawTag) use($browseTags, $baseLink) {
         return array('msg' => $rawTag, 'link' => $baseLink . '/' . str_replace(' ', '_', $rawTag));
     }, $data['browse_tags']);
     // FIXME: This should be in MinervaTemplate#getTemplateParser.
     $templateParser = new TemplateParser(__DIR__ . '/../../resources');
     return $templateParser->processTemplate('mobile.browse/tags', array('headerMsg' => wfMessage('mobile-frontend-browse-tags-header')->text(), 'tags' => $tags));
 }
Exemplo n.º 25
0
 /**
  * Return a message box.
  * @param string $html of contents of box
  * @param string $className corresponding to box
  * @return string of html representing a box.
  */
 public static function messageBox($html, $className)
 {
     $templateParser = new TemplateParser(__DIR__ . '/../resources/mobile.messageBox/');
     return $templateParser->processTemplate('MessageBox', array('className' => $className, 'msg' => $html));
 }
Exemplo n.º 26
0
function queue_email($controller_dblink, $to, $from, $subject, $email_data, $constants, $variables, $app_id, $send_date, $bcc_available = true)
{
    # Reply to
    $reply_to = $from;
    # Separating for validation
    $p = explode('@', $to, 2);
    # Bailing if not someone@someplace.com format
    if (count($p) < 2) {
        return false;
    }
    # Checking if the email is blocked
    $query = "\tSELECT\n\t\t\t\t\t\t`email`\n\t\t\t\t\tFROM\n\t\t\t\t\t\t" . NQ_BLOCKED_EMAILS_TABLE . "\n\t\t\t\t\tWHERE\n\t\t\t\t\t\t`app_id`\t=" . (int) $app_id . " AND\n\t\t\t\t\t\t`email`\t='" . mysqli_escape_string($controller_dblink, $to) . "'\n\t\t\t\t\tLIMIT 1";
    $blocked_data = mysqli_single_result_query($controller_dblink, $query);
    # This user has blocked the app from sending emails
    if (isset($blocked_data)) {
        # Adding our analytics
        $query = "\tINSERT INTO\n\t\t\t\t\t\t\t" . NQ_ANALYTICS_BLOCKED_TABLE . "\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\t`app_id`\t\t=" . (int) $app_id . ",\n\t\t\t\t\t\t\t`template_id`\t=" . (int) $email_data['id'] . ",\n\t\t\t\t\t\t\t`sender`\t\t='" . mysqli_escape_string($controller_dblink, $from) . "',\n\t\t\t\t\t\t\t`recipient`\t='" . mysqli_escape_string($controller_dblink, $to) . "',\n\t\t\t\t\t\t\t`created`\t\t=NOW()";
        mysqli_sub_query($controller_dblink, $query);
        # Blocked
        return -1;
    } else {
        # Applying our constants and variables
        $attachments_list = [];
        $body = TemplateParser::parse($email_data['body'], $constants, $variables, $app_id, $attachments_list);
        # Applying our unsubscribe
        if ($email_data['requires_unsubscribe'] == 1 && strpos($body, '%unsubscribe%') === false) {
            $body .= '	<div style="margin-top:10px;">%unsubscribe% from ' . $G_APP_DATA['name'] . '</div>';
        }
        # If we are going to track
        $mail_body = $body;
        $bcc_body = $body;
        # Adding our analytics
        $query = "\tINSERT INTO\n\t\t\t\t\t\t" . NQ_ANALYTICS_SENT_TABLE . "\n\t\t\t\t\tSET\n\t\t\t\t\t\t`app_id`\t\t=" . (int) $app_id . ",\n\t\t\t\t\t\t`template_id`\t\t=" . (int) $email_data['id'] . ",\n\t\t\t\t\t\t`sender`\t\t='" . mysqli_escape_string($controller_dblink, $from) . "',\n\t\t\t\t\t\t`recipient`\t\t='" . mysqli_escape_string($controller_dblink, $to) . "',\n\t\t\t\t\t\t`created`\t\t=NOW(),\n\t\t\t\t\t\t`requested_date`\t=NOW()";
        mysqli_sub_query($controller_dblink, $query);
        $analytics_id = mysqli_insert_id($controller_dblink);
        # If we are going to track
        $mail_body = $body;
        $bcc_body = $body;
        if ($email_data['track'] == 1) {
            # Our ids
            $hash_id = hash('sha256', $analytics_id . $to);
            # Updating the hash id
            $query = "\tUPDATE\n\t\t\t\t\t\t\t" . NQ_ANALYTICS_SENT_TABLE . "\n\t\t\t\t\t\tSET\n\t\t\t\t\t\t\t`hash_id`\t='" . $hash_id . "'\n\t\t\t\t\t\tWHERE\n\t\t\t\t\t\t\t`id`\t\t=" . (int) $analytics_id . "\n\t\t\t\t\t\tLIMIT 1";
            mysqli_sub_query($controller_dblink, $query);
            # Customizing the body
            $mail_body .= '<img style="display:none;" src="' . NQ_DOMAIN_ROOT . '/' . $app_id . '/track?ref=' . $hash_id . '" width="1" height="1" />';
        }
        # Inserting our unsubscribe link
        $keys = ['/%unsubscribe%/'];
        $values = ['<a href="' . NQ_DOMAIN_ROOT . '/' . $app_id . '/unsubscribe?ref=' . $hash_id . '&email=' . urlencode($to) . '" style="color:inherit;text-decoration:inherit;"> Unsubscribe </a>'];
        $mail_body = preg_replace($keys, $values, $mail_body);
        # Adding to the queue
        $query = "\tINSERT INTO\n\t\t\t\t\t\t" . NQ_QUEUE_TABLE . "\n\t\t\t\t\tSET\n\t\t\t\t\t\t`app_id`\t=" . (int) $app_id . ",\n\t\t\t\t\t\t`analytics_id`\t=" . (int) $analytics_id . ",\n\t\t\t\t\t\t`sender`\t='" . mysqli_escape_string($controller_dblink, $from) . "',\n\t\t\t\t\t\t`recipient`\t='" . mysqli_escape_string($controller_dblink, $to) . "',\n\t\t\t\t\t\t`subject`\t='" . mysqli_escape_string($controller_dblink, $subject) . "',\n\t\t\t\t\t\t`raw`\t\t='" . mysqli_escape_string($controller_dblink, build_raw_email($to, $from, $reply_to, $subject, $mail_body, $attachments_list, $app_id)) . "',\n\t\t\t\t\t\t`send_date`\t='" . date('Y-m-d H:i:s', $send_date) . "',\n\t\t\t\t\t\t`priority`\t=1";
        mysqli_sub_query($controller_dblink, $query);
        # Sending the bcc
        if ($bcc_available) {
            # Modifying to add our bcc header
            $bcc_body = trim('<div style="padding:10px;border-bottom:solid #E9E9E9 1px;margin-bottom:1px;line-height:2.0;">
									<div style="width:75px;color:#999;display:inline-block;text-align:right;padding-right:10px;"></div><b>BCC Email</b><br />
									<div style="width:75px;color:#999;display:inline-block;text-align:right;padding-right:10px;">sent to:</div>' . $to . '<br />
									<div style="width:75px;color:#999;display:inline-block;text-align:right;padding-right:10px;">from:</div>' . htmlentities($from) . '<br />
									<div style="width:75px;color:#999;display:inline-block;text-align:right;padding-right:10px;">date:</div>' . date('r') . '<br />
									<div style="width:75px;color:#999;display:inline-block;text-align:right;padding-right:10px;">send date:</div>' . date('r', $send_date) . '<br />
									<div style="width:75px;color:#999;display:inline-block;text-align:right;padding-right:10px;">tracking:</div>' . ($email_data['track'] == 1 ? 'Yes' : 'No') . '<br />
								</div>
								' . $bcc_body);
            # Sending bcc emails
            foreach (explode(',', $email_data['bcc']) as $bcc) {
                # Adding to the queue
                if (trim($bcc) != '') {
                    $query = "\tINSERT INTO\n\t\t\t\t\t\t\t\t\t" . NQ_QUEUE_TABLE . "\n\t\t\t\t\t\t\t\tSET\n\t\t\t\t\t\t\t\t\t`app_id`\t=" . (int) $app_id . ",\n\t\t\t\t\t\t\t\t\t`sender`\t='" . mysqli_escape_string($controller_dblink, $from) . "',\n\t\t\t\t\t\t\t\t\t`recipient`\t='" . mysqli_escape_string($controller_dblink, trim($bcc)) . "',\n\t\t\t\t\t\t\t\t\t`subject`\t='" . mysqli_escape_string($controller_dblink, $subject) . "',\n\t\t\t\t\t\t\t\t\t`raw`\t\t='" . mysqli_escape_string($controller_dblink, build_raw_email(trim($bcc), $from, $reply_to, $subject, $bcc_body, $attachments_list, $app_id)) . "',\n\t\t\t\t\t\t\t\t\t`send_date`\t=NOW(),\n\t\t\t\t\t\t\t\t\t`priority`\t=255";
                    mysqli_sub_query($controller_dblink, $query);
                }
            }
        }
        # Sent
        return 1;
    }
}
Exemplo n.º 27
0
 /**
  * Generates each row in the contributions list.
  *
  * Contributions which are marked "top" are currently on top of the history.
  * For these contributions, a [rollback] link is shown for users with roll-
  * back privileges. The rollback link restores the most recent version that
  * was not written by the target user.
  *
  * @todo This would probably look a lot nicer in a table.
  * @param object $row
  * @return string
  */
 function formatRow($row)
 {
     $ret = '';
     $classes = [];
     /*
      * There may be more than just revision rows. To make sure that we'll only be processing
      * revisions here, let's _try_ to build a revision out of our row (without displaying
      * notices though) and then trying to grab data from the built object. If we succeed,
      * we're definitely dealing with revision data and we may proceed, if not, we'll leave it
      * to extensions to subscribe to the hook to parse the row.
      */
     MediaWiki\suppressWarnings();
     try {
         $rev = new Revision($row);
         $validRevision = (bool) $rev->getId();
     } catch (Exception $e) {
         $validRevision = false;
     }
     MediaWiki\restoreWarnings();
     if ($validRevision) {
         $classes = [];
         $page = Title::newFromRow($row);
         $link = Linker::link($page, htmlspecialchars($page->getPrefixedText()), ['class' => 'mw-contributions-title'], $page->isRedirect() ? ['redirect' => 'no'] : []);
         # Mark current revisions
         $topmarktext = '';
         $user = $this->getUser();
         if ($row->rev_id === $row->page_latest) {
             $topmarktext .= '<span class="mw-uctop">' . $this->messages['uctop'] . '</span>';
             $classes[] = 'mw-contributions-current';
             # Add rollback link
             if (!$row->page_is_new && $page->quickUserCan('rollback', $user) && $page->quickUserCan('edit', $user)) {
                 $this->preventClickjacking();
                 $topmarktext .= ' ' . Linker::generateRollback($rev, $this->getContext());
             }
         }
         # Is there a visible previous revision?
         if ($rev->userCan(Revision::DELETED_TEXT, $user) && $rev->getParentId() !== 0) {
             $difftext = Linker::linkKnown($page, $this->messages['diff'], [], ['diff' => 'prev', 'oldid' => $row->rev_id]);
         } else {
             $difftext = $this->messages['diff'];
         }
         $histlink = Linker::linkKnown($page, $this->messages['hist'], [], ['action' => 'history']);
         if ($row->rev_parent_id === null) {
             // For some reason rev_parent_id isn't populated for this row.
             // Its rumoured this is true on wikipedia for some revisions (bug 34922).
             // Next best thing is to have the total number of bytes.
             $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
             $chardiff .= Linker::formatRevisionSize($row->rev_len);
             $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
         } else {
             $parentLen = 0;
             if (isset($this->mParentLens[$row->rev_parent_id])) {
                 $parentLen = $this->mParentLens[$row->rev_parent_id];
             }
             $chardiff = ' <span class="mw-changeslist-separator">. .</span> ';
             $chardiff .= ChangesList::showCharacterDifference($parentLen, $row->rev_len, $this->getContext());
             $chardiff .= ' <span class="mw-changeslist-separator">. .</span> ';
         }
         $lang = $this->getLanguage();
         $comment = $lang->getDirMark() . Linker::revComment($rev, false, true);
         $date = $lang->userTimeAndDate($row->rev_timestamp, $user);
         if ($rev->userCan(Revision::DELETED_TEXT, $user)) {
             $d = Linker::linkKnown($page, htmlspecialchars($date), ['class' => 'mw-changeslist-date'], ['oldid' => intval($row->rev_id)]);
         } else {
             $d = htmlspecialchars($date);
         }
         if ($rev->isDeleted(Revision::DELETED_TEXT)) {
             $d = '<span class="history-deleted">' . $d . '</span>';
         }
         # Show user names for /newbies as there may be different users.
         # Note that we already excluded rows with hidden user names.
         if ($this->contribs == 'newbie') {
             $userlink = ' . . ' . $lang->getDirMark() . Linker::userLink($rev->getUser(), $rev->getUserText());
             $userlink .= ' ' . $this->msg('parentheses')->rawParams(Linker::userTalkLink($rev->getUser(), $rev->getUserText()))->escaped() . ' ';
         } else {
             $userlink = '';
         }
         $flags = [];
         if ($rev->getParentId() === 0) {
             $flags[] = ChangesList::flag('newpage');
         }
         if ($rev->isMinor()) {
             $flags[] = ChangesList::flag('minor');
         }
         $del = Linker::getRevDeleteLink($user, $rev, $page);
         if ($del !== '') {
             $del .= ' ';
         }
         $diffHistLinks = $this->msg('parentheses')->rawParams($difftext . $this->messages['pipe-separator'] . $histlink)->escaped();
         # Tags, if any.
         list($tagSummary, $newClasses) = ChangeTags::formatSummaryRow($row->ts_tags, 'contributions', $this->getContext());
         $classes = array_merge($classes, $newClasses);
         Hooks::run('SpecialContributions::formatRow::flags', [$this->getContext(), $row, &$flags]);
         $templateParams = ['del' => $del, 'timestamp' => $d, 'diffHistLinks' => $diffHistLinks, 'charDifference' => $chardiff, 'flags' => $flags, 'articleLink' => $link, 'userlink' => $userlink, 'logText' => $comment, 'topmarktext' => $topmarktext, 'tagSummary' => $tagSummary];
         # Denote if username is redacted for this edit
         if ($rev->isDeleted(Revision::DELETED_USER)) {
             $templateParams['rev-deleted-user-contribs'] = $this->msg('rev-deleted-user-contribs')->escaped();
         }
         $templateParser = new TemplateParser();
         $ret = $templateParser->processTemplate('SpecialContributionsLine', $templateParams);
     }
     // Let extensions add data
     Hooks::run('ContributionsLineEnding', [$this, &$ret, $row, &$classes]);
     // TODO: Handle exceptions in the catch block above.  Do any extensions rely on
     // receiving empty rows?
     if ($classes === [] && $ret === '') {
         wfDebug("Dropping Special:Contribution row that could not be formatted\n");
         return "<!-- Could not format Special:Contribution row. -->\n";
     }
     // FIXME: The signature of the ContributionsLineEnding hook makes it
     // very awkward to move this LI wrapper into the template.
     return Html::rawElement('li', ['class' => $classes], $ret) . "\n";
 }
Exemplo n.º 28
0
 /**
  * Enhanced RC group
  * @param RCCacheEntry[] $block
  * @return string
  * @throws DomainException
  */
 protected function recentChangesBlockGroup($block)
 {
     $recentChangesFlags = $this->getConfig()->get('RecentChangesFlags');
     # Add the namespace and title of the block as part of the class
     $tableClasses = ['mw-collapsible', 'mw-collapsed', 'mw-enhanced-rc'];
     if ($block[0]->mAttribs['rc_log_type']) {
         # Log entry
         $tableClasses[] = Sanitizer::escapeClass('mw-changeslist-log-' . $block[0]->mAttribs['rc_log_type']);
     } else {
         $tableClasses[] = Sanitizer::escapeClass('mw-changeslist-ns' . $block[0]->mAttribs['rc_namespace'] . '-' . $block[0]->mAttribs['rc_title']);
     }
     if ($block[0]->watched && $block[0]->mAttribs['rc_timestamp'] >= $block[0]->watched) {
         $tableClasses[] = 'mw-changeslist-line-watched';
     } else {
         $tableClasses[] = 'mw-changeslist-line-not-watched';
     }
     # Collate list of users
     $userlinks = [];
     # Other properties
     $curId = 0;
     # Some catalyst variables...
     $namehidden = true;
     $allLogs = true;
     $RCShowChangedSize = $this->getConfig()->get('RCShowChangedSize');
     # Default values for RC flags
     $collectedRcFlags = [];
     foreach ($recentChangesFlags as $key => $value) {
         $flagGrouping = isset($recentChangesFlags[$key]['grouping']) ? $recentChangesFlags[$key]['grouping'] : 'any';
         switch ($flagGrouping) {
             case 'all':
                 $collectedRcFlags[$key] = true;
                 break;
             case 'any':
                 $collectedRcFlags[$key] = false;
                 break;
             default:
                 throw new DomainException("Unknown grouping type \"{$flagGrouping}\"");
         }
     }
     foreach ($block as $rcObj) {
         // If all log actions to this page were hidden, then don't
         // give the name of the affected page for this block!
         if (!$this->isDeleted($rcObj, LogPage::DELETED_ACTION)) {
             $namehidden = false;
         }
         $u = $rcObj->userlink;
         if (!isset($userlinks[$u])) {
             $userlinks[$u] = 0;
         }
         if ($rcObj->mAttribs['rc_type'] != RC_LOG) {
             $allLogs = false;
         }
         # Get the latest entry with a page_id and oldid
         # since logs may not have these.
         if (!$curId && $rcObj->mAttribs['rc_cur_id']) {
             $curId = $rcObj->mAttribs['rc_cur_id'];
         }
         $userlinks[$u]++;
     }
     # Sort the list and convert to text
     krsort($userlinks);
     asort($userlinks);
     $users = [];
     foreach ($userlinks as $userlink => $count) {
         $text = $userlink;
         $text .= $this->getLanguage()->getDirMark();
         if ($count > 1) {
             // @todo FIXME: Hardcoded '×'. Should be a message.
             $formattedCount = $this->getLanguage()->formatNum($count) . '×';
             $text .= ' ' . $this->msg('parentheses')->rawParams($formattedCount)->escaped();
         }
         array_push($users, $text);
     }
     # Article link
     $articleLink = '';
     $revDeletedMsg = false;
     if ($namehidden) {
         $revDeletedMsg = $this->msg('rev-deleted-event')->escaped();
     } elseif ($allLogs) {
         $articleLink = $this->maybeWatchedLink($block[0]->link, $block[0]->watched);
     } else {
         $articleLink = $this->getArticleLink($block[0], $block[0]->unpatrolled, $block[0]->watched);
     }
     $queryParams['curid'] = $curId;
     # Sub-entries
     $lines = [];
     foreach ($block as $i => $rcObj) {
         $line = $this->getLineData($block, $rcObj, $queryParams);
         if (!$line) {
             // completely ignore this RC entry if we don't want to render it
             unset($block[$i]);
             continue;
         }
         // Roll up flags
         foreach ($line['recentChangesFlagsRaw'] as $key => $value) {
             $flagGrouping = isset($recentChangesFlags[$key]['grouping']) ? $recentChangesFlags[$key]['grouping'] : 'any';
             switch ($flagGrouping) {
                 case 'all':
                     if (!$value) {
                         $collectedRcFlags[$key] = false;
                     }
                     break;
                 case 'any':
                     if ($value) {
                         $collectedRcFlags[$key] = true;
                     }
                     break;
                 default:
                     throw new DomainException("Unknown grouping type \"{$flagGrouping}\"");
             }
         }
         $lines[] = $line;
     }
     // Further down are some assumptions that $block is a 0-indexed array
     // with (count-1) as last key. Let's make sure it is.
     $block = array_values($block);
     if (empty($block) || !$lines) {
         // if we can't show anything, don't display this block altogether
         return '';
     }
     $logText = $this->getLogText($block, $queryParams, $allLogs, $collectedRcFlags['newpage'], $namehidden);
     # Character difference (does not apply if only log items)
     $charDifference = false;
     if ($RCShowChangedSize && !$allLogs) {
         $last = 0;
         $first = count($block) - 1;
         # Some events (like logs and category changes) have an "empty" size, so we need to skip those...
         while ($last < $first && $block[$last]->mAttribs['rc_new_len'] === null) {
             $last++;
         }
         while ($last < $first && $block[$first]->mAttribs['rc_old_len'] === null) {
             $first--;
         }
         # Get net change
         $charDifference = $this->formatCharacterDifference($block[$first], $block[$last]);
     }
     $numberofWatchingusers = $this->numberofWatchingusers($block[0]->numberofWatchingusers);
     $usersList = $this->msg('brackets')->rawParams(implode($this->message['semicolon-separator'], $users))->escaped();
     $templateParams = ['articleLink' => $articleLink, 'charDifference' => $charDifference, 'collectedRcFlags' => $this->recentChangesFlags($collectedRcFlags), 'languageDirMark' => $this->getLanguage()->getDirMark(), 'lines' => $lines, 'logText' => $logText, 'numberofWatchingusers' => $numberofWatchingusers, 'rev-deleted-event' => $revDeletedMsg, 'tableClasses' => $tableClasses, 'timestamp' => $block[0]->timestamp, 'users' => $usersList];
     $this->rcCacheIndex++;
     $templateParser = new TemplateParser();
     return $templateParser->processTemplate('EnhancedChangesListGroup', $templateParams);
 }
    /**
     * Render the settings form (with actual set settings) to display to user
     */
    private function getSettingsForm()
    {
        $out = $this->getOutput();
        $context = MobileContext::singleton();
        $user = $this->getUser();
        $out->setPageTitle($this->msg('mobile-frontend-main-menu-settings-heading'));
        if ($this->getRequest()->getCheck('success')) {
            $out->wrapWikiMsg("<div class=\"successbox\"><strong>\n\$1\n</strong></div><div id=\"mw-pref-clear\"></div>", 'savedprefs');
        }
        $betaEnabled = $context->isBetaGroupMember();
        $imagesChecked = $context->imagesDisabled() ? '' : 'checked';
        // images are off when disabled
        $imagesBeta = $betaEnabled ? 'checked' : '';
        $imagesDescriptionMsg = $this->msg('mobile-frontend-settings-images-explain')->parse();
        $disableMsg = $this->msg('mobile-frontend-images-status')->parse();
        $betaEnableMsg = $this->msg('mobile-frontend-settings-beta')->parse();
        $betaDescriptionMsg = $this->msg('mobile-frontend-opt-in-explain')->parse();
        $saveSettings = $this->msg('mobile-frontend-save-settings')->escaped();
        $action = $this->getPageTitle()->getLocalURL();
        $html = Html::openElement('form', array('class' => 'mw-mf-settings', 'method' => 'POST', 'action' => $action));
        $token = $user->isLoggedIn() ? Html::hidden('token', $user->getEditToken()) : '';
        $returnto = Html::hidden('returnto', $this->returnToTitle->getFullText());
        // array to save the data of options, which should be displayed here
        $options = array();
        // image settings
        $options['images'] = array('checked' => $imagesChecked, 'label' => $disableMsg, 'description' => $imagesDescriptionMsg, 'name' => 'enableImages', 'id' => 'enable-images-toggle');
        // beta settings
        if ($this->getMFConfig()->get('MFEnableBeta')) {
            $options['beta'] = array('checked' => $imagesBeta, 'label' => $betaEnableMsg, 'description' => $betaDescriptionMsg, 'name' => 'enableBeta', 'id' => 'enable-beta-toggle');
        }
        $templateParser = new TemplateParser(__DIR__ . '/../../resources/mobile.special.mobileoptions.scripts');
        // @codingStandardsIgnoreStart Long line
        foreach ($options as $key => $data) {
            if (isset($data['type']) && $data['type'] === 'hidden') {
                $html .= Html::element('input', array('type' => 'hidden', 'name' => $data['name'], 'value' => $data['checked']));
            } else {
                $html .= $templateParser->processTemplate('checkbox', $data);
            }
        }
        $className = MobileUI::buttonClass('constructive');
        $html .= <<<HTML
\t\t<input type="submit" class="{$className}" id="mw-mf-settings-save" value="{$saveSettings}">
\t\t{$token}
\t\t{$returnto}
\t</form>
HTML;
        // @codingStandardsIgnoreEnd
        $out->addHTML($html);
    }
Exemplo n.º 30
0
 /**
     Expects a filename to the simple config.
     @param string $file Path to file.
     @return object.
     **/
 function __construct($file)
 {
     $result = TemplateParser::parseSimpleTemplate($file);
     parent::__construct($file, $result[0], $result[1]);
 }