示例#1
0
 /**
  * @since 0.1
  *
  * @param mixed $input
  * @param array $args
  * @param Parser $parser
  * @param PPFrame $frame
  */
 public static function onSparkRender($input, array $args, Parser $parser, $frame = null)
 {
     global $wgVersion;
     global $wgOut;
     global $egSparkScriptJquery;
     global $egSparkScriptJquerySpark;
     static $loadedJs = false;
     if (version_compare($wgVersion, '1.17', '<')) {
         // We do not have resource loader
         if (!$loadedJs) {
             $wgOut->addScript('<script src="' . $egSparkScriptJquery . '" type="text/javascript"></script>');
             wfDebugLog('spark', "AddScript:" . ' <script src="' . $egSparkScriptJquery . '" type="text/javascript"></script>');
             //echo "AddScript:".' <script src="'.$egSparkScriptJquery.'" type="text/javascript"></script>';
             $wgOut->addScript('<script src="' . $egSparkScriptJquerySpark . '" type="text/javascript"></script>');
             wfDebugLog('spark', "AddScript:" . ' <script src="' . $egSparkScriptJquerySpark . '" type="text/javascript"></script>');
             //echo "AddScript:".' <script src="'.$egSparkScriptJquerySpark.'" type="text/javascript"></script>';
             $loadedJs = true;
         }
     } else {
         // We have resource loader
         // If we have resource loader
         if (!$loadedJs) {
             $parser->getOutput()->addModules('ext.spark');
             $loadedJs = true;
         }
     }
     $tag = new SparkTag($args, $input);
     // PPFrame maybe not existing
     return $tag->render($parser, $frame);
 }
 function execute($par)
 {
     $this->getParams();
     $html = '';
     $error = false;
     $renderedAds = array();
     try {
         $campaign = new AdCampaign($this->campaignName);
         $ads = $campaign->getAds();
         foreach ($ads as $ad) {
             $renderedAds[] = Ad::fromName($ad['name'])->renderHtml();
         }
     } catch (MWException $e) {
         wfDebugLog('Promoter', $e->getMessage());
         $error = $e->getMessage();
     }
     if ($this->isPreview) {
         $this->setHeaders();
         if ($error) {
             $html = "Exception {$error}.";
         } else {
             $html = '<div id="adPreview clearfix">';
             foreach ($renderedAds as $ad) {
                 $html .= '<div class="col-sm-4">' . $ad . '</div>';
             }
             $html .= '</div>';
         }
         $this->getOutput()->addHTML($html);
     } else {
         $this->getOutput()->disable();
         $this->sendHeaders();
         print_r($renderedAds);
     }
 }
 public function onSubmit(array $formData)
 {
     global $IP, $wgCreateWikiSQLfiles;
     $DBname = $formData['dbname'];
     $founderName = $formData['founder'];
     $siteName = $formData['sitename'];
     $language = $formData['language'];
     $private = $formData['private'];
     $reason = $formData['reason'];
     $dbw = wfGetDB(DB_MASTER);
     $farmerLogEntry = new ManualLogEntry('farmer', 'createwiki');
     $farmerLogEntry->setPerformer($this->getUser());
     $farmerLogEntry->setTarget($this->getTitle());
     $farmerLogEntry->setComment($reason);
     $farmerLogEntry->setParameters(array('4::wiki' => $DBname));
     $farmerLogID = $farmerLogEntry->insert();
     $farmerLogEntry->publish($farmerLogID);
     $dbw->query('SET storage_engine=InnoDB;');
     $dbw->query('CREATE DATABASE ' . $dbw->addIdentifierQuotes($DBname) . ';');
     $dbw->selectDB($DBname);
     foreach ($wgCreateWikiSQLfiles as $sqlfile) {
         $dbw->sourceFile($sqlfile);
     }
     $this->writeToDBlist($DBname, $siteName, $language, $private);
     $this->createMainPage($language);
     $shcreateaccount = exec("/usr/bin/php " . "{$IP}/extensions/CentralAuth/maintenance/createLocalAccount.php " . wfEscapeShellArg($founderName) . " --wiki " . wfEscapeShellArg($DBname));
     if (!strpos($shcreateaccount, 'created')) {
         wfDebugLog('CreateWiki', 'Failed to create local account for founder. - error: ' . $shcreateaccount);
         return wfMessage('createwiki-error-usernotcreated')->escaped();
     }
     $shpromoteaccount = exec("/usr/bin/php " . "{$IP}/maintenance/createAndPromote.php " . wfEscapeShellArg($founderName) . " --bureaucrat --sysop --force --wiki " . wfEscapeShellArg($DBname));
     $this->getOutput()->addHTML('<div class="successbox">' . wfMessage('createwiki-success')->escaped() . '</div>');
     return true;
 }
