Example #1
0
function process($title)
{
    global $wgOut, $wgTitle;
    $rev = Revision::newFromTitle($title);
    if (!$rev) {
        continue;
    }
    #echo "Checkng {$title->getText()}\n";
    $text = $rev->getText();
    $oldtext = $text;
    wfRunHooks('ArticleBeforeOutputWikiText', array(&$article, &$text));
    $html = $wgOut->parse($text);
    $wgTitle = $title;
    $html = WikihowArticleHTML::postProcess($html, array('no-ads' => 0));
    $editor = new Html5editor();
    $newtext = $editor->convertHTML2Wikitext($html, $oldtext);
    echo "{$title->getFullURL()} - {$title->getArticleID()}\n";
}
Example #2
0
 private function addMethod($articleId, $altMethod, $altSteps)
 {
     global $wgParser, $wgUser;
     $title = Title::newFromID($articleId);
     $result = array();
     if ($title) {
         $dbw = wfGetDB(DB_MASTER);
         $dbw->insert('altmethodadder', array('ama_page' => $articleId, 'ama_method' => $altMethod, 'ama_steps' => $altSteps, 'ama_user' => $wgUser->getID(), 'ama_timestamp' => wfTimestampNow()));
         $result['success'] = true;
         //Parse the wikiText that they gave us.
         //Need to add in a steps header so that mungeSteps
         //actually knows that it's a steps section
         $newMethod = $wgParser->parse("== Steps ==\n=== " . $altMethod . " ===\n" . $altSteps, $title, new ParserOptions())->getText();
         $result['html'] = WikihowArticleHTML::postProcess($newMethod, array('no-ads' => true));
     } else {
         $result['success'] = false;
     }
     return $result;
 }
 protected function getNonMobileHtml($title, $rev)
 {
     global $wgOut, $wgParser;
     $pOpts = $wgOut->parserOptions();
     $pOpts->setTidy(true);
     $pOut = $wgParser->parse($rev->getText(), $title, $pOpts, true, true, $rev->getId());
     $html = $pOut->mText;
     $pOpts->setTidy(false);
     // munge steps first
     $opts = array('no-ads' => true);
     $this->html = WikihowArticleHTML::postProcess($html, $opts);
 }
 public static function getXPath(&$bodyHtml, &$r)
 {
     global $wgWikiHowSections, $IP, $wgTitle;
     $lang = MobileWikihow::getSiteLanguage();
     // munge steps first
     $opts = array('no-ads' => true);
     require_once "{$IP}/skins/WikiHowSkin.php";
     $oldTitle = $wgTitle;
     $wgTitle = $r->getTitle();
     $vars['bodyHtml'] = WikihowArticleHTML::postProcess($bodyHtml, $opts);
     $vars['lang'] = $lang;
     EasyTemplate::set_path(dirname(__FILE__) . '/');
     $html = EasyTemplate::html('thumb_html.tmpl.php', $vars);
     require_once "{$IP}/extensions/wikihow/mobile/JSLikeHTMLElement.php";
     $doc = new DOMDocument('1.0', 'utf-8');
     $doc->registerNodeClass('DOMElement', 'JSLikeHTMLElement');
     $doc->strictErrorChecking = false;
     $doc->recover = true;
     @$doc->loadHTML($html);
     $doc->normalizeDocument();
     $xpath = new DOMXPath($doc);
     $wgTitle = $oldTitle;
     return $xpath;
 }
