示例#1
0
 function insertJobs(ResultWrapper $res)
 {
     $numRows = $res->numRows();
     $numBatches = ceil($numRows / $this->mRowsPerJob);
     $realBatchSize = $numRows / $numBatches;
     $boundaries = array();
     $start = false;
     $jobs = array();
     do {
         for ($i = 0; $i < $realBatchSize - 1; $i++) {
             $row = $res->fetchRow();
             if ($row) {
                 $id = $row[0];
             } else {
                 $id = false;
                 break;
             }
         }
         if ($id !== false) {
             // One less on the end to avoid duplicating the boundary
             $job = new HTMLCacheUpdateJob($this->mTitle, $this->mTable, $start, $id - 1);
         } else {
             $job = new HTMLCacheUpdateJob($this->mTitle, $this->mTable, $start, false);
         }
         $jobs[] = $job;
         $start = $id;
     } while ($start);
     Job::batchInsert($jobs);
 }
示例#2
0
 /**
  *
  * Add/update a page to wiki
  * @param string $pagename
  * @param string $text
  * @param boolean $hasSemanticInternal whether this text contains semanticInternal Object.
  * SemanticInternal Object needs some special handling. First there is a bug in current
  * SemanticInternal Object implemenattion: the semantic internal properties can not be
  * saved in the very first time. Second, if the semantic internal object saving is not from
  * a special page action, but a regular page saving action, the semantic internal object
  * is confused about the "CURRENT" page. So asynchronous saving through a task is needed.
  *
  * @param $summary
  */
 public static function addPage($pagename, $text, $force = true, $astask = false, $hasSemanticInternal = false, $summary = "Auto generation")
 {
     global $wgUser;
     $title = str_replace(' ', '_', $pagename);
     $t = Title::makeTitleSafe(NS_MAIN, $title);
     $article = new Article($t);
     if ($article->exists() && !$force) {
         return false;
     }
     if (!$astask) {
         $e = $article->exists();
         //do adding inline
         $article->doEdit($text, $summary);
         if ($hasSemanticInternal && !$e) {
             //one more time
             $article->doEdit($text, $summary);
         }
         return true;
     } else {
         //add article asynchronously.
         $jobs = array();
         $job_params = array();
         $job_params['user_id'] = $wgUser->getId();
         $job_params['edit_summary'] = $summary;
         $job_params['text'] = $text;
         $jobs[] = new DTImportJob($t, $job_params);
         if ($hasSemanticInternal && !$article->exists()) {
             $jobs[] = new DTImportJob($t, $job_params);
         }
         Job::batchInsert($jobs);
     }
 }
示例#3
0
 protected function insertJobs()
 {
     $batches = $this->mCache->partition($this->mTable, $this->mRowsPerJob);
     if (!$batches) {
         return;
     }
     foreach ($batches as $batch) {
         $params = array('table' => $this->mTable, 'start' => $batch[0], 'end' => $batch[1]);
         $jobs[] = new HTMLCacheUpdateJob($this->mTitle, $params);
     }
     Job::batchInsert($jobs);
 }
 protected function insertJobs(ResultWrapper $res)
 {
     $numRows = $res->numRows();
     if (!$numRows) {
         return;
         // sanity check
     }
     $numBatches = ceil($numRows / $this->mRowsPerJob);
     $realBatchSize = ceil($numRows / $numBatches);
     $jobs = array();
     do {
         $first = $last = false;
         // first/last page_id of this batch
         # Get $realBatchSize items (or less if not enough)...
         for ($i = 0; $i < $realBatchSize; $i++) {
             $row = $res->fetchRow();
             # Is there another row?
             if ($row) {
                 $id = $row[0];
                 $last = $id;
                 // $id is the last page_id of this batch
                 if ($first === false) {
                     $first = $id;
                 }
                 // set first page_id of this batch
                 # Out of rows?
             } else {
                 $id = false;
                 break;
             }
         }
         # Insert batch into the queue if there is anything there
         if ($first) {
             $params = array('table' => $this->mTable, 'start' => $first, 'end' => $last);
             $jobs[] = new FRExtraCacheUpdateJob($this->mTitle, $params);
         }
         $start = $id;
         // Where the last ID left off
     } while ($start);
     Job::batchInsert($jobs);
 }
 function modifyPages($source, $editSummary, $forPagesThatExist)
 {
     $text = "";
     $xml_parser = new DTXMLParser($source);
     $xml_parser->doParse();
     $jobs = array();
     $job_params = array();
     global $wgUser;
     $job_params['user_id'] = $wgUser->getId();
     $job_params['edit_summary'] = $editSummary;
     $job_params['for_pages_that_exist'] = $forPagesThatExist;
     foreach ($xml_parser->mPages as $page) {
         $title = Title::newFromText($page->getName());
         $job_params['text'] = $page->createText();
         $jobs[] = new DTImportJob($title, $job_params);
     }
     Job::batchInsert($jobs);
     global $wgLang;
     $text .= wfMsgExt('dt_import_success', array('parse'), $wgLang->formatNum(count($jobs)), 'XML');
     return $text;
 }
示例#6
0
 /** 
  * Insert jobs into the job queue to fix redirects to the given title
  * @param string $type The reason for the fix, see message double-redirect-fixed-<reason>
  * @param Title $redirTitle The title which has changed, redirects pointing to this title are fixed
  */
 public static function fixRedirects($reason, $redirTitle, $destTitle = false)
 {
     # Need to use the master to get the redirect table updated in the same transaction
     $dbw = wfGetDB(DB_MASTER);
     $res = $dbw->select(array('redirect', 'page'), array('page_namespace', 'page_title'), array('page_id = rd_from', 'rd_namespace' => $redirTitle->getNamespace(), 'rd_title' => $redirTitle->getDBkey()), __METHOD__);
     if (!$res->numRows()) {
         return;
     }
     $jobs = array();
     foreach ($res as $row) {
         $title = Title::makeTitle($row->page_namespace, $row->page_title);
         if (!$title) {
             continue;
         }
         $jobs[] = new self($title, array('reason' => $reason, 'redirTitle' => $redirTitle->getPrefixedDBkey()));
         # Avoid excessive memory usage
         if (count($jobs) > 10000) {
             Job::batchInsert($jobs);
             $jobs = array();
         }
     }
     Job::batchInsert($jobs);
 }
 function insertJobs(ResultWrapper $res)
 {
     $numRows = $res->numRows();
     $numBatches = ceil($numRows / $this->mRowsPerJob);
     $realBatchSize = $numRows / $numBatches;
     $start = false;
     $jobs = array();
     do {
         for ($i = 0; $i < $realBatchSize - 1; $i++) {
             $row = $res->fetchRow();
             if ($row) {
                 $id = $row[0];
             } else {
                 $id = false;
                 break;
             }
         }
         $params = array('table' => $this->mTable, 'start' => $start, 'end' => $id !== false ? $id - 1 : false);
         $jobs[] = new HTMLCacheUpdateJob($this->mTitle, $params);
         $start = $id;
     } while ($start);
     Job::batchInsert($jobs);
 }
示例#8
0
 function modifyPages($source, $editSummary, $forPagesThatExist)
 {
     $text = "";
     $xml_parser = new DTXMLParser($source);
     $xml_parser->doParse();
     $jobs = array();
     $job_params = array();
     $job_params['user_id'] = $this->getUser()->getId();
     $job_params['edit_summary'] = $editSummary;
     $job_params['for_pages_that_exist'] = $forPagesThatExist;
     foreach ($xml_parser->mPages as $page) {
         $title = Title::newFromText($page->getName());
         $job_params['text'] = $page->createText();
         $jobs[] = new DTImportJob($title, $job_params);
     }
     // MW 1.21+
     if (class_exists('JobQueueGroup')) {
         JobQueueGroup::singleton()->push($jobs);
     } else {
         Job::batchInsert($jobs);
     }
     $text .= $this->msg('dt_import_success')->numParams(count($jobs))->params('XML')->parseAsBlock();
     return $text;
 }
 /**
  * Automatically creates a page that's red-linked from the page being
  * viewed, if there's a property pointing from anywhere to that page
  * that's defined with the 'Creates pages with form' special property
  */
 static function createLinkedPage($title, $incoming_properties)
 {
     // if we're in a 'special' page, just exit - this is to prevent
     // constant additions being made from the 'Special:RecentChanges'
     // page, which shows pages that were previously deleted as red
     // links, even if they've since been recreated. The same might
     // hold true for other special pages.
     global $wgTitle;
     if (empty($wgTitle)) {
         return false;
     }
     if ($wgTitle->getNamespace() == NS_SPECIAL) {
         return false;
     }
     foreach ($incoming_properties as $property_name) {
         $auto_create_forms = self::getFormsThatPagePointsTo($property_name, SMW_NS_PROPERTY, self::AUTO_CREATE_FORM);
         if (count($auto_create_forms) > 0) {
             global $sfgFormPrinter;
             $form_name = $auto_create_forms[0];
             $form_title = Title::makeTitleSafe(SF_NS_FORM, $form_name);
             $form_definition = SFUtils::getPageText($form_title);
             $preloadContent = null;
             // allow extensions to set/change the preload text
             wfRunHooks('sfEditFormPreloadText', array(&$preloadContent, $title, $form_title));
             list($form_text, $javascript_text, $data_text, $form_page_title, $generated_page_name) = $sfgFormPrinter->formHTML($form_definition, false, false, null, $preloadContent, 'Some very long page name that will hopefully never get created ABCDEF123', null);
             $params = array();
             // Get user "responsible" for all auto-generated
             // pages from red links.
             $userID = 1;
             global $sfgAutoCreateUser;
             if (!is_null($sfgAutoCreateUser)) {
                 $user = User::newFromName($sfgAutoCreateUser);
                 if (!is_null($user)) {
                     $userID = $user->getId();
                 }
             }
             $params['user_id'] = $userID;
             $params['page_text'] = $data_text;
             $job = new SFCreatePageJob($title, $params);
             Job::batchInsert(array($job));
             return true;
         }
     }
     return false;
 }