示例#4
0
 function doTransform($image, $dstPath, $dstUrl, $params, $flags = 0)
 {
     global $wgSVGConverters, $wgSVGConverter, $wgSVGConverterPath;
     if (!$this->normaliseParams($image, $params)) {
         return new TransformParameterError($params);
     }
     $clientWidth = $params['width'];
     $clientHeight = $params['height'];
     $physicalWidth = $params['physicalWidth'];
     $physicalHeight = $params['physicalHeight'];
     $srcPath = $image->getPath();
     if ($flags & self::TRANSFORM_LATER) {
         return new ThumbnailImage($image, $dstUrl, $clientWidth, $clientHeight, $dstPath);
     }
     if (!wfMkdirParents(dirname($dstPath))) {
         return new MediaTransformError('thumbnail_error', $clientWidth, $clientHeight, wfMsg('thumbnail_dest_directory'));
     }
     $err = false;
     if (isset($wgSVGConverters[$wgSVGConverter])) {
         $cmd = str_replace(array('$path/', '$width', '$height', '$input', '$output'), array($wgSVGConverterPath ? wfEscapeShellArg("{$wgSVGConverterPath}/") : "", intval($physicalWidth), intval($physicalHeight), wfEscapeShellArg($srcPath), wfEscapeShellArg($dstPath)), $wgSVGConverters[$wgSVGConverter]) . " 2>&1";
         wfProfileIn('rsvg');
         wfDebug(__METHOD__ . ": {$cmd}\n");
         $err = wfShellExec($cmd, $retval);
         wfProfileOut('rsvg');
     }
     $removed = $this->removeBadFile($dstPath, $retval);
     if ($retval != 0 || $removed) {
         wfDebugLog('thumbnail', sprintf('thumbnail failed on %s: error %d "%s" from "%s"', wfHostname(), $retval, trim($err), $cmd));
         return new MediaTransformError('thumbnail_error', $clientWidth, $clientHeight, $err);
     } else {
         return new ThumbnailImage($image, $dstUrl, $clientWidth, $clientHeight, $dstPath);
     }
 }
 public function testSomething()
 {
     // meaningless set of ids used for repeatability
     $ids = array_map(array('Flow\\Model\\UUID', 'create'), array("s3z44zhp93j5vvc8", "s3z44zhqt7yt8220", "s46w00pmmw0otc0q", "s3qvc7cnor86wvb4", "s3qvc7bbcxr3f340", "s3gre9r27pobtg0n", "s3cdl3dfqf8brx18", "s3cdl3dhajnz43r0"));
     // Use 2 repos with 2 caches, the one you insert with reads from cache
     // the other reads from db due to different cache
     $cache[] = new BufferedCache(new BufferedBagOStuff(new \HashBagOStuff()), 600);
     $cache[] = new BufferedCache(new BufferedBagOStuff(new \HashBagOStuff()), 600);
     $dbf = Container::get('db.factory');
     $repo[] = new TreeRepository($dbf, $cache[0]);
     $repo[] = new TreeRepository($dbf, $cache[1]);
     // id0 as new root
     wfDebugLog('Flow', "\n\n************** id0 as new root ************");
     $repo[0]->insert($ids[0]);
     $this->assertEquals(array($ids[0]), $repo[0]->findRootPath($ids[0]));
     $this->assertEquals(array($ids[0]), $repo[1]->findRootPath($ids[0]));
     // id1 as child of id0
     wfDebugLog('Flow', "\n\n************** id1 as child of id0 ************");
     $repo[0]->insert($ids[1], $ids[0]);
     $this->assertEquals(array($ids[0], $ids[1]), $repo[0]->findRootPath($ids[1]));
     $this->assertEquals(array($ids[0], $ids[1]), $repo[1]->findRootPath($ids[1]));
     // id2 as child of id0
     wfDebugLog('Flow', "\n\n************** id2 as child of id0 ************");
     $repo[0]->insert($ids[2], $ids[0]);
     $this->assertEquals(array($ids[0], $ids[2]), $repo[0]->findRootPath($ids[2]));
     $this->assertEquals(array($ids[0], $ids[2]), $repo[1]->findRootPath($ids[2]));
     // id3 as child of id1
     wfDebugLog('Flow', "\n\n************** id3 as child of id1 ************");
     $repo[0]->insert($ids[3], $ids[1]);
     $this->assertEquals(array($ids[0], $ids[1], $ids[3]), $repo[0]->findRootPath($ids[3]));
     $this->assertEquals(array($ids[0], $ids[1], $ids[3]), $repo[1]->findRootPath($ids[3]));
 }
示例#6
0
 public static function parse($parser)
 {
     $parser->disableCache();
     $title = $parser->getTitle()->getText();
     $titleArray = explode(':', $title);
     $ontAbbr = $titleArray[0];
     $termID = str_replace(' ', '_', $titleArray[1]);
     $ontology = new OntologyData($ontAbbr);
     $sql = new SQLStore(wfGetDB(DB_SLAVE));
     $magics = $sql->getObjectMagicWords($ontAbbr);
     $objects = array();
     foreach ($magics as $magic => $object) {
         $objects[$magic] = $object['iri'];
         $objects[$object['iri']] = $object['iri'];
         $objects[$object['id']] = $object['iri'];
     }
     $operations = $GLOBALS['okwRDFConfig']['restriction']['operation'];
     $types = $GLOBALS['okwRDFConfig']['restriction']['type'];
     $params = array();
     for ($i = 2; $i < func_num_args(); $i++) {
         $params[] = func_get_arg($i);
     }
     list($options, $valids, $invalids) = self::extractAxiom($params, $ontology, $objects, $operations, $types, false);
     $axioms = array();
     foreach ($valids as $index => $value) {
         $axioms[] = $value['text'];
         $GLOBALS['okwCache']['axiom'][$value['type']][] = $value['text'];
     }
     wfDebugLog('OntoKiWi', sprintf('OKW\\Parser\\AxiomParser: parsed axiom {%s} for [[%s]]', join(';', $axioms), $title));
     wfDebugLog('OntoKiWi', '[caches] OKW\\Parser\\AxiomParser: axiom');
     return array('', 'noparse' => true);
 }