Example #5
0
 function execute($par)
 {
     global $wgOut, $wgRequest, $wgUser, $wgParser;
     if (!in_array('importxml', $wgUser->getRights())) {
         $wgOut->showErrorPage('nosuchspecialpage', 'nospecialpagetext');
         return;
     }
     // used through ajax
     if ($wgRequest->getVal('delete')) {
         $wgOut->disable();
         $dbw = wfGetDB(DB_MASTER);
         $dbw->delete('import_articles', array('ia_id' => $wgRequest->getVal('delete')));
         return;
     }
     if ($wgRequest->getVal('publishedcsv')) {
         $wgOut->disable();
         header("Content-type: text/plain;");
         $dbr = wfGetDB(DB_MASTER);
         if ($wgRequest->getVal('errs')) {
             $opts = array('ia_publish_err' => 1);
         } else {
             $opts = array('ia_published' => 1);
         }
         $res = $dbr->select('import_articles', array('ia_title', 'ia_published_timestamp'), $opts, "ImportXML::execute", array("ORDER BY" => "ia_published_timestamp"));
         while ($row = $dbr->fetchObject($res)) {
             $t = Title::newFromDBKey($row->ia_title);
             $ts = date("Y-m-d", wfTimestamp(TS_UNIX, $row->ia_published_timestamp));
             echo "{$t->getFullURL()}\t{$t->getText()}\t{$ts}\n";
         }
         return;
     }
     // used through ajax
     if ($wgRequest->getVal('view')) {
         $wgOut->disable();
         $dbr = wfGetDB(DB_MASTER);
         $text = $dbr->selectField('import_articles', array('ia_text'), array('ia_id' => $wgRequest->getVal('view')));
         echo "<textarea class='xml_edit' id='xml_input'>{$text}</textarea><br/>" . '<a onclick="save_xml(' . $wgRequest->getVal('view') . ');" class="button button136" style="float: left;" onmouseover="button_swap(this);" onmouseout="button_unswap(this);">Save</a>';
         return;
     }
     // used through ajax
     if ($wgRequest->getVal('update')) {
         $wgOut->disable();
         $dbw = wfGetDB(DB_MASTER);
         $dbw->update('import_articles', array('ia_text' => $wgRequest->getVal('text')), array('ia_id' => $wgRequest->getVal('update')));
         return;
     }
     if ($wgRequest->getVal('preview')) {
         $dbr = wfGetDB(DB_SLAVE);
         $text = $dbr->selectField('import_articles', array('ia_text'), array('ia_id' => $wgRequest->getVal('preview')));
         $title = $dbr->selectField('import_articles', array('ia_title'), array('ia_id' => $wgRequest->getVal('preview')));
         $t = Title::newFromText($title);
         # try this parse, this is for debugging only
         $popts = $wgOut->parserOptions();
         $popts->setTidy(true);
         $popts->enableLimitReport();
         $parserOutput = $wgParser->parse($text, $t, $popts);
         $popts->setTidy(false);
         $popts->enableLimitReport(false);
         $wgOut->setPageTitle(wfMsg('howto', $t->getText()));
         $html = WikihowArticleHTML::postProcess($parserOutput->getText());
         $wgOut->addHTML($html);
         return;
     }
     if ($wgRequest->wasPosted() && ($wgRequest->getVal('xml') || sizeof($_FILES) > 0)) {
         $dbw = wfGetDB(DB_MASTER);
         // input can either come from an XML file or copy+pasted input from the textarea
         // use the file if we have it.
         $input = $wgRequest->getVal('xml');
         foreach ($_FILES as $f) {
             if (trim($f['tmp_name']) == "") {
                 continue;
             }
             $input = preg_replace('@\\r@', "\n", file_get_contents($f['tmp_name']));
             break;
         }
         $articles = self::parseXML($input);
         foreach ($articles as $t => $text) {
             $title = Title::newFromText($t);
             if (!$title) {
                 $wgOut->addHTML("cant make title out of {$t}<br/>");
                 continue;
             }
             if ($dbw->selectField('import_articles', 'count(*)', array('ia_title' => $title->getDBKey())) > 0) {
                 $wgOut->addHTML("Article {$title->getText()} already exists, not adding.<br/>");
                 continue;
             }
             $dbw->insert('import_articles', array('ia_title' => $title->getDBKey(), 'ia_text' => $text, 'ia_timestamp' => wfTimestampNow()));
             $wgOut->addHTML("Article {$title->getText()} saved.<br/>");
         }
     } else {
         if ($wgRequest->wasPosted() && $wgRequest->getVal('publish_articles')) {
             self::publishArticles();
         }
     }
     $wgOut->addHTML('<style type="text/css" media="all">/*<![CDATA[*/ @import "/extensions/min/f/extensions/wikihow/import_xml.css"; /*]]>*/</style>');
     $wgOut->addScript('<script type="text/javascript" src="/extensions/min/f/extensions/wikihow/import_xml.js"></script>');
     $wgOut->addHTML("\n\t\t\t<form method='post' action='/Special:ImportXML' enctype='multipart/form-data'>\n\t\t\t<input type='hidden' name='publish_articles' value='1'/>\n\t\t\t<a href='#' id='hide_btn' style='float: right;' class='button white_button_150' onmouseover='button_swap(this);' onmouseout='button_unswap(this);' onclick='hidePublished();'>Show Published</a><br/>\n\t\t\t<table class='importxml'><tr class='toprow'><td>ID</td><td>Title</td>\n\t\t\t<td>Created</td><td>Preview</td>\n\t\t\t<td>Published?</td>\n\t\t\t<td>Edit</td><td>Delete?</td>\n\t\t\t<td>Publish</td>\n\t\t\t</tr>");
     $dbr = wfGetDB(DB_SLAVE);
     $res = $dbr->select('import_articles', array('ia_published', 'ia_title', 'ia_id', 'ia_timestamp'), array(), "ImportXML", array("ORDER BY" => "ia_id"));
     while ($row = $dbr->fetchObject($res)) {
         $t = Title::newFromText($row->ia_title);
         if ($t) {
             $class = $row->ia_published == 1 ? "pub" : "";
             $safe_title = urlencode(htmlspecialchars($row->ia_title));
             $wgOut->addHTML("<tr id='row_{$row->ia_id}' class='{$class}'><td>{$row->ia_id}</td><td>{$t->getText()}</td><td>{$row->ia_timestamp}</td>\n\t\t\t\t\t<td><a href='/Special:ImportXML?preview={$row->ia_id}' target='new'>Preview</a></td>\n\t\t\t\t\t<td>" . ($row->ia_published == 1 ? "yes" : "no") . "</td>\n\t\t\t\t\t<td><a onclick=\"edit_xml({$row->ia_id});\">Edit</a></td>\n\t\t\t\t\t<td><input style='height: 24px; width: 24px;' type='image' src='/extensions/wikihow/rcwidget/rcwDelete.png' onclick='return delete_xml({$row->ia_id}, \"{$safe_title}\");'></td>\n\t\t\t\t\t<td><input type='checkbox' name='publish_{$row->ia_id}'></a></td>\n\t\t\t\t</tr>");
         }
     }
     $wgOut->addHTML("</table>\n\t\t\t<input type='submit' value='Publish'/>\n\t\t\t</form>\n\t\t<br/>\n\t\t<a href='/Special:ImportXML?publishedcsv=1'>Published(CSV)</a> | \n\t\t<a href='/Special:ImportXML?publishedcsv=1&errs=1'>Errors (CSV) </a>\n\t\t<br/><br/>Insert new articles:\n\t\t<form action='/Special:ImportXML' method='post' accept-charset='UTF-8' enctype='multipart/form-data'>\n\n\t\t\t<textarea class='xmlinput' name='xml'></textarea><br/>\n\t\t\tOr, use an input file in XML format: <input type='file' name='uploadFile'> <br/>\n\t\t\t<input type='submit'>\n\t\t</form>\n\t\t<div id='magicbox'></div>\n\t\t");
 }
    /**
     * Parse and transform the document from the old HTML for NS_MAIN articles to the new mobile
     * style. This should probably be pulled out and added to a subclass that can then be extended for
     * builders that focus on building NS_MAIN articles
     */
    protected function parseNonMobileArticle(&$article)
    {
        global $IP, $wgContLang, $wgLanguageCode;
        $sectionMap = array(wfMsg('Intro') => 'intro', wfMsg('Ingredients') => 'ingredients', wfMsg('Steps') => 'steps', wfMsg('Video') => 'video', wfMsg('Tips') => 'tips', wfMsg('Warnings') => 'warnings', wfMsg('relatedwikihows') => 'relatedwikihows', wfMsg('sourcescitations') => 'sources', wfMsg('thingsyoullneed') => 'thingsyoullneed', wfMsg('article_info') => 'article_info');
        $lang = MobileWikihow::getSiteLanguage();
        $imageNsText = $wgContLang->getNsText(NS_IMAGE);
        $device = $this->getDevice();
        // munge steps first
        $opts = array('no-ads' => true);
        $article = WikihowArticleHTML::postProcess($article, $opts);
        // Make doc correctly formed
        $articleText = <<<DONE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{$lang}" lang="{$lang}">
<head>
\t<meta http-equiv="Content-Type" content="text/html; charset='utf-8'" />
</head>
<body>
{$article}
</body>
</html>
DONE;
        require_once "{$IP}/extensions/wikihow/mobile/JSLikeHTMLElement.php";
        $doc = new DOMDocument('1.0', 'utf-8');
        $doc->registerNodeClass('DOMElement', 'JSLikeHTMLElement');
        $doc->strictErrorChecking = false;
        $doc->recover = true;
        //$doc->preserveWhiteSpace = false;
        //$wgOut->setarticlebodyonly(true);
        @$doc->loadHTML($articleText);
        $doc->normalizeDocument();
        //echo $doc->saveHtml();exit;
        $xpath = new DOMXPath($doc);
        // Delete #featurestar node
        $node = $doc->getElementById('featurestar');
        if (!empty($node)) {
            $node->parentNode->removeChild($node);
        }
        $node = $doc->getElementById('newaltmethod');
        if (!empty($node)) {
            $node->parentNode->removeChild($node);
        }
        // Remove all "Edit" links
        $nodes = $xpath->query('//a[@id = "gatEditSection"]');
        foreach ($nodes as $node) {
            $node->parentNode->removeChild($node);
        }
        // Resize youtube video
        $nodes = $xpath->query('//embed');
        foreach ($nodes as $node) {
            $url = '';
            $src = $node->attributes->getNamedItem('src')->nodeValue;
            if (!$device['show-youtube'] || stripos($src, 'youtube.com') === false) {
                $parent = $node->parentNode;
                $grandParent = $parent->parentNode;
                if ($grandParent && $parent) {
                    $grandParent->removeChild($parent);
                }
            } else {
                foreach (array(&$node, &$node->parentNode) as $node) {
                    $widthAttr = $node->attributes->getNamedItem('width');
                    $oldWidth = (int) $widthAttr->nodeValue;
                    $newWidth = $device['max-video-width'];
                    if ($newWidth < $oldWidth) {
                        $widthAttr->nodeValue = (string) $newWidth;
                        $heightAttr = $node->attributes->getNamedItem('height');
                        $oldHeight = (int) $heightAttr->nodeValue;
                        $newHeight = (int) round($newWidth * $oldHeight / $oldWidth);
                        $heightAttr->nodeValue = (string) $newHeight;
                    }
                }
            }
        }
        // Remove templates from intro so that they don't muck up
        // the text and images we extract
        $nodes = $xpath->query('//div[@class = "template_top"]');
        foreach ($nodes as $node) {
            $node->parentNode->removeChild($node);
        }
        // Grab intro text
        $intro = '';
        $nodes = $xpath->query('//body/div/p');
        foreach ($nodes as $i => $node) {
            $text = $node->textContent;
            if (!empty($text) && $i == 0) {
                $introNode = $node;
                $intro = Wikitext::removeRefsFromFlattened($text);
                break;
            }
        }
        if ($introNode) {
            // Grab first image from article
            $imgs = $xpath->query('.//img', $introNode->parentNode);
            $firstImage = '';
            foreach ($imgs as $img) {
                // parent is an <a> tag
                $parent = $img->parentNode;
                if ($parent->nodeName == 'a') {
                    $href = $parent->attributes->getNamedItem('href')->nodeValue;
                    if (preg_match('@(Image|' . $imageNsText . '):@', $href)) {
                        $firstImage = preg_replace('@^.*(Image|' . $imageNsText . '):([^:]*)([#].*)?$@', '$2', $href);
                        $firstImage = urldecode($firstImage);
                        break;
                    }
                }
            }
            // Remove intro node
            $parent = $introNode->parentNode;
            $parent->removeChild($introNode);
        }
        // Get rid of the <span> element to standardize the html for the
        // next dom query
        $nodes = $xpath->query('//div/span/a[@class = "image"]');
        foreach ($nodes as $a) {
            $parent = $a->parentNode;
            $grandParent = $parent->parentNode;
            $grandParent->replaceChild($a, $parent);
        }
        // Resize all resize-able images
        $nodes = $xpath->query('//div/a[@class = "image"]/img');
        $imgNum = 1;
        foreach ($nodes as $img) {
            $srcNode = $img->attributes->getNamedItem('src');
            $widthNode = $img->attributes->getNamedItem('width');
            $width = (int) $widthNode->nodeValue;
            $heightNode = $img->attributes->getNamedItem('height');
            $height = (int) $heightNode->nodeValue;
            $imageClasses = $img->parentNode->parentNode->attributes->getNamedItem('class')->nodeValue;
            /*
            if (!stristr($imageClasses, "tcenter")) {
            	$img->parentNode->parentNode->parentNode->attributes->getNamedItem('class')->nodeValue = '';
            	$img->parentNode->parentNode->parentNode->attributes->getNamedItem('style')->nodeValue = '';
            }
            */
            if (stristr($imageClasses, "tcenter") !== false) {
                $newWidth = $device['full-image-width'];
                $newHeight = (int) round($device['full-image-width'] * $height / $width);
            } else {
                $newWidth = $device['max-image-width'];
                $newHeight = (int) round($device['max-image-width'] * $height / $width);
            }
            $a = $img->parentNode;
            $href = $a->attributes->getNamedItem('href')->nodeValue;
            if (!$href) {
                $onclick = $a->attributes->getNamedItem('onclick')->nodeValue;
                $onclick = preg_replace('@.*",[ ]*"@', '', $onclick);
                $onclick = preg_replace('@".*@', '', $onclick);
                $imgName = preg_replace('@.*(Image|' . $imageNsText . '|' . urlencode($imageNsText) . '):@', '', $onclick);
            } else {
                $imgName = preg_replace('@^/(Image|' . $imageNsText . '|' . urlencode($imageNsText) . '):@', '', $href);
            }
            $title = Title::newFromURL($imgName, NS_IMAGE);
            if (!$title) {
                $imgName = urldecode($imgName);
                $title = Title::newFromURL($imgName, NS_IMAGE);
            }
            if ($title) {
                $image = RepoGroup::singleton()->findFile($title);
                if ($image) {
                    list($thumb, $newWidth, $newHeight) = self::makeThumbDPI($image, $newWidth, $newHeight, $device['enlarge-thumb-high-dpi']);
                    $url = wfGetPad($thumb->getUrl());
                    $srcNode->nodeValue = $url;
                    $widthNode->nodeValue = $newWidth;
                    $heightNode->nodeValue = $newHeight;
                    // change surrounding div width and height
                    $div = $a->parentNode;
                    $styleNode = $div->attributes->getNamedItem('style');
                    //removing the set width/height
                    $styleNode->nodeValue = '';
                    //$div->attributes->getNamedItem('class')->nodeValue = '';
                    /*					if (preg_match('@^(.*width:)[0-9]+(px;\s*height:)[0-9]+(.*)$@', $styleNode->nodeValue, $m)) {
                    						$styleNode->nodeValue = $m[1] . $newWidth . $m[2] . $newHeight . $m[3];
                    					}
                    */
                    //default width/height for the srcset
                    $bigWidth = 600;
                    $bigHeight = 800;
                    // change grandparent div width too
                    $grandparent = $div;
                    if ($grandparent && $grandparent->nodeName == 'div') {
                        $class = $grandparent->attributes->getNamedItem('class');
                        if ($class) {
                            $isThumb = stristr($class->nodeValue, 'mthumb') !== false;
                            $isRight = stristr($class->nodeValue, 'tright') !== false;
                            $isLeft = stristr($class->nodeValue, 'tleft') !== false;
                            $isCenter = stristr($class->nodeValue, 'tcenter') !== false;
                            if ($isThumb) {
                                if ($isRight) {
                                    $style = $grandparent->attributes->getNamedItem('style');
                                    $style->nodeValue = 'width:' . $newWidth . 'px;height:' . $newHeight . 'px;';
                                    $bigWidth = 300;
                                    $bigHeight = 500;
                                } elseif ($isCenter) {
                                    $style = $grandparent->attributes->getNamedItem('style');
                                    $style->nodeValue = 'width:' . $newWidth . 'px;height:' . $newHeight . 'px;';
                                    $bigWidth = 600;
                                    $bigHeight = 800;
                                } elseif ($isLeft) {
                                    //if its centered or on the left, give it double the width if too big
                                    $style = $grandparent->attributes->getNamedItem('style');
                                    $oldStyle = $style->nodeValue;
                                    $matches = array();
                                    preg_match('@(width:\\s*)[0-9]+@', $oldStyle, $matches);
                                    if ($matches[0]) {
                                        $curSize = intval(substr($matches[0], 6));
                                        //width: = 6
                                        if ($newWidth * 2 < $curSize) {
                                            $existingCSS = preg_replace('@(width:\\s*)[0-9]+@', 'width:' . $newWidth * 2, $oldStyle);
                                            $style->nodeValue = $existingCSS;
                                        }
                                    }
                                    $bigWidth = 300;
                                    $bigHeight = 500;
                                }
                            }
                        }
                    }
                    list($thumb, $newWidth, $newHeight) = self::makeThumbDPI($image, $bigWidth, $bigHeight, $device['enlarge-thumb-high-dpi']);
                    $url = wfGetPad($thumb->getUrl());
                    $img->setAttribute('srcset', $url . ' ' . $newWidth . 'w');
                    //if we couldn't make it big enough, let's add a class
                    if ($newWidth < $bigWidth) {
                        $imgclass = $img->getAttribute('class');
                        $img->setAttribute('class', $imgclass . ' not_huge');
                    }
                    //add the hidden info
                    /*
                    $newDiv = new DOMElement( 'div', htmlentities('test') );
                    $a->appendChild($newDiv);
                    $newDiv->setAttribute('style', 'display:none;');
                    */
                    $a->setAttribute('id', 'image-zoom-' . $imgNum);
                    $a->setAttribute('class', 'image-zoom');
                    $a->setAttribute('href', '#');
                    global $wgServerName;
                    $href = $wgServerName . $href;
                    if (!preg_match("/^http:\\/\\//", $href)) {
                        $href = "http://" . $serverName . $href;
                    }
                    $href = preg_replace("/\\m\\./", "", $href);
                    $href = preg_replace("/^http:\\/\\/wikihow\\.com/", "http://www.wikihow.com", $href);
                    $details = array('url' => $url, 'width' => $newWidth, 'height' => $newHeight, 'credits_page' => $href);
                    $newDiv = new DOMElement('div', htmlentities(json_encode($details)));
                    $a->appendChild($newDiv);
                    $newDiv->setAttribute('style', 'display:none;');
                    $newDiv->setAttribute('id', 'image-details-' . $imgNum);
                    $imgNum++;
                } else {
                    //huh? can't find it? well, then let's not display it
                    $img->parentNode->parentNode->parentNode->parentNode->setAttribute('style', 'display:none;');
                }
            } else {
                //huh? can't find it? well, then let's not display it
                $img->parentNode->parentNode->parentNode->parentNode->setAttribute('style', 'display:none;');
            }
        }
        // Remove template from images, add new zoom one
        $nodes = $xpath->query('//img');
        foreach ($nodes as $node) {
            $src = $node->attributes ? $node->attributes->getNamedItem('src') : null;
            $src = $src ? $src->nodeValue : '';
            if (stripos($src, 'magnify-clip.png') !== false) {
                $parent = $node->parentNode;
                $parent->parentNode->removeChild($parent);
            }
        }
        //get rid of the corners and watermarks
        $nodes = $xpath->query('//div[@class = "corner top_left" 
								or @class = "corner bottom_left"
								or @class = "corner top_right"
								or @class = "corner bottom_right"
								or @class = "wikihow_watermark"]');
        foreach ($nodes as $node) {
            $parent = $node->parentNode;
            $parent->removeChild($node);
        }
        //gotta swap in larger images if the client's width is big enough
        //(i.e. tablet et al)
        $nodes = $xpath->query('//img[@class = "mwimage101" 
								or @class = "mwimage101 not_huge"]');
        foreach ($nodes as $node) {
            //make a quick unique id for this
            $id = md5($node->attributes->getNamedItem('src')->nodeValue) . rand();
            $node->setAttribute('id', $id);
            //pass it to our custom function for swapping in larger images
            $swap_it = 'if (isBig) WH.mobile.swapEm("' . $id . '");';
            $scripttag = new DOMElement('script', htmlentities($swap_it));
            $node->appendChild($scripttag);
        }
        // Change the width attribute from any tables with a width set.
        // This often happen around video elements.
        $nodes = $xpath->query('//table/@width');
        foreach ($nodes as $node) {
            $width = preg_replace('@px\\s*$@', '', $node->nodeValue);
            if ($width > $device['screen-width'] - 20) {
                $node->nodeValue = $device['screen-width'] - 20;
            }
        }
        // Surround step content in its own div. We do this to support other features like checkmarks
        $nodes = $xpath->query('//div[@id="steps"]/ol/li');
        foreach ($nodes as $node) {
            $node->innerHTML = '<div class="step_content">' . $node->innerHTML . '</div>';
        }
        //remove quiz
        $nodes = $xpath->query('//div[@class = "quiz_cta"]');
        foreach ($nodes as $node) {
            $node->parentNode->removeChild($node);
        }
        //remove quiz header
        $nodes = $xpath->query('//h3/span[text()="Quiz"]');
        foreach ($nodes as $node) {
            $parentNode = $node->parentNode;
            $parentNode->parentNode->removeChild($parentNode);
        }
        //pull out the first 6 related wikihows and format them
        $nodes = $xpath->query('//div[@id="relatedwikihows"]/ul/li');
        $count = 0;
        $related_boxes = array();
        foreach ($nodes as $node) {
            if ($count > 6) {
                break;
            }
            //grab the title
            preg_match('@href=\\"\\/(.*?)?\\"@', $node->innerHTML, $m);
            $title = Title::newFromText($m[1]);
            if (!$title) {
                continue;
            }
            $temp_box = $this->makeRelatedBox($title);
            if ($temp_box) {
                $related_boxes[] = $temp_box;
                $last_node = $node;
                $parent = $node->parentNode;
                $last_parent = $parent;
                $parent->removeChild($node);
                $count++;
            }
        }
        //only 1? not enough. throw it back
        if ($count == 1) {
            $related_boxes = array();
            $last_parent->appendChild($last_node);
        }
        // Inject html into the DOM tree for specific features (ie thumb ratings, ads, etc)
        $this->mobileParserBeforeHtmlSave($xpath);
        //self::walkTree($doc->documentElement, 1);
        $html = $doc->saveXML();
        $sections = array();
        $sectionsHtml = explode('<h2>', $html);
        unset($sectionsHtml[0]);
        // remove leftovers from intro section
        foreach ($sectionsHtml as $i => &$section) {
            $section = '<h2>' . $section;
            if (preg_match('@^<h2[^>]*>\\s*<span[^>]*>\\s*([^<]+)@i', $section, $m)) {
                $heading = trim($m[1]);
                $section = preg_replace('@^<h2[^>]*>\\s*<span[^>]*>\\s*([^<]+)</span>(\\s|\\n)*</h2>@i', '', $section);
                if (isset($sectionMap[$heading])) {
                    $key = $sectionMap[$heading];
                    $sections[$key] = array('name' => $heading, 'html' => $section);
                }
            }
        }
        // Remove Video section if there is no longer a youtube video
        if (isset($sections['video'])) {
            if (!preg_match('@<object@i', $sections['video']['html'])) {
                unset($sections['video']);
            }
        }
        // Add the related boxes
        if (isset($sections['relatedwikihows']) && !empty($related_boxes)) {
            $sections['relatedwikihows']['boxes'] = $related_boxes;
        }
        // Add article info
        $sections['article_info']['name'] = wfMsg('article_info');
        $sections['article_info']['html'] = $this->getArticleInfo($title);
        // Remove </body></html> from html
        if (count($sections) > 0) {
            $keys = array_keys($sections);
            $last =& $sections[$keys[count($sections) - 2]]['html'];
            $last = preg_replace('@</body>(\\s|\\n)*</html>(\\s|\\n)*$@', '', $last);
        }
        // Add a simple form for uploading images of completed items to the article
        if ($wgLanguageCode == 'en' && isset($sections['steps']) && isset($device['show-upload-images']) && $device['show-upload-images']) {
            require_once "{$IP}/extensions/wikihow/mobile/MobileUciHtmlBuilder.class.php";
            $userCompletedImages = new MobileUciHtmlBuilder();
            $sections['steps']['html'] .= $userCompletedImages->createByHtml($this->t);
        }
        return array($sections, $intro, $firstImage);
    }