示例#10
0
 /**
  * Generate pages (form and templates) specified in the list.
  */
 public static function generatePages($pageSchemaObj, $selectedPages)
 {
     global $wgUser;
     $psFormItems = $pageSchemaObj->getFormItemsList();
     $form_items = array();
     $jobs = array();
     $templateHackUsed = false;
     $isCategoryNameSet = false;
     // Generate every specified template
     foreach ($psFormItems as $psFormItem) {
         if ($psFormItem['type'] == 'Template') {
             $psTemplate = $psFormItem['item'];
             $templateName = $psTemplate->getName();
             $templateTitle = Title::makeTitleSafe(NS_TEMPLATE, $templateName);
             $fullTemplateName = PageSchemas::titleString($templateTitle);
             $template_fields = self::getFieldsFromTemplateSchema($psTemplate);
             // Get property for use in either #set_internal
             // or #subobject, defined by either SIO's or
             // SMW's Page Schemas portion. We don't need
             // to record which one it came from, because
             // SF's code to generate the template runs its
             // own, similar check.
             // @TODO - $internalObjProperty should probably
             // have a more generic name.
             if (class_exists('SIOPageSchemas')) {
                 $internalObjProperty = SIOPageSchemas::getInternalObjectPropertyName($psTemplate);
             } elseif (method_exists('SMWPageSchemas', 'getConnectingPropertyName')) {
                 $internalObjProperty = SMWPageSchemas::getConnectingPropertyName($psTemplate);
             } else {
                 $internalObjProperty = null;
             }
             // TODO - actually, the category-setting should be
             // smarter than this: if there's more than one
             // template in the schema, it should probably be only
             // the first non-multiple template that includes the
             // category tag.
             if ($psTemplate->isMultiple()) {
                 $categoryName = null;
             } else {
                 if ($isCategoryNameSet == false) {
                     $categoryName = $pageSchemaObj->getCategoryName();
                     $isCategoryNameSet = true;
                 } else {
                     $categoryName = null;
                 }
             }
             if (method_exists($psTemplate, 'getFormat')) {
                 $templateFormat = $psTemplate->getFormat();
             } else {
                 $templateFormat = null;
             }
             $sfTemplate = new SFTemplate($templateName, $template_fields);
             $sfTemplate->setConnectingProperty($internalObjProperty);
             $sfTemplate->setCategoryName($categoryName);
             $sfTemplate->setFormat($templateFormat);
             // Set Cargo table, if one was set in the schema.
             $cargoArray = $psTemplate->getObject('cargo_TemplateDetails');
             if (!is_null($cargoArray)) {
                 $sfTemplate->mCargoTable = PageSchemas::getValueFromObject($cargoArray, 'Table');
             }
             $templateText = $sfTemplate->createText();
             if (in_array($fullTemplateName, $selectedPages)) {
                 $params = array();
                 $params['user_id'] = $wgUser->getId();
                 $params['page_text'] = $templateText;
                 $jobs[] = new PSCreatePageJob($templateTitle, $params);
                 if (strpos($templateText, '{{!}}') > 0) {
                     $templateHackUsed = true;
                 }
             }
             $templateValues = self::getTemplateValues($psTemplate);
             if (array_key_exists('Label', $templateValues)) {
                 $templateLabel = $templateValues['Label'];
             } else {
                 $templateLabel = null;
             }
             $form_fields = self::getFormFieldInfo($psTemplate, $template_fields);
             // Create template info for form, for use in generating
             // the form (if it will be generated).
             $form_template = SFTemplateInForm::create($templateName, $templateLabel, $psTemplate->isMultiple(), null, $form_fields);
             $form_items[] = array('type' => 'template', 'name' => $form_template->getTemplateName(), 'item' => $form_template);
         } elseif ($psFormItem['type'] == 'Section') {
             $psPageSection = $psFormItem['item'];
             $form_section = self::getPageSection($psPageSection);
             $form_section->setSectionLevel($psPageSection->getSectionLevel());
             $form_items[] = array('type' => 'section', 'name' => $form_section->getSectionName(), 'item' => $form_section);
         }
     }
     // Create the "!" hack template, if it's necessary
     if ($templateHackUsed) {
         $templateTitle = Title::makeTitleSafe(NS_TEMPLATE, '!');
         if (!$templateTitle->exists()) {
             $params = array();
             $params['user_id'] = $wgUser->getId();
             $params['page_text'] = '|';
             $jobs[] = new PSCreatePageJob($templateTitle, $params);
         }
     }
     if (class_exists('JobQueueGroup')) {
         JobQueueGroup::singleton()->push($jobs);
     } else {
         // MW <= 1.20
         Job::batchInsert($jobs);
     }
     // Create form, if it's specified.
     $formName = self::getFormName($pageSchemaObj);
     $categoryName = $pageSchemaObj->getCategoryName();
     if (!empty($formName)) {
         $formInfo = self::getMainFormInfo($pageSchemaObj);
         $formTitle = Title::makeTitleSafe(SF_NS_FORM, $formName);
         $fullFormName = PageSchemas::titleString($formTitle);
         if (in_array($fullFormName, $selectedPages)) {
             self::generateForm($formName, $formTitle, $form_items, $formInfo, $categoryName);
         }
     }
 }
	function doSpecialReplaceText() {
		global $wgOut, $wgRequest, $wgLang;
		$linker = class_exists( 'DummyLinker' ) ? new DummyLinker : new Linker;

		$this->target = $wgRequest->getText( 'target' );
		$this->replacement = $wgRequest->getText( 'replacement' );
		$this->use_regex = $wgRequest->getBool( 'use_regex' );
		$this->category = $wgRequest->getText( 'category' );
		$this->prefix = $wgRequest->getText( 'prefix' );
		$this->edit_pages = $wgRequest->getBool( 'edit_pages' );
		$this->move_pages = $wgRequest->getBool( 'move_pages' );
		$this->selected_namespaces = self::getSelectedNamespaces();

		if ( $wgRequest->getCheck( 'continue' ) ) {
			if ( $this->target === '' ) {
				$this->showForm( 'replacetext_givetarget' );
				return;
			}
		}

		if ( $wgRequest->getCheck( 'replace' ) ) {
			$replacement_params = array();
			$replacement_params['user_id'] = $this->user->getId();
			$replacement_params['target_str'] = $this->target;
			$replacement_params['replacement_str'] = $this->replacement;
			$replacement_params['use_regex'] = $this->use_regex;
			$replacement_params['edit_summary'] = wfMsgForContent( 'replacetext_editsummary', $this->target, $this->replacement );
			$replacement_params['create_redirect'] = false;
			$replacement_params['watch_page'] = false;
			foreach ( $wgRequest->getValues() as $key => $value ) {
				if ( $key == 'create-redirect' && $value == '1' ) {
					$replacement_params['create_redirect'] = true;
				} elseif ( $key == 'watch-pages' && $value == '1' ) {
					$replacement_params['watch_page'] = true;
				}
			}
			$jobs = array();
			foreach ( $wgRequest->getValues() as $key => $value ) {
				if ( $value == '1' && $key !== 'replace' ) {
					if ( strpos( $key, 'move-' ) !== false ) {
						$title = Title::newFromID( substr( $key, 5 ) );
						$replacement_params['move_page'] = true;
					} else {
						$title = Title::newFromID( $key );
					}
					if ( $title !== null )
						$jobs[] = new ReplaceTextJob( $title, $replacement_params );
				}
			}
			Job::batchInsert( $jobs );

			$count = $wgLang->formatNum( count( $jobs ) );
			$wgOut->addWikiMsg( 'replacetext_success', "<tt><nowiki>{$this->target}</nowiki></tt>", "<tt><nowiki>{$this->replacement}</nowiki></tt>", $count );

			// Link back
			$wgOut->addHTML( $linker->link( $this->getTitle(), wfMsgHtml( 'replacetext_return' ) ) );
			return;
		} elseif ( $wgRequest->getCheck( 'target' ) ) { // very long elseif, look for "end elseif"
			// first, check that at least one namespace has been
			// picked, and that either editing or moving pages
			// has been selected
			if ( count( $this->selected_namespaces ) == 0 ) {
				$this->showForm( 'replacetext_nonamespace' );
				return;
			}
			if ( ! $this->edit_pages && ! $this->move_pages ) {
				$this->showForm( 'replacetext_editormove' );
				return;
			}

			$jobs = array();
			$titles_for_edit = array();
			$titles_for_move = array();
			$unmoveable_titles = array();

			// if user is replacing text within pages...
			if ( $this->edit_pages ) {
				$res = $this->doSearchQuery( $this->target, $this->selected_namespaces, $this->category, $this->prefix , $this->use_regex );
				foreach ( $res as $row ) {
					$title = Title::makeTitleSafe( $row->page_namespace, $row->page_title );
					$context = $this->extractContext( $row->old_text, $this->target, $this->use_regex );
					$titles_for_edit[] = array( $title, $context );
				}
			}
			if ( $this->move_pages ) {
				$res = $this->getMatchingTitles( $this->target, $this->selected_namespaces, $this->category, $this->prefix, $this->use_regex );
				foreach ( $res as $row ) {
					$title = Title::makeTitleSafe( $row->page_namespace, $row->page_title );
					// see if this move can happen
					$cur_page_name = str_replace( '_', ' ', $row->page_title );
					if ( $this->use_regex ) {
						$new_page_name = preg_replace( "/".$this->target."/U", $this->replacement, $cur_page_name );
					} else {
						$new_page_name = str_replace( $this->target, $this->replacement, $cur_page_name );
					}
					$new_title = Title::makeTitleSafe( $row->page_namespace, $new_page_name );
					$err = $title->isValidMoveOperation( $new_title );
					if ( $title->userCan( 'move' ) && !is_array( $err ) ) {
						$titles_for_move[] = $title;
					} else {
						$unmoveable_titles[] = $title;
					}
				}
			}
			// if no results were found, check to see if a bad
			// category name was entered
			if ( count( $titles_for_edit ) == 0 && count( $titles_for_move ) == 0 ) {
				$bad_cat_name = false;
				if ( ! empty( $this->category ) ) {
					$category_title = Title::makeTitleSafe( NS_CATEGORY, $this->category );
					if ( ! $category_title->exists() ) $bad_cat_name = true;
				}
				if ( $bad_cat_name ) {
					$link = $linker->link( $category_title, htmlspecialchars( ucfirst( $this->category ) ) );
					$wgOut->addHTML( wfMsgHtml( 'replacetext_nosuchcategory', $link ) );
				} else {
					if ( $this->edit_pages )
						$wgOut->addWikiMsg( 'replacetext_noreplacement', "<tt><nowiki>{$this->target}</nowiki></tt>" );
					if ( $this->move_pages )
						$wgOut->addWikiMsg( 'replacetext_nomove', "<tt><nowiki>{$this->target}</nowiki></tt>" );
				}
				// link back to starting form
				//FIXME: raw html message
				$wgOut->addHTML( '<p>' . $linker->link( $this->getTitle(), wfMsgHtml( 'replacetext_return' ) ) . '</p>' );
			} else {
				// Show a warning message if the replacement
				// string is either blank or found elsewhere on
				// the wiki (since undoing the replacement
				// would be difficult in either case).
				$warning_msg = null;

				if ( $this->replacement === '' ) {
					$warning_msg = wfMsg('replacetext_blankwarning');
				} elseif ( count( $titles_for_edit ) > 0 ) {
					$res = $this->doSearchQuery( $this->replacement, $this->selected_namespaces, $this->category, $this->prefix, $this->use_regex );
					$count = $res->numRows();
					if ( $count > 0 ) {
						$warning_msg = wfMsgExt( 'replacetext_warning', 'parsemag',
							$wgLang->formatNum( $count ),
							"<tt><nowiki>{$this->replacement}</nowiki></tt>"
						);
					}
				} elseif ( count( $titles_for_move ) > 0 ) {
					$res = $this->getMatchingTitles( $this->replacement, $this->selected_namespaces, $this->category, $this->prefix, $this->use_regex );
					$count = $res->numRows();
					if ( $count > 0 ) {
						$warning_msg = wfMsgExt( 'replacetext_warning', 'parsemag',
							$wgLang->formatNum( $count ),
							$this->replacement
						);
					}
				}

				if ( ! is_null( $warning_msg ) ) {
					$wgOut->addWikiText("<div class=\"errorbox\">$warning_msg</div><br clear=\"both\" />");
				}

				$this->pageListForm( $titles_for_edit, $titles_for_move, $unmoveable_titles );
			}
			return;
		}

		// if we're still here, show the starting form
		$this->showForm();
	}