示例#7
0
 /**
  * Does update. First deletes, then inserts.
  * @param $data
  */
 function updateData(SMWSemanticData $data)
 {
     $export = SMWExporter::makeExportData($data);
     $sparqlDeleteText = "";
     $sparqlUpdateText = "INSERT DATA {\n";
     // let other extensions add additional RDF data for this page (i.e. Semantic Internal Objects)
     //this code is based on the modifications made on SemanticMediaWiki/includes/export/SMW_OWLExport.php
     $additionalDataArray = array();
     $fullexport = true;
     $backlinks = false;
     wfRunHooks('smwAddToRDFExport', array($data->getSubject()->getTitle(), &$additionalDataArray, $fullexport, $backlinks));
     // this writes update text for each of the Semantic Internal Objects
     foreach ($additionalDataArray as $additionalData) {
         $subject_uri = SMWExporter::expandURI($additionalData->getSubject()->getName());
         // remove subject from triple store
         $sparqlDeleteText .= $this->writeDeleteText($subject_uri);
         //add new data associated with internal objects
         $sparqlUpdateText .= $this->writeUpdateText($additionalData->getTripleList());
     }
     $subject_uri = SMWExporter::expandURI($export->getSubject()->getName());
     // remove subject from triple store
     $sparqlDeleteText .= $this->writeDeleteText($subject_uri);
     $triple_list = $export->getTripleList();
     $sparqlUpdateText .= $this->writeUpdateText($triple_list);
     $sparqlUpdateText .= "}";
     //delete the old triples
     wfDebugLog('SPARQL_LOG', "#===DELETE===\n" . $sparqlDeleteText);
     $response = $this->do_joseki_post($sparqlDeleteText);
     //insert the new triples
     wfDebugLog('SPARQL_LOG', "#===INSERT===\n" . $sparqlUpdateText);
     $response = $this->do_joseki_post($sparqlUpdateText);
     //can the delete and insert statements be combined, or will this lead to concurrency issues?
     return parent::updateData($data);
 }
示例#8
0
 public static function parse($parser)
 {
     $parser->disableCache();
     $title = $parser->getTitle()->getText();
     $titleArray = explode(':', $title);
     $ontAbbr = $titleArray[0];
     $termID = str_replace(' ', '_', $titleArray[1]);
     $ontology = new OntologyData($ontAbbr);
     $term = $ontology->parseTermByID($termID);
     $params = array();
     for ($i = 2; $i < func_num_args(); $i++) {
         $params[] = func_get_arg($i);
     }
     list($options, $valids, $invalids) = self::extractSupClass($params, $ontology);
     $pathType = $GLOBALS['okwHierarchyConfig']['pathType'];
     $supClasses = array();
     if (!empty($valids)) {
         foreach ($valids as $index => $value) {
             $supClasses[] = $value['iri'];
             $hierarchy = $ontology->parseTermHierarchy($term, $pathType, $value['iri']);
             if ($value['iri'] == $GLOBALS['okwRDFConfig']['Thing']) {
                 $GLOBALS['okwCache']['hierarchy'][$index] = $hierarchy;
             } else {
                 foreach ($hierarchy as $path) {
                     if (!empty($path['path'])) {
                         $GLOBALS['okwCache']['hierarchy'][$index] = $hierarchy;
                     }
                 }
             }
         }
     }
     wfDebugLog('OntoKiWi', sprintf('OKW\\Parser\\HierarchyParser: parsed hierarchy {%s} for [[%s]]', join(';', $supClasses), $title));
     wfDebugLog('OntoKiWi', '[caches] OKW\\Parser\\HierarchyParser: hierarchy');
     return array('', 'noparse' => true);
 }
 /**
  * Marks the given entity ids for prefetching.
  *
  * @param EntityId[] $entityIds
  */
 public function prefetch(array $entityIds)
 {
     $entityIdCount = count($entityIds);
     if ($entityIdCount > $this->maxCacheKeys) {
         // Ouch... fetching everything wouldn't fit into the cache, thus
         // other functions might not find what they're looking for.
         // Create a new, large enough MapCacheLRU to mitigate this.
         $this->cache = new MapCacheLRU($entityIdCount + 1);
         $this->maxCacheKeys = $entityIdCount + 1;
         wfDebugLog('PrefetchingWikiPageEntityMetaDataAccessor', "Needed to create a new MapCacheLRU instance for {$entityIdCount} entities.");
     }
     if ($entityIdCount + count($this->toFetch) > $this->maxCacheKeys) {
         // Fetching everything would exceed the capacity of the cache,
         // thus discard all older entity ids as we can safely ignore these.
         $this->toFetch = array();
     }
     foreach ($entityIds as $entityId) {
         $idSerialization = $entityId->getSerialization();
         if ($this->cache->has($idSerialization)) {
             // Make sure the entities we already know about are not going
             // to be purged, by requesting them.
             $this->cache->get($idSerialization);
         } else {
             $this->toFetch[$idSerialization] = $entityId;
         }
     }
 }
 /**
  * Parser hook handler for {{#articletype}}
  *
  * @param Parser $parser : Parser instance available to render
  *  wikitext into html, or parser methods.
  *
  * @return string: HTML to insert in the page.
  */
 public static function renderGallery($input, array $args, Parser $parser, PPFrame $frame)
 {
     $parser->getOutput()->addModules('ext.promoter.gallery');
     $pageName = $parser->getTitle()->getText();
     try {
         $renderedAds = array();
         $adChooser = new AdChooser($pageName, !$parser->getUser()->isLoggedIn());
         $ads = $adChooser->getAds();
         foreach ($ads as $ad) {
             $renderedAds[] = Ad::fromName($ad['name'])->renderHtml();
         }
     } catch (AdCampaignExistenceException $e) {
         wfDebugLog('Promoter', $e->getMessage());
         //@todo i18n
         return '<span class="error">No campaign for this page</span>';
     } catch (MWException $e) {
         wfDebugLog('Promoter', $e->getMessage());
         return '<span class="error text-danger">An error occurred [' . $e->getMessage() . ']</span>';
     }
     $html = '<div class="promotion-gallery hidden hidden-print">' . '<h5 class="sr-only">זוהי גלריה המקדמת ערכים שונים באתר.</h5>' . '<div class="gallery-controls">' . '<span class="sr-only">בכל רגע מוצגות 3 ידיעות בגלריה. ניתן להציג ידיעה נוספת או לחזור לאחור באמצעות הכפתורים הבאים, או באמצעות מקשי החיצים כאשר הפוקוס הוא על הגלריה</span>' . '<a href="#" class="owl-prev"><span class="fa fa-chevron-right fa-lg" title="הקודם"></span><span class="sr-only">הצגת הידיעה הקודמת</span></a>' . '<a href="#" class="owl-next"><span class="fa fa-chevron-left fa-lg" title="הבא"></span><span class="sr-only">הצגת הידיעה הבאה</span></a>' . '</div>';
     if ($args['title']) {
         $html .= '<div class="header">' . $args['title'] . '</div>';
     }
     $html .= '<div class="owl-carousel clearfix" tabindex="0">' . implode('', $renderedAds) . '</div>' . '</div>';
     return $html;
 }