Example #7
0
 private function getNextMethod()
 {
     global $wgUser, $wgOut, $wgParser;
     $dbw = wfGetDB(DB_MASTER);
     $expired = wfTimestamp(TS_MW, time() - MethodGuardian::METHOD_EXPIRED);
     $i = 0;
     $content['error'] = true;
     $goodRevision = false;
     do {
         $skippedIds = $this->skipTool->getSkipped();
         $where = array();
         $where[] = "ama_checkout < '{$expired}'";
         $where[] = "ama_patrolled = 0";
         if ($skippedIds) {
             $where[] = "ama_id NOT IN ('" . implode("','", $skippedIds) . "')";
         }
         $row = $dbw->selectRow(MethodGuardian::TABLE_NAME, array('*'), $where, __METHOD__, array("LIMIT" => 1));
         $content['sql' . $i] = $dbw->lastQuery();
         $content['row'] = $row;
         if ($row !== false) {
             $title = Title::newFromID($row->ama_page);
             $isRedirect = false;
             if ($title) {
                 $dbr = wfGetDB(DB_SLAVE);
                 $isRedirect = intval($dbr->selectField('page', 'page_is_redirect', array('page_id' => $row->ama_page), __METHOD__, array("LIMIT" => 1)));
             }
             if ($title && !$isRedirect) {
                 $this->skipTool->useItem($row->ama_id);
                 $revision = Revision::newFromTitle($title);
                 $popts = $wgOut->parserOptions();
                 $popts->setTidy(true);
                 $parserOutput = $wgOut->parse($revision->getText(), $title, $popts);
                 $content['article'] = WikihowArticleHTML::processArticleHTML($parserOutput, array('no-ads', 'ns' => NS_MAIN));
                 $content['method'] = $row->ama_method;
                 $content['methodId'] = $row->ama_id;
                 $content['articleId'] = $row->ama_page;
                 $newMethod = $wgParser->parse("== Steps ==\n=== " . $row->ama_method . " ===\n" . $row->ama_steps, $title, new ParserOptions())->getText();
                 $content['steps'] = WikihowArticleHTML::postProcess($newMethod, array('no-ads' => true));
                 //$content['steps'] = $row->ama_steps;
                 $content['articleTitle'] = "<a href='{$title->getLocalURL()}'>{$title->getText()}</a>";
                 $content['error'] = false;
             } else {
                 //article must no longer exist or be a redirect, so delete the tips associated with that article
                 $dbw = wfGetDB(DB_MASTER);
                 $dbw->delete(MethodGuardian::TABLE_NAME, array('ama_page' => $row->ama_page));
             }
         }
         $i++;
         // Check up to 5 titles.
         // If no good title then return an error message
     } while ($i <= 5 && !$title && $row !== false);
     $content['i'] = $i;
     $content['methodCount'] = self::getCount();
     return $content;
 }
 function parse($t, $a, $text)
 {
     global $wgOut, $wgParser;
     # try this parse, this is for debugging only
     $popts = $wgOut->parserOptions();
     $popts->setTidy(true);
     $popts->enableLimitReport();
     #Html5WrapTemplates($a, &$newtext);
     $parserOutput = $wgParser->parse($text, $t, $popts, true, true, $a->getRevIdFetched());
     $popts->setTidy(false);
     $popts->enableLimitReport(false);
     $html = WikihowArticleHTML::postProcess($parserOutput->getText(), array('no-ads'));
     $this->debug("output.html", $wtext . "\n\n-----------\n" . $html);
     return $html;
 }