示例#12
0
 /**
  * Generate pages (form and templates) specified in the list.
  */
 public static function generatePages($pageSchemaObj, $selectedPages)
 {
     global $wgUser;
     $psTemplates = $pageSchemaObj->getTemplates();
     $form_templates = array();
     $jobs = array();
     foreach ($psTemplates as $psTemplate) {
         // Generate every specified template
         $templateName = $psTemplate->getName();
         $templateTitle = Title::makeTitleSafe(NS_TEMPLATE, $templateName);
         $fullTemplateName = PageSchemas::titleString($templateTitle);
         $template_fields = self::getFieldsFromTemplateSchema($psTemplate);
         if (class_exists('SIOPageSchemas')) {
             $internalObjProperty = SIOPageSchemas::getInternalObjectPropertyName($psTemplate);
         } else {
             $internalObjProperty = null;
         }
         // TODO - actually, the category-setting should be
         // smarter than this: if there's more than one
         // template in the schema, it should probably be only
         // the first non-multiple template that includes the
         // category tag.
         if ($psTemplate->isMultiple()) {
             $categoryName = null;
         } else {
             $categoryName = $pageSchemaObj->getCategoryName();
         }
         $templateText = SFTemplateField::createTemplateText($templateName, $template_fields, $internalObjProperty, $categoryName, null, null, null);
         if (in_array($fullTemplateName, $selectedPages)) {
             $params = array();
             $params['user_id'] = $wgUser->getId();
             $params['page_text'] = $templateText;
             $jobs[] = new PSCreatePageJob($templateTitle, $params);
         }
         $templateValues = self::getTemplateValues($psTemplate);
         if (array_key_exists('Label', $templateValues)) {
             $templateLabel = $templateValues['Label'];
         } else {
             $templateLabel = null;
         }
         $form_fields = self::getFormFieldInfo($psTemplate, $template_fields);
         // Create template info for form, for use in generating
         // the form (if it will be generated).
         $form_template = SFTemplateInForm::create($templateName, $templateLabel, $psTemplate->isMultiple(), null, $form_fields);
         $form_templates[] = $form_template;
     }
     Job::batchInsert($jobs);
     // Create form, if it's specified.
     $formName = self::getFormName($pageSchemaObj);
     if (!empty($formName)) {
         $formInfo = self::getMainFormInfo($pageSchemaObj);
         $formTitle = Title::makeTitleSafe(SF_NS_FORM, $formName);
         $fullFormName = PageSchemas::titleString($formTitle);
         if (in_array($fullFormName, $selectedPages)) {
             self::generateForm($formName, $formTitle, $form_templates, $formInfo, $categoryName);
         }
     }
 }
	public function notifyUsers() {
		global $wgSitename, $wgSMTP, $wgEmergencyContact, $wgEnotifyMeJob;
		$sStore = NMStorage::getDatabase();

		$nm_send_jobs = array();
		$id = 0;

		if ( count( $this->m_notifyHtmlMsgs ) > 0 ) {
			$notifications = $sStore->getNotifyMe( array_keys( $this->m_notifyHtmlMsgs ) );
		}
		$html_style = '';
		// <style>
		// table.smwtable{background-color: #EEEEFF;}
		// table.smwtable th{background-color: #EEEEFF;text-align: left;}
		// table.smwtable td{background-color: #FFFFFF;padding: 1px;padding-left: 5px;padding-right: 5px;text-align: left;vertical-align: top;}
		// table.smwtable tr.smwfooter td{font-size: 90%;line-height: 1;background-color: #EEEEFF;padding: 0px;padding-left: 5px;padding-right: 5px;text-align: right;vertical-align: top;}
		// </style>';
		$html_showall = array();
		foreach ( $this->m_notifyHtmlMsgs as $notify_id => $msg ) {
			$html_msg = $html_style;
			$showing_all = false;
			if ( isset( $notifications[$notify_id] ) && $notifications[$notify_id]['show_all'] ) {
				SMWQueryProcessor::processFunctionParams( SMWNotifyProcessor::getQueryRawParams( $notifications[$notify_id]['query'] ), $querystring, $params, $printouts );

				$format = 'auto';
				if ( array_key_exists( 'format', $params ) ) {
					$format = strtolower( trim( $params['format'] ) );
					global $smwgResultFormats;
					if ( !array_key_exists( $format, $smwgResultFormats ) ) {
						$format = 'auto';
					}
				}
				$query  = SMWQueryProcessor::createQuery( $querystring, $params, SMWQueryProcessor::INLINE_QUERY, $format, $printouts );
				$res = smwfGetStore()->getQueryResult( $query );
				$printer = SMWQueryProcessor::getResultPrinter( $format, SMWQueryProcessor::INLINE_QUERY, $res );
				$result = $printer->getResult( $res, $params, SMW_OUTPUT_HTML );
				// FIXME: hardcode switch to full url
				global $wgScriptPath, $wgServer;
				$result = str_replace ( $wgScriptPath, $wgServer . $wgScriptPath, $result );
				$html_msg .= $result . '<br/>';
				$html_showall[$notify_id] = array ( 'name' => $notifications[$notify_id]['name'], 'html' => $result );

				$showing_all = true;
				$link = $res->getQueryLink()->getURL();
			}
			global $smwgNMHideDiffWhenShowAll;
			if ( !( $smwgNMHideDiffWhenShowAll && $showing_all ) ) {
				$html_msg .= wfMsg( 'smw_nm_hint_notification_html', $this->m_notifyHtmlMsgs[$notify_id] );
				if ( isset( $this->m_notifyHtmlPropMsgs[$notify_id] ) ) {
					$html_msg .= wfMsg( 'smw_nm_hint_nmtable_html', $this->m_notifyHtmlPropMsgs[$notify_id] );
				}
			}
			if ( $showing_all ) {
				$id = $sStore->addNotifyRSS( 'nid', $notify_id, "All current items, " . date( 'Y-m-d H:i:s', time() ), $this->applyStyle( $html_msg ), $link );
			} else {
				$id = $sStore->addNotifyRSS( 'nid', $notify_id, $this->m_title->getText(), $this->applyStyle( $html_msg ) );
			}
		}
		foreach ( $this->m_userMsgs as $user_id => $msg ) {
			// generate RSS items
			$html_msg = $html_style;
			foreach ( array_unique( $this->m_userNMs[$user_id] ) as $showall_nid ) {
				if ( isset( $html_showall[$showall_nid] ) ) {
					$html_msg .= wfMsg( 'smw_nm_hint_item_html', $html_showall[$showall_nid]['name'], $html_showall[$showall_nid]['html'] );
				}
			}

			$html_msg .= wfMsg( 'smw_nm_hint_notification_html', $this->m_userHtmlNMMsgs[$user_id] );
			if ( isset( $this->m_userHtmlPropMsgs[$user_id] ) ) {
				$html_msg .= wfMsg( 'smw_nm_hint_nmtable_html', $this->m_userHtmlPropMsgs[$user_id] );
			}

			global $wgNMReportModifier, $wgUser;
			if ( $wgNMReportModifier ) {
				$userText = $wgUser->getName();
				if ( $wgUser->getId() == 0 ) {
					$page = SpecialPage::getTitleFor( 'Contributions', $userText );
				} else {
					$page = Title::makeTitle( NS_USER, $userText );
				}
				$l = '<a href="' . $page->getFullUrl() . '">' . htmlspecialchars( $userText ) . '</a>';
				$html_msg .= wfMsg( 'smw_nm_hint_modifier_html', $l );
				$msg .= wfMsg( 'smw_nm_hint_modifier', $wgUser->getName() );
			}

			$id = $sStore->addNotifyRSS( 'uid', $user_id, $this->m_title->getText(), $this->applyStyle( $html_msg ) );

			if ( $wgEnotifyMeJob ) {
				// send notifications by mail
				$user_info = $sStore->getUserInfo( $user_id );
				$user = User::newFromRow( $user_info );
				if ( ( $user_info->user_email != '' ) && $user->getOption( 'enotifyme' ) ) {
					$name = ( ( $user_info->user_real_name == '' ) ? $user_info->user_name:$user_info->user_real_name );

					$params = array( 'to' => new MailAddress( $user_info->user_email, $name ),
						'from' => new MailAddress( $wgEmergencyContact, 'Admin' ),
						'subj' => wfMsg( 'smw_nm_hint_mail_title', $this->m_title->getText(), $wgSitename ),
						'body' => wfMsg( 'smw_nm_hint_mail_body', $name, $msg ),
						'replyto' => new MailAddress( $wgEmergencyContact, 'Admin' ) );

					$nm_send_jobs[] = new SMW_NMSendMailJob( $this->m_title, $params );
				}
			}
		}

		if ( $wgEnotifyMeJob ) {
			if ( count( $nm_send_jobs ) ) {
				Job :: batchInsert( $nm_send_jobs );
			}
		} else {
			global $phpInterpreter;
			if ( !isset( $phpInterpreter ) ) {
				// if $phpInterpreter is not set, assume it is in search path
				// if not, starting of bot will FAIL!
				$phpInterpreter = "php";
			}
			// copy from SMW_GardeningBot.php
			ob_start();
			phpinfo();
			$info = ob_get_contents();
			ob_end_clean();
			// Get Systemstring
			preg_match( '!\nSystem(.*?)\n!is', strip_tags( $info ), $ma );
			// Check if it consists 'windows' as string
			preg_match( '/[Ww]indows/', $ma[1], $os );
			global $smwgNMIP ;
			if ( $os[0] == '' && $os[0] == null ) {

				// FIXME: $runCommand must allow whitespaces in paths too
				$runCommand = "$phpInterpreter -q $smwgNMIP/specials/SMWNotifyMe/SMW_NMSendMailAsync.php";
				// TODO: test async code for linux.
				// low prio
				$nullResult = `$runCommand > /dev/null &`;
			}
			else // windowze
			{
				$runCommand = "\"\"$phpInterpreter\" -q \"$smwgNMIP/specials/SMWNotifyMe/SMW_NMSendMailAsync.php\"\"";
				$wshShell = new COM( "WScript.Shell" );
				$runCommand = "cmd /C " . $runCommand;

				$oExec = $wshShell->Run( $runCommand, 7, false );
			}
		}
	}
 /**
  * Helper method to write information about some redirect. Various updates
  * can be necessary if redirects are resolved as identities in SMW. The
  * title and namespace of the affected page and of its updated redirect
  * target are given. The target can be empty ('') to delete any redirect.
  * Returns the canonical ID that is now to be used for the subject.
  *
  * This method does not change the ids of the affected pages, and thus it
  * is not concerned with updates of the data that is currently stored for
  * the subject. Normally, a subject that is a redirect will not have other
  * data, but this method does not depend on this.
  *
  * @note Please make sure you fully understand this code before making any
  * changes here. Keeping the redirect structure consistent is important,
  * and errors in this code can go unnoticed for quite some time.
  *
  * @note This method merely handles the addition or deletion of a redirect
  * statement in the wiki. It does not assume that any page contents has
  * been changed (e.g. moved). See changeTitle() for additional handling in
  * this case.
  */
 protected function updateRedirects($subject_t, $subject_ns, $curtarget_t = '', $curtarget_ns = -1)
 {
     global $smwgQEqualitySupport, $smwgEnableUpdateJobs;
     // *** First get id of subject, old redirect target, and current (new) redirect target ***//
     $sid = $this->getSMWPageID($subject_t, $subject_ns, '', '', false);
     // find real id of subject, if any
     /// NOTE: $sid can be 0 here; this is useful to know since it means that fewer table updates are needed
     $new_tid = $curtarget_t ? $this->makeSMWPageID($curtarget_t, $curtarget_ns, '', '', false) : 0;
     // real id of new target, if given
     $db = wfGetDB(DB_SLAVE);
     $row = $db->selectRow(array('smw_redi2'), 'o_id', array('s_title' => $subject_t, 's_namespace' => $subject_ns), __METHOD__);
     $old_tid = $row !== false ? $row->o_id : 0;
     // real id of old target, if any
     /// NOTE: $old_tid and $new_tid both (intentionally) ignore further redirects: no redirect chains
     if ($old_tid == $new_tid) {
         // no change, all happy
         return $new_tid == 0 ? $sid : $new_tid;
     }
     // note that this means $old_tid != $new_tid in all cases below
     // *** Make relevant changes in property tables (don't write the new redirect yet) ***//
     $db = wfGetDB(DB_MASTER);
     // now we need to write something
     if ($old_tid == 0 && $sid != 0 && $smwgQEqualitySupport != SMW_EQ_NONE) {
         // new redirect
         // $smwgQEqualitySupport requires us to change all tables' page references from $sid to $new_tid.
         // Since references must not be 0, we don't have to do this is $sid == 0.
         $this->changeSMWPageID($sid, $new_tid, $subject_ns, $curtarget_ns, false, true);
     } elseif ($old_tid != 0) {
         // existing redirect is changed or deleted
         $db->delete('smw_redi2', array('s_title' => $subject_t, 's_namespace' => $subject_ns), __METHOD__);
         if ($smwgEnableUpdateJobs && $smwgQEqualitySupport != SMW_EQ_NONE) {
             // entries that refer to old target may in fact refer to subject,
             // but we don't know which: schedule affected pages for update
             $jobs = array();
             foreach (self::getPropertyTables() as $proptable) {
                 if ($proptable->name == 'smw_redi2') {
                     continue;
                 }
                 // can safely be skipped
                 if ($proptable->idsubject) {
                     $from = $db->tableName($proptable->name) . ' INNER JOIN ' . $db->tableName('smw_ids') . ' ON s_id=smw_id';
                     $select = 'DISTINCT smw_title AS t,smw_namespace AS ns';
                 } else {
                     $from = $db->tableName($proptable->name);
                     $select = 'DISTINCT s_title AS t,s_namespace AS ns';
                 }
                 if ($subject_ns == SMW_NS_PROPERTY && !$proptable->fixedproperty) {
                     $res = $db->select($from, $select, array('p_id' => $old_tid), __METHOD__);
                     foreach ($res as $row) {
                         $title = Title::makeTitleSafe($row->ns, $row->t);
                         if (!is_null($title)) {
                             $jobs[] = new SMWUpdateJob($title);
                         }
                     }
                     $db->freeResult($res);
                 }
                 foreach ($proptable->objectfields as $fieldname => $type) {
                     if ($type == 'p') {
                         $res = $db->select($from, $select, array($fieldname => $old_tid), __METHOD__);
                         foreach ($res as $row) {
                             $title = Title::makeTitleSafe($row->ns, $row->t);
                             if (!is_null($title)) {
                                 $jobs[] = new SMWUpdateJob($title);
                             }
                         }
                         $db->freeResult($res);
                     }
                 }
             }
             /// NOTE: we do not update the concept cache here; this remains an offline task
             /// NOTE: this only happens if $smwgEnableUpdateJobs was true above:
             Job::batchInsert($jobs);
         }
     }
     // *** Finally, write the new redirect data ***//
     if ($new_tid != 0) {
         // record a new redirect
         // Redirecting done right:
         // (1) make a new ID with iw SMW_SQL2_SMWREDIIW or
         //     change iw field of current ID in this way,
         // (2) write smw_redi2 table,
         // (3) update canonical cache.
         // This order must be obeyed unless you really understand what you are doing!
         if ($old_tid == 0 && $smwgQEqualitySupport != SMW_EQ_NONE) {
             // mark subject as redirect (if it was no redirect before)
             if ($sid == 0) {
                 // every redirect page must have an ID
                 $sid = $this->makeSMWPageID($subject_t, $subject_ns, SMW_SQL2_SMWREDIIW, '', false);
             } else {
                 $db->update('smw_ids', array('smw_iw' => SMW_SQL2_SMWREDIIW), array('smw_id' => $sid), __METHOD__);
                 $this->m_idCache->setId($subject_t, $subject_ns, '', '', 0);
                 $this->m_idCache->setId($subject_t, $subject_ns, SMW_SQL2_SMWREDIIW, '', $sid);
             }
         }
         $db->insert('smw_redi2', array('s_title' => $subject_t, 's_namespace' => $subject_ns, 'o_id' => $new_tid), __METHOD__);
     } else {
         // delete old redirect
         // This case implies $old_tid != 0 (or we would have new_tid == old_tid above).
         // Therefore $subject had a redirect, and it must also have an ID.
         // This shows that $sid != 0 here.
         if ($smwgQEqualitySupport != SMW_EQ_NONE) {
             // mark subject as non-redirect
             $db->update('smw_ids', array('smw_iw' => ''), array('smw_id' => $sid), __METHOD__);
             $this->m_idCache->setId($subject_t, $subject_ns, '', '', $sid);
         }
     }
     // *** Flush some caches to be safe, though they are not essential in runs with redirect updates ***//
     unset($this->m_semdata[$sid]);
     unset($this->m_semdata[$new_tid]);
     unset($this->m_semdata[$old_tid]);
     unset($this->m_sdstate[$sid]);
     unset($this->m_sdstate[$new_tid]);
     unset($this->m_sdstate[$old_tid]);
     return $new_tid == 0 ? $sid : $new_tid;
 }
