/**
     * Initialize SMWWriter for the page corresponding to title
     * in object variable
     * @param boolean $delete
     */
    private function initSMWWriter( $delete = false ) {
        // Create add and remove objects, to use in SMWWriter calls
		
        // TODO: Should rather use (but not possible with current SMWWriter API?):
    	// $page_di = SMWDIWikiPage::newFromTitle( Title::makeTitle($this->m_ns, $this->m_wikititle) );
    	$page = SMWWikiPageValue::makePage( $this->m_wikititle, $this->m_ns );
    	$page_di = $page->getDataItem(); 
    	$page_data = new SMWSemanticData( $page_di ); 
    	
    	$dummypage = SMWWikiPageValue::makePage( false, $this->m_ns );
    	$dummypage_di = $dummypage->getDataItem();
        $dummypag_data = new SMWSemanticData( $dummypage_di ); 
    	
        
        $this->m_smwwriter = new SMWWriter( $page->getTitle() );
        if ( $delete ) {
            $this->m_smwwriter_add    = $page_data;
            $this->m_smwwriter_remove = $dummypag_data;
        } else {
            $this->m_smwwriter_add    = $dummypag_data;
            $this->m_smwwriter_remove = $page_data;
        }
    }
示例#2
0
 public function getPropertySubjects(SMWDIProperty $property, $value, $requestoptions = null)
 {
     wfProfileIn("SMWSQLStoreLight::getPropertySubjects (SMW)");
     if ($property->isInverse()) {
         // inverses are working differently
         $noninverse = clone $property;
         $noninverse->setInverse(false);
         $result = $this->getPropertyValues($value, $noninverse, $requestoptions);
         wfProfileOut("SMWSQLStoreLight::getPropertySubjects (SMW)");
         return $result;
     }
     // ***  First build $select, $from, and $where for the DB query  ***//
     $tablename = SMWSQLStoreLight::findPropertyTableName($property);
     $db = wfGetDB(DB_SLAVE);
     $from = $db->tableName('page') . " AS p INNER JOIN " . $db->tableName($tablename) . " AS t ON t.pageid=p.page_id";
     $where = 't.propname=' . $db->addQuotes($property->getDBkey());
     if ($value !== null) {
         $valuestring = $tablename == 'smwsimple_special' ? reset($value->getDBkeys()) : serialize($value->getDBkeys());
         $where .= ' AND t.value=' . $db->addQuotes($valuestring);
     }
     $select = array('p.page_title AS title', 'p.page_namespace AS namespace');
     // ***  Now execute the query and read the results  ***//
     $result = array();
     $res = $db->select($from, $select, $where . $this->getSQLConditions($requestoptions, 'p.page_title', 'p.page_title'), 'SMW::getPropertySubjects', $this->getSQLOptions($requestoptions, 'p.page_title') + array('DISTINCT'));
     foreach ($res as $row) {
         $result[] = SMWWikiPageValue::makePage($row->title, $row->namespace, $row->title);
     }
     $db->freeResult($res);
     wfProfileOut("SMWSQLStoreLight::getPropertySubjects (SMW)");
     return $result;
 }
