function getImagePage($filename)
 {
     $title = Title::makeTitleSafe(NS_FILE, $filename);
     $file = $this->dataFile($filename);
     $iPage = new ImagePage($title);
     $iPage->setFile($file);
     return $iPage;
 }
 /**
  * @param ImagePage $imagePage
  */
 public function __construct($imagePage)
 {
     global $wgShowArchiveThumbnails;
     $this->current = $imagePage->getPage()->getFile();
     $this->img = $imagePage->getDisplayedFile();
     $this->title = $imagePage->getTitle();
     $this->imagePage = $imagePage;
     $this->showThumb = $wgShowArchiveThumbnails && $this->img->canRender();
     $this->setContext($imagePage->getContext());
 }
 /**
  * @param ImagePage $imagePage
  */
 function __construct($imagePage)
 {
     parent::__construct($imagePage->getContext());
     $this->mImagePage = $imagePage;
     $this->mTitle = clone $imagePage->getTitle();
     $this->mTitle->setFragment('#filehistory');
     $this->mImg = null;
     $this->mHist = array();
     $this->mRange = array(0, 0);
     // display range
 }
Example #4
0
 public function getDuplicates()
 {
     wfProfileIn(__METHOD__);
     $img = $this->getDisplayedFile();
     $handler = $img->getHandler();
     if ($handler instanceof VideoHandler && $handler->isBroken()) {
         wfProfileOut(__METHOD__);
         return $this->dupes = array();
     } else {
         $dupes = parent::getDuplicates();
         $finalDupes = array();
         foreach ($dupes as $dupe) {
             if (WikiaFileHelper::isFileTypeVideo($dupe) && $dupe instanceof WikiaLocalFile) {
                 if ($dupe->getProviderName() != $img->getProviderName()) {
                     continue;
                 }
                 if ($dupe->getVideoId() != $img->getVideoId()) {
                     continue;
                 }
                 $finalDupes[] = $dupe;
             }
         }
         wfProfileOut(__METHOD__);
         return $finalDupes;
     }
 }
Example #5
0
 public function doDelete($reason)
 {
     wfRunHooks('ImageDoDeleteBegin', array(&$this, &$reason));
     // there is no return code at the moment
     /*$ret = */
     parent::doDelete($reason);
     wfRunHooks('ImageDoDeleteEnd', array(&$this, &$reason));
     /*return $ret;*/
 }
 /**
  * change title tag for Video Page and Image Page
  * @author Jacek Jursza
  * @param ImagePage $imgPage
  * @param $html
  * @return bool
  */
 static function onImagePageAfterImageLinks($imgPage, $html)
 {
     $file = $imgPage->getDisplayedFile();
     /* @var $file LocalRepo */
     $title = $imgPage->getTitle();
     /* @var $title Title */
     $newTitle = '';
     if (!empty($file) && !empty($title) && !F::app()->checkSkin('monobook')) {
         if ((new WikiaFileHelper())->isFileTypeVideo($file)) {
             $newTitle = wfMsg('seotweaks-video') . ' - ' . $title->getBaseText();
         } else {
             // It's not Video so lets check if it is Image
             if ($file instanceof LocalFile && $file->getHandler() instanceof BitmapHandler) {
                 $newTitle = wfMsg('seotweaks-image') . ' - ' . $title->getBaseText();
             }
         }
         if (!empty($newTitle)) {
             F::app()->wg->Out->setPageTitle($newTitle);
         }
     }
     return true;
 }