示例#15
0
 protected function queueJobs($jobs, $dryrun = false)
 {
     $this->output("Queuing batch of " . count($jobs) . " double redirects.\n");
     Job::batchInsert($dryrun ? array() : $jobs);
 }
 function createAllPages()
 {
     $out = $this->getOutput();
     $req = $this->getRequest();
     $user = $this->getUser();
     $template_name = trim($req->getVal("template_name"));
     $template_multiple = $req->getBool("template_multiple");
     // If this is a multiple-instance template, there
     // shouldn't be a corresponding form or category.
     if ($template_multiple) {
         $form_name = null;
         $category_name = null;
     } else {
         $form_name = trim($req->getVal("form_name"));
         $category_name = trim($req->getVal("category_name"));
     }
     if ($template_name === '' || !$template_multiple && ($form_name === '' || $category_name === '')) {
         $out->addWikiMsg('sf_createclass_missingvalues');
         return;
     }
     $fields = array();
     $jobs = array();
     // Cycle through all the rows passed in.
     for ($i = 1; $req->getVal("field_name_{$i}") != ''; $i++) {
         // Go through the query values, setting the appropriate
         // local variables.
         $field_name = trim($req->getVal("field_name_{$i}"));
         $property_name = trim($req->getVal("property_name_{$i}"));
         $property_type = $req->getVal("property_type_{$i}");
         $allowed_values = $req->getVal("allowed_values_{$i}");
         $is_list = $req->getCheck("is_list_{$i}");
         // Create an SFTemplateField object based on these
         // values, and add it to the $fields array.
         $field = SFTemplateField::create($field_name, $field_name, $property_name, $is_list);
         if (defined('CARGO_VERSION')) {
             $field->setFieldType($property_type);
             // Hopefully it's safe to use a Cargo
             // utility method here.
             $possibleValues = CargoUtils::smartSplit(',', $allowed_values);
             $field->setPossibleValues($possibleValues);
         }
         $fields[] = $field;
         // Create the property, and make a job for it.
         if (defined('SMW_VERSION') && !empty($property_name)) {
             $full_text = SFCreateProperty::createPropertyText($property_type, '', $allowed_values);
             $property_title = Title::makeTitleSafe(SMW_NS_PROPERTY, $property_name);
             $params = array();
             $params['user_id'] = $user->getId();
             $params['page_text'] = $full_text;
             $params['edit_summary'] = wfMessage('sf_createproperty_editsummary', $property_type)->inContentLanguage()->text();
             $jobs[] = new SFCreatePageJob($property_title, $params);
         }
     }
     // Also create the "connecting property", if there is one.
     $connectingProperty = trim($req->getVal('connecting_property'));
     if (defined('SMW_VERSION') && $connectingProperty != '') {
         global $smwgContLang;
         $datatypeLabels = $smwgContLang->getDatatypeLabels();
         $property_type = $datatypeLabels['_wpg'];
         $full_text = SFCreateProperty::createPropertyText($property_type, '', $allowed_values);
         $property_title = Title::makeTitleSafe(SMW_NS_PROPERTY, $connectingProperty);
         $params = array();
         $params['user_id'] = $user->getId();
         $params['page_text'] = $full_text;
         $params['edit_summary'] = wfMessage('sf_createproperty_editsummary', $property_type)->inContentLanguage()->text();
         $jobs[] = new SFCreatePageJob($property_title, $params);
     }
     // Create the template, and save it (might as well save
     // one page, instead of just creating jobs for all of them).
     $template_format = $req->getVal("template_format");
     $sfTemplate = new SFTemplate($template_name, $fields);
     if (defined('CARGO_VERSION')) {
         $sfTemplate->mCargoTable = trim($req->getVal("cargo_table"));
     }
     if (defined('SMW_VERSION') && $template_multiple) {
         $sfTemplate->setConnectingProperty($connectingProperty);
     } else {
         $sfTemplate->setCategoryName($category_name);
     }
     $sfTemplate->setFormat($template_format);
     $full_text = $sfTemplate->createText();
     $template_title = Title::makeTitleSafe(NS_TEMPLATE, $template_name);
     $edit_summary = '';
     if (method_exists('WikiPage', 'doEditContent')) {
         // MW 1.21+
         $template_page = new WikiPage($template_title);
         $content = new WikitextContent($full_text);
         $template_page->doEditContent($content, $edit_summary);
     } else {
         // MW <= 1.20
         $template_article = new Article($template_title);
         $template_article->doEdit($full_text, $edit_summary);
     }
     // Create the form, and make a job for it.
     if ($form_name != '') {
         $form_template = SFTemplateInForm::create($template_name, '', false);
         $form_items = array();
         $form_items[] = array('type' => 'template', 'name' => $form_template->getTemplateName(), 'item' => $form_template);
         $form = SFForm::create($form_name, $form_items);
         $full_text = $form->createMarkup();
         $form_title = Title::makeTitleSafe(SF_NS_FORM, $form_name);
         $params = array();
         $params['user_id'] = $user->getId();
         $params['page_text'] = $full_text;
         $jobs[] = new SFCreatePageJob($form_title, $params);
     }
     // Create the category, and make a job for it.
     if ($category_name != '') {
         $full_text = SFCreateCategory::createCategoryText($form_name, $category_name, '');
         $category_title = Title::makeTitleSafe(NS_CATEGORY, $category_name);
         $params = array();
         $params['user_id'] = $user->getId();
         $params['page_text'] = $full_text;
         $jobs[] = new SFCreatePageJob($category_title, $params);
     }
     if (class_exists('JobQueueGroup')) {
         JobQueueGroup::singleton()->push($jobs);
     } else {
         // MW <= 1.20
         Job::batchInsert($jobs);
     }
     $out->addWikiMsg('sf_createclass_success');
 }
	protected function performAction() {
		$jobs = array();
		$target = $this->title;
		$base = $this->title->getPrefixedText();

		$translationPages = $this->getTranslationPages();
		foreach ( $translationPages as $old ) {
			$jobs[$old->getPrefixedText()] = DeleteJob::newJob( $old, $base, !$this->singleLanguage(), $this->user );
		}

		$sectionPages = $this->getSectionPages();
		foreach ( $sectionPages as $old ) {
			$jobs[$old->getPrefixedText()] = DeleteJob::newJob( $old, $base, !$this->singleLanguage(), $this->user );
		}

		if ( !$this->doSubpages ) {
			$subpages = $this->getSubpages();
			foreach ( $subpages as $old ) {
				if ( TranslatablePage::isTranslationPage( $old ) ) {
					continue;
				}

				$jobs[$old->getPrefixedText()] = DeleteJob::newJob( $old, $base, !$this->singleLanguage(), $this->user );
			}
		}

		Job::batchInsert( $jobs );

		$cache = wfGetCache( CACHE_DB );
		$cache->set( wfMemcKey( 'pt-base', $target->getPrefixedText() ), array_keys( $jobs ), 60 * 60 * 6 );


		if ( !$this->singleLanguage() ) {
			$this->page->removeTags();
		}

		MessageGroups::clearCache();
		MessageIndexRebuildJob::newJob()->insert();

		global $wgOut;
		$wgOut->addWikiMsg( 'pt-deletepage-started' );
	}