/**
 * Set $wgDebugLogGroups['UploadBlacklist'] to direct logging to a particular
 * file instead of the debug log.
 *
 * @param string $action
 * @param string $hash
 * @param string $saveName
 * @param string $tempName
 * @access private
 */
function ubLog( $action, $hash, $saveName, $tempName ) {
	global $wgUser;
	$user = $wgUser->getName();
	$ip = wfGetIP();
	$ts = wfTimestamp( TS_DB );
	wfDebugLog( 'UploadBlacklist', "$ts $action [$hash] name:$saveName file:$tempName user:$user ip:$ip" );
}
示例#12
0
 public static function parse($parser)
 {
     $parser->disableCache();
     $title = $parser->getTitle()->getText();
     $titleArray = explode(':', $title);
     $ontAbbr = $titleArray[0];
     $sql = new SQLStore(wfGetDB(DB_SLAVE));
     $magic = $sql->getAnnotationMagicWords($ontAbbr);
     $params = array();
     for ($i = 2; $i < func_num_args(); $i++) {
         $params[] = func_get_arg($i);
     }
     list($options, $valids, $invalids) = self::extractAnnotation($params, $magic);
     $annotations = array();
     $cache =& $GLOBALS['okwCache']['annotation'];
     foreach ($valids as $index => $annotation) {
         $annotations[] = $annotation['iri'];
         if (array_key_exists($annotation['iri'], $cache)) {
             if ($annotation['type'] == 'unique') {
                 $cache[$annotation['iri']]['value'] = $annotation['value'];
             } else {
                 $cache[$annotation['iri']]['value'] = array_merge($annotation['value'], $cache[$annotation['iri']]['value']);
             }
         } else {
             $cache[$annotation['iri']]['name'] = $annotation['name'];
             $cache[$annotation['iri']]['value'] = $annotation['value'];
         }
     }
     wfDebugLog('OntoKiWi', sprintf('OKW\\Parser\\AnnotationParser: parsed annotation {%s} for [[%s]]', join(';', $annotations), $title));
     wfDebugLog('OntoKiWi', '[caches] OKW\\Parser\\AnnotationParser: annotation');
     return array('', 'noparse' => true);
 }
 /**
  * Get contents of a javascript file for inline use.
  *
  * Roughly based MediaWiki core methods:
  * - ResourceLoader::filter()
  * - ResourceLoaderFileModule::readScriptFiles()
  *
  * @param string $name Path to file relative to /modules/inline/
  * @return string Minified script
  * @throws Exception If file doesn't exist
  */
 protected static function getInlineScript($name)
 {
     // Get file
     $filePath = __DIR__ . '/../../modules/inline/' . $name;
     if (!file_exists($filePath)) {
         throw new Exception(__METHOD__ . ": file not found: \"{$filePath}\"");
     }
     $contents = file_get_contents($filePath);
     // Try minified from cache
     $key = wfMemcKey('centralauth', 'minify-js', md5($contents));
     $cache = wfGetCache(CACHE_ANYTHING);
     $cacheEntry = $cache->get($key);
     if (is_string($cacheEntry)) {
         return $cacheEntry;
     }
     // Compute new value
     $result = '';
     try {
         $result = JavaScriptMinifier::minify($contents) . "\n/* cache key: {$key} */";
         $cache->set($key, $result);
     } catch (Exception $e) {
         MWExceptionHandler::logException($e);
         wfDebugLog('CentralAuth', __METHOD__ . ": minification failed for {$name}: {$e}");
         $result = ResourceLoader::formatException($e) . "\n" . $contents;
     }
     return $result;
 }
示例#14
0
/**
 * Get the Swift thumbnail container for this wiki.
 *
 * @param $site string
 * @param $lang string
 * @param $relPath string Path relative to container
 * @return CF_Container|null
 */