function efImageReviewDisplayStatus(ImagePage $imagePage, &$html)
{
    global $wgCityId, $wgExternalDatawareDB, $wgUser;
    if (!$wgUser->isAllowed('imagereviewstats')) {
        return true;
    }
    if (!$imagePage->getTitle()->exists()) {
        return true;
    }
    $html .= Xml::element('h2', array(), wfMsg('imagereview-imagepage-header'));
    $reviews = array();
    $headers = array(wfMessage('imagereview-imagepage-table-header-reviewer')->text(), wfMessage('imagereview-imagepage-table-header-state')->text(), wfMessage('imagereview-imagepage-table-header-time')->text());
    $where = array('wiki_id' => $wgCityId, 'page_id' => $imagePage->getId());
    $dbr = wfGetDB(DB_SLAVE, array(), $wgExternalDatawareDB);
    $res = $dbr->select('image_review_stats', '*', $where);
    if ($dbr->numRows($res) == 0) {
        //check if image is in the queue at all!
        $imgCurState = $dbr->selectField('image_review', 'state', $where);
        if (false === $imgCurState) {
            /**
             * If the file is a local one and is older than 1 hour - send it to ImageReview
             * since it's probably been restored, and is not just a fresh file.
             */
            $lastTouched = new DateTime($imagePage->getRevisionFetched()->getTimestamp());
            $now = new DateTime();
            $file = $imagePage->getDisplayedFile();
            if ($file instanceof WikiaLocalFile && $lastTouched < $now->modify('-1 hour')) {
                $scribeEventProducer = new ScribeEventProducer('edit');
                $user = User::newFromName($file->getUser());
                if ($scribeEventProducer->buildEditPackage($imagePage, $user, null, null, $file)) {
                    $logParams = ['cityId' => $wgCityId, 'pageId' => $imagePage->getID(), 'pageTitle' => $imagePage->getTitle()->getText(), 'uploadUser' => $user->getName()];
                    \Wikia\Logger\WikiaLogger::instance()->info('ImageReviewLog', ['message' => 'Image moved back to queue', 'params' => $logParams]);
                    $scribeEventProducer->sendLog();
                }
            }
            // oh oh, image is not in queue at all
            $html .= wfMsg('imagereview-imagepage-not-in-queue');
        } else {
            // image is in the queue but not reviewed yet
            $html .= wfMsg('imagereview-state-0');
        }
    } else {
        // go through the list and display review states
        while ($row = $dbr->fetchObject($res)) {
            $data = array();
            $data[] = User::newFromId($row->reviewer_id)->getName();
            $data[] = wfMsg('imagereview-state-' . $row->review_state);
            $data[] = $row->review_end . ' (UTC)';
            $reviews[] = $data;
        }
        $html .= Xml::buildTable($reviews, array('class' => 'wikitable filehistory sortable', 'style' => 'width: 60%'), $headers);
    }
    return true;
}
 /**
  * Initializes required fields.
  */
 private function initFields()
 {
     if ($this->oUser === null) {
         throw new BsException(__METHOD__ . ' - No user specified.');
     }
     $this->sUserDisplayName = BsCore::getInstance()->getUserDisplayName($this->oUser);
     $sUserImage = $this->oUser->getOption('MW::UserImage', '');
     //BsConfig::get() won't work on first call
     //Is it a URL? Some external image?
     $aParsedUrl = parse_url($sUserImage);
     if (!empty($sUserImage) && ($sUserImage[0] == '/' || isset($aParsedUrl['scheme']))) {
         $this->sImageUploadPath = SpecialPage::getTitleFor('Preferences')->getLinkUrl();
         $aPathInfo = pathinfo($aParsedUrl['path']);
         $aFileExtWhitelist = array('gif', 'jpg', 'jpeg', 'png');
         $this->sImagePath = $aParsedUrl['scheme'] . '://' . $aParsedUrl['host'] . $aParsedUrl['path'];
         if (!in_array(strtolower($aPathInfo['extension']), $aFileExtWhitelist)) {
             $this->sImagePath = BsConfig::get('MW::AnonUserImage');
         }
         return;
     }
     $oUserImageFile = RepoGroup::singleton()->getLocalRepo()->newFile($sUserImage);
     if ($oUserImageFile) {
         $UserImageArticle = new ImagePage($oUserImageFile->getTitle());
         $this->sImageUploadPath = $UserImageArticle->getUploadUrl();
         if ($oUserImageFile->exists() === false) {
             $this->sImagePath = BsConfig::get('MW::DefaultUserImage');
         } else {
             $oUserThumbnail = $oUserImageFile->transform(array('width' => 64, 'height' => 64));
             if ($oUserThumbnail !== false) {
                 $this->sImagePath = $oUserThumbnail->getUrl();
             } else {
                 $this->sImagePath = $oUserImageFile->getUrl();
             }
         }
     } else {
         $this->sImagePath = BsConfig::get('MW::DefaultUserImage');
     }
 }
Example #9
0
 /**
  * @return String Url where user can re-upload the file
  */
 public function getUploadUrl()
 {
     wfProfileIn(__METHOD__);
     if ($this->isVideo()) {
         $this->loadFile();
         $file = $this->getDisplayedFile();
         $uploadTitle = SpecialPage::getTitleFor('WikiaVideoAdd');
         $name = $file->getName();
         $url = $uploadTitle->getFullUrl(array('name' => $name));
     } else {
         $url = parent::getUploadUrl();
     }
     wfProfileOut(__METHOD__);
     return $url;
 }