示例#18
0
 function queueRecursiveJobs()
 {
     global $wgUpdateRowsPerJob;
     wfProfileIn(__METHOD__);
     $cache = $this->mTitle->getBacklinkCache();
     $batches = $cache->partition('templatelinks', $wgUpdateRowsPerJob);
     if (!$batches) {
         wfProfileOut(__METHOD__);
         return;
     }
     $jobs = array();
     foreach ($batches as $batch) {
         list($start, $end) = $batch;
         $params = array('start' => $start, 'end' => $end);
         $jobs[] = new RefreshLinksJob2($this->mTitle, $params);
     }
     Job::batchInsert($jobs);
     wfProfileOut(__METHOD__);
 }
 /**
  * @param $upload UploadBase
  * @param $mime
  * @param $error
  * @return bool
  */
 public static function insertJobs($upload, $mime, &$error)
 {
     global $wgPdfCreateThumbnailsInJobQueue;
     if (!$wgPdfCreateThumbnailsInJobQueue) {
         return true;
     }
     if (!MimeMagic::singleton()->isMatchingExtension('pdf', $mime)) {
         return true;
         // not a PDF, abort
     }
     $title = $upload->getTitle();
     $uploadFile = $upload->getLocalFile();
     if (is_null($uploadFile)) {
         wfDebugLog('thumbnails', '$uploadFile seems to be null, should never happen...');
         return true;
         // should never happen, but it's better to be secure
     }
     $metadata = $uploadFile->getMetadata();
     $unserialized = unserialize($metadata);
     $pages = intval($unserialized['Pages']);
     $jobs = array();
     for ($i = 1; $i <= $pages; $i++) {
         $jobs[] = new CreatePdfThumbnailsJob($title, array('page' => $i, 'jobtype' => self::BIG_THUMB));
         $jobs[] = new CreatePdfThumbnailsJob($title, array('page' => $i, 'jobtype' => self::SMALL_THUMB));
     }
     Job::batchInsert($jobs);
     return true;
 }