function wmfGetSwiftThumbContainer($site, $lang, $relPath)
{
    global $wmfSwiftConfig;
    // from PrivateSettings.php
    $auth = new CF_Authentication($wmfSwiftConfig['user'], $wmfSwiftConfig['key'], NULL, $wmfSwiftConfig['authUrl']);
    try {
        $auth->authenticate();
    } catch (Exception $e) {
        wfDebugLog('swiftThumb', "Could not establish a connection to Swift.");
        return null;
    }
    $conn = new CF_Connection($auth);
    $wikiId = "{$site}-{$lang}";
    // Get the full swift container name, including any shard suffix
    $name = "{$wikiId}-local-thumb";
    if (in_array($wikiId, array('wikipedia-commons', 'wikipedia-en'))) {
        // Code stolen from FileBackend::getContainerShard()
        if (preg_match("!^(?:[^/]{2,}/)*[0-9a-f]/(?P<shard>[0-9a-f]{2})(?:/|\$)!", $relPath, $m)) {
            $name .= '.' . $m['shard'];
        } else {
            throw new MWException("Can't determine shard of path '{$relPath}' for '{$wikiId}'.");
        }
    }
    try {
        $container = $conn->get_container($name);
    } catch (NoSuchContainerException $e) {
        // container not created yet
        $container = null;
        wfDebugLog('swiftThumb', "Could not access `{$name}`; container does not exist.");
    }
    return $container;
}
 static function onArticleDeleteComplete(&$article, &$user, $reason, $id)
 {
     $title = $article->getTitle();
     if ($title->getNamespace() != NS_LQT_THREAD) {
         return true;
     }
     $threads = Threads::where(array('thread_root' => $id));
     if (!count($threads)) {
         wfDebugLog('LiquidThreads', __METHOD__ . ": no threads with root {$id}, ignoring...\n");
         return true;
     }
     $thread = array_pop($threads);
     // Mark the thread as deleted
     $thread->delete($reason);
     // Avoid orphaning subthreads, update their parentage.
     if ($thread->replies() && $thread->isTopmostThread()) {
         $reason = wfMsg('lqt-delete-parent-deleted', $reason);
         self::recursivelyDeleteReplies($thread, $reason);
         global $wgOut;
         $wgOut->addWikiMsg('lqt-delete-replies-done');
     } elseif ($thread->replies()) {
         foreach ($thread->replies() as $reply) {
             $reply->setSuperthread($thread->superthread());
             $reply->save();
         }
     }
     // Synchronise the first 500 threads, in reverse order by thread id. If
     // there are more threads to synchronise, the job queue will take over.
     Threads::synchroniseArticleData($article, 500, 'cascade');
     return true;
 }
 /**
  * Try to create and attach the user.
  * @throws Exception
  * @return bool Success
  */
 public function run()
 {
     $username = $this->params['name'];
     $from = $this->params['from'];
     $wiki = wfWikiID();
     if (isset($this->params['session'])) {
         // restore IP and other request data
         $this->params['session']['userId'] = 0;
         $this->params['session']['sessionId'] = '';
         $callback = RequestContext::importScopedSession($this->params['session']);
     }
     $user = User::newFromName($username);
     $centralUser = CentralAuthUser::getInstance($user);
     if ($user->getId() !== 0) {
         wfDebugLog('CentralAuth', __CLASS__ . ": tried to create local account for {$username} " . "on {$wiki} from {$from} but one already exists\n");
         return true;
     } elseif (!$centralUser->exists()) {
         wfDebugLog('CentralAuth', __CLASS__ . ": tried to create local account for {$username} " . "on {$wiki} from {$from} but no global account exists\n");
         return true;
     } elseif ($centralUser->attachedOn($wiki)) {
         wfDebugLog('CentralAuth', __CLASS__ . ": tried to create local account for {$username} " . "on {$wiki} from {$from} but an attached local account already exists\n");
         return true;
     }
     $success = CentralAuthHooks::attemptAddUser($user);
     if ($success) {
         $centralUser->invalidateCache();
     }
     return true;
 }
示例#17
0
    private function run()
    {
        global $wgServerName, $wgScriptPath;
        $params = $this->extractRequestParams();
        wfDebugLog('p2p', 'ApiQueryPatch params ' . $params['patchId']);
        $array = array(1 => 'id', 2 => 'onPage', 3 => 'operation', 4 => 'previous', 5 => 'siteID', 6 => 'mime', 7 => 'size', 8 => 'url', 9 => 'DateAtt', 10 => 'siteUrl', 11 => 'causal');
        $array1 = array(1 => 'patchID', 2 => 'onPage', 3 => 'hasOperation', 4 => 'previous', 5 => 'siteID', 6 => 'mime', 7 => 'size', 8 => 'url', 9 => 'DateAtt', 10 => 'siteUrl', 11 => 'causal');
        $query = '';
        for ($j = 1; $j <= count($array1); $j++) {
            $query = $query . '?' . $array1[$j] . '
';
        }
        $res = utils::getSemanticQuery('[[patchID::' . $params['patchId'] . ']]', $query);
        $count = $res->getCount();
        for ($i = 0; $i < $count; $i++) {
            $row = $res->getNext();
            if ($row === false) {
                break;
            }
            for ($j = 1; $j <= count($array); $j++) {
                if ($j == 3) {
                    $col = $row[$j]->getContent();
                    // SMWResultArray object
                    foreach ($col as $object) {
                        // SMWDataValue object
                        $wikiValue = $object->getWikiValue();
                        $op[] = $wikiValue;
                    }
                    $results[$j] = $op;
                } else {
                    $col = $row[$j]->getContent();
                    // SMWResultArray object
                    foreach ($col as $object) {
                        // SMWDataValue object
                        $wikiValue = $object->getWikiValue();
                        $results[$j] = $wikiValue;
                    }
                }
            }
        }
        $result = $this->getResult();
        // $data = str_replace('"', '', $data);
        // $data = explode('!',$data);
        if ($results[1]) {
            for ($i = 1; $i <= count($array); $i++) {
                if ($results[$i] != null) {
                    if ($i == 2) {
                        $title = trim($results[$i], ":");
                        $result->addValue(array('query', $this->getModuleName()), $array[$i], $title);
                    } elseif ($i == 3) {
                        $op = $results[$i];
                        $result->setIndexedTagName($op, $array[$i]);
                        $result->addValue('query', $this->getModuleName(), $op);
                    } else {
                        $result->addValue(array('query', $this->getModuleName()), $array[$i], $results[$i]);
                    }
                }
            }
        }
    }
 /**
  * @param ReferenceFactory $factory
  * @param Extractor[] $extractors
  * @param string $text
  * @return Reference[]
  * @throws MWException
  * @throws \Flow\Exception\WikitextException
  */
 protected function extractReferences(ReferenceFactory $factory, array $extractors, $text)
 {
     $dom = Utils::createDOM($text);
     $output = array();
     $xpath = new DOMXPath($dom);
     foreach ($extractors as $extractor) {
         $elements = $xpath->query($extractor->getXPath());
         if (!$elements) {
             $class = get_class($extractor);
             throw new MWException("Malformed xpath from {$class}: " . $extractor->getXPath());
         }
         foreach ($elements as $element) {
             try {
                 $ref = $extractor->perform($factory, $element);
             } catch (InvalidReferenceException $e) {
                 wfDebugLog('Flow', 'Invalid reference detected, skipping element');
                 $ref = null;
             }
             // no reference was generated
             if ($ref === null) {
                 continue;
             }
             // reference points to a special page
             if ($ref->getSrcTitle()->isSpecialPage()) {
                 continue;
             }
             $output[] = $ref;
         }
     }
     return $output;
 }
 public function run()
 {
     $done = false;
     $startTime = microtime(true);
     while (!$done) {
         $readSockets = $writeSockets = array();
         /**
          * @var $client SquidPurgeClient
          */
         foreach ($this->clients as $clientIndex => $client) {
             $sockets = $client->getReadSocketsForSelect();
             foreach ($sockets as $i => $socket) {
                 $readSockets["{$clientIndex}/{$i}"] = $socket;
             }
             $sockets = $client->getWriteSocketsForSelect();
             foreach ($sockets as $i => $socket) {
                 $writeSockets["{$clientIndex}/{$i}"] = $socket;
             }
         }
         if (!count($readSockets) && !count($writeSockets)) {
             break;
         }
         $exceptSockets = null;
         $timeout = min($startTime + $this->timeout - microtime(true), 1);
         MediaWiki\suppressWarnings();
         $numReady = socket_select($readSockets, $writeSockets, $exceptSockets, $timeout);
         MediaWiki\restoreWarnings();
         if ($numReady === false) {
             wfDebugLog('squid', __METHOD__ . ': Error in stream_select: ' . socket_strerror(socket_last_error()) . "\n");
             break;
         }
         // Check for timeout, use 1% tolerance since we aimed at having socket_select()
         // exit at precisely the overall timeout
         if (microtime(true) - $startTime > $this->timeout * 0.99) {
             wfDebugLog('squid', __CLASS__ . ": timeout ({$this->timeout}s)\n");
             break;
         } elseif (!$numReady) {
             continue;
         }
         foreach ($readSockets as $key => $socket) {
             list($clientIndex, ) = explode('/', $key);
             $client = $this->clients[$clientIndex];
             $client->doReads();
         }
         foreach ($writeSockets as $key => $socket) {
             list($clientIndex, ) = explode('/', $key);
             $client = $this->clients[$clientIndex];
             $client->doWrites();
         }
         $done = true;
         foreach ($this->clients as $client) {
             if (!$client->isIdle()) {
                 $done = false;
             }
         }
     }
     foreach ($this->clients as $client) {
         $client->close();
     }
 }