Example #9
0
 private function getCoachTip($content)
 {
     global $wgUser, $wgOut;
     $content['error'] = true;
     // get a coach tip that the users hasn't seen before
     $userId = $wgUser->getID();
     $where = array("tpt_id != 1 AND tpt_id NOT IN (SELECT tpc_test_id from tipspatrol_completed_test where tpc_user_id = {$userId})");
     $dbr = wfGetDB(DB_SLAVE);
     $res = $dbr->select('tipspatrol_test', array('*'), $where, __METHOD__);
     $numRows = $res->numRows();
     if ($numRows < 1) {
         return false;
     }
     $index = rand(0, $numRows - 1);
     $res->seek($index);
     $row = $res->current();
     $title = Title::newFromID($row->tpt_page_id);
     $revision = Revision::newFromTitle($title);
     $parserOutput = $wgOut->parse($revision->getText());
     $content['article'] = WikihowArticleHTML::postProcess($parserOutput, array('no-ads'));
     $content['tip'] = $row->tpt_tip;
     $content['tipId'] = $row->tpt_id;
     $content['articleId'] = $row->tpt_page_id;
     $content['articleTitle'] = $title->getText();
     $content['articleUrl'] = $title->getPartialUrl();
     $content['tipCount'] = self::getCount();
     $content['coaching'] = true;
     $content['error'] = false;
     return true;
 }