示例#20
0
 /**
  * Creates the property page for each property specified in the
  * passed-in Page Schemas XML object.
  */
 public static function generatePages($pageSchemaObj, $selectedPages)
 {
     global $wgUser;
     $jobs = array();
     $jobParams = array();
     $jobParams['user_id'] = $wgUser->getId();
     $propertyDataArray = self::getAllPropertyData($pageSchemaObj);
     foreach ($propertyDataArray as $propertyData) {
         $propTitle = Title::makeTitleSafe(SMW_NS_PROPERTY, $propertyData['name']);
         if (!in_array($propTitle, $selectedPages)) {
             continue;
         }
         $jobParams['page_text'] = self::createPropertyText($propertyData['Type'], $propertyData['allowed_values']);
         $jobs[] = new PSCreatePageJob($propTitle, $jobParams);
     }
     Job::batchInsert($jobs);
 }
示例#21
0
 function queueRecursiveJobs()
 {
     global $wgUpdateRowsPerJob;
     wfProfileIn(__METHOD__);
     $dbr = wfGetDB(DB_SLAVE);
     $res = $dbr->select('templatelinks', array('tl_from'), array('tl_namespace' => $this->mTitle->getNamespace(), 'tl_title' => $this->mTitle->getDBkey()), __METHOD__);
     $numRows = $res->numRows();
     if (!$numRows) {
         wfProfileOut(__METHOD__);
         return;
         // nothing to do
     }
     $numBatches = ceil($numRows / $wgUpdateRowsPerJob);
     $realBatchSize = $numRows / $numBatches;
     $start = false;
     $jobs = array();
     do {
         for ($i = 0; $i <= $realBatchSize - 1; $i++) {
             $row = $res->fetchRow();
             if ($row) {
                 $id = $row[0];
             } else {
                 $id = false;
                 break;
             }
         }
         $params = array('start' => $start, 'end' => $id !== false ? $id - 1 : false);
         $jobs[] = new RefreshLinksJob2($this->mTitle, $params);
         # Hit page caches while we're at it if set to do so...
         if ($this->mTouchTmplLinks) {
             $params['table'] = 'templatelinks';
             $jobs[] = new HTMLCacheUpdateJob($this->mTitle, $params);
         }
         $start = $id;
     } while ($start);
     $dbr->freeResult($res);
     Job::batchInsert($jobs);
     wfProfileOut(__METHOD__);
 }