示例#20
0
 function send($recipients, $headers, $body)
 {
     $this->_sanitizeHeaders($headers);
     list($from, $textHeaders) = $this->prepareHeaders($headers);
     $priority = 0;
     if (isset($headers['X-Priority'])) {
         $priority = $headers['X-Priority'];
     }
     $category = '';
     if (isset($headers['X-Msg-Category'])) {
         $category = $headers['X-Msg-Category'];
     }
     global $wgCityId, $wgWikiaMailerDB;
     $wgCityId = $wgCityId == null ? 0 : $wgCityId;
     // fake city-id for contractor/staff.
     // FB:4431 Write mail to archive database now
     $dbw = wfGetDb(DB_MASTER, array(), $wgWikiaMailerDB);
     $dbw->begin(__METHOD__);
     foreach ($recipients as $recipient) {
         // TODO: SHOULD WE FILTER BASED ON BLOCKS / SPAMS HERE?  FOR NOW WE WILL LET SENDGRID HANDLE THAT.
         $dbw->insert(self::$MAIL_TABLE_NAME, array('src' => $from, 'subj' => $headers['Subject'], 'dst' => $recipient, 'hdr' => $textHeaders, 'msg' => $body, 'city_id' => $wgCityId, 'priority' => $priority, 'category' => $category), __METHOD__);
         // Add postback token so that we can verify that any postback actually comes from SendGrid.
         $emailId = $dbw->insertId();
         $postbackToken = wfGetEmailPostbackToken($emailId, $recipient);
         $textHeaders .= $this->sep . "X-CallbackToken: " . $postbackToken;
         $dbw->update(self::$MAIL_TABLE_NAME, array('hdr' => $textHeaders), array('id' => $emailId), __METHOD__);
         wfDebugLog("enotif", __METHOD__ . ": email added to database with data: {$recipient} {$from} {$headers['Subject']}", true);
     }
     $dbw->commit(__METHOD__);
 }