Example #10
0
 /**
  * Resolves the url of images provided as wiki page; leaves others alone.
  * 
  * @since 1.0
  * 
  * @param string $file
  * 
  * @return string
  */
 public static function getFileUrl($file)
 {
     $title = Title::newFromText($file, NS_FILE);
     if (!is_null($title) && $title->getNamespace() == NS_FILE && $title->exists()) {
         $imagePage = new ImagePage($title);
         $file = $imagePage->getDisplayedFile()->getURL();
     }
     return $file;
 }
	/**
	 * Fills the $markerData array with the locations and their meta data.
	 *
	 * @param unknown_type $parser
	 */
	private function setMarkerData( $parser ) {
		$this->coordinates = explode( ';', $this->coordinates );
		
		$this->title = Xml::escapeJsString( $parser->recursiveTagParse( $this->title ) );
		$this->label = Xml::escapeJsString( $parser->recursiveTagParse( $this->label ) );
		
		foreach ( $this->coordinates as $coordinates ) {
			$args = explode( '~', $coordinates );
			
			$markerData = array( 'location' => $args[0] );
			
			if ( count( $args ) > 1 ) {
				// Parse and add the point specific title if it's present.
				$markerData['title'] = $parser->recursiveTagParse( $args[1] );
				
				if ( count( $args ) > 2 ) {
					// Parse and add the point specific label if it's present.
					$markerData['label'] = $parser->recursiveTagParse( $args[2] );
					
					if ( count( $args ) > 3 ) {
						// Add the point specific icon if it's present.
						$markerData['icon'] = $args[3];
					}
				}
			}
			
			// If there is no point specific icon, use the general icon parameter when available.
			if ( ! array_key_exists( 'icon', $markerData ) && strlen( $this->icon ) > 0 ) $markerData['icon'] = $this->icon;
			
			// Get the url for the icon when there is one, else set the icon to an empty string.
			if ( array_key_exists( 'icon', $markerData ) ) {
				$icon_image_page = new ImagePage( Title::newFromText( $markerData['icon'] ) );
				$markerData['icon'] = $icon_image_page->getDisplayedFile()->getURL();
			}
			else {
				$markerData['icon'] = '';
			}
			
			$this->markerData[] = $markerData;
		}
	}
 /**
  * @static
  * @param Title $fileTitle
  * @param array $config ( contextWidth, contextHeight, imageMaxWidth, userAvatarWidth )
  * TODO - this method is very specific to lightbox.  This needs to be refactored back out to lightbox, and return just the basic objects (file, user, tect)
  * @return array
  */
 public static function getMediaDetail($fileTitle, $config = array())
 {
     $data = array('mediaType' => '', 'videoEmbedCode' => '', 'playerAsset' => '', 'imageUrl' => '', 'fileUrl' => '', 'rawImageUrl' => '', 'description' => '', 'userThumbUrl' => '', 'userId' => '', 'userName' => '', 'userPageUrl' => '', 'articles' => array(), 'providerName' => '', 'videoViews' => 0, 'exists' => false, 'isAdded' => true, 'extraHeight' => 0);
     if (!empty($fileTitle)) {
         if ($fileTitle->getNamespace() != NS_FILE) {
             $fileTitle = Title::newFromText($fileTitle->getDBKey(), NS_FILE);
         }
         $file = self::getFileFromTitle($fileTitle, true);
         if (!empty($file)) {
             $config = self::getMediaDetailConfig($config);
             $data['exists'] = true;
             $data['mediaType'] = self::isFileTypeVideo($file) ? 'video' : 'image';
             $width = (int) $file->getWidth();
             $height = (int) $file->getHeight();
             if ($data['mediaType'] == 'video') {
                 $width = $config['contextWidth'] ? $config['contextWidth'] : $width;
                 $height = $config['contextHeight'] ? $config['contextHeight'] : $height;
                 if (isset($config['maxHeight'])) {
                     $file->setEmbedCodeMaxHeight($config['maxHeight']);
                 }
                 $options = ['autoplay' => true, 'isAjax' => true, 'isInline' => !empty($config['isInline'])];
                 $data['videoEmbedCode'] = $file->getEmbedCode($width, $options);
                 $data['playerAsset'] = $file->getPlayerAssetUrl();
                 $data['videoViews'] = MediaQueryService::getTotalVideoViewsByTitle($fileTitle->getDBKey());
                 $data['providerName'] = $file->getProviderName();
                 $data['duration'] = $file->getMetadataDuration();
                 $data['isAdded'] = self::isAdded($file);
                 $mediaPage = self::getMediaPage($fileTitle);
                 // Extra height is needed for lightbox when more elements must be fitted
                 if (strtolower($data['providerName']) == 'crunchyroll') {
                     $data['extraHeight'] = CrunchyrollVideoHandler::CRUNCHYROLL_WIDGET_HEIGHT_PX;
                 }
             } else {
                 $width = !empty($config['imageMaxWidth']) ? min($config['imageMaxWidth'], $width) : $width;
                 $mediaPage = new ImagePage($fileTitle);
             }
             $thumb = $file->transform(array('width' => $width, 'height' => $height), 0);
             $user = User::newFromId($file->getUser('id'));
             // get article list
             $mediaQuery = new ArticlesUsingMediaQuery($fileTitle);
             $articleList = $mediaQuery->getArticleList();
             if ($data['isAdded']) {
                 $data['fileUrl'] = $fileTitle->getFullUrl();
             } else {
                 $data['fileUrl'] = self::getFullUrlPremiumVideo($fileTitle->getDBkey());
             }
             $data['imageUrl'] = $thumb->getUrl();
             $data['rawImageUrl'] = $file->getUrl();
             $data['userId'] = $user->getId();
             $data['userName'] = $user->getName();
             $data['userThumbUrl'] = AvatarService::getAvatarUrl($user, $config['userAvatarWidth']);
             $data['userPageUrl'] = $user->getUserPage()->getFullURL();
             $data['description'] = $mediaPage->getContent();
             $data['articles'] = $articleList;
             $data['width'] = $width;
             $data['height'] = $height;
         }
     }
     return $data;
 }