示例#3
0
文件: utils.php 项目: hala54/DSMW
    /**
     * Used to get properties (and/or) categories (and/or) templates (and/or)
     * linked with the given page(s)
     *
     * @param <String or array> $pages pagename
     * @param <bool> $properties True if you want to get the properties pages
     * @param <bool> $categories True if you want to get the categories pages
     * @param <bool> $templates True if you want to get the templates pages
     * @param <bool> $pagelinks True if you want to get the link pages
     * @return <array> $result An array of pages (cat, prop, templ or articles)
     */
    static function getDependencies($pages, $properties = true, $categories = false, $templates = false, $pagelinks = false)
    {
        $result = array();
        if (is_string($pages)) {
            $pages = array($pages);
        } elseif (!is_string($pages) && !is_array($pages)) {
            throw new MWException(__METHOD__ . ': $pages parameter is neither an
 array nor a string');
        }
        foreach ($pages as $page) {
            if ($properties) {
                // get the properties
                $title = Title::newFromText($page);
                $dbkey = $title->getDBkey();
                $namespace = $title->getNamespace();
                $value = SMWWikiPageValue::makePage($dbkey, $namespace);
                $data = smwfGetStore()->getSemanticData($value, false);
                // data instance of SMWSemanticData
                $props = $data->getProperties();
                foreach ($props as $property) {
                    if ($property->isUserDefined()) {
                        // user defined property
                        $property->setCaption(preg_replace('/[ ]/u', '&nbsp;', $property->getWikiValue(), 2));
                        if ($property->getWikiPageValue() != null) {
                            $obj = $property->getWikiPageValue();
                            $text = $obj->getPrefixedText();
                            $result[] = $text;
                        }
                    }
                }
            }
            if ($categories) {
                // get the categories
                $tables = array();
                $where = array();
                $fields = array('cl_from', 'cl_to');
                $options = array();
                $join_conds = array();
                $tables[] = 'categorylinks';
                $db = wfGetDB(DB_SLAVE);
                $pageid = $db->selectField('page', 'page_id', array('page_title' => $page));
                $where['cl_from'] = $pageid;
                $options['USE INDEX'] = array('categorylinks' => 'cl_from');
                $options['ORDER BY'] = 'cl_to';
                $res = $db->select($tables, $fields, $where, __METHOD__, $options, $join_conds);
                while ($row = $db->fetchObject($res)) {
                    $title = Title::makeTitle(NS_CATEGORY, $row->cl_to);
                    $pageName = $title->getPrefixedDBkey();
                    $result[] = $pageName;
                }
                $db->freeResult($res);
            }
            //end if categories
            if ($templates) {
                // get the templates
                $tables = array('templatelinks');
                $where = array();
                $options = array();
                $join_conds = array();
                $prefix = 'tl';
                $fields = array($prefix . '_from AS pl_from', $prefix . '_namespace AS pl_namespace', $prefix . '_title AS pl_title');
                $db = wfGetDB(DB_SLAVE);
                $pageid = $db->selectField('page', 'page_id', array('page_title' => $page));
                $where[$prefix . '_from'] = $pageid;
                //$this->addWhereFld($this->prefix . '_namespace', $params['namespace']);
                $options['ORDER BY'] = "{$prefix}_title";
                $options['USE INDEX'] = "{$prefix}_from";
                //$options['LIMIT'] = $params['limit'] + 1;
                $res = $db->select($tables, $fields, $where, __METHOD__, $options, $join_conds);
                while ($row = $db->fetchObject($res)) {
                    $title = Title::makeTitle($row->pl_namespace, $row->pl_title);
                    $pageName = $title->getPrefixedDBkey();
                    $result[] = $pageName;
                }
                $db->freeResult($res);
            }
            //end if templates
            if ($pagelinks) {
                // get the templates
                $tables = array('pagelinks');
                $where = array();
                $options = array();
                $join_conds = array();
                $prefix = 'pl';
                $fields = array($prefix . '_from AS pl_from', $prefix . '_namespace AS pl_namespace', $prefix . '_title AS pl_title');
                $db = wfGetDB(DB_SLAVE);
                $pageid = $db->selectField('page', 'page_id', array('page_title' => $page));
                $where[$prefix . '_from'] = $pageid;
                //$this->addWhereFld($this->prefix . '_namespace', $params['namespace']);
                $options['ORDER BY'] = "{$prefix}_title";
                $options['USE INDEX'] = "{$prefix}_from";
                //$options['LIMIT'] = $params['limit'] + 1;
                $res = $db->select($tables, $fields, $where, __METHOD__, $options, $join_conds);
                while ($row = $db->fetchObject($res)) {
                    $title = Title::makeTitle($row->pl_namespace, $row->pl_title);
                    $pageName = $title->getPrefixedDBkey();
                    $result[] = $pageName;
                }
                $db->freeResult($res);
            }
            //end if $pagelinks
        }
        //end foreach
        return $result;
    }
function renderFolkTagCloud($input, $args, $parser)
{
    # definition of variables
    $append = '';
    $count = 0;
    $max_tags = 1000;
    $min_count = 1;
    $increase_factor = 100;
    $min_font_size = 77;
    $font_size = 0;
    $htmlout = '';
    # disable cache
    $parser->disableCache();
    # not needed with searchlink data
    # build URL path
    # global $wgServer, $wgArticlePath;
    # $path = $wgServer . $wgArticlePath;
    # default tagging property
    $tag_name = 'FolkTag';
    # use a user-defined tagging property as default
    global $wgFTCTagName;
    if (isset($wgFTCTagName)) {
        $tag_name = $wgFTCTagName;
    }
    # use a user-defined tagging property for this tag cloud
    if (isset($args['property'])) {
        $tag_name = str_replace(' ', '_', ucfirst($args['property']));
    }
    # maximum of tags shown
    if (isset($args['maxtags'])) {
        $max_tags = intval($args['maxtags']);
    }
    # minimum frequency for tags to be shown
    if (isset($args['mincount'])) {
        $min_count = intval($args['mincount']);
    }
    # increase factor
    if (isset($args['increasefactor'])) {
        $increase_factor = intval($args['increasefactor']);
    }
    # minimum font size
    if (isset($args['minfontsize'])) {
        $min_font_size = intval($args['minfontsize']);
    }
    # get database
    $db =& wfGetDB(DB_SLAVE);
    $store = new SMWSQLStore2();
    extract($db->tableNames('categorylinks', 'page'));
    # make tagging property an SMWPorpertyValue in order to access store
    $property = SMWPropertyValue::makeProperty($tag_name);
    # initialising result arrays
    $values = array();
    $result = array();
    $links = array();
    # if there is no filter category:
    if ($input == NULL) {
        $values = ft_getPropertyValues($property, $store);
        # $values = $store->getPropertyValues(NULL, $property);
    } else {
        $categories = explode(',', $input);
        # include subcategories:
        if (isset($args['subcategorylevel'])) {
            $subcategories = array();
            foreach ($categories as $category) {
                $subcategories = array_merge($subcategories, getSubCategories($category, intval($args['subcategorylevel'])));
            }
            $categories = array_merge($categories, $subcategories);
        }
        # start building sql
        $sql = "SELECT page_title, page_namespace\n\t\t\t\tFROM {$page}\n\t\t\t\tINNER JOIN {$categorylinks}\n\t\t\t\tON {$page}.page_id = {$categorylinks}.cl_from\n\t\t\t\tAND (";
        # disjunction of filter categories
        foreach ($categories as $category) {
            $category = trim($category);
            $category = str_replace(' ', '_', $category);
            $category = str_replace("'", "\\'", $category);
            $sql .= "{$categorylinks}.cl_to = '{$category}' OR ";
        }
        # remainder of sql (FALSE is required to absorb the last OR)
        $sql .= "FALSE) GROUP BY page_title";
        # query
        $res = $db->query($sql);
        # parsing result of sql query: get name and namespace of pages placed in the
        # filter categories and look up all values of the given property for each page
        for ($i = 0; $i < $db->numRows($res); $i++) {
            $row = $db->fetchObject($res);
            $pagename = $row->page_title;
            $namespace = $row->page_namespace;
            $values = array_merge($values, $store->getPropertyValues(SMWWikiPageValue::makePage($pagename, $namespace), $property));
        }
        $db->freeResult($res);
    }
    # counting frequencies
    foreach ($values as $value) {
        # get surface form of property value
        $tag = $value->getShortHTMLText();
        # get Searchlink data for property and current property value
        $link = SMWInfolink::newPropertySearchLink($tag, $tag_name, $tag)->getHTML();
        if (array_key_exists($tag, $result)) {
            $result[$tag] += 1;
        } else {
            $result[$tag] = 1;
            $links[$tag] = $link;
        }
    }
    # sorting results
    arsort($result);
    # if too many tags are found, remove rear part of result array
    if (count($result) > $max_tags) {
        $result = array_slice($result, 0, $max_tags, true);
    }
    # get minimum and maximum frequency for computing font sizes
    $min = end($result) or $min = 0;
    $max = reset($result) or $max = 1;
    if ($max == $min) {
        $max += 1;
    }
    # sorting results by frequency
    if (isset($args['order'])) {
        if ($args['order'] != "frequency") {
            # ksort($result, SORT_STRING);
            uksort($result, 'compareLowercase');
        }
    } else {
        uksort($result, 'compareLowercase');
    }
    # start building html output
    $htmlOut = $htmlOut . "<div align=justify>";
    foreach ($result as $label => $count) {
        if ($count >= $min_count) {
            if (isset($args['increase'])) {
                # computing font size (logarithmic)
                if ($args[increase] = 'log') {
                    $font_size = $min_font_size + $increase_factor * (log($count) - log($min)) / (log($max) - log($min));
                } else {
                    $font_size = $min_font_size + $increase_factor * ($count - $min) / ($max - $min);
                }
            } else {
                $font_size = $min_font_size + $increase_factor * ($count - $min) / ($max - $min);
            }
            $style = "font-size: {$font_size}%;";
            # link to special page search by property with parameters
            # property=tagging property and value=current tag
            # find URL in searchlink data
            $matches = array();
            preg_match('/href="(.)*"/U', $links[$label], $matches);
            $url = $matches[0];
            # include freqency in brackets in output
            if ($args['count']) {
                $append = " ({$count})";
            }
            # appending tag
            $currentRow = "<a style=\"{$style}\" {$url}>" . $label . $append . "</a>&#160; ";
            $htmlOut = $htmlOut . $currentRow;
        }
    }
    $htmlOut = $htmlOut . "</div>";
    return $htmlOut;
}
示例#5
0
 function addSemanticResultWrapper($dbr, $res, $num, $query, $mainlabel, $printouts)
 {
     $qr = array();
     $count = 0;
     $store = smwfGetStore();
     while ($count < $num && ($row = $dbr->fetchObject($res))) {
         $count++;
         if (class_exists('SMWDIWikiPage')) {
             // SMW 1.6
             $qr[] = new SMWDIWikiPage($row->t, $row->ns, null);
         } else {
             $qr[] = SMWWikiPageValue::makePage($row->t, $row->ns, $row->sortkey);
         }
         if (method_exists($store, 'cacheSMWPageID')) {
             if (method_exists('SMWDIWikiPage', 'getSubobjectName')) {
                 // SMW 1.6
                 $store->cacheSMWPageID($row->id, $row->t, $row->ns, $row->iw, '');
             } else {
                 $store->cacheSMWPageID($row->id, $row->t, $row->ns, $row->iw);
             }
         }
     }
     if ($dbr->fetchObject($res)) {
         $count++;
     }
     $dbr->freeResult($res);
     $printrequest = new SMWPrintRequest(SMWPrintRequest::PRINT_THIS, $mainlabel);
     $main_printout = array();
     $main_printout[$printrequest->getHash()] = $printrequest;
     $printouts = array_merge($main_printout, $printouts);
     return new SMWQueryResult($printouts, $query, $qr, $store, $count > $num);
 }
	/**
	 * Reads the paramstring for remove and add and turns it into
	 * SMWSemanticData object that can be used with the SMWWriter API
	 *
	 * @param Title $title Title of the page to be modified
	 * @param string $text The param value
	 * @return SMWSemanticData Object with the interpreted data from the param value
	 */
	private function readData( Title $title, /* string */ $text ) {
		if ( empty( $text ) )
			return new SMWSemanticData( SMWWikiPageValue::makePage( false, 0 ) );
		if ( $text == '*' )
			return new SMWSemanticData( SMWWikiPageValue::makePage( $title, 0 ) );

		$result = new SMWSemanticData( SMWWikiPageValue::makePageFromTitle( $title ) );

		$matches = array();
		preg_match_all( "/\[\[([^\[\]]*)\]\]/", $text, $matches, PREG_PATTERN_ORDER );
		foreach ( $matches[1] as $match ) {
			$parts = explode( "::", $match );
			if ( count( $parts ) != 2 ) continue;
			$property = SMWPropertyValue::makeUserProperty( trim( $parts[0] ) );
			if ( trim( $parts[1] ) == '*' )
				$value = SMWDataValueFactory::newPropertyObjectValue( $property, false );
			else
				$value = SMWDataValueFactory::newPropertyObjectValue( $property, trim( $parts[1] ) );
			$result->addPropertyObjectValue( $property, $value );
		}
		return $result;
	}
示例#7
0
 /**
  * @see superclass
  */
 function getPropertySubjects(SMWPropertyValue $property, $value, $requestoptions = NULL)
 {
     if (!$property->isUserDefined()) {
         return parent::getPropertySubjects($property, $value, $requestoptions);
     }
     if (smwfCheckIfPredefinedSMWHaloProperty($property)) {
         return parent::getPropertyValues($subject, $property, $requestoptions, $outputformat);
     }
     global $smwgTripleStoreGraph;
     $client = TSConnection::getConnector();
     $client->connect();
     $values = array();
     $propertyName = $property->getWikiPageValue()->getTitle()->getDBkey();
     $limit = isset($requestoptions->limit) ? " LIMIT " . $requestoptions->limit : "";
     $offset = isset($requestoptions->offset) ? " OFFSET " . $requestoptions->offset : "";
     $nsPrefixProp = $this->tsNamespace->getNSPrefix($property->getWikiPageValue()->getTitle()->getNamespace());
     try {
         if (is_null($value)) {
             $response = $client->query("SELECT ?s WHERE { GRAPH ?g { ?s <{$smwgTripleStoreGraph}/{$nsPrefixProp}#{$propertyName}> ?o. } } {$limit} {$offset}", "merge=false|graph={$smwgTripleStoreGraph}");
         } else {
             if ($value instanceof SMWWikiPageValue) {
                 $objectName = $value->getTitle()->getDBkey();
                 $nsPrefixObj = $this->tsNamespace->getNSPrefix($value->getTitle()->getNamespace());
                 $response = $client->query("SELECT ?s WHERE { GRAPH ?g { ?s <{$smwgTripleStoreGraph}/{$nsPrefixProp}#{$propertyName}> <{$smwgTripleStoreGraph}/{$nsPrefixObj}#{$objectName}>. } } {$limit} {$offset}", "merge=false");
             } else {
                 $objectvalue = str_replace('"', '\\"', array_shift($value->getDBkeys()));
                 $objecttype = WikiTypeToXSD::getXSDType($value->getTypeID());
                 $response = $client->query("SELECT ?s WHERE { GRAPH ?g { ?s <{$smwgTripleStoreGraph}/{$nsPrefixProp}#{$propertyName}> \"{$objectvalue}\"^^{$objecttype}. } } {$limit} {$offset}", "merge=false");
             }
         }
     } catch (Exception $e) {
         wfDebug("Triplestore does probably not run.\n");
         $response = TSNamespaces::$EMPTY_SPARQL_XML;
     }
     // query
     global $smwgSPARQLResultEncoding;
     // PHP strings are always interpreted in ISO-8859-1 but may be actually encoded in
     // another charset.
     if (isset($smwgSPARQLResultEncoding) && $smwgSPARQLResultEncoding == 'UTF-8') {
         $response = utf8_decode($response);
     }
     $dom = simplexml_load_string($response);
     $annotations = array();
     $results = $dom->xpath('//result');
     foreach ($results as $r) {
         $children = $r->children();
         // binding nodes
         $b = $children->binding[0];
         // predicate
         $sv = $b->children()->uri[0];
         $title = $this->getTitleFromURI((string) $sv);
         $value = SMWWikiPageValue::makePage($title->getDBkey(), $title->getNamespace());
         $metadata = $sv->attributes();
         foreach ($metadata as $mdProperty => $mdValue) {
             if (strpos($mdProperty, "_meta_") === 0) {
                 $value->setMetadata(substr($mdProperty, 6), explode("|||", $mdValue));
             }
         }
         $values[] = $value;
     }
     return $values;
 }