示例#21
0
 public static function display($perm, $formName, $title)
 {
     $html = '';
     $sql = new SQLStore(wfGetDB(DB_SLAVE));
     if ($formName == 'edit') {
         $titleArray = explode(':', $title);
         $ontAbbr = $titleArray[0];
         $termID = str_replace(' ', '_', $titleArray[1]);
         $magic = $sql->getAnnotationMagicWords($ontAbbr);
         $ontology = new OntologyData($ontAbbr);
         $term = $ontology->parseTermByID($termID);
         $html .= self::printEditForm($perm, $ontAbbr, $term, $magic);
         wfDebugLog('OntoKiWi', 'OKW\\Display\\FormDisplayPrinter:: display: edit form');
     } else {
         if ($formName == 'create') {
             $sql = new SQLStore(wfGetDB(DB_SLAVE));
             $ontologies = $sql->getOntologies();
             $magic = $sql->getAnnotationMagicWords();
             $html .= self::printCreateForm($perm, $ontAbbr, $title, $ontologies, $magic);
             wfDebugLog('OntoKiWi', 'OKW\\Display\\FormDisplayPrinter:: display: create form');
         } else {
             #TODO: Throw Exception
         }
     }
     return $html;
 }
 /**
  * Receives an html string. It find all images and run them through
  * wfIsBadImage() to determine if the image can be shown.
  *
  * @param DOMNode $node
  * @param Title $title
  * @throws \MWException
  */
 public function apply(DOMNode $node, Title $title)
 {
     if (!$node instanceof DOMElement) {
         return;
     }
     $resource = $node->getAttribute('resource');
     if ($resource === '') {
         return;
     }
     $image = Utils::createRelativeTitle($resource, $title);
     if (!$image) {
         wfDebugLog('Flow', __METHOD__ . ': Could not construct title for node: ' . $node->ownerDocument->saveXML($node));
         return;
     }
     if (!call_user_func($this->isFiltered, $image->getDBkey(), $title)) {
         return;
     }
     // Move up the DOM and remove the typeof="mw:Image" node
     $nodeToRemove = $node->parentNode;
     while ($nodeToRemove instanceof DOMElement && $nodeToRemove->getAttribute('typeof') !== 'mw:Image') {
         $nodeToRemove = $nodeToRemove->parentNode;
     }
     if (!$nodeToRemove) {
         throw new \MWException('Did not find parent mw:Image to remove');
     }
     $nodeToRemove->parentNode->removeChild($nodeToRemove);
 }
 function execute($par)
 {
     $this->getParams();
     $html = '';
     $chosenAd = null;
     $error = false;
     try {
         $adChooser = new AdChooser($this->campaignName, $this->anonymous);
         $chosenAd = $adChooser->chooseAd();
         $chosenAd = Ad::fromName($chosenAd['name']);
         $html = $chosenAd->renderHtml();
     } catch (MWException $e) {
         wfDebugLog('Promoter', $e->getMessage());
         $error = $e->getMessage();
     }
     if ($this->isPreview) {
         $this->setHeaders();
         $html = $error ? "Exception {$error}." : '<div id="adPreview" class="col-md-3 col-sm-4">' . $html . '</div>';
         $this->getOutput()->addHTML($html);
     } else {
         $this->getOutput()->disable();
         $this->sendHeaders();
         if ($error) {
             echo "mw.promoter.insertAd( false /* due to internal exception ({$error}) */ );";
         } else {
             echo $this->getJsData($chosenAd);
         }
     }
 }
示例#24
0
 /**
  * Set the browser cookie
  * @param string $name name of cookie
  * @param string $value value to give cookie
  * @param int|null $expire Unix timestamp (in seconds) when the cookie should expire.
  *        0 (the default) causes it to expire $wgCookieExpiration seconds from now.
  *        null causes it to be a session cookie.
  * @param array $options Assoc of additional cookie options:
  *     prefix: string, name prefix ($wgCookiePrefix)
  *     domain: string, cookie domain ($wgCookieDomain)
  *     path: string, cookie path ($wgCookiePath)
  *     secure: bool, secure attribute ($wgCookieSecure)
  *     httpOnly: bool, httpOnly attribute ($wgCookieHttpOnly)
  *     raw: bool, if true uses PHP's setrawcookie() instead of setcookie()
  *   For backwards compatability, if $options is not an array then it and
  *   the following two parameters will be interpreted as values for
  *   'prefix', 'domain', and 'secure'
  * @since 1.22 Replaced $prefix, $domain, and $forceSecure with $options
  */
 public function setcookie($name, $value, $expire = 0, $options = null)
 {
     global $wgCookiePath, $wgCookiePrefix, $wgCookieDomain;
     global $wgCookieSecure, $wgCookieExpiration, $wgCookieHttpOnly;
     if (!is_array($options)) {
         // Backwards compatability
         $options = array('prefix' => $options);
         if (func_num_args() >= 5) {
             $options['domain'] = func_get_arg(4);
         }
         if (func_num_args() >= 6) {
             $options['secure'] = func_get_arg(5);
         }
     }
     $options = array_filter($options, function ($a) {
         return $a !== null;
     }) + array('prefix' => $wgCookiePrefix, 'domain' => $wgCookieDomain, 'path' => $wgCookiePath, 'secure' => $wgCookieSecure, 'httpOnly' => $wgCookieHttpOnly, 'raw' => false);
     if ($expire === null) {
         $expire = 0;
         // Session cookie
     } elseif ($expire == 0 && $wgCookieExpiration != 0) {
         $expire = time() + $wgCookieExpiration;
     }
     $func = $options['raw'] ? 'setrawcookie' : 'setcookie';
     if (wfRunHooks('WebResponseSetCookie', array(&$name, &$value, &$expire, $options))) {
         wfDebugLog('cookie', $func . ': "' . implode('", "', array($options['prefix'] . $name, $value, $expire, $options['path'], $options['domain'], $options['secure'], $options['httpOnly'])) . '"');
         call_user_func($func, $options['prefix'] . $name, $value, $expire, $options['path'], $options['domain'], $options['secure'], $options['httpOnly']);
     }
 }
 /**
  * Set the browser cookie
  * @param string $name name of cookie
  * @param string $value value to give cookie
  * @param int $expire Unix timestamp (in seconds) when the cookie should expire.
  *        0 (the default) causes it to expire $wgCookieExpiration seconds from now.
  * @param string $prefix Prefix to use, if not $wgCookiePrefix (use '' for no prefix)
  * @param string $domain Cookie domain to use, if not $wgCookieDomain
  * @param $forceSecure Bool:
  *   true: force the cookie to be set with the secure attribute
  *   false: force the cookie to be set without the secure attribute
  *   null: use the value from $wgCookieSecure
  */
 public function setcookie($name, $value, $expire = 0, $prefix = null, $domain = null, $forceSecure = null)
 {
     global $wgCookiePath, $wgCookiePrefix, $wgCookieDomain;
     global $wgCookieSecure, $wgCookieExpiration, $wgCookieHttpOnly;
     if ($expire == 0) {
         $expire = time() + $wgCookieExpiration;
     }
     if ($prefix === null) {
         $prefix = $wgCookiePrefix;
     }
     if ($domain === null) {
         $domain = $wgCookieDomain;
     }
     if (is_null($forceSecure)) {
         $secureCookie = $wgCookieSecure;
     } else {
         $secureCookie = $forceSecure;
     }
     // Mark the cookie as httpOnly if $wgCookieHttpOnly is true,
     // unless the requesting user-agent is known to have trouble with
     // httpOnly cookies.
     $httpOnlySafe = $wgCookieHttpOnly && wfHttpOnlySafe();
     wfDebugLog('cookie', 'setcookie: "' . implode('", "', array($prefix . $name, $value, $expire, $wgCookiePath, $domain, $secureCookie, $httpOnlySafe)) . '"');
     setcookie($prefix . $name, $value, $expire, $wgCookiePath, $domain, $secureCookie, $httpOnlySafe);
 }