Example #13
0
	/**
	 * Shortcut to get the Title object from the page
	 * @return Title
	 */
	final public function getTitle() {
		return $this->page->getTitle();
	}
 public static function SetApprovedFileInDB($title, $timestamp, $sha1)
 {
     $dbr = wfGetDB(DB_MASTER);
     $file_title = $title->getDBkey();
     $old_file_title = $dbr->selectField('approved_revs_files', 'file_title', array('file_title' => $file_title));
     if ($old_file_title) {
         $dbr->update('approved_revs_files', array('approved_timestamp' => $timestamp, 'approved_sha1' => $sha1), array('file_title' => $file_title));
     } else {
         $dbr->insert('approved_revs_files', array('file_title' => $file_title, 'approved_timestamp' => $timestamp, 'approved_sha1' => $sha1));
     }
     // Update "cache" in memory
     self::$mApprovedFileInfo[$file_title] = array($timestamp, $sha1);
     $log = new LogPage('approval');
     $imagepage = ImagePage::newFromID($title->getArticleID());
     $display_file_url = $imagepage->getDisplayedFile()->getFullURL();
     // $url = $title->getDisplayedFile()->getFullURL(); // link to the imagepage, or directly to the approved file?
     // $url = $file_obj->getFullURL();
     $rev_link = Xml::element('a', array('href' => $display_file_url, 'title' => 'unique identifier: ' . $sha1), substr($sha1, 0, 8));
     $logParams = array($rev_link);
     $log->addEntry('approve', $title, '', $logParams);
     // Run this hook like for 'approve', create new hook, or do nothing?
     // wfRunHooks( 'ApprovedRevsRevisionApproved', array( $parser, $title, $rev_id ) );
 }
Example #15
0
 public function setProperty($name, $value)
 {
     global $egMultiMaps_CoordinatesSeparator, $egMultiMaps_OptionsSeparator;
     if (strtolower($name) != 'icon') {
         return parent::setProperty($name, $value);
     }
     // Explode icon, it containt 'icon', 'size', 'anchor', 'shadow', 'shSize', 'shAnchor'
     $properties = array_map('trim', explode($egMultiMaps_CoordinatesSeparator, $value));
     // Icon URL
     if (!empty($properties[0])) {
         $v = $properties[0];
         if ($v[0] == '/' && $GLOBALS['egMultiMaps_IconAllowFromDirectory'] === true) {
             if (preg_match('#[^0-9a-zA-Zа-яА-Я/_=\\.\\+\\-]#', $v) || mb_strpos($v, '/../') !== false) {
                 $this->errormessages[] = \wfMessage('multimaps-marker-incorrect-icon-url', $v)->escaped();
                 return false;
             }
             $v = $GLOBALS['wgServer'] . $GLOBALS['egMultiMaps_IconPath'] . $v;
         } else {
             $title = \Title::newFromText($v, NS_FILE);
             if (!is_null($title) && $title->exists()) {
                 $imagePage = new \ImagePage($title);
                 $v = $imagePage->getDisplayedFile()->getURL();
             } else {
                 $this->errormessages[] = \wfMessage('multimaps-marker-incorrect-icon', $v)->escaped();
                 return false;
             }
         }
         $this->properties['icon'] = htmlspecialchars($v, ENT_NOQUOTES);
     }
     // Icon size
     if (!empty($properties[1])) {
         $v = array_map('intval', explode($egMultiMaps_OptionsSeparator, $properties[1]));
         if (count($v) != 2) {
             $this->errormessages[] = \wfMessage('multimaps-marker-incorrect-icon-size', $v, $value)->escaped();
             return false;
         }
         $this->properties['size'] = $v;
     }
     // Icon anchor
     if (!empty($properties[2])) {
         $v = array_map('intval', explode($egMultiMaps_OptionsSeparator, $properties[2]));
         if (count($v) != 2) {
             $this->errormessages[] = \wfMessage('multimaps-marker-incorrect-icon-anchor', $v, $value)->escaped();
             return false;
         }
         $this->properties['anchor'] = $v;
     }
     // Shadow URL
     if (!empty($properties[3])) {
         $v = $properties[3];
         if ($v[0] == '/' && $GLOBALS['egMultiMaps_IconAllowFromDirectory'] === true) {
             if (preg_match('#[^0-9a-zA-Zа-яА-Я./_=\\+\\-]#', $v) || preg_match('#/../#', $v)) {
                 $this->errormessages[] = \wfMessage('multimaps-marker-incorrect-shadow-url', $v)->escaped();
                 return false;
             }
             $v = $GLOBALS['wgServer'] . $GLOBALS['egMultiMaps_IconPath'] . $v;
         } else {
             $title = \Title::newFromText($v, NS_FILE);
             if (!is_null($title) && $title->exists()) {
                 $imagePage = new \ImagePage($title);
                 $v = $imagePage->getDisplayedFile()->getURL();
             } else {
                 $this->errormessages[] = \wfMessage('multimaps-marker-incorrect-shadow-file', $v)->escaped();
                 return false;
             }
         }
         $this->properties['shadow'] = htmlspecialchars($v, ENT_NOQUOTES);
     }
     // Shadow size
     if (!empty($properties[4])) {
         $v = array_map('intval', explode($egMultiMaps_OptionsSeparator, $properties[4]));
         if (count($v) != 2) {
             $this->errormessages[] = \wfMessage('multimaps-marker-incorrect-shadow-size', $v, $value)->escaped();
             return false;
         }
         $this->properties['shSize'] = $v;
     }
     // Shadow anchor
     if (!empty($properties[5])) {
         $v = array_map('intval', explode($egMultiMaps_OptionsSeparator, $properties[5]));
         if (count($v) != 2) {
             $this->errormessages[] = \wfMessage('multimaps-marker-incorrect-shadow-anchor', $v, $value)->escaped();
             return false;
         }
         $this->properties['shAnchor'] = $v;
     }
     return true;
 }