示例#22
0
 /**
  * Run a refreshLinks2 job
  * @return boolean success
  */
 function run()
 {
     global $wgParser;
     wfProfileIn(__METHOD__);
     $linkCache = LinkCache::singleton();
     $linkCache->clear();
     if (is_null($this->title)) {
         $this->error = "refreshLinks2: Invalid title";
         wfProfileOut(__METHOD__);
         return false;
     }
     if (!isset($this->params['start']) || !isset($this->params['end'])) {
         $this->error = "refreshLinks2: Invalid params";
         wfProfileOut(__METHOD__);
         return false;
     }
     $start = intval($this->params['start']);
     $end = intval($this->params['end']);
     $dbr = wfGetDB(DB_SLAVE);
     $res = $dbr->select(array('templatelinks', 'page'), array('page_namespace', 'page_title'), array('page_id=tl_from', "tl_from >= '{$start}'", "tl_from <= '{$end}'", 'tl_namespace' => $this->title->getNamespace(), 'tl_title' => $this->title->getDBkey()), __METHOD__);
     # Not suitable for page load triggered job running!
     # Gracefully switch to refreshLinks jobs if this happens.
     if (php_sapi_name() != 'cli') {
         $jobs = array();
         while ($row = $dbr->fetchObject($res)) {
             $title = Title::makeTitle($row->page_namespace, $row->page_title);
             $jobs[] = new RefreshLinksJob($title, '');
         }
         Job::batchInsert($jobs);
         return true;
     }
     # Re-parse each page that transcludes this page and update their tracking links...
     while ($row = $dbr->fetchObject($res)) {
         $title = Title::makeTitle($row->page_namespace, $row->page_title);
         $revision = Revision::newFromTitle($title);
         if (!$revision) {
             $this->error = 'refreshLinks: Article not found "' . $title->getPrefixedDBkey() . '"';
             wfProfileOut(__METHOD__);
             return false;
         }
         wfProfileIn(__METHOD__ . '-parse');
         $options = new ParserOptions();
         $parserOutput = $wgParser->parse($revision->getText(), $title, $options, true, true, $revision->getId());
         wfProfileOut(__METHOD__ . '-parse');
         wfProfileIn(__METHOD__ . '-update');
         $update = new LinksUpdate($title, $parserOutput, false);
         $update->doUpdate();
         wfProfileOut(__METHOD__ . '-update');
         wfProfileOut(__METHOD__);
     }
     return true;
 }
 public static function createPageWithForm($title, $formName)
 {
     global $sfgFormPrinter;
     $formTitle = Title::makeTitleSafe(SF_NS_FORM, $formName);
     $formDefinition = SFUtils::getPageText($formTitle);
     $preloadContent = null;
     // Allow outside code to set/change the preloaded text.
     Hooks::run('sfEditFormPreloadText', array(&$preloadContent, $title, $formTitle));
     list($formText, $javascriptText, $dataText, $formPageTitle, $generatedPageName) = $sfgFormPrinter->formHTML($formDefinition, false, false, null, $preloadContent, 'Some very long page name that will hopefully never get created ABCDEF123', null);
     $params = array();
     // Get user "responsible" for all auto-generated
     // pages from red links.
     $userID = 1;
     global $sfgAutoCreateUser;
     if (!is_null($sfgAutoCreateUser)) {
         $user = User::newFromName($sfgAutoCreateUser);
         if (!is_null($user)) {
             $userID = $user->getId();
         }
     }
     $params['user_id'] = $userID;
     $params['page_text'] = $dataText;
     $job = new SFCreatePageJob($title, $params);
     $jobs = array($job);
     if (class_exists('JobQueueGroup')) {
         JobQueueGroup::singleton()->push($jobs);
     } else {
         // MW <= 1.20
         Job::batchInsert($jobs);
     }
 }
	protected function performAction() {
		$jobs = array();

		$target = $this->newTitle;
		$base = $this->oldTitle->getPrefixedText();
		$oldLatest = $this->oldTitle->getLatestRevId();

		$params = array(
			'base-source' => $this->oldTitle->getPrefixedText(),
			'base-target' => $this->newTitle->getPrefixedText(),
		);

		$translationPages = $this->getTranslationPages();
		foreach ( $translationPages as $old ) {
			$to = $this->newPageTitle( $base, $old, $target );
			$jobs[$old->getPrefixedText()] = MoveJob::newJob( $old, $to, $params, $this->user );
		}

		$sectionPages = $this->getSectionPages();
		foreach ( $sectionPages as $old ) {
			$to = $this->newPageTitle( $base, $old, $target );
			$jobs[$old->getPrefixedText()] = MoveJob::newJob( $old, $to, $params, $this->user );
		}

		if ( $this->moveSubpages ) {
			$subpages = $this->getSubpages();
			foreach ( $subpages as $old ) {
				if ( TranslatablePage::isTranslationPage( $old ) ) {
					continue;
				}

				$to = $this->newPageTitle( $base, $old, $target );
				$jobs[$old->getPrefixedText()] = MoveJob::newJob( $old, $to, $params, $this->user );
			}
		}

		// This is used by MoveJob
		wfGetCache( CACHE_ANYTHING )->set( wfMemcKey( 'translate-pt-move', $base ), count( $jobs ) );
		Job::batchInsert( $jobs );

		MoveJob::forceRedirects( false );

		$errors = $this->oldTitle->moveTo( $this->newTitle, true, $this->reason, false );
		if ( is_array( $errors ) ) {
			$this->showErrors( $errors );
		}

		MoveJob::forceRedirects( true );

		$newTpage = TranslatablePage::newFromTitle( $this->newTitle );
		$newTpage->addReadyTag( $this->newTitle->getLatestRevId( GAID_FOR_UPDATE ) );

		if ( $newTpage->getMarkedTag() === $oldLatest ) {
			$newTpage->addMarkedTag( $this->newTitle->getLatestRevId( GAID_FOR_UPDATE ) );
		}

		MessageGroups::clearCache();
		MessageIndexRebuildJob::newJob()->insert();

		global $wgOut;
		$wgOut->addWikiMsg( 'pt-movepage-started' );
	}
 function modifyPages($pages, $editSummary, $forPagesThatExist)
 {
     global $wgUser, $wgLang;
     $text = "";
     $jobs = array();
     $jobParams = array();
     $jobParams['user_id'] = $wgUser->getId();
     $jobParams['edit_summary'] = $editSummary;
     $jobParams['for_pages_that_exist'] = $forPagesThatExist;
     foreach ($pages as $page) {
         $title = Title::newFromText($page->getName());
         if (is_null($title)) {
             $text .= '<p>' . wfMsg('img-auth-badtitle', $page->getName()) . "</p>\n";
             continue;
         }
         $jobParams['text'] = $page->createText();
         $jobs[] = new DTImportJob($title, $jobParams);
     }
     Job::batchInsert($jobs);
     $text .= wfMsgExt('dt_import_success', array('parse'), $wgLang->formatNum(count($jobs)), 'CSV');
     return $text;
 }
	/**
	 * Automatically creates a page that's red-linked from the page being
	 * viewed, if there's a property pointing from anywhere to that page
	 * that's defined with the 'Creates pages with form' special property
	 */
	static function createLinkedPage( $title, $incoming_properties ) {
		// if we're in a 'special' page, just exit - this is to prevent
		// constant additions being made from the 'Special:RecentChanges'
		// page, which shows pages that were previously deleted as red
		// links, even if they've since been recreated. The same might
		// hold true for other special pages.
		global $wgTitle;
		if ( empty( $wgTitle ) )
			return false;
		if ( $wgTitle->getNamespace() == NS_SPECIAL )
			return false;

		foreach ( $incoming_properties as $property_name ) {
			$auto_create_forms = self::getFormsThatPagePointsTo( $property_name, SMW_NS_PROPERTY, self::AUTO_CREATE_FORM );
			if ( count( $auto_create_forms ) > 0 ) {
				global $sfgFormPrinter;
				$form_name = $auto_create_forms[0];
				$form_title = Title::makeTitleSafe( SF_NS_FORM, $form_name );
				$form_article = new Article( $form_title );
				$form_definition = $form_article->getContent();
				list ( $form_text, $javascript_text, $data_text, $form_page_title, $generated_page_name ) =
					$sfgFormPrinter->formHTML( $form_definition, false, false, null, null, 'Some very long page name that will hopefully never get created ABCDEF123', null );
				$params = array();
				global $wgUser;
				$params['user_id'] = $wgUser->getId();
				$params['page_text'] = $data_text;
				$job = new SFCreatePageJob( $title, $params );
				Job::batchInsert( array( $job ) );

				return true;
			}
		}

		return false;
	}
	function execute( $query ) {
		global $wgOut, $wgRequest, $wgUser, $sfgScriptPath;
		global $wgLang, $smwgContLang;

		# Check permissions
		if ( !$wgUser->isAllowed( 'createclass' ) ) {
			$this->displayRestrictionError();
			return;
		}

		$this->setHeaders();
		$wgOut->addExtensionStyle( $sfgScriptPath . "/skins/SemanticForms.css" );
		$numStartingRows = 10;
		self::addJavascript( $numStartingRows );

		$property_name_error_str = '';
		$save_page = $wgRequest->getCheck( 'save' );
		if ( $save_page ) {
			$template_name = trim( $wgRequest->getVal( "template_name" ) );
			$form_name = trim( $wgRequest->getVal( "form_name" ) );
			$category_name = trim( $wgRequest->getVal( "category_name" ) );
			if ( $template_name === '' | $form_name === '' || $category_name === '' ) {
				$wgOut->addWikiMsg( 'sf_createclass_missingvalues' );
				return;
			}
			$fields = array();
			$jobs = array();
			// cycle through all the rows passed in
			for ( $i = 1; $wgRequest->getCheck( "property_name_$i" ); $i++ ) {
				// go through the query values, setting the appropriate local variables
				$property_name = trim( $wgRequest->getVal( "property_name_$i" ) );
				if ( empty( $property_name ) ) continue;
				$field_name = trim( $wgRequest->getVal( "field_name_$i" ) );
				if ( $field_name === '' )
					$field_name = $property_name;
				$property_type = $wgRequest->getVal( "property_type_$i" );
				$allowed_values = $wgRequest->getVal( "allowed_values_$i" );
				$is_list = $wgRequest->getCheck( "is_list_$i" );
				// create an SFTemplateField based on these
				// values, and add it to the $fields array
				$field = SFTemplateField::create( $field_name, $field_name, $property_name, $is_list );
				$fields[] = $field;

				// create the property, and make a job for it
				$full_text = SFCreateProperty::createPropertyText( $property_type, '', $allowed_values );
				$property_title = Title::makeTitleSafe( SMW_NS_PROPERTY, $property_name );
				$params = array();
				$params['user_id'] = $wgUser->getId();
				$params['page_text'] = $full_text;
				$jobs[] = new SFCreatePageJob( $property_title, $params );
			}

			// create the template, and save it
			$full_text = SFTemplateField::createTemplateText( $template_name, $fields, null, $category_name, null, null, null );
			$template_title = Title::makeTitleSafe( NS_TEMPLATE, $template_name );
			$template_article = new Article( $template_title, 0 );
			$edit_summary = '';
			$template_article->doEdit( $full_text, $edit_summary );

			// create the form, and make a job for it
			$form_template = SFTemplateInForm::create( $template_name, '', false );
			$form_templates = array( $form_template );
			$form = SFForm::create( $form_name, $form_templates );
			$full_text = $form->createMarkup();
			$form_title = Title::makeTitleSafe( SF_NS_FORM, $form_name );
			$params = array();
			$params['user_id'] = $wgUser->getId();
			$params['page_text'] = $full_text;
			$jobs[] = new SFCreatePageJob( $form_title, $params );

			// create the category, and make a job for it
			$full_text = SFCreateCategory::createCategoryText( $form_name, $category_name, '' );
			$category_title = Title::makeTitleSafe( NS_CATEGORY, $category_name );
			$params = array();
			$params['user_id'] = $wgUser->getId();
			$params['page_text'] = $full_text;
			$jobs[] = new SFCreatePageJob( $category_title, $params );
			Job::batchInsert( $jobs );

			$wgOut->addWikiMsg( 'sf_createclass_success' );
			return;
		}

		$datatype_labels = $smwgContLang->getDatatypeLabels();

		// make links to all the other 'Create...' pages, in order to
		// link to them at the top of the page
		$sk = $wgUser->getSkin();
		$creation_links = array();
		$creation_links[] = SFUtils::linkForSpecialPage( $sk, 'CreateProperty' );
		$creation_links[] = SFUtils::linkForSpecialPage( $sk, 'CreateTemplate' );
		$creation_links[] = SFUtils::linkForSpecialPage( $sk, 'CreateForm' );
		$creation_links[] = SFUtils::linkForSpecialPage( $sk, 'CreateCategory' );
		$create_class_docu = wfMsg( 'sf_createclass_docu', $wgLang->listToText( $creation_links ) );
		$leave_field_blank = wfMsg( 'sf_createclass_leavefieldblank' );
		$form_name_label = wfMsg( 'sf_createclass_nameinput' );
		$template_name_label = wfMsg( 'sf_createtemplate_namelabel' );
		$category_name_label = wfMsg( 'sf_createcategory_name' );
		$property_name_label = wfMsg( 'sf_createproperty_propname' );
		$field_name_label = wfMsg( 'sf_createtemplate_fieldname' );
		$type_label = wfMsg( 'sf_createproperty_proptype' );
		$allowed_values_label = wfMsg( 'sf_createclass_allowedvalues' );
		$list_of_values_label = wfMsg( 'sf_createclass_listofvalues' );

		$text = <<<END
<form action="" method="post">
	<p>$create_class_docu</p>
	<p>$leave_field_blank</p>
	<p>$template_name_label <input type="text" size="30" name="template_name"></p>
	<p>$form_name_label <input type="text" size="30" name="form_name"></p>
	<p>$category_name_label <input type="text" size="30" name="category_name"></p>
	<div>
		<table id="mainTable">
		<tr>
			<th colspan="2">$property_name_label</th>
			<th>$field_name_label</th>
			<th>$type_label</th>
			<th>$allowed_values_label</th>
			<th>$list_of_values_label</th>
		</tr>

END;
		// Make one more row than what we're displaying - use the
		// last row as a "starter row", to be cloned when the
		// "Add another" button is pressed.
		for ( $i = 1; $i <= $numStartingRows + 1; $i++ ) {
			if ( $i == $numStartingRows + 1 ) {
				$rowString = 'id="starterRow" style="display: none"';
				$n = 'starter';
			} else {
				$rowString = '';
				$n = $i;
			}
			$text .= <<<END
		<tr $rowString>
			<td>$n.</td>
			<td><input type="text" size="25" name="property_name_$n" /></td>
			<td><input type="text" size="25" name="field_name_$n" /></td>
			<td>
			<select name="property_type_$n">

END;
			$optionsStr ="";
			foreach ( $datatype_labels as $label ) {
				$text .= "				<option>$label</option>\n";
				$optionsStr .= $label . ",";
			}
			$text .= <<<END
			</select>
			</td>
			<td><input type="text" size="25" name="allowed_values_$n" /></td>
			<td><input type="checkbox" name="is_list_$n" /></td>

END;
		}
		$text .= <<<END
		</tr>
		</table>
	</div>

END;
		$add_another_button = Html::element( 'input',
			array(
				'type' => 'button',
				'value' => wfMsg( 'sf_formedit_addanother' ),
				'onclick' => "createClassAddRow()"
			)
		);
		$text .= Html::rawElement( 'p', null, $add_another_button ) . "\n";
		// Set 'title' as hidden field, in case there's no URL niceness
		$cc = $this->getTitle();
		$text .= SFFormUtils::hiddenFieldHTML( 'title', SFUtils::titleURLString( $cc ) );
		$text .= Html::element( 'input',
			array(
				'type' => 'submit',
				'name' => 'save',
				'value' => wfMsg( 'sf_createclass_create' )
			)
		);
		$text .= "</form>\n";
		$wgOut->addHTML( $text );
	}