示例#26
0
 /**
  * Checks a User object for a blacklisted email address
  *
  * @param User $user
  * @return bool True on valid email
  */
 public function checkUser(User $user)
 {
     $blacklists = $this->getBlacklists();
     $whitelists = $this->getWhitelists();
     // The email to check
     $email = $user->getEmail();
     if (!count($blacklists)) {
         // Nothing to check
         return true;
     }
     // Check for whitelisted email addresses
     if (is_array($whitelists)) {
         wfDebugLog('SpamBlacklist', "Excluding whitelisted email addresses from " . count($whitelists) . " regexes: " . implode(', ', $whitelists) . "\n");
         foreach ($whitelists as $regex) {
             if (preg_match($regex, $email)) {
                 // Whitelisted email
                 return true;
             }
         }
     }
     # Do the match
     wfDebugLog('SpamBlacklist', "Checking e-mail address against " . count($blacklists) . " regexes: " . implode(', ', $blacklists) . "\n");
     foreach ($blacklists as $regex) {
         if (preg_match($regex, $email)) {
             return false;
         }
     }
     return true;
 }
 private function addListenersToCollection()
 {
     $this->eventListenerCollection->registerCallback('factbox.cache.delete', function ($dispatchContext) {
         if ($dispatchContext->has('subject')) {
             $title = $dispatchContext->get('subject')->getTitle();
         } else {
             $title = $dispatchContext->get('title');
         }
         $applicationFactory = ApplicationFactory::getInstance();
         $applicationFactory->getCache()->delete($applicationFactory->newCacheFactory()->getFactboxCacheKey($title->getArticleID()));
     });
     $this->eventListenerCollection->registerCallback('exporter.reset', function () {
         Exporter::getInstance()->clear();
     });
     $this->eventListenerCollection->registerCallback('query.comparator.reset', function () {
         QueryComparator::getInstance()->clear();
     });
     /**
      * Emitted during NewRevisionFromEditComplete, UpdateJob, ArticleDelete
      */
     $this->eventListenerCollection->registerCallback('cached.propertyvalues.prefetcher.reset', function ($dispatchContext) {
         if ($dispatchContext->has('title')) {
             $subject = DIWikiPage::newFromTitle($dispatchContext->get('title'));
         } else {
             $subject = $dispatchContext->get('subject');
         }
         wfDebugLog('smw', 'Clear CachedPropertyValuesPrefetcher for ' . $subject->getHash());
         $applicationFactory = ApplicationFactory::getInstance();
         $applicationFactory->getCachedPropertyValuesPrefetcher()->resetCacheBy($subject);
         $dispatchContext->set('propagationstop', true);
     });
     $this->registerStateChangeEvents();
     return $this->eventListenerCollection;
 }
示例#28
0
function wfNumberOfWikisAssignValue(&$parser, &$cache, &$magicWordId, &$ret)
{
    global $wgMemc;
    if ($magicWordId == 'NUMBEROFWIKIS') {
        $key = wfMemcKey('shoutwiki', 'numberofwikis');
        $data = $wgMemc->get($key);
        if ($data != '') {
            // We have it in cache? Oh goody, let's just use the cached value!
            wfDebugLog('NumberOfWikis', 'Got the amount of wikis from memcached');
            // return value
            $ret = $data;
        } else {
            // Not cached → have to fetch it from the database
            $dbr = wfGetDB(DB_SLAVE);
            $res = $dbr->select('wiki_list', 'COUNT(*) AS count', array('wl_deleted' => 0), __METHOD__);
            wfDebugLog('NumberOfWikis', 'Got the amount of wikis from DB');
            foreach ($res as $row) {
                // Store the count in cache...
                // (86400 = seconds in a day)
                $wgMemc->set($key, $row->count, 86400);
                // ...and return the value to the user
                $ret = $row->count;
            }
        }
    }
    return true;
}
示例#29
0
 /**
  * Function
  *
  * registerDatabase()
  * 
  * Check and setup okw_ontology, okw_object_property and okw_annotation_property exists in MediaWiki database.
  */
 private function registerDatabase()
 {
     $sql = new SQLStore(wfGetDB(DB_MASTER));
     if (!$sql->isSetUp()) {
         wfDebugLog('OntoKiWi', 'Database: setting up OntoKiWi MySQL tables');
         $sql->setup();
     }
 }
 /**
  * If requested title doesn't exist, redirect to duplicate title (same name but different case) if exists.
  * NOTE: As of MediaWiki 1.18.0, $article is NULL 
  * @param Title $title
  * @param type $article
  * @param type $output
  * @param type $user
  * @param type $request
  * @param type $mediaWiki
  * @return boolean 
  */
 public static function redirectDuplicate(&$title, $article, &$output, &$user, $request, $mediaWiki)
 {
     if ($title->getNamespace() != NS_SPECIAL && !$title->isKnown() && ($duplicate = TitleKey::exactMatchTitle($title))) {
         wfDebugLog('preventduplicate', "{$title->getPrefixedDBkey()} asked, doesn't exist, suggest to use {$duplicate->getPrefixedDBkey()} instead");
         $title = $duplicate;
     }
     return true;
 }