Example #16
0
 /**
  * Pushes the image to the specified wiki.
  *
  * @since 0.5
  *
  * @param Title $title
  * @param string $target
  * @param string $token
  */
 protected function pushToTarget(Title $title, $target, $token)
 {
     global $egPushDirectFileUploads;
     $imagePage = new ImagePage($title);
     $requestData = array('action' => 'upload', 'format' => 'json', 'token' => $token, 'filename' => $title->getText(), 'ignorewarnings' => '1');
     if ($egPushDirectFileUploads) {
         $requestData['file'] = '@' . $imagePage->getFile()->getPath();
     } else {
         $requestData['url'] = $imagePage->getDisplayedFile()->getFullUrl();
     }
     $reqArgs = array('method' => 'POST', 'timeout' => 'default', 'postData' => $requestData);
     if ($egPushDirectFileUploads) {
         if (!function_exists('curl_init')) {
             $this->dieUsage(wfMsg('push-api-err-nocurl'), 'image-push-nocurl');
         } elseif (!defined('CurlHttpRequest::SUPPORTS_FILE_POSTS') || !CurlHttpRequest::SUPPORTS_FILE_POSTS) {
             $this->dieUsage(wfMsg('push-api-err-nofilesupport'), 'image-push-nofilesupport');
         } else {
             $req = new CurlHttpRequest($target, $reqArgs);
         }
     } else {
         $req = PushFunctions::getHttpRequest($target, $reqArgs);
     }
     if (array_key_exists($target, $this->cookieJars)) {
         $req->setCookieJar($this->cookieJars[$target]);
     }
     $status = $req->execute();
     if ($status->isOK()) {
         $response = $req->getContent();
         $this->getResult()->addValue(null, null, FormatJson::decode($response));
         wfRunHooks('PushAPIAfterImagePush', array($title, $target, $token, $response));
     } else {
         $this->dieUsage(wfMsg('push-special-err-push-failed'), 'page-push-failed');
     }
 }