示例#28
0
 /**
  * Run a refreshLinks2 job
  * @return boolean success
  */
 function run()
 {
     global $wgParser, $wgContLang;
     wfProfileIn(__METHOD__);
     $linkCache = LinkCache::singleton();
     $linkCache->clear();
     if (is_null($this->title)) {
         $this->error = "refreshLinks2: Invalid title";
         wfProfileOut(__METHOD__);
         return false;
     }
     if (!isset($this->params['start']) || !isset($this->params['end'])) {
         $this->error = "refreshLinks2: Invalid params";
         wfProfileOut(__METHOD__);
         return false;
     }
     // Back compat for pre-r94435 jobs
     $table = isset($this->params['table']) ? $this->params['table'] : 'templatelinks';
     $titles = $this->title->getBacklinkCache()->getLinks($table, $this->params['start'], $this->params['end']);
     # Not suitable for page load triggered job running!
     # Gracefully switch to refreshLinks jobs if this happens.
     if (php_sapi_name() != 'cli') {
         $jobs = array();
         foreach ($titles as $title) {
             $jobs[] = new RefreshLinksJob($title, '');
         }
         Job::batchInsert($jobs);
         wfProfileOut(__METHOD__);
         return true;
     }
     $options = ParserOptions::newFromUserAndLang(new User(), $wgContLang);
     # Re-parse each page that transcludes this page and update their tracking links...
     foreach ($titles as $title) {
         $revision = Revision::newFromTitle($title);
         if (!$revision) {
             $this->error = 'refreshLinks: Article not found "' . $title->getPrefixedDBkey() . '"';
             wfProfileOut(__METHOD__);
             return false;
         }
         wfProfileIn(__METHOD__ . '-parse');
         $parserOutput = $wgParser->parse($revision->getText(), $title, $options, true, true, $revision->getId());
         wfProfileOut(__METHOD__ . '-parse');
         wfProfileIn(__METHOD__ . '-update');
         $update = new LinksUpdate($title, $parserOutput, false);
         $update->doUpdate();
         wfProfileOut(__METHOD__ . '-update');
         wfWaitForSlaves();
     }
     wfProfileOut(__METHOD__);
     return true;
 }
示例#29
0
 /**
  * Do the rename operation
  */
 function rename()
 {
     global $wgMemc, $wgDBname, $wgAuth;
     wfProfileIn(__METHOD__);
     $dbw = wfGetDB(DB_MASTER);
     // Rename and touch the user before re-attributing edits,
     // this avoids users still being logged in and making new edits while
     // being renamed, which leaves edits at the old name.
     $dbw->update('user', array('user_name' => $this->new, 'user_touched' => $dbw->timestamp()), array('user_name' => $this->old), __METHOD__);
     // Update ipblock list if this user has a block in there.
     $dbw->update('ipblocks', array('ipb_address' => $this->new), array('ipb_user' => $this->uid, 'ipb_address' => $this->old), __METHOD__);
     // Update this users block/rights log. Ideally, the logs would be historical,
     // but it is really annoying when users have "clean" block logs by virtue of
     // being renamed, which makes admin tasks more of a pain...
     $oldTitle = Title::makeTitle(NS_USER, $this->old);
     $newTitle = Title::makeTitle(NS_USER, $this->new);
     $dbw->update('logging', array('log_title' => $newTitle->getDBKey()), array('log_type' => array('block', 'rights'), 'log_namespace' => NS_USER, 'log_title' => $oldTitle->getDBKey()), __METHOD__);
     // Do immediate updates!
     foreach ($this->tables as $table => $field) {
         $dbw->update($table, array($field => $this->new), array($field => $this->old), __METHOD__);
     }
     // Construct jobqueue updates...
     foreach ($this->tablesJob as $table => $params) {
         $userTextC = $params[0];
         // some *_user_text column
         $userIDC = $params[1];
         // some *_user column
         $timestampC = $params[2];
         // some *_timestamp column
         $res = $dbw->select($table, array($userTextC, $timestampC), array($userTextC => $this->old, $userIDC => $this->uid), __METHOD__, array('ORDER BY' => "{$timestampC} ASC"));
         global $wgUpdateRowsPerJob;
         $batchSize = 500;
         // Lets not flood the job table!
         $jobSize = $wgUpdateRowsPerJob;
         // How many rows per job?
         $jobParams = array();
         $jobParams['table'] = $table;
         $jobParams['column'] = $userTextC;
         $jobParams['uidColumn'] = $userIDC;
         $jobParams['timestampColumn'] = $timestampC;
         $jobParams['oldname'] = $this->old;
         $jobParams['newname'] = $this->new;
         $jobParams['userID'] = $this->uid;
         // Timestamp column data for index optimizations
         $jobParams['minTimestamp'] = '0';
         $jobParams['maxTimestamp'] = '0';
         $jobParams['count'] = 0;
         // Insert into queue!
         $jobRows = 0;
         $done = false;
         while (!$done) {
             $jobs = array();
             for ($i = 0; $i < $batchSize; $i++) {
                 $row = $dbw->fetchObject($res);
                 if (!$row) {
                     # If there are any job rows left, add it to the queue as one job
                     if ($jobRows > 0) {
                         $jobParams['count'] = $jobRows;
                         $jobs[] = Job::factory('renameUser', $oldTitle, $jobParams);
                         $jobParams['minTimestamp'] = '0';
                         $jobParams['maxTimestamp'] = '0';
                         $jobParams['count'] = 0;
                         $jobRows = 0;
                     }
                     $done = true;
                     break;
                 }
                 # If we are adding the first item, since the ORDER BY is ASC, set
                 # the min timestamp
                 if ($jobRows == 0) {
                     $jobParams['minTimestamp'] = $row->{$timestampC};
                 }
                 # Keep updating the last timestamp, so it should be correct when the last item is added.
                 $jobParams['maxTimestamp'] = $row->{$timestampC};
                 # Update nice counter
                 $jobRows++;
                 # Once a job has $jobSize rows, add it to the queue
                 if ($jobRows >= $jobSize) {
                     $jobParams['count'] = $jobRows;
                     $jobs[] = Job::factory('renameUser', $oldTitle, $jobParams);
                     $jobParams['minTimestamp'] = '0';
                     $jobParams['maxTimestamp'] = '0';
                     $jobParams['count'] = 0;
                     $jobRows = 0;
                 }
             }
             Job::batchInsert($jobs);
         }
         $dbw->freeResult($res);
     }
     // Clear caches and inform authentication plugins
     $user = User::newFromId($this->uid);
     $user->invalidateCache();
     $wgAuth->updateExternalDB($user);
     wfRunHooks('RenameUserComplete', array($this->uid, $this->old, $this->new));
     wfProfileOut(__METHOD__);
 }
示例#30
0
 function queueRecursiveJobs()
 {
     wfProfileIn(__METHOD__);
     $batchSize = 100;
     $dbr =& wfGetDB(DB_SLAVE);
     $res = $dbr->select(array('templatelinks', 'page'), array('page_namespace', 'page_title'), array('page_id=tl_from', 'tl_namespace' => $this->mTitle->getNamespace(), 'tl_title' => $this->mTitle->getDBkey()), __METHOD__);
     $done = false;
     while (!$done) {
         $jobs = array();
         for ($i = 0; $i < $batchSize; $i++) {
             $row = $dbr->fetchObject($res);
             if (!$row) {
                 $done = true;
                 break;
             }
             $title = Title::makeTitle($row->page_namespace, $row->page_title);
             $jobs[] = Job::factory('refreshLinks', $title);
         }
         Job::batchInsert($jobs);
     }
     $dbr->freeResult($res);
     wfProfileOut(__METHOD__);
 }