/**
  * Resizes image by width or height only if the source image is bigger than the given width/height.
  * This prevents ugly upscaling.
  *
  * @param int  $width [optional]
  * @param int  $height [optional]
  * @param bool $upscale [optional]
  *
  * @return Image
  */
 public function getImageAt($width = null, $height = null, $upscale = false)
 {
     if (!$this->owner->exists()) {
         return $this->owner;
     }
     $realWidth = $this->owner->getWidth();
     $realHeight = $this->owner->getHeight();
     if ($width && $height) {
         return $realWidth < $width && $realHeight < $height && !$upscale ? $this->owner : $this->owner->Fit($width, $height);
     } else {
         if ($width) {
             return $realWidth < $width && !$upscale ? $this->owner : $this->owner->ScaleWidth($width);
         } else {
             return $realHeight < $height && !$upscale ? $this->owner : $this->owner->ScaleHeight($height);
         }
     }
 }
Example #2
0
 /**
  * Receives image name, type and url if any from DB.
  *
  * @param string $p_imageId
  */
 private function GetImage($p_imageId)
 {
     $this->m_image = new Image($p_imageId);
     if (!$this->m_image->exists()) {
         $this->ExitError('Image not found');
     }
     if (!$this->setSourcePath()) {
         $this->ExitError('File "' . $this->m_image->getImageStorageLocation() . $this->m_image->getUrl() . '" not found');
     }
     $this->m_image->fixMissingThumbnail();
     $this->PushImage();
 }
     $exts[] = ltrim($ext, '.');
 }
 # Search the directory given and pull out suitable candidates
 $files = findFiles($dir, $exts);
 # Set up a fake user for this operation
 $wgUser = User::newFromName('Image import script');
 $wgUser->setLoaded(true);
 # Batch "upload" operation
 foreach ($files as $file) {
     $base = basename($file);
     # Validate a title
     $title = Title::makeTitleSafe(NS_IMAGE, $base);
     if (is_object($title)) {
         # Check existence
         $image = new Image($title);
         if (!$image->exists()) {
             global $wgUploadDirectory;
             # copy() doesn't create paths so if the hash path doesn't exist, we
             # have to create it
             makeHashPath(wfGetHashPath($image->name));
             # Stash the file
             echo "Saving {$base}...";
             if (copy($file, $image->getFullPath())) {
                 echo "importing...";
                 # Grab the metadata
                 $image->loadFromFile();
                 # Record the upload
                 if ($image->recordUpload('', 'Importing image file')) {
                     # We're done!
                     echo "done.\n";
                 } else {
Example #4
0
 function pageTitleLinks()
 {
     global $wgOut, $wgTitle, $wgUser, $wgContLang, $wgRequest;
     extract($wgRequest->getValues('oldid', 'diff'));
     $action = $wgRequest->getText('action');
     $s = $this->printableLink();
     $disclaimer = $this->disclaimerLink();
     # may be empty
     if ($disclaimer) {
         $s .= ' | ' . $disclaimer;
     }
     if ($wgOut->isArticleRelated()) {
         if ($wgTitle->getNamespace() == NS_IMAGE) {
             $name = $wgTitle->getDBkey();
             $image = new Image($wgTitle);
             if ($image->exists()) {
                 $link = htmlspecialchars($image->getURL());
                 $style = $this->getInternalLinkAttributes($link, $name);
                 $s .= " | <a href=\"{$link}\"{$style}>{$name}</a>";
             }
         }
     }
     if ('history' == $action || isset($diff) || isset($oldid)) {
         $s .= ' | ' . $this->makeKnownLinkObj($wgTitle, wfMsg('currentrev'));
     }
     if ($wgUser->getNewtalk()) {
         # do not show "You have new messages" text when we are viewing our
         # own talk page
         if (!$wgTitle->equals($wgUser->getTalkPage())) {
             $tl = $this->makeKnownLinkObj($wgUser->getTalkPage(), wfMsg('newmessageslink'));
             $s .= ' | <strong>' . wfMsg('newmessages', $tl) . '</strong>';
             # disable caching
             $wgOut->setSquidMaxage(0);
             $wgOut->enableClientCache(false);
         }
     }
     $undelete = $this->getUndeleteLink();
     if (!empty($undelete)) {
         $s .= ' | ' . $undelete;
     }
     return $s;
 }
Example #5
0
 /**
  * Returns an article images list based on the given parameters.
  *
  * @param array $p_parameters
  *    An array of ComparisonOperation objects
  * @param string $p_order
  *    An array of columns and directions to order by
  * @param integer $p_start
  *    The record number to start the list
  * @param integer $p_limit
  *    The offset. How many records from $p_start will be retrieved.
  * @param integer $p_count
  *    The total count of the elements; this count is computed without
  *    applying the start ($p_start) and limit parameters ($p_limit)
  *
  * @return array $articleImagesList
  *    An array of Image objects
  */
 public static function GetList(array $p_parameters, array $p_order = array(), $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false)
 {
     global $g_ado_db;
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $paramsArray['parameters'] = serialize($p_parameters);
         $paramsArray['order'] = is_null($p_order) ? 'null' : $p_order;
         $paramsArray['start'] = $p_start;
         $paramsArray['limit'] = $p_limit;
         $cacheListObj = new CampCacheList($paramsArray, __METHOD__);
         $articleImagesList = $cacheListObj->fetchFromCache();
         if ($articleImagesList !== false && is_array($articleImagesList)) {
             return $articleImagesList;
         }
     }
     $hasArticleNr = false;
     $selectClauseObj = new SQLSelectClause();
     $countClauseObj = new SQLSelectClause();
     // sets the where conditions
     foreach ($p_parameters as $param) {
         $comparisonOperation = self::ProcessListParameters($param);
         if (sizeof($comparisonOperation) < 3) {
             break;
         }
         if (strpos($comparisonOperation['left'], 'NrArticle')) {
             $hasArticleNr = true;
         }
         $whereCondition = $g_ado_db->escapeOperation($comparisonOperation);
         $selectClauseObj->addWhere($whereCondition);
         $countClauseObj->addWhere($whereCondition);
     }
     // validates whether article number was given
     if ($hasArticleNr === false) {
         CampTemplate::singleton()->trigger_error('Missing parameter Article ' . 'Number in statement list_article_images');
         return;
     }
     // sets the columns to be fetched
     $tmpImage = new Image();
     $columnNames = $tmpImage->getColumnNames(true);
     foreach ($columnNames as $columnName) {
         $selectClauseObj->addColumn($columnName);
     }
     $countClauseObj->addColumn('COUNT(*)');
     // sets the base table Attachment
     $selectClauseObj->setTable($tmpImage->getDbTableName());
     $countClauseObj->setTable($tmpImage->getDbTableName());
     unset($tmpImage);
     // adds the ArticleImages join and condition to the query
     $selectClauseObj->addTableFrom('ArticleImages');
     $selectClauseObj->addWhere('ArticleImages.IdImage = Images.Id');
     $countClauseObj->addTableFrom('ArticleImages');
     $countClauseObj->addWhere('ArticleImages.IdImage = Images.Id');
     // sets the ORDER BY condition
     $p_order = array_merge($p_order, self::$s_defaultOrder);
     $order = self::ProcessListOrder($p_order);
     foreach ($order as $orderDesc) {
         $orderColumn = $orderDesc['field'];
         $orderDirection = $orderDesc['dir'];
         $selectClauseObj->addOrderBy($orderColumn . ' ' . $orderDirection);
     }
     // sets the limit
     $selectClauseObj->setLimit($p_start, $p_limit);
     // builds the query executes it
     $selectQuery = $selectClauseObj->buildQuery();
     $images = $g_ado_db->GetAll($selectQuery);
     if (is_array($images)) {
         $countQuery = $countClauseObj->buildQuery();
         $p_count = $g_ado_db->GetOne($countQuery);
         // builds the array of image objects
         $articleImagesList = array();
         foreach ($images as $image) {
             $imgObj = new Image($image['Id']);
             if ($imgObj->exists()) {
                 $articleImagesList[] = $imgObj;
             }
         }
     } else {
         $articleImagesList = array();
         $p_count = 0;
     }
     if (!$p_skipCache && CampCache::IsEnabled()) {
         $cacheListObj->storeInCache($articleImagesList);
     }
     return $articleImagesList;
 }
Example #6
0
    /**
     * Returns an images list based on the given parameters.
     *
     * @param array $p_parameters
     *    An array of ComparionOperation objects
     * @param string $p_order
     *    An array of columns and directions to order by
     * @param integer $p_start
     *    The record number to start the list
     * @param integer $p_limit
     *    The offset. How many records from $p_start will be retrieved.
     *
     * @return array $issueList
     *    An array of Issue objects
     */
    public static function GetList(array $p_parameters, array $p_order = array(),
                                   $p_start = 0, $p_limit = 0, &$p_count, $p_skipCache = false)
    {
        global $g_ado_db;

        if (!$p_skipCache && CampCache::IsEnabled()) {
        	$paramsArray['parameters'] = serialize($p_parameters);
        	$paramsArray['order'] = (is_null($p_order)) ? 'null' : $p_order;
        	$paramsArray['start'] = $p_start;
        	$paramsArray['limit'] = $p_limit;
        	$cacheListObj = new CampCacheList($paramsArray, __METHOD__);
        	$imagesList = $cacheListObj->fetchFromCache();
        	if ($imagesList !== false && is_array($imagesList)) {
        		return $imagesList;
        	}
        }

        $selectClauseObj = new SQLSelectClause();
        $countClauseObj = new SQLSelectClause();

        // sets the where conditions
        foreach ($p_parameters as $param) {
            $comparisonOperation = self::ProcessListParameters($param);
            if (sizeof($comparisonOperation) < 1) {
                break;
            }

            if ($comparisonOperation['symbol'] == 'match') {
            	$whereCondition = 'MATCH(' . $comparisonOperation['left'] . ") AGAINST('"
            	    . $g_ado_db->escape($comparisonOperation['right']) . "' IN BOOLEAN MODE)";
            } else {
            	$whereCondition = $comparisonOperation['left'] . ' '
            	    . $comparisonOperation['symbol'] . " '"
            	    . $g_ado_db->escape($comparisonOperation['right']) . "' ";
            }
            $selectClauseObj->addWhere($whereCondition);
            $countClauseObj->addWhere($whereCondition);
        }

        // sets the columns to be fetched
        $tmpImage = new Image();
		$columnNames = $tmpImage->getColumnNames(true);
        foreach ($columnNames as $columnName) {
            $selectClauseObj->addColumn($columnName);
        }
        $countClauseObj->addColumn('COUNT(*)');

        // sets the base table
        $selectClauseObj->setTable($tmpImage->getDbTableName());
        $countClauseObj->setTable($tmpImage->getDbTableName());
        unset($tmpImage);

        // sets the ORDER BY condition
        $p_order = array_merge($p_order, self::$s_defaultOrder);
        $order = self::ProcessListOrder($p_order);
        foreach ($order as $orderDesc) {
            $orderColumn = $orderDesc['field'];
            $orderDirection = $orderDesc['dir'];
            $selectClauseObj->addOrderBy($orderColumn . ' ' . $orderDirection);
        }

        // sets the limit
        $selectClauseObj->setLimit($p_start, $p_limit);

        // builds the query and executes it
        $selectQuery = $selectClauseObj->buildQuery();
        $images = $g_ado_db->GetAll($selectQuery);
        if (is_array($images)) {
        	$countQuery = $countClauseObj->buildQuery();
        	$p_count = $g_ado_db->GetOne($countQuery);

        	// builds the array of image objects
        	$imagesList = array();
        	foreach ($images as $image) {
        		$imgObj = new Image($image['Id']);
        		if ($imgObj->exists()) {
        			$imagesList[] = $imgObj;
        		}
        	}
        } else {
        	$imagesList = array();
        	$p_count = 0;
        }
        if (!$p_skipCache && CampCache::IsEnabled()) {
        	$cacheListObj->storeInCache($imagesList);
        }

        return $imagesList;
    } // fn GetList
Example #7
0
$f_article_number = Input::Get('f_article_number', 'int', 0);
$f_image_id = Input::Get('f_image_id', 'int', 0);

if (!Input::IsValid()) {
	camp_html_display_error(getGS('Invalid input: $1', Input::GetErrorString()), null, true);
	exit;
}

$articleObj = new Article($f_language_selected, $f_article_number);
if (!$articleObj->exists()) {
	camp_html_display_error(getGS('Article does not exist.'), null, true);
	exit;
}

$imageObj = new Image($f_image_id);
if (!$imageObj->exists()) {
	camp_html_display_error(getGS('Image does not exist.'), null, true);
	exit;
}

// This file can only be accessed if the user has the right to change articles
// or the user created this article and it hasnt been published yet.
if (!$g_user->hasPermission('AttachImageToArticle')) {
	camp_html_display_error(getGS("You do not have the right to attach images to articles."), null, true);
	exit;
}

ArticleImage::AddImageToArticle($f_image_id, $f_article_number);

?>
<script>
Example #8
0
 public function getAutoPostPhotos()
 {
     $photos = [];
     $details = @$this->getAutoPost();
     if (!$details) {
         $this->forceDeleteIt();
         return $photos;
     }
     if ($details['type'] == 'add-photos') {
         foreach ($details['photos'] as $photo) {
             //$file = base_path(str_replace('%d', 600, $photo->path));
             if (\Image::exists($photo->path)) {
                 $photos[] = $photo->path;
             }
         }
     }
     return $photos;
 }
Example #9
0
 /**
  * Create a direct link to a given uploaded file.
  *
  * @param Title  $title
  * @param string $text   pre-sanitized HTML
  * @param bool   $nourl  Mask absolute URLs, so the parser doesn't
  *                       linkify them (it is currently not context-aware)
  * @return string HTML
  *
  * @access public
  * @todo Handle invalid or missing images better.
  */
 function makeMediaLinkObj($title, $text = '', $nourl = false)
 {
     if (is_null($title)) {
         ### HOTFIX. Instead of breaking, return empty string.
         return $text;
     } else {
         $name = $title->getDBKey();
         $img = new Image($title);
         if ($img->exists()) {
             $url = $img->getURL();
             if ($nourl) {
                 $url = str_replace("http://", UNIQ_PREFIX . "NOPARSEhttp://", $url);
             }
             $class = 'internal';
         } else {
             $upload = Title::makeTitle(NS_SPECIAL, 'Upload');
             $url = $upload->getLocalUrl('wpDestFile=' . urlencode($img->getName()));
             $class = 'new';
         }
         $alt = htmlspecialchars($title->getText());
         if ($text == '') {
             $text = $alt;
         }
         $u = htmlspecialchars($url);
         return "<a href=\"{$u}\" class='{$class}' title=\"{$alt}\">{$text}</a>";
     }
 }
 public function exists()
 {
     $this->createLocalIfNeeded();
     return parent::exists();
 }
Example #11
0
 /**
  * Process [[ ]] wikilinks
  *
  * @private
  */
 function replaceInternalLinks($s)
 {
     global $wgContLang;
     static $fname = 'Parser::replaceInternalLinks';
     wfProfileIn($fname);
     wfProfileIn($fname . '-setup');
     static $tc = FALSE;
     # the % is needed to support urlencoded titles as well
     if (!$tc) {
         $tc = Title::legalChars() . '#%';
     }
     $sk =& $this->mOptions->getSkin();
     #split the entire text string on occurences of [[
     $a = explode('[[', ' ' . $s);
     #get the first element (all text up to first [[), and remove the space we added
     $s = array_shift($a);
     $s = substr($s, 1);
     # Match a link having the form [[namespace:link|alternate]]trail
     static $e1 = FALSE;
     if (!$e1) {
         $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
     }
     # Match cases where there is no "]]", which might still be images
     static $e1_img = FALSE;
     if (!$e1_img) {
         $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
     }
     # Match the end of a line for a word that's not followed by whitespace,
     # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
     $e2 = wfMsgForContent('linkprefix');
     $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
     if (is_null($this->mTitle)) {
         throw new MWException(__METHOD__ . ": \$this->mTitle is null\n");
     }
     $nottalk = !$this->mTitle->isTalkPage();
     if ($useLinkPrefixExtension) {
         if (preg_match($e2, $s, $m)) {
             $first_prefix = $m[2];
         } else {
             $first_prefix = false;
         }
     } else {
         $prefix = '';
     }
     $selflink = $this->mTitle->getPrefixedText();
     $useSubpages = $this->areSubpagesAllowed();
     wfProfileOut($fname . '-setup');
     # Loop for each link
     for ($k = 0; isset($a[$k]); $k++) {
         $line = $a[$k];
         if ($useLinkPrefixExtension) {
             wfProfileIn($fname . '-prefixhandling');
             if (preg_match($e2, $s, $m)) {
                 $prefix = $m[2];
                 $s = $m[1];
             } else {
                 $prefix = '';
             }
             # first link
             if ($first_prefix) {
                 $prefix = $first_prefix;
                 $first_prefix = false;
             }
             wfProfileOut($fname . '-prefixhandling');
         }
         $might_be_img = false;
         wfProfileIn("{$fname}-e1");
         if (preg_match($e1, $line, $m)) {
             # page with normal text or alt
             $text = $m[2];
             # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
             # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row f***s up,
             # the real problem is with the $e1 regex
             # See bug 1300.
             #
             # Still some problems for cases where the ] is meant to be outside punctuation,
             # and no image is in sight. See bug 2095.
             #
             if ($text !== '' && substr($m[3], 0, 1) === ']' && strpos($text, '[') !== false) {
                 $text .= ']';
                 # so that replaceExternalLinks($text) works later
                 $m[3] = substr($m[3], 1);
             }
             # fix up urlencoded title texts
             if (strpos($m[1], '%') !== false) {
                 # Should anchors '#' also be rejected?
                 $m[1] = str_replace(array('<', '>'), array('&lt;', '&gt;'), urldecode($m[1]));
             }
             $trail = $m[3];
         } elseif (preg_match($e1_img, $line, $m)) {
             # Invalid, but might be an image with a link in its caption
             $might_be_img = true;
             $text = $m[2];
             if (strpos($m[1], '%') !== false) {
                 $m[1] = urldecode($m[1]);
             }
             $trail = "";
         } else {
             # Invalid form; output directly
             $s .= $prefix . '[[' . $line;
             wfProfileOut("{$fname}-e1");
             continue;
         }
         wfProfileOut("{$fname}-e1");
         wfProfileIn("{$fname}-misc");
         # Don't allow internal links to pages containing
         # PROTO: where PROTO is a valid URL protocol; these
         # should be external links.
         if (preg_match('/^(\\b(?:' . wfUrlProtocols() . '))/', $m[1])) {
             $s .= $prefix . '[[' . $line;
             continue;
         }
         # Make subpage if necessary
         if ($useSubpages) {
             $link = $this->maybeDoSubpageLink($m[1], $text);
         } else {
             $link = $m[1];
         }
         $noforce = substr($m[1], 0, 1) != ':';
         if (!$noforce) {
             # Strip off leading ':'
             $link = substr($link, 1);
         }
         wfProfileOut("{$fname}-misc");
         wfProfileIn("{$fname}-title");
         $nt = Title::newFromText($this->unstripNoWiki($link, $this->mStripState));
         if (!$nt) {
             $s .= $prefix . '[[' . $line;
             wfProfileOut("{$fname}-title");
             continue;
         }
         $ns = $nt->getNamespace();
         $iw = $nt->getInterWiki();
         wfProfileOut("{$fname}-title");
         if ($might_be_img) {
             # if this is actually an invalid link
             wfProfileIn("{$fname}-might_be_img");
             if ($ns == NS_IMAGE && $noforce) {
                 #but might be an image
                 $found = false;
                 while (isset($a[$k + 1])) {
                     #look at the next 'line' to see if we can close it there
                     $spliced = array_splice($a, $k + 1, 1);
                     $next_line = array_shift($spliced);
                     $m = explode(']]', $next_line, 3);
                     if (count($m) == 3) {
                         # the first ]] closes the inner link, the second the image
                         $found = true;
                         $text .= "[[{$m[0]}]]{$m[1]}";
                         $trail = $m[2];
                         break;
                     } elseif (count($m) == 2) {
                         #if there's exactly one ]] that's fine, we'll keep looking
                         $text .= "[[{$m[0]}]]{$m[1]}";
                     } else {
                         #if $next_line is invalid too, we need look no further
                         $text .= '[[' . $next_line;
                         break;
                     }
                 }
                 if (!$found) {
                     # we couldn't find the end of this imageLink, so output it raw
                     #but don't ignore what might be perfectly normal links in the text we've examined
                     $text = $this->replaceInternalLinks($text);
                     $s .= "{$prefix}[[{$link}|{$text}";
                     # note: no $trail, because without an end, there *is* no trail
                     wfProfileOut("{$fname}-might_be_img");
                     continue;
                 }
             } else {
                 #it's not an image, so output it raw
                 $s .= "{$prefix}[[{$link}|{$text}";
                 # note: no $trail, because without an end, there *is* no trail
                 wfProfileOut("{$fname}-might_be_img");
                 continue;
             }
             wfProfileOut("{$fname}-might_be_img");
         }
         $wasblank = '' == $text;
         if ($wasblank) {
             $text = $link;
         }
         # Link not escaped by : , create the various objects
         if ($noforce) {
             # Interwikis
             wfProfileIn("{$fname}-interwiki");
             if ($iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName($iw)) {
                 $this->mOutput->addLanguageLink($nt->getFullText());
                 $s = rtrim($s . "\n");
                 $s .= trim($prefix . $trail, "\n") == '' ? '' : $prefix . $trail;
                 wfProfileOut("{$fname}-interwiki");
                 continue;
             }
             wfProfileOut("{$fname}-interwiki");
             if ($ns == NS_IMAGE) {
                 wfProfileIn("{$fname}-image");
                 if (!wfIsBadImage($nt->getDBkey(), $this->mTitle)) {
                     # recursively parse links inside the image caption
                     # actually, this will parse them in any other parameters, too,
                     # but it might be hard to fix that, and it doesn't matter ATM
                     $text = $this->replaceExternalLinks($text);
                     $text = $this->replaceInternalLinks($text);
                     # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
                     $s .= $prefix . $this->armorLinks($this->makeImage($nt, $text)) . $trail;
                     $this->mOutput->addImage($nt->getDBkey());
                     wfProfileOut("{$fname}-image");
                     continue;
                 } else {
                     # We still need to record the image's presence on the page
                     $this->mOutput->addImage($nt->getDBkey());
                 }
                 wfProfileOut("{$fname}-image");
             }
             if ($ns == NS_CATEGORY) {
                 wfProfileIn("{$fname}-category");
                 $s = rtrim($s . "\n");
                 # bug 87
                 if ($wasblank) {
                     if ($this->mTitle->getNamespace() == NS_CATEGORY) {
                         $sortkey = $this->mTitle->getText();
                     } else {
                         $sortkey = $this->mTitle->getPrefixedText();
                     }
                 } else {
                     $sortkey = $text;
                 }
                 $sortkey = Sanitizer::decodeCharReferences($sortkey);
                 $sortkey = str_replace("\n", '', $sortkey);
                 $sortkey = $wgContLang->convertCategoryKey($sortkey);
                 $this->mOutput->addCategory($nt->getDBkey(), $sortkey);
                 /**
                  * Strip the whitespace Category links produce, see bug 87
                  * @todo We might want to use trim($tmp, "\n") here.
                  */
                 $s .= trim($prefix . $trail, "\n") == '' ? '' : $prefix . $trail;
                 wfProfileOut("{$fname}-category");
                 continue;
             }
         }
         if ($nt->getPrefixedText() === $selflink && $nt->getFragment() === '') {
             # Self-links are handled specially; generally de-link and change to bold.
             $s .= $prefix . $sk->makeSelfLinkObj($nt, $text, '', $trail);
             continue;
         }
         # Special and Media are pseudo-namespaces; no pages actually exist in them
         if ($ns == NS_MEDIA) {
             $link = $sk->makeMediaLinkObj($nt, $text);
             # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
             $s .= $prefix . $this->armorLinks($link) . $trail;
             $this->mOutput->addImage($nt->getDBkey());
             continue;
         } elseif ($ns == NS_SPECIAL) {
             $s .= $this->makeKnownLinkHolder($nt, $text, '', $trail, $prefix);
             continue;
         } elseif ($ns == NS_IMAGE) {
             $img = new Image($nt);
             if ($img->exists()) {
                 // Force a blue link if the file exists; may be a remote
                 // upload on the shared repository, and we want to see its
                 // auto-generated page.
                 $s .= $this->makeKnownLinkHolder($nt, $text, '', $trail, $prefix);
                 $this->mOutput->addLink($nt);
                 continue;
             }
         }
         $s .= $this->makeLinkHolder($nt, $text, '', $trail, $prefix);
     }
     wfProfileOut($fname);
     return $s;
 }
Example #12
0
 public function showAdminElements($userKey)
 {
     $this->tmpl->assign('key', $_GET['key']);
     $this->tmpl->addSubtemplate('editAndDelete');
     if (Image::exists($this->bookId)) {
         $this->tmpl->addSubtemplate('imgDeleteButton');
     } elseif (Image::uploadable()) {
         $this->tmpl->addSubtemplate('imgUploadButton');
     }
     if (isset($_GET['new'])) {
         $this->tmpl->addSubtemplate('messageNew');
     }
     if (isset($_GET['renew'])) {
         if ($_GET['renew']) {
             $this->tmpl->addSubtemplate('messageRenewed');
         } else {
             $this->tmpl->addSubtemplate('messageNotRenewed');
         }
     }
     if (isset($_GET['uploaded'])) {
         $this->tmpl->addSubtemplate('messageUploaded');
     }
 }
 /**
  * If an exact title match can be find, or a very slightly close match,
  * return the title. If no match, returns NULL.
  *
  * @static
  * @param string $term
  * @return Title
  * @private
  */
 function getNearMatch($searchterm)
 {
     global $wgContLang;
     $allSearchTerms = array($searchterm);
     if ($wgContLang->hasVariants()) {
         $allSearchTerms = array_merge($allSearchTerms, $wgContLang->convertLinkToAllVariants($searchterm));
     }
     foreach ($allSearchTerms as $term) {
         # Exact match? No need to look further.
         $title = Title::newFromText($term);
         if (is_null($title)) {
             return NULL;
         }
         if ($title->getNamespace() == NS_SPECIAL || $title->exists()) {
             return $title;
         }
         # Now try all lower case (i.e. first letter capitalized)
         #
         $title = Title::newFromText($wgContLang->lc($term));
         if ($title->exists()) {
             return $title;
         }
         # Now try capitalized string
         #
         $title = Title::newFromText($wgContLang->ucwords($term));
         if ($title->exists()) {
             return $title;
         }
         # Now try all upper case
         #
         $title = Title::newFromText($wgContLang->uc($term));
         if ($title->exists()) {
             return $title;
         }
         # Now try Word-Caps-Breaking-At-Word-Breaks, for hyphenated names etc
         $title = Title::newFromText($wgContLang->ucwordbreaks($term));
         if ($title->exists()) {
             return $title;
         }
         global $wgCapitalLinks, $wgContLang;
         if (!$wgCapitalLinks) {
             // Catch differs-by-first-letter-case-only
             $title = Title::newFromText($wgContLang->ucfirst($term));
             if ($title->exists()) {
                 return $title;
             }
             $title = Title::newFromText($wgContLang->lcfirst($term));
             if ($title->exists()) {
                 return $title;
             }
         }
     }
     $title = Title::newFromText($searchterm);
     # Entering an IP address goes to the contributions page
     if ($title->getNamespace() == NS_USER && User::isIP($title->getText()) || User::isIP(trim($searchterm))) {
         return SpecialPage::getTitleFor('Contributions', $title->getDbkey());
     }
     # Entering a user goes to the user page whether it's there or not
     if ($title->getNamespace() == NS_USER) {
         return $title;
     }
     # Go to images that exist even if there's no local page.
     # There may have been a funny upload, or it may be on a shared
     # file repository such as Wikimedia Commons.
     if ($title->getNamespace() == NS_IMAGE) {
         $image = new Image($title);
         if ($image->exists()) {
             return $title;
         }
     }
     # MediaWiki namespace? Page may be "implied" if not customized.
     # Just return it, with caps forced as the message system likes it.
     if ($title->getNamespace() == NS_MEDIAWIKI) {
         return Title::makeTitle(NS_MEDIAWIKI, $wgContLang->ucfirst($title->getText()));
     }
     # Quoted term? Try without the quotes...
     $matches = array();
     if (preg_match('/^"([^"]+)"$/', $searchterm, $matches)) {
         return SearchEngine::getNearMatch($matches[1]);
     }
     return NULL;
 }
Example #14
0
/**
 * Callback function that converts BibTeX text pasted into wiki into
 * an HTML table, which can then be imported by Exhibit using the 
 * Exhibit Extension for Mediawiki. See Parse_Entries.php for proper credit to author.
 * @param {String} $input This is the text the user enters ino the wikitext input box.
 */
function bibtexToHTMLTable($input, $argv)
{
    include "Parse_Entries.php";
    try {
        if ($argv["file"]) {
            $file = $argv["file"];
            if (preg_match("@^http://@", $file)) {
                // get a remote url via fopen
                $fp = @fopen($file, "r");
                if ($fp) {
                    $input .= stream_get_contents($fp);
                    fclose($fp);
                }
            } else {
                // treat as an uploaded file on the wiki
                $image = new Image(Title::makeTitle(NS_IMAGE, $file));
                if ($image->exists()) {
                    $input .= file_get_contents($image->getImagePath());
                }
            }
        }
        //Use the bibtex parser to get arrays from the bibtex in the <bibtex> tags.
        $parse = new PARSEENTRIES();
        $parse->loadBibtexString($input);
        $parse->extractEntries();
        list($preamble, $strings, $entries, $undefinedStrings) = $parse->returnArrays();
        //Find all the fields in these bibtex entries:
        $fields = array();
        foreach ($entries as $entry) {
            $thekeys = array_keys($entry);
            foreach ($thekeys as $key) {
                array_push($fields, $key);
            }
        }
        $fields = array_unique($fields);
        //Make sure bibtexCitation is first field, since it must be unique, makes
        //table look better. Find where it is now, and switch with what's there.
        reset($fields);
        $count = 0;
        while ($thekey = current($fields)) {
            if ($thekey == "bibtexCitation") {
                break;
            } else {
                $count++;
                next($fields);
            }
        }
        $tempval = $fields[0];
        $fields[0] = "bibtexCitation";
        $fields[$count] = $tempval;
        //Construct table header with these fields.
        $output = '<table id="bibtextable"><tr>';
        foreach ($fields as $field) {
            if ($field == "bibtexCitation") {
                $output .= "\n<th ex:name=\"label\">{$field}</th>";
            } else {
                $output .= "\n<th ex:name=\"{$field}\">{$field}</th>";
            }
        }
        $output .= "</tr>\n";
        //Fill in rest of table, with fields in right column.
        foreach ($entries as $entry) {
            $output .= "<tr>";
            foreach ($fields as $field) {
                if (array_key_exists($field, $entry)) {
                    if ($field == "author") {
                        $entry[$field] = str_replace(" and ", " ; ", $entry[$field]);
                    }
                    $output .= "<td>{$entry[$field]}</td>";
                } else {
                    $output .= "<td></td>";
                }
            }
            $output .= "</tr>\n";
        }
        $output .= "</table>";
        //Give a reasonable default lens.
        //$output .= '<div ex:role="exhibit-lens" ex:itemTypes="Publication" class="publication-lens"  style="display: none"> <span ex:control="copy-button" class="copy-button"></span> <div><span class="publication-title" ex:content=".label"></span><i ex:if-exists=".venue"><span ex:content=".venue"></span>, </i> <i ex:if-exists=".event"><span ex:content=".event"></span>, </i> <span ex:content=".year"></span>.  <span ex:if-exists=".status">(<span ex:content=".status"></span>)</span> </div> <div class="authors" ex:content=".author"></div> <div ex:if-exists=".abstract" class="abstract" ex:content=".abstract"></div> <div ex:if-exists=".excerpt" class="excerpt" ex:content=".excerpt"></div> <div class="downloads"> <a ex:if-exists=".url" ex:href-content=".url">[Source]</a> <a ex:if-exists=".talkURL" ex:href-content=".talkURL">[Talk Video]</a> <a ex:if-exists=".screencastURL" ex:href-content=".screencastURL">[Screencast <span ex:content=".screencastKB"></span> KB]</a> <a ex:if-exists=".pdfURL" ex:href-content=".pdfURL">[PDF <span ex:content=".pdfKB"></span> KB]</a> <a ex:if-exists=".pptURL" ex:href-content=".pptURL">[PowerPoint <span ex:content=".pptKB"></span> KB]</a> <a ex:if-exists=".psURL" ex:href-content=".psURL">[PS <span ex:content=".psKB"></span> KB]</a> </div> </div>';
        $output .= '<div ex:role="exhibit-lens" style="display:none"> <div> <div style="font-size:120%; font-style:italic"> <span ex:content=".title"></span> </div> <div> Authors: <span ex:content=".author"></span>, <span ex:content=".year" style="font-size: 80%; font-weight:bold"></span>.  </div> </div> <div><a ex:if-exists=".pdfurl" ex:href-content=".pdfurl">[PDF <span ex:content=".pdfkb"></span> KB]</a> </div>';
    } catch (Exception $e) {
        $output = "Error in Bibtex";
    }
    return $output;
}