Example #17
0
 /**
  * Resolves the url of images provided as wiki page; leaves others alone.
  * 
  * @since 1.0
  * @deprecated
  * 
  * @param string $file
  * 
  * @return string
  */
 public static function getFileUrl($file)
 {
     $title = Title::makeTitle(NS_FILE, $file);
     if ($title !== null && $title->exists()) {
         $imagePage = new ImagePage($title);
         return $imagePage->getDisplayedFile()->getURL();
     }
     return '';
 }
 /**
  * @brief      Adds the properties, hooks into SMWStore::updateDataBefore.
  *
  * @param      SMWStore $store, SMWSemanticData $newData
  *
  * @return     true
  *
  */
 public function sespUpdateDataBefore($store, $data)
 {
     global $sespSpecialProperties, $wgDisableCounters;
     // just some compat mode
     global $smwgPageSpecialProperties2;
     if (isset($smwgPageSpecialProperties2) && !isset($sespSpecialProperties)) {
         $sespSpecialProperties = $smwgPageSpecialProperties2;
     }
     /* Get array of properties to set */
     if (!isset($sespSpecialProperties)) {
         wfDebug(__METHOD__ . ": SESP array is not specified, please add the following\n");
         wfDebug("variables to your LocalSettings.php:\n");
         wfDebug("\$sespSpecialProperties\n");
         return true;
     }
     /* Get current title and article */
     $title = $data->getSubject()->getTitle();
     $article = Article::newFromTitle($title, RequestContext::getMain());
     // return if $title or $article is null
     if (is_null($title) || is_null($article)) {
         return true;
     }
     /**************************/
     /* CUSER (First author)   */
     /**************************/
     if (in_array('_CUSER', $sespSpecialProperties)) {
         $firstRevision = $title->getFirstRevision();
         if ($firstRevision !== null) {
             $firstAuthor = User::newFromId($firstRevision->getRawUser());
             if ($firstAuthor) {
                 $property = new SMWDIProperty('___CUSER');
                 $dataItem = SMWDIWikiPage::newFromTitle($firstAuthor->getUserPage());
                 $data->addPropertyObjectValue($property, $dataItem);
             }
         }
     }
     // end if _CUSER
     /**************************/
     /* REVID (Revision ID)    */
     /**************************/
     if (in_array('_REVID', $sespSpecialProperties)) {
         $property = new SMWDIProperty('___REVID');
         $dataItem = new SMWDINumber($article->getRevIdFetched());
         $data->addPropertyObjectValue($property, $dataItem);
     }
     /********************************/
     /* VIEWS (Number of page views) */
     /********************************/
     if (in_array('_VIEWS', $sespSpecialProperties) && !$wgDisableCounters) {
         $property = new SMWDIProperty('___VIEWS');
         $dataItem = new SMWDINumber($article->getCount());
         $data->addPropertyObjectValue($property, $dataItem);
     }
     /*****************************/
     /* EUSER (Page contributors) */
     /*****************************/
     if (in_array('_EUSER', $sespSpecialProperties)) {
         /* Create property */
         $property = new SMWDIProperty('___EUSER');
         /* Get options */
         global $wgSESPExcludeBots;
         if (!isset($wgSESPExcludeBots)) {
             $wgSESPExcludeBots = false;
         }
         /* Get author from current revision */
         $u = User::newFromId($article->getUser());
         /* Get authors from earlier revisions */
         $authors = $article->getContributors();
         while ($u) {
             if (!$u->isHidden() && !(in_array('bot', $u->getRights()) && $wgSESPExcludeBots) && !$u->isAnon()) {
                 //no anonymous users
                 /* Add values*/
                 $dataItem = SMWDIWikiPage::newFromTitle($u->getUserPage());
                 $data->addPropertyObjectValue($property, $dataItem);
             }
             $u = $authors->current();
             $authors->next();
         }
     }
     /******************************/
     /* NREV (Number of revisions) */
     /******************************/
     if (in_array('_NREV', $sespSpecialProperties)) {
         /* Create property */
         $property = new SMWDIProperty('___NREV');
         /* Get number of revisions */
         $dbr =& wfGetDB(DB_SLAVE);
         $num = $dbr->estimateRowCount("revision", "*", array("rev_page" => $title->getArticleID()));
         /* Add values */
         $dataItem = new SMWDINumber($num);
         $data->addPropertyObjectValue($property, $dataItem);
     }
     /*****************************************/
     /* NTREV (Number of talk page revisions) */
     /*****************************************/
     if (in_array('_NTREV', $sespSpecialProperties)) {
         /* Create property */
         $property = new SMWDIProperty('___NTREV');
         /* Get number of revisions */
         if (!isset($dbr)) {
             $dbr =& wfGetDB(DB_SLAVE);
         }
         $talkPage = $title->getTalkPage();
         $num = $dbr->estimateRowCount("revision", "*", array("rev_page" => $talkPage->getArticleID()));
         /* Add values */
         $dataItem = new SMWDINumber($num);
         $data->addPropertyObjectValue($property, $dataItem);
     }
     /************************/
     /* SUBP (Get sub pages) */
     /************************/
     if (in_array('_SUBP', $sespSpecialProperties)) {
         /* Create property */
         $property = new SMWDIProperty('___SUBP');
         $subpages = $title->getSubpages(-1);
         //-1 = no limit. Returns TitleArray object
         /* Add values*/
         foreach ($subpages as $t) {
             $dataItem = SMWDIWikiPage::newFromTitle($t);
             $data->addPropertyObjectValue($property, $dataItem);
         }
         // end foreach
     }
     // end _SUBP
     /************************/
     /* MIMETYPE */
     /************************/
     if ($title->inNamespace(NS_FILE) && in_array('_MIMETYPE', $sespSpecialProperties)) {
         // Build image page instance
         $imagePage = new ImagePage($title);
         $file = $imagePage->getFile();
         $mimetype = $file->getMimeType();
         $mediaType = MimeMagic::singleton()->findMediaType($mimetype);
         list($mimetypemajor, $mimetypeminor) = $file->splitMime($mimetype);
         // MIMETYPE
         $property = new SMWDIProperty('___MIMETYPE');
         $dataItem = new SMWDIString($mimetypeminor);
         $data->addPropertyObjectValue($property, $dataItem);
         // MEDIATYPE
         $property = new SMWDIProperty('___MEDIATYPE');
         $dataItem = new SMWDIString($mediaType);
         $data->addPropertyObjectValue($property, $dataItem);
     }
     // end if MIMETYPE
     /************************/
     /* IMAGEMETA */
     /************************/
     function convertexifdate($exifString)
     {
         $exifPieces = explode(":", $exifString);
         if ($exifPieces[0] && $exifPieces[1] && $exifPieces[2]) {
             $res = new DateTime($exifPieces[0] . "-" . $exifPieces[1] . "-" . $exifPieces[2] . ":" . $exifPieces[3] . ":" . $exifPieces[4]);
             return $res;
         } else {
             return false;
         }
     }
     if ($title->inNamespace(NS_FILE) && in_array('_METADATA', $sespSpecialProperties)) {
         $imagePage = new ImagePage($title);
         $file = $imagePage->getFile();
         $metadata = $file->getMetadata();
         if ($metadata === ExifBitmapHandler::OLD_BROKEN_FILE || $metadata === ExifBitmapHandler::BROKEN_FILE) {
             // So we don't try and display metadata from PagedTiffHandler
             // for example when using InstantCommons.
             return true;
         }
         $exif = unserialize($metadata);
         if ($exif) {
             if (count($exif)) {
                 // EXIFDATETIME
                 if (array_key_exists('DateTimeOriginal', $exif) || array_key_exists('DateTime', $exif)) {
                     $property = new SMWDIProperty('___EXIFDATETIME');
                     if (array_key_exists('DateTimeOriginal', $exif)) {
                         $exifstr = $exif['DateTimeOriginal'];
                     } else {
                         $exifstr = $exif['DateTime'];
                     }
                     $datetime = convertexifdate($exifstr);
                     if ($datetime) {
                         $dataItem = new SMWDITime(SMWDITime::CM_GREGORIAN, $datetime->format('Y'), $datetime->format('n'), $datetime->format('j'), $datetime->format('G'), $datetime->format('i'));
                         $data->addPropertyObjectValue($property, $dataItem);
                     }
                 }
                 // EXIFSOFTWARE
                 if (array_key_exists('Software', $exif) || array_key_exists('metadata', $exif) && array_key_exists('Software', $exif['metadata'])) {
                     $str = array_key_exists('Software', $exif) ? $exif['Software'] : $exif['metadata']['Software'];
                     if (is_array($str)) {
                         $str = array_key_exists('x-default', $str) ? $str['x-default'] : $str[0];
                     }
                     if (!$str) {
                         return true;
                     }
                     $property = new SMWDIProperty('___EXIFSOFTWARE');
                     $dataItem = new SMWDIString($str);
                     $data->addPropertyObjectValue($property, $dataItem);
                 }
                 // EXIFLATLON
                 /*
                 //TODO
                      if ( array_key_exists( 'GPSLatitudeRef', $exif ) || array_key_exists( 'GPSLongitudeRef', $exif ) ) {
                      } */
                 //EXIFLATLON
             }
         }
     }
     //IMAGEMETA
     /************************/
     /* SHORTURL             */
     /************************/
     //FIXME handle internal and external links
     if (in_array('_SHORTURL', $sespSpecialProperties) && class_exists('ShortUrlUtils')) {
         global $wgShortUrlPrefix;
         if (!is_string($wgShortUrlPrefix)) {
             $urlPrefix = SpecialPage::getTitleFor('ShortUrl')->getFullUrl() . '/';
         } else {
             $urlPrefix = $wgShortUrlPrefix;
         }
         if (ShortUrlUtils::needsShortUrl($title)) {
             $shortId = ShortUrlUtils::encodeTitle($title);
             $shortURL = $urlPrefix . $shortId;
             $property = new SMWDIProperty('___SHORTURL');
             $dataItem = new SMWDIUri('http', $shortURL, '', '');
             $data->addPropertyObjectValue($property, $dataItem);
         } else {
         }
     }
     // end if SHORTURL
     return true;
 }
 /**
  * Get a Filepage as parsed HTML
  * @param Title $title
  * @return string
  */
 private function getFilePage(Title $title)
 {
     // HACK: HACK: HACK:
     $context = new DerivativeContext($this->getContext());
     $context->setTitle($title);
     $context->setOutput(new OutputPage($context));
     $page = new ImagePage($title);
     $page->setContext($context);
     // T123821: Without setting the wiki page on the derivative context,
     // DerivativeContext#getWikiPage will (eventually) fall back to
     // RequestContext#getWikiPage. Here, the request context is distinct from the
     // derivative context and deliberately constructed with a bad title in the prelude
     // of api.php.
     $context->setWikiPage($page->getPage());
     $page->view();
     $html = $context->getOutput()->getHTML();
     return $html;
 }
 public static function setApprovedFileInDB($title, $timestamp, $sha1)
 {
     $parser = new Parser();
     $parser->setTitle($title);
     $dbr = wfGetDB(DB_MASTER);
     $fileTitle = $title->getDBkey();
     $oldFileTitle = $dbr->selectField('approved_revs_files', 'file_title', array('file_title' => $fileTitle));
     if ($oldFileTitle) {
         $dbr->update('approved_revs_files', array('approved_timestamp' => $timestamp, 'approved_sha1' => $sha1), array('file_title' => $fileTitle));
     } else {
         $dbr->insert('approved_revs_files', array('file_title' => $fileTitle, 'approved_timestamp' => $timestamp, 'approved_sha1' => $sha1));
     }
     // Update "cache" in memory
     self::$mApprovedFileInfo[$fileTitle] = array($timestamp, $sha1);
     $log = new LogPage('approval');
     $imagepage = ImagePage::newFromID($title->getArticleID());
     $displayedFileUrl = $imagepage->getDisplayedFile()->getFullURL();
     $revisionAnchorTag = Xml::element('a', array('href' => $displayedFileUrl, 'title' => 'unique identifier: ' . $sha1), substr($sha1, 0, 8));
     $logParams = array($revisionAnchorTag);
     $log->addEntry('approve', $title, '', $logParams);
     wfRunHooks('ApprovedRevsFileRevisionApproved', array($parser, $title, $timestamp, $sha1));
 }
Example #21
0
 /**
  * Record a file upload in the upload log and the image table
  */
 function recordUpload2($oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null)
 {
     if (is_null($user)) {
         global $wgUser;
         $user = $wgUser;
     }
     $dbw = $this->repo->getMasterDB();
     $dbw->begin();
     if (!$props) {
         $props = $this->repo->getFileProps($this->getVirtualUrl());
     }
     if ($timestamp === false) {
         $timestamp = $dbw->timestamp();
     }
     $props['description'] = $comment;
     $props['user'] = $user->getId();
     $props['user_text'] = $user->getName();
     $props['timestamp'] = wfTimestamp(TS_MW, $timestamp);
     // DB -> TS_MW
     $this->setProps($props);
     # Delete thumbnails
     $this->purgeThumbnails();
     # The file is already on its final location, remove it from the squid cache
     SquidUpdate::purge(array($this->getURL()));
     # Fail now if the file isn't there
     if (!$this->fileExists) {
         wfDebug(__METHOD__ . ": File " . $this->getRel() . " went missing!\n");
         return false;
     }
     $reupload = false;
     # Test to see if the row exists using INSERT IGNORE
     # This avoids race conditions by locking the row until the commit, and also
     # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
     $dbw->insert('image', array('img_name' => $this->getName(), 'img_size' => $this->size, 'img_width' => intval($this->width), 'img_height' => intval($this->height), 'img_bits' => $this->bits, 'img_media_type' => $this->media_type, 'img_major_mime' => $this->major_mime, 'img_minor_mime' => $this->minor_mime, 'img_timestamp' => $timestamp, 'img_description' => $comment, 'img_user' => $user->getId(), 'img_user_text' => $user->getName(), 'img_metadata' => $this->metadata, 'img_sha1' => $this->sha1), __METHOD__, 'IGNORE');
     if ($dbw->affectedRows() == 0) {
         $reupload = true;
         # Collision, this is an update of a file
         # Insert previous contents into oldimage
         $dbw->insertSelect('oldimage', 'image', array('oi_name' => 'img_name', 'oi_archive_name' => $dbw->addQuotes($oldver), 'oi_size' => 'img_size', 'oi_width' => 'img_width', 'oi_height' => 'img_height', 'oi_bits' => 'img_bits', 'oi_timestamp' => 'img_timestamp', 'oi_description' => 'img_description', 'oi_user' => 'img_user', 'oi_user_text' => 'img_user_text', 'oi_metadata' => 'img_metadata', 'oi_media_type' => 'img_media_type', 'oi_major_mime' => 'img_major_mime', 'oi_minor_mime' => 'img_minor_mime', 'oi_sha1' => 'img_sha1'), array('img_name' => $this->getName()), __METHOD__);
         # Update the current image row
         $dbw->update('image', array('img_size' => $this->size, 'img_width' => intval($this->width), 'img_height' => intval($this->height), 'img_bits' => $this->bits, 'img_media_type' => $this->media_type, 'img_major_mime' => $this->major_mime, 'img_minor_mime' => $this->minor_mime, 'img_timestamp' => $timestamp, 'img_description' => $comment, 'img_user' => $user->getId(), 'img_user_text' => $user->getName(), 'img_metadata' => $this->metadata, 'img_sha1' => $this->sha1), array('img_name' => $this->getName()), __METHOD__);
     } else {
         # This is a new file
         # Update the image count
         $dbw->begin();
         $site_stats = $dbw->tableName('site_stats');
         $dbw->query("UPDATE {$site_stats} SET ss_images=ss_images+1", __METHOD__);
         $dbw->commit();
     }
     $descTitle = $this->getTitle();
     $article = new ImagePage($descTitle);
     $article->setFile($this);
     # Add the log entry
     $log = new LogPage('upload');
     $action = $reupload ? 'overwrite' : 'upload';
     $log->addEntry($action, $descTitle, $comment, array(), $user);
     if ($descTitle->exists()) {
         # Create a null revision
         $latest = $descTitle->getLatestRevID();
         $nullRevision = Revision::newNullRevision($dbw, $descTitle->getArticleId(), $log->getRcComment(), false);
         $nullRevision->insertOn($dbw);
         wfRunHooks('NewRevisionFromEditComplete', array($article, $nullRevision, $latest, $user));
         $article->updateRevisionOn($dbw, $nullRevision);
         # Invalidate the cache for the description page
         $descTitle->invalidateCache();
         $descTitle->purgeSquid();
     } else {
         # New file; create the description page.
         # There's already a log entry, so don't make a second RC entry
         # Squid and file cache for the description page are purged by doEdit.
         $article->doEdit($pageText, $comment, EDIT_NEW | EDIT_SUPPRESS_RC);
     }
     # Commit the transaction now, in case something goes wrong later
     # The most important thing is that files don't get lost, especially archives
     $dbw->commit();
     # Save to cache and purge the squid
     # We shall not saveToCache before the commit since otherwise
     # in case of a rollback there is an usable file from memcached
     # which in fact doesn't really exist (bug 24978)
     $this->saveToCache();
     # Hooks, hooks, the magic of hooks...
     wfRunHooks('FileUpload', array($this, $reupload, $descTitle->exists()));
     # Invalidate cache for all pages using this file
     $update = new HTMLCacheUpdate($this->getTitle(), 'imagelinks');
     $update->doUpdate();
     # Invalidate cache for all pages that redirects on this page
     $redirs = $this->getTitle()->getRedirectsHere();
     foreach ($redirs as $redir) {
         $update = new HTMLCacheUpdate($redir, 'imagelinks');
         $update->doUpdate();
     }
     return true;
 }
Example #22
0
 function __construct($image)
 {
     parent::__construct($image->getTitle());
     $this->img = $image;
 }
 /**
  * Get a Filepage as parsed HTML
  * @param Title $title
  * @return string
  */
 private function getFilePage(Title $title)
 {
     //HACK: HACK: HACK:
     $context = new DerivativeContext($this->getContext());
     $context->setTitle($title);
     $context->setOutput(new OutputPage($context));
     $page = new ImagePage($title);
     $page->setContext($context);
     $page->view();
     $html = $context->getOutput()->getHTML();
     return $html;
 }
Example #24
0
 static function getImageURL($image)
 {
     // stripe brackets... cant use them in the lookup
     $image = str_replace('[[', '', $image);
     $image = str_replace(']]', '', $image);
     // check to see if they passed in Image: or File: and add if needed
     if (stripos($image, 'Image:') === false && stripos($image, 'File:') === false) {
         $image = "File:" . $image;
     }
     $titleObj = Title::newFromText($image);
     if (!$titleObj) {
         return null;
     }
     if (!$titleObj->exists()) {
         return null;
     }
     $img = new ImagePage($titleObj);
     // we're good, return the URL
     return $img->getDisplayedFile()->getUrl();
 }