Esempio n. 1
0
 /**
  * @return bool Whether this sign-off has been struck
  */
 public function isStruck()
 {
     return $this->timestampStruck !== Block::infinity();
 }
 public function convertExpiry($str)
 {
     if (strlen($str) == 0) {
         return;
     }
     if ($str == 'infinite' || $str == 'indefinite') {
         return Block::infinity();
     } else {
         # Convert GNU-style date, on error returns -1 for PHP <5.1 and false for PHP >=5.1
         $expiry = strtotime($str);
         if ($expiry < 0 || $expiry === false) {
             return;
         }
         return wfTimestamp(TS_MW, $expiry);
     }
 }
Esempio n. 3
0
 public function execute()
 {
     global $wgUser, $wgRestrictionTypes, $wgRestrictionLevels;
     $params = $this->extractRequestParams();
     $titleObj = NULL;
     if (!isset($params['title'])) {
         $this->dieUsageMsg(array('missingparam', 'title'));
     }
     if (!isset($params['token'])) {
         $this->dieUsageMsg(array('missingparam', 'token'));
     }
     if (empty($params['protections'])) {
         $this->dieUsageMsg(array('missingparam', 'protections'));
     }
     if (!$wgUser->matchEditToken($params['token'])) {
         $this->dieUsageMsg(array('sessionfailure'));
     }
     $titleObj = Title::newFromText($params['title']);
     if (!$titleObj) {
         $this->dieUsageMsg(array('invalidtitle', $params['title']));
     }
     $errors = $titleObj->getUserPermissionsErrors('protect', $wgUser);
     if ($errors) {
         // We don't care about multiple errors, just report one of them
         $this->dieUsageMsg(reset($errors));
     }
     $expiry = (array) $params['expiry'];
     if (count($expiry) != count($params['protections'])) {
         if (count($expiry) == 1) {
             $expiry = array_fill(0, count($params['protections']), $expiry[0]);
         } else {
             $this->dieUsageMsg(array('toofewexpiries', count($expiry), count($params['protections'])));
         }
     }
     $protections = array();
     $expiryarray = array();
     $resultProtections = array();
     foreach ($params['protections'] as $i => $prot) {
         $p = explode('=', $prot);
         $protections[$p[0]] = $p[1] == 'all' ? '' : $p[1];
         if ($titleObj->exists() && $p[0] == 'create') {
             $this->dieUsageMsg(array('create-titleexists'));
         }
         if (!$titleObj->exists() && $p[0] != 'create') {
             $this->dieUsageMsg(array('missingtitles-createonly'));
         }
         if (!in_array($p[0], $wgRestrictionTypes) && $p[0] != 'create') {
             $this->dieUsageMsg(array('protect-invalidaction', $p[0]));
         }
         if (!in_array($p[1], $wgRestrictionLevels) && $p[1] != 'all') {
             $this->dieUsageMsg(array('protect-invalidlevel', $p[1]));
         }
         if (in_array($expiry[$i], array('infinite', 'indefinite', 'never'))) {
             $expiryarray[$p[0]] = Block::infinity();
         } else {
             $exp = strtotime($expiry[$i]);
             if ($exp < 0 || $exp == false) {
                 $this->dieUsageMsg(array('invalidexpiry', $expiry[$i]));
             }
             $exp = wfTimestamp(TS_MW, $exp);
             if ($exp < wfTimestampNow()) {
                 $this->dieUsageMsg(array('pastexpiry', $expiry[$i]));
             }
             $expiryarray[$p[0]] = $exp;
         }
         $resultProtections[] = array($p[0] => $protections[$p[0]], 'expiry' => $expiryarray[$p[0]] == Block::infinity() ? 'infinite' : wfTimestamp(TS_ISO_8601, $expiryarray[$p[0]]));
     }
     $cascade = $params['cascade'];
     $articleObj = new Article($titleObj);
     if ($params['watch']) {
         $articleObj->doWatch();
     }
     if ($titleObj->exists()) {
         $ok = $articleObj->updateRestrictions($protections, $params['reason'], $cascade, $expiryarray);
     } else {
         $ok = $titleObj->updateTitleProtection($protections['create'], $params['reason'], $expiryarray['create']);
     }
     if (!$ok) {
         // This is very weird. Maybe the article was deleted or the user was blocked/desysopped in the meantime?
         // Just throw an unknown error in this case, as it's very likely to be a race condition
         $this->dieUsageMsg(array());
     }
     $res = array('title' => $titleObj->getPrefixedText(), 'reason' => $params['reason']);
     if ($cascade) {
         $res['cascade'] = '';
     }
     $res['protections'] = $resultProtections;
     $this->getResult()->setIndexedTagName($res['protections'], 'protection');
     $this->getResult()->addValue(null, $this->getModuleName(), $res);
 }
Esempio n. 4
0
 /**
  * Update the article's restriction field, and leave a log entry.
  *
  * @param $limit Array: set of restriction keys
  * @param $reason String
  * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
  * @param $expiry Array: per restriction type expiration
  * @return bool true on success
  */
 public function updateRestrictions($limit = array(), $reason = '', &$cascade = 0, $expiry = array())
 {
     global $wgUser, $wgContLang;
     $restrictionTypes = $this->mTitle->getRestrictionTypes();
     $id = $this->mTitle->getArticleID();
     if ($id <= 0) {
         wfDebug("updateRestrictions failed: article id {$id} <= 0\n");
         return false;
     }
     if (wfReadOnly()) {
         wfDebug("updateRestrictions failed: read-only\n");
         return false;
     }
     if (!$this->mTitle->userCan('protect')) {
         wfDebug("updateRestrictions failed: insufficient permissions\n");
         return false;
     }
     if (!$cascade) {
         $cascade = false;
     }
     // Take this opportunity to purge out expired restrictions
     Title::purgeExpiredRestrictions();
     # FIXME: Same limitations as described in ProtectionForm.php (line 37);
     # we expect a single selection, but the schema allows otherwise.
     $current = array();
     $updated = Article::flattenRestrictions($limit);
     $changed = false;
     foreach ($restrictionTypes as $action) {
         if (isset($expiry[$action])) {
             # Get current restrictions on $action
             $aLimits = $this->mTitle->getRestrictions($action);
             $current[$action] = implode('', $aLimits);
             # Are any actual restrictions being dealt with here?
             $aRChanged = count($aLimits) || !empty($limit[$action]);
             # If something changed, we need to log it. Checking $aRChanged
             # assures that "unprotecting" a page that is not protected does
             # not log just because the expiry was "changed".
             if ($aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action]) {
                 $changed = true;
             }
         }
     }
     $current = Article::flattenRestrictions($current);
     $changed = $changed || $current != $updated;
     $changed = $changed || $updated && $this->mTitle->areRestrictionsCascading() != $cascade;
     $protect = $updated != '';
     # If nothing's changed, do nothing
     if ($changed) {
         if (wfRunHooks('ArticleProtect', array(&$this, &$wgUser, $limit, $reason))) {
             $dbw = wfGetDB(DB_MASTER);
             # Prepare a null revision to be added to the history
             $modified = $current != '' && $protect;
             if ($protect) {
                 $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
             } else {
                 $comment_type = 'unprotectedarticle';
             }
             $comment = $wgContLang->ucfirst(wfMsgForContent($comment_type, $this->mTitle->getPrefixedText()));
             # Only restrictions with the 'protect' right can cascade...
             # Otherwise, people who cannot normally protect can "protect" pages via transclusion
             $editrestriction = isset($limit['edit']) ? array($limit['edit']) : $this->mTitle->getRestrictions('edit');
             # The schema allows multiple restrictions
             if (!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction)) {
                 $cascade = false;
             }
             $cascade_description = '';
             if ($cascade) {
                 $cascade_description = ' [' . wfMsgForContent('protect-summary-cascade') . ']';
             }
             if ($reason) {
                 $comment .= ": {$reason}";
             }
             $editComment = $comment;
             $encodedExpiry = array();
             $protect_description = '';
             foreach ($limit as $action => $restrictions) {
                 if (!isset($expiry[$action])) {
                     $expiry[$action] = Block::infinity();
                 }
                 $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw);
                 if ($restrictions != '') {
                     $protect_description .= "[{$action}={$restrictions}] (";
                     if ($encodedExpiry[$action] != 'infinity') {
                         $protect_description .= wfMsgForContent('protect-expiring', $wgContLang->timeanddate($expiry[$action], false, false), $wgContLang->date($expiry[$action], false, false), $wgContLang->time($expiry[$action], false, false));
                     } else {
                         $protect_description .= wfMsgForContent('protect-expiry-indefinite');
                     }
                     $protect_description .= ') ';
                 }
             }
             $protect_description = trim($protect_description);
             if ($protect_description && $protect) {
                 $editComment .= " ({$protect_description})";
             }
             if ($cascade) {
                 $editComment .= "{$cascade_description}";
             }
             # Update restrictions table
             foreach ($limit as $action => $restrictions) {
                 if ($restrictions != '') {
                     $dbw->replace('page_restrictions', array(array('pr_page', 'pr_type')), array('pr_page' => $id, 'pr_type' => $action, 'pr_level' => $restrictions, 'pr_cascade' => $cascade && $action == 'edit' ? 1 : 0, 'pr_expiry' => $encodedExpiry[$action]), __METHOD__);
                 } else {
                     $dbw->delete('page_restrictions', array('pr_page' => $id, 'pr_type' => $action), __METHOD__);
                 }
             }
             # Insert a null revision
             $nullRevision = Revision::newNullRevision($dbw, $id, $editComment, true);
             $nullRevId = $nullRevision->insertOn($dbw);
             $latest = $this->getLatest();
             # Update page record
             $dbw->update('page', array('page_touched' => $dbw->timestamp(), 'page_restrictions' => '', 'page_latest' => $nullRevId), array('page_id' => $id), 'Article::protect');
             wfRunHooks('NewRevisionFromEditComplete', array($this, $nullRevision, $latest, $wgUser));
             wfRunHooks('ArticleProtectComplete', array(&$this, &$wgUser, $limit, $reason));
             # Update the protection log
             $log = new LogPage('protect');
             if ($protect) {
                 $params = array($protect_description, $cascade ? 'cascade' : '');
                 $log->addEntry($modified ? 'modify' : 'protect', $this->mTitle, trim($reason), $params);
             } else {
                 $log->addEntry('unprotect', $this->mTitle, $reason);
             }
         }
         # End hook
     }
     # End "changed" check
     return true;
 }
 public function execute()
 {
     global $wgUser;
     $this->getMain()->requestWriteMode();
     $params = $this->extractRequestParams();
     $titleObj = NULL;
     if (!isset($params['title'])) {
         $this->dieUsageMsg(array('missingparam', 'title'));
     }
     if (!isset($params['token'])) {
         $this->dieUsageMsg(array('missingparam', 'token'));
     }
     if (!isset($params['protections']) || empty($params['protections'])) {
         $this->dieUsageMsg(array('missingparam', 'protections'));
     }
     if (!$wgUser->matchEditToken($params['token'])) {
         $this->dieUsageMsg(array('sessionfailure'));
     }
     $titleObj = Title::newFromText($params['title']);
     if (!$titleObj) {
         $this->dieUsageMsg(array('invalidtitle', $params['title']));
     }
     $errors = $titleObj->getUserPermissionsErrors('protect', $wgUser);
     if (!empty($errors)) {
         // We don't care about multiple errors, just report one of them
         $this->dieUsageMsg(current($errors));
     }
     if (in_array($params['expiry'], array('infinite', 'indefinite', 'never'))) {
         $expiry = Block::infinity();
     } else {
         $expiry = strtotime($params['expiry']);
         if ($expiry < 0 || $expiry == false) {
             $this->dieUsageMsg(array('invalidexpiry'));
         }
         $expiry = wfTimestamp(TS_MW, $expiry);
         if ($expiry < wfTimestampNow()) {
             $this->dieUsageMsg(array('pastexpiry'));
         }
     }
     $protections = array();
     foreach ($params['protections'] as $prot) {
         $p = explode('=', $prot);
         $protections[$p[0]] = $p[1] == 'all' ? '' : $p[1];
         if ($titleObj->exists() && $p[0] == 'create') {
             $this->dieUsageMsg(array('create-titleexists'));
         }
         if (!$titleObj->exists() && $p[0] != 'create') {
             $this->dieUsageMsg(array('missingtitles-createonly'));
         }
     }
     $dbw = wfGetDb(DB_MASTER);
     $dbw->begin();
     if ($titleObj->exists()) {
         $articleObj = new Article($titleObj);
         $ok = $articleObj->updateRestrictions($protections, $params['reason'], $params['cascade'], $expiry);
     } else {
         $ok = $titleObj->updateTitleProtection($protections['create'], $params['reason'], $expiry);
     }
     if (!$ok) {
         // This is very weird. Maybe the article was deleted or the user was blocked/desysopped in the meantime?
         // Just throw an unknown error in this case, as it's very likely to be a race condition
         $this->dieUsageMsg(array());
     }
     $dbw->commit();
     $res = array('title' => $titleObj->getPrefixedText(), 'reason' => $params['reason']);
     if ($expiry == Block::infinity()) {
         $res['expiry'] = 'infinity';
     } else {
         $res['expiry'] = wfTimestamp(TS_ISO_8601, $expiry);
     }
     if ($params['cascade']) {
         $res['cascade'] = '';
     }
     $res['protections'] = $protections;
     $this->getResult()->addValue(null, $this->getModuleName(), $res);
 }
Esempio n. 6
0
$wgUser = User::newFromName($userName);
if (!$wgUser) {
    print "Invalid username\n";
    exit(1);
}
if ($wgUser->isAnon()) {
    $wgUser->addToDatabase();
}
if (empty($wgWikiaKeyPages)) {
    $wgWikiaKeyPages = array('Image:Wiki.png', 'Image:Favicon.ico');
}
#--- define restriction level and duration
$restrictions['edit'] = 'sysop';
$restrictions['move'] = 'sysop';
$titleRestrictions = 'sysop';
$expiry = Block::infinity();
#--- define reason msg and fetch it
$wgMessageCache->addMessages(array('createwiki-protect-reason' => 'Part of the official interface'));
$reason = wfMsgForContent('createwiki-protect-reason');
$wgUser->addGroup('staff');
$wgUser->addGroup('bot');
foreach ($wgWikiaKeyPages as $pageName) {
    $title = Title::newFromText($pageName);
    $article = new Article($title);
    if ($article->exists()) {
        $ok = $article->updateRestrictions($restrictions, $reason, 0, $expiry);
    } else {
        $ok = $title->updateTitleProtection($titleRestrictions, $reason, $expiry);
    }
    if ($ok) {
        print "Protected key page: {$pageName}\n";
 /**
  * Callback function to output a block
  */
 function formatRow($block)
 {
     global $wgUser, $wgLang;
     wfProfileIn(__METHOD__);
     static $sk = null, $msg = null;
     if (is_null($sk)) {
         $sk = $wgUser->getSkin();
     }
     if (is_null($msg)) {
         $msg = array();
         $keys = array('infiniteblock', 'expiringblock', 'unblocklink', 'anononlyblock', 'createaccountblock', 'noautoblockblock', 'emailblock');
         foreach ($keys as $key) {
             $msg[$key] = wfMsgHtml($key);
         }
         $msg['blocklistline'] = wfMsg('blocklistline');
     }
     # Prepare links to the blocker's user and talk pages
     $blocker_id = $block->getBy();
     $blocker_name = $block->getByName();
     $blocker = $sk->userLink($blocker_id, $blocker_name);
     $blocker .= $sk->userToolLinks($blocker_id, $blocker_name);
     # Prepare links to the block target's user and contribs. pages (as applicable, don't do it for autoblocks)
     if ($block->mAuto) {
         $target = $block->getRedactedName();
         # Hide the IP addresses of auto-blocks; privacy
     } else {
         $target = $sk->userLink($block->mUser, $block->mAddress) . $sk->userToolLinks($block->mUser, $block->mAddress, false, Linker::TOOL_LINKS_NOBLOCK);
     }
     $formattedTime = $wgLang->timeanddate($block->mTimestamp, true);
     $properties = array();
     if ($block->mExpiry === "" || $block->mExpiry === Block::infinity()) {
         $properties[] = $msg['infiniteblock'];
     } else {
         $properties[] = wfMsgReplaceArgs($msg['expiringblock'], array($wgLang->timeanddate($block->mExpiry, true)));
     }
     if ($block->mAnonOnly) {
         $properties[] = $msg['anononlyblock'];
     }
     if ($block->mCreateAccount) {
         $properties[] = $msg['createaccountblock'];
     }
     if (!$block->mEnableAutoblock && $block->mUser) {
         $properties[] = $msg['noautoblockblock'];
     }
     if ($block->mBlockEmail && $block->mUser) {
         $properties[] = $msg['emailblock'];
     }
     $properties = implode(', ', $properties);
     $line = wfMsgReplaceArgs($msg['blocklistline'], array($formattedTime, $blocker, $target, $properties));
     $unblocklink = '';
     if ($wgUser->isAllowed('block')) {
         $titleObj = SpecialPage::getTitleFor("Ipblocklist");
         $unblocklink = ' (' . $sk->makeKnownLinkObj($titleObj, $msg['unblocklink'], 'action=unblock&id=' . urlencode($block->mId)) . ')';
     }
     $comment = $sk->commentBlock($block->mReason);
     $s = "{$line} {$comment}";
     if ($block->mHideName) {
         $s = '<span class="history-deleted">' . $s . '</span>';
     }
     wfProfileOut(__METHOD__);
     return "<li>{$s} {$unblocklink}</li>\n";
 }
Esempio n. 8
0
 /**
  * Backend block code.
  * $userID and $expiry will be filled accordingly
  * @return array(message key, arguments) on failure, empty array on success
  */
 function doBlock(&$userId = null, &$expiry = null)
 {
     global $wgUser, $wgSysopUserBans, $wgSysopRangeBans;
     $userId = 0;
     # Expand valid IPv6 addresses, usernames are left as is
     $this->BlockAddress = IP::sanitizeIP($this->BlockAddress);
     # isIPv4() and IPv6() are used for final validation
     $rxIP4 = '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}';
     $rxIP6 = '\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}:\\w{1,4}';
     $rxIP = "({$rxIP4}|{$rxIP6})";
     # Check for invalid specifications
     if (!preg_match("/^{$rxIP}\$/", $this->BlockAddress)) {
         $matches = array();
         if (preg_match("/^({$rxIP4})\\/(\\d{1,2})\$/", $this->BlockAddress, $matches)) {
             # IPv4
             if ($wgSysopRangeBans) {
                 if (!IP::isIPv4($this->BlockAddress) || $matches[2] < 16 || $matches[2] > 32) {
                     return array('ip_range_invalid');
                 }
                 $this->BlockAddress = Block::normaliseRange($this->BlockAddress);
             } else {
                 # Range block illegal
                 return array('range_block_disabled');
             }
         } else {
             if (preg_match("/^({$rxIP6})\\/(\\d{1,3})\$/", $this->BlockAddress, $matches)) {
                 # IPv6
                 if ($wgSysopRangeBans) {
                     if (!IP::isIPv6($this->BlockAddress) || $matches[2] < 64 || $matches[2] > 128) {
                         return array('ip_range_invalid');
                     }
                     $this->BlockAddress = Block::normaliseRange($this->BlockAddress);
                 } else {
                     # Range block illegal
                     return array('range_block_disabled');
                 }
             } else {
                 # Username block
                 if ($wgSysopUserBans) {
                     $user = User::newFromName($this->BlockAddress);
                     if (!is_null($user) && $user->getID()) {
                         # Use canonical name
                         $userId = $user->getID();
                         $this->BlockAddress = $user->getName();
                     } else {
                         return array('nosuchusershort', htmlspecialchars($user ? $user->getName() : $this->BlockAddress));
                     }
                 } else {
                     return array('badipaddress');
                 }
             }
         }
     }
     $reasonstr = $this->BlockReasonList;
     if ($reasonstr != 'other' && $this->BlockReason != '') {
         // Entry from drop down menu + additional comment
         $reasonstr .= ': ' . $this->BlockReason;
     } elseif ($reasonstr == 'other') {
         $reasonstr = $this->BlockReason;
     }
     $expirestr = $this->BlockExpiry;
     if ($expirestr == 'other') {
         $expirestr = $this->BlockOther;
     }
     if (strlen($expirestr) == 0) {
         return array('ipb_expiry_invalid');
     }
     if ($expirestr == 'infinite' || $expirestr == 'indefinite') {
         $expiry = Block::infinity();
     } else {
         # Convert GNU-style date, on error returns -1 for PHP <5.1 and false for PHP >=5.1
         $expiry = strtotime($expirestr);
         if ($expiry < 0 || $expiry === false) {
             return array('ipb_expiry_invalid');
         }
         $expiry = wfTimestamp(TS_MW, $expiry);
     }
     # Create block
     # Note: for a user block, ipb_address is only for display purposes
     $block = new Block($this->BlockAddress, $userId, $wgUser->getID(), $reasonstr, wfTimestampNow(), 0, $expiry, $this->BlockAnonOnly, $this->BlockCreateAccount, $this->BlockEnableAutoblock, $this->BlockHideName, $this->BlockEmail);
     if (wfRunHooks('BlockIp', array(&$block, &$wgUser))) {
         if (!$block->insert()) {
             return array('ipb_already_blocked', htmlspecialchars($this->BlockAddress));
         }
         wfRunHooks('BlockIpComplete', array($block, $wgUser));
         # Prepare log parameters
         $logParams = array();
         $logParams[] = $expirestr;
         $logParams[] = $this->blockLogFlags();
         # Make log entry, if the name is hidden, put it in the oversight log
         $log_type = $this->BlockHideName ? 'oversight' : 'block';
         $log = new LogPage($log_type);
         $log->addEntry('block', Title::makeTitle(NS_USER, $this->BlockAddress), $reasonstr, $logParams);
         # Report to the user
         return array();
     } else {
         return array('hookaborted');
     }
 }
Esempio n. 9
0
 public static function doNamespaceRestriction($uid, $user)
 {
     global $wgUser, $wgRequest;
     $r = new UserRestriction();
     $r->setType(UserRestriction::NAMESPACE);
     $r->setNamespace($wgRequest->getVal('namespace'));
     $r->setSubjectId($uid);
     $r->setSubjectText($user);
     $r->setBlockerId($wgUser->getId());
     $r->setBlockerText($wgUser->getName());
     $r->setReason($wgRequest->getVal('reason'));
     $r->setExpiry(UserRestriction::convertExpiry($wgRequest->getVal('expiry')));
     $r->setTimestamp(wfTimestampNow(TS_MW));
     $r->commit();
     $logExpiry = $wgRequest->getVal('expiry') ? $wgRequest->getVal('expiry') : Block::infinity();
     $l = new LogPage('restrict');
     $l->addEntry('restrict', Title::makeTitle(NS_USER, $user), $r->getReason(), array($r->getType(), $r->getNamespace(), $logExpiry));
 }
Esempio n. 10
0
 /**
  * @static
  * @param $result ApiResult
  * @param $vals
  * @param $params
  * @param $type
  * @param $ts
  * @return array
  */
 public static function addLogParams($result, &$vals, $params, $type, $ts)
 {
     $params = explode("\n", $params);
     switch ($type) {
         case 'move':
             if (isset($params[0])) {
                 $title = Title::newFromText($params[0]);
                 if ($title) {
                     $vals2 = array();
                     ApiQueryBase::addTitleInfo($vals2, $title, 'new_');
                     $vals[$type] = $vals2;
                 }
             }
             if (isset($params[1]) && $params[1]) {
                 $vals[$type]['suppressedredirect'] = '';
             }
             $params = null;
             break;
         case 'patrol':
             $vals2 = array();
             list($vals2['cur'], $vals2['prev'], $vals2['auto']) = $params;
             $vals[$type] = $vals2;
             $params = null;
             break;
         case 'rights':
             $vals2 = array();
             list($vals2['old'], $vals2['new']) = $params;
             $vals[$type] = $vals2;
             $params = null;
             break;
         case 'block':
             $vals2 = array();
             list($vals2['duration'], $vals2['flags']) = $params;
             // Indefinite blocks have no expiry time
             if (Block::parseExpiryInput($params[0]) !== Block::infinity()) {
                 $vals2['expiry'] = wfTimestamp(TS_ISO_8601, strtotime($params[0], wfTimestamp(TS_UNIX, $ts)));
             }
             $vals[$type] = $vals2;
             $params = null;
             break;
     }
     if (!is_null($params)) {
         $result->setIndexedTagName($params, 'param');
         $vals = array_merge($vals, $params);
     }
     return $vals;
 }
 /**
  * Submit the form parameters for the page config to the DB.
  * 
  * @return mixed (true on success, error string on failure)
  */
 public function doSubmit()
 {
     # Double-check permissions
     if (!$this->isAllowed()) {
         return 'stablize_denied';
     }
     # Parse and cleanup the expiry time given...
     $expiry = $this->getExpiry();
     if ($expiry === false) {
         return 'stabilize_expiry_invalid';
     } elseif ($expiry !== Block::infinity() && $expiry < wfTimestampNow()) {
         return 'stabilize_expiry_old';
     }
     # Update the DB row with the new config...
     $changed = FRPageConfig::setStabilitySettings($this->page, $this->getNewConfig());
     # Log if this actually changed anything...
     if ($changed) {
         $article = new FlaggableWikiPage($this->page);
         if (FlaggedRevs::useOnlyIfProtected()) {
             # Config may have changed to allow stable versions, so refresh
             # the tracking table to account for any hidden reviewed versions...
             $frev = FlaggedRevision::determineStable($this->page, FR_MASTER);
             if ($frev) {
                 $article->updateStableVersion($frev);
             } else {
                 $article->clearStableVersion();
             }
         }
         # Update logs and make a null edit
         $nullRev = $this->updateLogsAndHistory($article);
         # Null edit may have been auto-reviewed already
         $frev = FlaggedRevision::newFromTitle($this->page, $nullRev->getId(), FR_MASTER);
         $updatesDone = (bool) $frev;
         // stableVersionUpdates() already called?
         # Check if this null edit is to be reviewed...
         if ($this->reviewThis && !$frev) {
             $flags = null;
             # Review this revision of the page...
             $ok = FlaggedRevs::autoReviewEdit($article, $this->user, $nullRev, $flags, true);
             if ($ok) {
                 FlaggedRevs::markRevisionPatrolled($nullRev);
                 // reviewed -> patrolled
                 $updatesDone = true;
                 // stableVersionUpdates() already called
             }
         }
         # Update page and tracking tables and clear cache.
         if (!$updatesDone) {
             FlaggedRevs::stableVersionUpdates($this->page);
         }
     }
     # Apply watchlist checkbox value (may be NULL)
     $this->updateWatchlist();
     # Take this opportunity to purge out expired configurations
     FRPageConfig::purgeExpiredConfigurations();
     return true;
 }
    public function showForm($err = null)
    {
        $out = $this->getOutput();
        $form = $this->form;
        // convenience
        $title = $this->form->getPage();
        $oldConfig = $form->getOldConfig();
        $s = '';
        // form HTML string
        # Add any error messages
        if ("" != $err) {
            $out->setSubtitle(wfMsgHtml('formerror'));
            $out->addHTML("<p class='error'>{$err}</p>\n");
        }
        # Add header text
        if (!$form->isAllowed()) {
            $s .= wfMsgExt('stabilization-perm', 'parse', $title->getPrefixedText());
        } else {
            $s .= wfMsgExt('stabilization-text', 'parse', $title->getPrefixedText());
        }
        # Borrow some protection messages for dropdowns
        $reasonDropDown = Xml::listDropDown('wpReasonSelection', wfMsgForContent('protect-dropdown'), wfMsgForContent('protect-otherreason-op'), $form->getReasonSelection(), 'mwStabilize-reason', 4);
        $scExpiryOptions = wfMsgForContent('protect-expiry-options');
        $showProtectOptions = $scExpiryOptions !== '-' && $form->isAllowed();
        $dropdownOptions = array();
        // array of <label,value>
        # Add the current expiry as a dropdown option
        if ($oldConfig['expiry'] && $oldConfig['expiry'] != Block::infinity()) {
            $timestamp = $this->getLang()->timeanddate($oldConfig['expiry']);
            $d = $this->getLang()->date($oldConfig['expiry']);
            $t = $this->getLang()->time($oldConfig['expiry']);
            $dropdownOptions[] = array(wfMsg('protect-existing-expiry', $timestamp, $d, $t), 'existing');
        }
        # Add "other time" expiry dropdown option
        $dropdownOptions[] = array(wfMsg('protect-othertime-op'), 'othertime');
        # Add custom expiry dropdown options (from MediaWiki message)
        foreach (explode(',', $scExpiryOptions) as $option) {
            if (strpos($option, ":") === false) {
                $show = $value = $option;
            } else {
                list($show, $value) = explode(":", $option);
            }
            $dropdownOptions[] = array($show, $value);
        }
        # Actually build the options HTML...
        $expiryFormOptions = '';
        foreach ($dropdownOptions as $option) {
            $show = htmlspecialchars($option[0]);
            $value = htmlspecialchars($option[1]);
            $expiryFormOptions .= Xml::option($show, $value, $form->getExpirySelection() === $value) . "\n";
        }
        # Build up the form...
        $s .= Xml::openElement('form', array('name' => 'stabilization', 'action' => $this->getTitle()->getLocalUrl(), 'method' => 'post'));
        # Add stable version override and selection options
        $s .= Xml::fieldset(wfMsg('stabilization-def'), false) . "\n" . Xml::radioLabel(wfMsg('stabilization-def1'), 'wpStableconfig-override', 1, 'default-stable', 1 == $form->getOverride(), $this->disabledAttr()) . '<br />' . "\n" . Xml::radioLabel(wfMsg('stabilization-def2'), 'wpStableconfig-override', 0, 'default-current', 0 == $form->getOverride(), $this->disabledAttr()) . "\n" . Xml::closeElement('fieldset');
        # Add autoreview restriction select
        $s .= Xml::fieldset(wfMsg('stabilization-restrict'), false) . $this->buildSelector($form->getAutoreview()) . Xml::closeElement('fieldset') . Xml::fieldset(wfMsg('stabilization-leg'), false) . Xml::openElement('table');
        # Add expiry dropdown to form...
        if ($showProtectOptions && $form->isAllowed()) {
            $s .= "\n\t\t\t\t<tr>\n\t\t\t\t\t<td class='mw-label'>" . Xml::label(wfMsg('stabilization-expiry'), 'mwStabilizeExpirySelection') . "</td>\n\t\t\t\t\t<td class='mw-input'>" . Xml::tags('select', array('id' => 'mwStabilizeExpirySelection', 'name' => 'wpExpirySelection', 'onchange' => 'onFRChangeExpiryDropdown()') + $this->disabledAttr(), $expiryFormOptions) . "</td>\n\t\t\t\t</tr>";
        }
        # Add custom expiry field to form...
        $attribs = array('id' => "mwStabilizeExpiryOther", 'onkeyup' => 'onFRChangeExpiryField()') + $this->disabledAttr();
        $s .= "\n\t\t\t<tr>\n\t\t\t\t<td class='mw-label'>" . Xml::label(wfMsg('stabilization-othertime'), 'mwStabilizeExpiryOther') . '</td>
				<td class="mw-input">' . Xml::input("mwStabilize-expiry", 50, $form->getExpiryCustom(), $attribs) . '</td>
			</tr>';
        # Add comment input and submit button
        if ($form->isAllowed()) {
            $watchLabel = wfMsgExt('watchthis', 'parseinline');
            $watchAttribs = array('accesskey' => wfMsg('accesskey-watch'), 'id' => 'wpWatchthis');
            $watchChecked = $this->getUser()->getOption('watchdefault') || $title->userIsWatching();
            $reviewLabel = wfMsgExt('stabilization-review', 'parseinline');
            $s .= ' <tr>
					<td class="mw-label">' . xml::label(wfMsg('stabilization-comment'), 'wpReasonSelection') . '</td>
					<td class="mw-input">' . $reasonDropDown . '</td>
				</tr>
				<tr>
					<td class="mw-label">' . Xml::label(wfMsg('stabilization-otherreason'), 'wpReason') . '</td>
					<td class="mw-input">' . Xml::input('wpReason', 70, $form->getReasonExtra(), array('id' => 'wpReason', 'maxlength' => 255)) . '</td>
				</tr>
				<tr>
					<td></td>
					<td class="mw-input">' . Xml::check('wpReviewthis', $form->getReviewThis(), array('id' => 'wpReviewthis')) . "<label for='wpReviewthis'>{$reviewLabel}</label>" . '&#160;&#160;&#160;&#160;&#160;' . Xml::check('wpWatchthis', $watchChecked, $watchAttribs) . "&#160;<label for='wpWatchthis' " . Xml::expandAttributes(array('title' => Linker::titleAttrib('watch', 'withaccess'))) . ">{$watchLabel}</label>" . '</td>
				</tr>
				<tr>
					<td></td>
					<td class="mw-submit">' . Xml::submitButton(wfMsg('stabilization-submit')) . '</td>
				</tr>' . Xml::closeElement('table') . Html::hidden('title', $this->getTitle()->getPrefixedDBKey()) . Html::hidden('page', $title->getPrefixedText()) . Html::hidden('wpEditToken', $this->getUser()->editToken());
        } else {
            $s .= Xml::closeElement('table');
        }
        $s .= Xml::closeElement('fieldset') . Xml::closeElement('form');
        $out->addHTML($s);
        $out->addHTML(Xml::element('h2', null, htmlspecialchars(LogPage::logName('stable'))));
        LogEventsList::showLogExtract($out, 'stable', $title->getPrefixedText(), '', array('lim' => 25));
        # Add some javascript for expiry dropdowns
        $out->addScript("<script type=\"text/javascript\">\n\t\t\t\tfunction onFRChangeExpiryDropdown() {\n\t\t\t\t\tdocument.getElementById('mwStabilizeExpiryOther').value = '';\n\t\t\t\t}\n\t\t\t\tfunction onFRChangeExpiryField() {\n\t\t\t\t\tdocument.getElementById('mwStabilizeExpirySelection').value = 'othertime';\n\t\t\t\t}\n\t\t\t</script>");
    }
Esempio n. 13
0
function poUpdateRestrictions($article, $restrictions, $cascade = false, $expiration = null)
{
    global $wgProtectOwnDoProtect, $wgUser, $wgProtectOwnCacheUserCan, $wgProtectOwnCacheIsOwner;
    if ($expiration === null) {
        $expiration = array();
        $infinity = Block::infinity();
        foreach ($restrictions as $action => $level) {
            $expiration[$action] = $infinity;
        }
    }
    # temporary assign protect right, in order to update the restricitons
    $wgProtectOwnDoProtect = true;
    // tells spSetRestrictionsAssignDynamicRights to add the "protect" right
    //	wfDebugLog( 'ProtectOwn', 'Form: purge user\'s rights then force reload');
    $wgUser->mRights = null;
    // clear current user rights
    $wgUser->getRights();
    // force rights reloading
    $wgProtectOwnDoProtect = false;
    wfDebugLog('ProtectOwn', "UpdateRestrictions: restrictions =\n " . var_export($restrictions, true) . "\nexpiration=\n" . var_export($expiration, true));
    // update restrictions
    $success = $article->updateRestrictions($restrictions, 'ProtectOwn', $cascade, $expiration);
    // note that this article function check that the user has sufficient rights
    # clear userCan and isOwner caches
    # because of protect right granted few instants
    # IsOwner cache clearing should not be necessary, but IsOwner hook may be affected by restrictions update
    //	wfDebugLog( 'ProtectOwn', 'Form: purge userCan and isOwner caches');
    $wgProtectOwnCacheUserCan = array();
    $wgProtectOwnCacheIsOwner = array();
    # remove temporary assigned protect right by reloading rights with $wgSetRestrictionsDoProtect = false
    //	wfDebugLog( 'ProtectOwn', 'Form: purge user\'s rights then force reload');
    $wgUser->mRights = null;
    // clear current user rights (and clear the "protect" right
    $wgUser->getRights();
    // force rights reloading
    return $success;
}
 /**
  * protect key pages
  *
  * @author Lucas 'TOR' Garczewski <*****@*****.**>
  */
 private function protectKeyPages()
 {
     global $wgUser, $wgWikiaKeyPages;
     $saveUser = $wgUser;
     $wgUser = \User::newFromName(self::WIKIA_USER);
     if (empty($wgWikiaKeyPages)) {
         $wgWikiaKeyPages = array('File:Wiki.png', 'File:Favicon.ico');
     }
     /**
      * define restriction level and duration
      */
     $restrictions["edit"] = 'sysop';
     $restrictions["move"] = 'sysop';
     $restrictions["create"] = 'sysop';
     $titleRestrictions = 'sysop';
     $expiry_string = \Block::infinity();
     $expiry_array = array('edit' => $expiry_string, 'move' => $expiry_string);
     /**
      *  define reason msg and fetch it
      */
     $reason = wfMsgForContent('autocreatewiki-protect-reason');
     foreach ($wgWikiaKeyPages as $pageName) {
         $title = \Title::newFromText($pageName);
         $article = new \Article($title);
         if ($article->exists()) {
             $cascade = 0;
             $ok = $article->updateRestrictions($restrictions, $reason, $cascade, $expiry_array);
         } else {
             $wikiPage = \WikiPage::factory($title);
             $ignored_reference = false;
             // doing this because MW1.19 doUpdateRestrictions() is weird, and has this passed by reference
             $status = $wikiPage->doUpdateRestrictions(array('create' => $titleRestrictions), array('create' => $expiry_string), $ignored_reference, $reason, $wgUser);
             $ok = $status->isOK();
         }
         if ($ok) {
             $this->info('Protected key page', ['page_name' => $pageName]);
         } else {
             $this->warning('failed to protect key page', ['page_name' => $pageName]);
         }
     }
     $wgUser = $saveUser;
 }
    function doScrapeInsert()
    {
        foreach ($this->streams as &$stream) {
            if (!isset($stream->date_start_time)) {
                $stream->date_start_time = 0;
            }
            if ($stream->date_start_time == 0) {
                print 'error stream ' . $stream->name . ' missing time info' . "\n";
                continue;
            }
            $hors = strpos($stream->name, 'house') !== false ? 'h' : 's';
            $date_req = date('Y-m-d', $stream->date_start_time);
            if (strpos($stream->name, date('m-d-y', $stream->date_start_time)) === false) {
                $dTitle = Title::newFromText('Archive:Stream_DateMissMatch');
                append_to_wiki_page($dTitle, 'DateMissMatch:[[Stream:' . $stream->stream_name . ']]:' . date('m-d-y', $stream->date_start_time) . "\n");
                // use date from stream name:
                // house_da_01-01-07_
                preg_match('/[0-9]+\\-[0-9]+\\-[0-9][0-9]/U', $stream->name, $matches);
                if (isset($matches[0])) {
                    list($month, $day, $year) = explode('-', $matches[0]);
                    $date_req = '20' . $year . '-' . $month . '-' . $day;
                } else {
                    die('could not find date in stream name');
                }
            }
            $cspan_url = $this->base_url . $this->base_query . '&date=' . $date_req . '&hors=' . $hors;
            echo $cspan_url . "\n";
            $rawpage = $this->doRequest($cspan_url);
            // get the title and href if present:
            $patern = '/overlib\\(\'(.*)\\((Length: ([^\\)]*)).*CAPTION,\'<font size=2>(.*)<((.*href="([^"]*))|.*)>/';
            preg_match_all($patern, $rawpage, $matches);
            $cspan_person_ary = array();
            // format matches:
            foreach ($matches[0] as $k => $v) {
                $href = '';
                $href_match = array();
                preg_match('/href="(.*)"/', $matches[5][$k], $href_match);
                if (count($href_match) != 0) {
                    $href = $href_match[1];
                }
                $porg = str_replace('<br />', ' ', $matches[4][$k]);
                $porg = preg_replace('/[D|R|I]+\\-\\[.*\\]/', '', $porg);
                $pparts = explode(',', $porg);
                if (isset($pparts[1]) && isset($pparts[0])) {
                    $pname = trim($pparts[1]) . '_' . trim($pparts[0]);
                    if (mv_is_valid_person($pname)) {
                        $cspan_person_ary[] = array('start_time' => strip_tags($matches[1][$k]), 'length' => $matches[3][$k], 'person_title' => str_replace('<br />', ' ', $matches[4][$k]), 'Spoken_by' => $pname, 'href' => $href);
                    }
                }
            }
            // group people in page matches
            // $g_cspan_matches=array();
            // $prev_person=null;
            // foreach($person_time_ary as $ptag){
            //	$g_cspan_matches[strtolower($ptag['Spoken_by'])][]=$ptag;
            // }
            // retrive db rows to find match:
            $dbr = wfGetDB(DB_SLAVE);
            // $mvd_res = MV_Index::getMVDInRange($stream->id, null, null, $mvd_type='ht_en',false,$smw_properties=array('Spoken_by'), '');
            /*while ($row = $dbr->fetchObject($mvd_res)) {
              $db_person_ary=$g_row_matches=array();
              //group peole in db matches:
              $cur_person = '';
              $curKey=0;
             	while ($row = $dbr->fetchObject($mvd_res)) {
             		if(!isset($row->Spoken_by))continue;
            			if($cur_person!=$row->Spoken_by){
            				$g_row_matches[]=get_object_vars($row);
            				$curKey=count($g_row_matches)-1;
            				$cur_person=$row->Spoken_by;
            			}else{
            				$g_row_matches[$curKey]['end_wiki_title']=$row->wiki_title;
            				$g_row_matches[$curKey]['end_time']+=($row->end_time-$row->start_time);
            			}
            			//print_r($g_row_matches);
            			//if($curKey>2){
            			//	die;
            			//}
             	} */
            // get people from metavid table (and conform to mvd_res)
            $sql = 'SELECT  (`people_time`.`time`-`streams`.`adj_start_time`) as `time`,
		    	   `person_lookup`.`name_clean`	 as `Spoken_by`,
				   `person_lookup`.`first` as `first`,
				   `person_lookup`.`last` as `last`
		    	   FROM  `metavid`.`people_attr_stream_time` as `people_time`
		    	   RIGHT JOIN `metavid`.`streams` as `streams` ON `streams`.`id`=`people_time`.`stream_fk`
		    	   LEFT JOIN `metavid`.`people` as `person_lookup` ON  `person_lookup`.`id` = `people_time`.`people_fk`
		    	   WHERE `streams`.`name`=\'' . $stream->name . '\'
		    	   ORDER BY `people_time`.`time` ';
            $people_res = $dbr->query($sql);
            $cur_person = '';
            $curKey = 0;
            while ($row = $dbr->fetchObject($people_res)) {
                if (!isset($row->Spoken_by)) {
                    continue;
                }
                $cur_row_person = $row->first . '_' . $row->last;
                if ($cur_person != $cur_row_person) {
                    $db_person_ary[] = get_object_vars($row);
                    $curKey = count($db_person_ary) - 1;
                    $db_person_ary[$curKey]['Spoken_by'] = $row->first . '_' . $row->last;
                    $db_person_ary[$curKey]['start_time'] = $row->time;
                    // not on screen a long time if only one hit:
                    $db_person_ary[$curKey]['end_time'] = $row->time + 10;
                    $cur_person = $cur_row_person;
                } else {
                    // update the end time:
                    $db_person_ary[$curKey]['end_time'] = $row->time;
                }
            }
            // list on screen times for everyone:
            foreach ($db_person_ary as $row) {
                print $row['Spoken_by'] . ' on screen for ' . ($row['end_time'] - $row['start_time']) . "\n";
                // $db_person_ary[]=$row;
            }
            // print_r($db_person_ary);
            // die;
            // count($cspan_person_ary)
            $cur_db_inx = 0;
            $cur_person = null;
            $fistValid = true;
            for ($i = 0; $i < count($cspan_person_ary); $i++) {
                // print "looking at: ". $cspan_person_ary[$i]['Spoken_by'] . "\n";
                print "\tCSPAN: " . $cspan_person_ary[$i]['Spoken_by'] . ' on screen for ' . $cspan_person_ary[$i]['length'] . ' or:' . npt2seconds($cspan_person_ary[$i]['length']) . "\n";
                // set up cur, the next and prev pointers:
                $cur_person = $cspan_person_ary[$i]['Spoken_by'];
                // make sure next is not the same as current:
                // note: we don't group above since the same person can give two subsequent different speeches
                $next_person = $cur_person;
                $k_person_inx = 1;
                $person_insert_set = array();
                while ($next_person == $cur_person) {
                    if (isset($cspan_person_ary[$i + $k_person_inx])) {
                        $potential_next_person = mv_is_valid_person($cspan_person_ary[$i + $k_person_inx]['Spoken_by']) ? $cspan_person_ary[$i + $k_person_inx]['Spoken_by'] : null;
                        if ($potential_next_person == null && $k_person_inx == 1) {
                            $next_person = null;
                            break;
                        } elseif ($potential_next_person != null) {
                            $next_person = $potential_next_person;
                        }
                        $k_person_inx++;
                    } else {
                        $next_person = null;
                    }
                }
                // should be no need to make sure prev is not the same as current (as we do greedy look ahead below)
                // $prev_person = $cur_person;
                // $k=1;
                // while($prev_person==$cur_person){
                if (isset($cspan_person_ary[$i - 1])) {
                    $prev_person = mv_is_valid_person($cspan_person_ary[$i - 1]['Spoken_by']) ? $cspan_person_ary[$i - 1]['Spoken_by'] : null;
                } else {
                    $prev_person = null;
                }
                // }
                if (mv_is_valid_person($cspan_person_ary[$i]['Spoken_by'])) {
                    // print "\tis valid person looking for db sync\n";
                    // print "\t prev: $prev_person cur: $cur_person next: $next_person\n";
                    if ($prev_person == null && $next_person == null) {
                        print "error both prev and next are null skiping person\n";
                        continue;
                    }
                    // check how long they where on screen (also check subquent)
                    $cspan_on_screen_time = npt2seconds($cspan_person_ary[$i]['length']);
                    // print "NOW STARTING AT: $cur_db_inx of " . count($db_person_ary) . "\n";
                    for ($j = $cur_db_inx; $j < count($db_person_ary); $j++) {
                        // print "searchig db on: " . $db_person_ary[$j]['Spoken_by'] . "!=" . $cspan_person_ary[$i]['Spoken_by'] . " \n";
                        $prevMatch = $curMatch = $nextMatch = false;
                        if ($cur_db_inx == 0 || $prev_person == null) {
                            // no need to check prev in db_inx
                            $prevMatch = true;
                            //	print "(no back check)";
                        } else {
                            if ($db_person_ary[$j - 1]['Spoken_by'] == $prev_person) {
                                //	print "found prev match: $prev_person\n;";
                                $prevMatch = true;
                            }
                        }
                        if (isset($db_person_ary[$j])) {
                            if (isset($cspan_person_ary[$i])) {
                                if ($db_person_ary[$j]['Spoken_by'] == $cspan_person_ary[$i]['Spoken_by']) {
                                    //	print "found cur match:". $cspan_person_ary[$i]['Spoken_by']."\n";
                                    $curMatch = true;
                                }
                            }
                        }
                        if ($next_person == null) {
                            // no need to check next in db_inx
                            $nextMatch = true;
                            //	print "(no next check)";
                        } else {
                            if (isset($db_person_ary[$j + 1])) {
                                if ($db_person_ary[$j + 1]['Spoken_by'] == $next_person) {
                                    // print "found next match:".$next_person."\n";
                                    $nextMatch = true;
                                }
                            }
                        }
                        // if we have a match set do insert proc:
                        if ($prevMatch && $curMatch && $nextMatch) {
                            // print "FOUND Match on $j\n";
                            // print "\t prev: $prev_person cur: $cur_person next: $next_person\n";
                            $cur_db_inx = $j;
                            // add all additional info we can from c-span:
                            // also push forward for all of current (we should always hit the first series of the same person first )
                            $k = 0;
                            // build insert set:
                            $cur_start_time = $db_person_ary[$j]['start_time'];
                            while ($cur_person == $cspan_person_ary[$i + $k]['Spoken_by']) {
                                // use the last cspan_person for start case
                                $cspan_person_ary[$i + $k]['wiki_start_time'] = $cur_start_time;
                                if (npt2seconds($cspan_person_ary[$i + $k]['length']) > $db_person_ary[$j]['end_time'] - $cur_start_time) {
                                    $cspan_person_ary[$i + $k]['wiki_end_time'] = $db_person_ary[$j]['end_time'];
                                    // already used up our db_person_ary continue:
                                    print "a cspan insert sync " . ' ' . $cspan_person_ary[$i + $k]['wiki_start_time'] . " to " . $cspan_person_ary[$i + $k]['wiki_end_time'] . " of " . $db_person_ary[$j]['end_time'] . " for: " . $cspan_person_ary[$i]['Spoken_by'] . "\n";
                                    break;
                                } else {
                                    $cspan_person_ary[$i + $k]['wiki_end_time'] = $cur_start_time + npt2seconds($cspan_person_ary[$i + $k]['length']);
                                    // print "add " . npt2seconds($cspan_person_ary[$i+$k]['length']) . "\n";
                                    $cur_start_time += npt2seconds($cspan_person_ary[$i + $k]['length']);
                                }
                                print "p cspan insert sync " . ' ' . $cspan_person_ary[$i + $k]['wiki_start_time'] . " to " . $cspan_person_ary[$i + $k]['wiki_end_time'] . " of " . $db_person_ary[$j]['end_time'] . " for: " . $cspan_person_ary[$i]['Spoken_by'] . "\n";
                                // print_r($db_person_ary[$j]);
                                // print_r($cspan_person_ary[$i+$k]);
                                $k++;
                                if (!isset($cspan_person_ary[$i + $k])) {
                                    break;
                                }
                            }
                            $k--;
                            // extend the last property if within 100 seconds
                            if (abs($cspan_person_ary[$i + $k]['wiki_end_time'] - $db_person_ary[$j]['end_time']) < 100) {
                                $cspan_person_ary[$i + $k]['wiki_end_time'] = $db_person_ary[$j]['end_time'];
                                print "updated cspan insert for: " . $cspan_person_ary[$i]['Spoken_by'] . ' ' . $cspan_person_ary[$i + $k]['wiki_start_time'] . " to " . $cspan_person_ary[$i + $k]['wiki_end_time'] . " of " . $db_person_ary[$j]['end_time'] . "\n";
                            }
                            $k++;
                            //	   						/die;
                            // move the index to the current:
                            $i = $i + $k;
                            continue;
                        }
                    }
                } else {
                    // print $cspan_person_ary[$i]['Spoken_by'] . " is not valid person\n";
                }
            }
            print "Get Additonal C-SPAN Data For \"synced\" Data:\n";
            foreach ($cspan_person_ary as $pData) {
                if (isset($pData['wiki_start_time'])) {
                    // init:
                    $bill_categories = array();
                    $annotate_body = '';
                    $body = '';
                    $bill_key = null;
                    $rawpage = $this->doRequest($this->base_url . $pData['href']);
                    // $rawpage = $this->doRequest('http://www.c-spanarchives.org/congress/?q=node/77531&id=8330447');
                    preg_match('/<\\/td><th><center>([^<]*)<\\/center><\\/th><td>/U', $rawpage, $title_matches);
                    preg_match('/<table width="400">\\n<tr><td>\\n(.*)<\\/tr><\\/td>/', $rawpage, $page_matches);
                    if (isset($title_matches[1]) && isset($page_matches[1])) {
                        $title = trim($title_matches[1]);
                        $body = $page_matches[1];
                        // print_r($page_matches);
                    } else {
                        print "error can't find title or body\n";
                        print "skip...";
                        continue;
                    }
                    // do debate tag search:
                    preg_match('/<td colspan="2">Debate:\\s*<[^>]*>([^<]*)/U', $rawpage, $debate_matches);
                    if (isset($debate_matches[1])) {
                        $bill_key = trim($debate_matches[1]);
                        print "found debate: tag " . $bill_key . "\n";
                        // build gov-track-congress-session friendly debate url:
                        if ($this->get_and_process_billid($bill_key, $stream->date_start_time) != null) {
                            $bill_categories[$bill_key] = $bill_key;
                        }
                    }
                    // title fix hack for C-span error motion to procceed
                    // @@todo add in the rest of the motions:
                    if (strpos($title, 'MOTION TO PROCEED') !== false) {
                        $title = str_replace('MOTION TO PROCEED', '', $title);
                        // $annotate_body.="[[Bill Motion:=MOTION TO PROCEED]]\n";
                    }
                    // fix title case
                    $title = ucwords(strtolower($title));
                    // don't Cap a Few of the Words: '
                    $title = str_replace(array(' And', ' Or', ' Of', ' A'), array(' and', ' or', ' of', ' a'), $title);
                    // replace '' with ``
                    $body = str_replace('\'\'', '``', $body);
                    // replace bill names with [[Catgory:: bill name #]]
                    // $bill_pattern = '/(H\.R\.\s[0-9]+)/';
                    $bill_pattern = '/';
                    $bill_pattern_ary = array();
                    $or = '';
                    foreach ($this->bill_types as $cspanT => $govtrakT) {
                        $cspanT = str_replace('RES', '[\\s]?RES', $cspanT);
                        // sometimes spaces before res in text
                        $cspanT = str_replace('CON', '[\\s]?CON', $cspanT);
                        // sometimes spaces before res in text
                        // replace . with \.[\s]?
                        $bill_pattern .= $or . '(' . str_replace('.', '\\.[\\s]?', $cspanT) . '\\s?[0-9]+)';
                        $bill_pattern_ary[] = '(' . str_replace('.', '\\.[\\s]?', $cspanT) . '\\s?[0-9]+)';
                        $or = '|';
                    }
                    $bill_pattern .= '/i';
                    // case insensative
                    // $body='bla bla H.R. 3453 test S. 3494 some more text';
                    // print "pattern:".$bill_pattern . "\n";
                    preg_match_all($bill_pattern, $body, $bill_matches);
                    // print_r($bill_matches);
                    // die;
                    if (isset($bill_matches[1])) {
                        foreach ($bill_matches as $k => $bill_type_ary) {
                            if ($k != 0) {
                                if (isset($bill_type_ary[0])) {
                                    $bill_name = $bill_type_ary[0];
                                } elseif (isset($bill_type_ary[1])) {
                                    $bill_name = $bill_type_ary[1];
                                } else {
                                    continue;
                                }
                                // if the first letter is lower case not likely a bill
                                if (trim($bill_name) == '') {
                                    continue;
                                }
                                if (islower(substr($bill_name, 0, 1))) {
                                    continue;
                                }
                                // conform white space and case:
                                $bill_name = str_replace(array('S. ', 'Con. ', 'Res. '), array('S.', 'CON.', 'RES. '), $bill_name);
                                // make sure its not a false possitave and load bill data from govTrack:
                                if ($this->get_and_process_billid($bill_name, $stream->date_start_time)) {
                                    $bill_categories[$bill_name] = $bill_name;
                                }
                            }
                        }
                    }
                    // add speech by attribute to annotation body:
                    $annotate_body .= 'Speech By: [[Speech by:=' . str_replace('_', ' ', $pData['Spoken_by']) . ']] ';
                    // add speech by attribute to body as well?
                    $body .= "\n\n" . 'Speech By: [[Speech by:=' . str_replace('_', ' ', $pData['Spoken_by']) . ']] ';
                    // add any mentions of bills with linkback to full bill title:
                    $body = preg_replace_callback($bill_pattern_ary, array('self', 'bill_pattern_cp'), $body);
                    // source the doument:
                    $body .= "\n\n" . 'Source: [[Data Source Name:=C-SPAN Congressional Chronicle]] [[Data Source URL:=' . $this->base_url . $pData['href'] . ']]';
                    $body .= "\n";
                    // add the title to the top of the page:
                    $body = "==={$title}===\n" . $body;
                    $cspan_title_str = $this->get_aligned_time_title($pData, 'Thomas_en', $stream);
                    if (!$cspan_title_str) {
                        $cspan_title_str = 'Thomas_en:' . $stream->name . '/' . seconds2npt($pData['wiki_start_time']) . '/' . seconds2npt($pData['wiki_end_time']);
                    }
                    $cspanTitle = Title::makeTitle(MV_NS_MVD, ucfirst($cspan_title_str));
                    // print "do edit ".$cspanTitle->getText()."\n";
                    do_update_wiki_page($cspanTitle, $body);
                    // protect editing of the offical record (but allow moving for sync)
                    $cspanTitle->loadRestrictions();
                    global $wgRestrictionTypes;
                    foreach ($wgRestrictionTypes as $action) {
                        // Fixme: this form currently requires individual selections,
                        // but the db allows multiples separated by commas.
                        $mRestrictions[$action] = implode('', $cspanTitle->getRestrictions($action));
                    }
                    $article = new Article($cspanTitle);
                    $mRestrictions['edit']['sysop'] = true;
                    $expiry = Block::infinity();
                    $dbw = wfGetDB(DB_MASTER);
                    $dbw->begin();
                    $ok = $article->updateRestrictions($mRestrictions, wfMsg('mv_source_material'), false, $expiry);
                    if ($ok) {
                        print "updated permisions for " . $cspanTitle->getText() . "\n";
                        $dbw->commit();
                    } else {
                        print "failed to update restrictions :(\n";
                    }
                    // process each bill to the annotation body;
                    $bcat = '';
                    $bill_lead_in = "\n\nBill ";
                    // print_r($bill_categories);
                    foreach ($bill_categories as $bill) {
                        if (trim($bill) != '') {
                            // use short title for category and long title for semantic link... (highly arbitrary)
                            $annotate_body .= $bill_lead_in . '[[Bill:=' . $this->cur_bill_short_title . ']] ';
                            $bill_lead_in = ' , ';
                            $annotate_body .= "[[Category:{$bill}]] ";
                        }
                    }
                    if (trim($title) != '') {
                        $annotate_body .= "[[Category:{$title}]]\n";
                    }
                    // see if we can align with an existing speech page:
                    $anno_title_str = $this->get_aligned_time_title($pData, 'Anno_en', $stream);
                    if (!$anno_title_str) {
                        $anno_title_str = 'Anno_en:' . $stream->name . '/' . seconds2npt($pData['wiki_start_time']) . '/' . seconds2npt($pData['wiki_end_time']);
                    }
                    $annoTitle = Title::makeTitle(MV_NS_MVD, ucfirst($anno_title_str));
                    do_update_wiki_page($annoTitle, $annotate_body);
                    // [Page: S14580] replaced with:  [[Category:BillName]]
                    // would be good to link into the official record for "pages"
                    // [[Speech by:=name]]
                    // [[category:=title]]
                    // for documentation:
                    // semantic qualities would be Aruging For:billX or Arguging Agaist billY
                    // these pages are non-editable
                    // maybe put the category info into annotations layer? (since it applies to both?)
                    // do new page mvd:or_
                }
            }
            // $inx_cspan_person_ary = array_keys($g_row_matches);
            // $inx_row_person_ary = array_keys($g_person_time_ary);
            // for($i=0;$i<5;$i++){
            // }
            // find match person1->person2
            // average switch time to get offset of stream
            // use offset to insert all $person_time_array data
        }
    }
Esempio n. 16
0
 /**
  * Blocks the user specified in the parameters for the given expiry, with the
  * given reason, and with all other settings provided in the params. If the block
  * succeeds, produces a result containing the details of the block and notice
  * of success. If it fails, the result will specify the nature of the error.
  */
 public function execute()
 {
     global $wgUser;
     $this->getMain()->requestWriteMode();
     $params = $this->extractRequestParams();
     if ($params['gettoken']) {
         $res['blocktoken'] = $wgUser->editToken();
         $this->getResult()->addValue(null, $this->getModuleName(), $res);
         return;
     }
     if (is_null($params['user'])) {
         $this->dieUsageMsg(array('missingparam', 'user'));
     }
     if (is_null($params['token'])) {
         $this->dieUsageMsg(array('missingparam', 'token'));
     }
     if (!$wgUser->matchEditToken($params['token'])) {
         $this->dieUsageMsg(array('sessionfailure'));
     }
     if (!$wgUser->isAllowed('block')) {
         $this->dieUsageMsg(array('cantblock'));
     }
     if ($params['hidename'] && !$wgUser->isAllowed('hideuser')) {
         $this->dieUsageMsg(array('canthide'));
     }
     if ($params['noemail'] && !$wgUser->isAllowed('blockemail')) {
         $this->dieUsageMsg(array('cantblock-email'));
     }
     if (wfReadOnly()) {
         $this->dieUsageMsg(array('readonlytext'));
     }
     $form = new IPBlockForm('');
     $form->BlockAddress = $params['user'];
     $form->BlockReason = is_null($params['reason']) ? '' : $params['reason'];
     $form->BlockReasonList = 'other';
     $form->BlockExpiry = $params['expiry'] == 'never' ? 'infinite' : $params['expiry'];
     $form->BlockOther = '';
     $form->BlockAnonOnly = $params['anononly'];
     $form->BlockCreateAccount = $params['nocreate'];
     $form->BlockEnableAutoBlock = $params['autoblock'];
     $form->BlockEmail = $params['noemail'];
     $form->BlockHideName = $params['hidename'];
     $dbw = wfGetDb(DB_MASTER);
     $dbw->begin();
     $retval = $form->doBlock($userID, $expiry);
     if (!empty($retval)) {
         // We don't care about multiple errors, just report one of them
         $this->dieUsageMsg($retval);
     }
     $dbw->commit();
     $res['user'] = $params['user'];
     $res['userID'] = $userID;
     $res['expiry'] = $expiry == Block::infinity() ? 'infinite' : $expiry;
     $res['reason'] = $params['reason'];
     if ($params['anononly']) {
         $res['anononly'] = '';
     }
     if ($params['nocreate']) {
         $res['nocreate'] = '';
     }
     if ($params['autoblock']) {
         $res['autoblock'] = '';
     }
     if ($params['noemail']) {
         $res['noemail'] = '';
     }
     if ($params['hidename']) {
         $res['hidename'] = '';
     }
     $this->getResult()->addValue(null, $this->getModuleName(), $res);
 }
Esempio n. 17
0
 /**
  * protect key pages
  *
  * @author Lucas 'TOR' Garczewski <*****@*****.**>
  */
 private function protectKeyPages()
 {
     global $wgUser, $wgWikiaKeyPages;
     $wgUser = User::newFromName("CreateWiki script");
     if ($wgUser->isAnon()) {
         $wgUser->addToDatabase();
     }
     if (empty($wgWikiaKeyPages)) {
         $wgWikiaKeyPages = array('File:Wiki.png', 'File:Favicon.ico');
     }
     /**
      * define restriction level and duration
      */
     $restrictions["edit"] = 'sysop';
     $restrictions["move"] = 'sysop';
     $restrictions["create"] = 'sysop';
     $titleRestrictions = 'sysop';
     $expiry_string = Block::infinity();
     $expiry_array = array('edit' => $expiry_string, 'move' => $expiry_string);
     /**
      *  define reason msg and fetch it
      */
     $reason = wfMsgForContent('autocreatewiki-protect-reason');
     $wgUser->addGroup('staff');
     foreach ($wgWikiaKeyPages as $pageName) {
         $title = Title::newFromText($pageName);
         $article = new Article($title);
         if ($article->exists()) {
             $cascade = 0;
             $ok = $article->updateRestrictions($restrictions, $reason, $cascade, $expiry_array);
         } else {
             $wikiPage = WikiPage::factory($title);
             $ignored_reference = false;
             // doing this because MW1.19 doUpdateRestrictions() is weird, and has this passed by reference
             $status = $wikiPage->doUpdateRestrictions(array('create' => $titleRestrictions), array('create' => $expiry_string), $ignored_reference, $reason, $wgUser);
             $ok = $status->isOK();
         }
         if ($ok) {
             Wikia::log(__METHOD__, "ok", "Protected key page: {$pageName}");
         } else {
             Wikia::log(__METHOD__, "err", "Failed while trying to protect {$pageName}");
         }
     }
     $wgUser->removeGroup("staff");
 }
Esempio n. 18
0
function doProtect($limit = array(), $reason = '', &$expiry = '')
{
    global $wgUser, $wgRestrictionTypes, $wgContLang, $wgTitle;
    $id = $wgTitle->getArticleID();
    if (wfReadOnly() || $id == 0) {
        return false;
    }
    if (strlen($expiry) == 0) {
        $expiry = 'infinite';
    }
    if ($expiry == 'infinite' || $expiry == 'indefinite') {
        $expiry = Block::infinity();
    } else {
        # Convert GNU-style date, on error returns -1 for PHP <5.1 and false for PHP >=5.1
        $expiry = strtotime($expiry);
        if ($expiry < 0 || $expiry === false) {
            //invalid expiry, rewrite to infinity
            $expiry = Block::infinity();
        } else {
            // Fixme: non-qualified absolute times are not in users specified timezone
            // and there isn't notice about it in the ui
            $expiry = wfTimestamp(TS_MW, $expiry);
        }
    }
    // Take this opportunity to purge out expired restrictions
    Title::purgeExpiredRestrictions();
    # FIXME: Same limitations as described in ProtectionForm.php (line 37);
    # we expect a single selection, but the schema allows otherwise.
    $current = array();
    foreach ($wgRestrictionTypes as $action) {
        $current[$action] = implode('', $wgTitle->getRestrictions($action));
    }
    $current = Article::flattenRestrictions($current);
    $updated = Article::flattenRestrictions($limit);
    $changed = $current != $updated;
    $changed = $changed || $wgTitle->mRestrictionsExpiry != $expiry;
    $protect = $updated != '';
    # If nothing's changed, do nothing
    if ($changed) {
        global $wgGroupPermissions;
        $dbw = wfGetDB(DB_MASTER);
        $encodedExpiry = Block::encodeExpiry($expiry, $dbw);
        $expiry_description = '';
        if ($encodedExpiry != 'infinity') {
            $expiry_description = ' (' . wfMsgForContent('protect-expiring', $wgContLang->timeanddate($expiry, false, false)) . ')';
        }
        # Prepare a null revision to be added to the history
        $modified = $current != '' && $protect;
        if ($protect) {
            $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
        } else {
            $comment_type = 'unprotectedarticle';
        }
        $comment = $wgContLang->ucfirst(wfMsgForContent($comment_type, $wgTitle->getPrefixedText()));
        if ($reason) {
            $comment .= ": {$reason}";
        }
        if ($protect) {
            $comment .= " [{$updated}]";
        }
        if ($expiry_description && $protect) {
            $comment .= "{$expiry_description}";
        }
        # Update restrictions table
        foreach ($limit as $action => $restrictions) {
            if ($restrictions != '') {
                $dbw->replace('page_restrictions', array(array('pr_page', 'pr_type')), array('pr_page' => $id, 'pr_type' => $action, 'pr_level' => $restrictions, 'pr_cascade' => 0, 'pr_expiry' => $encodedExpiry), __METHOD__);
            } else {
                $dbw->delete('page_restrictions', array('pr_page' => $id, 'pr_type' => $action), __METHOD__);
            }
        }
        # Insert a null revision
        $nullRevision = Revision::newNullRevision($dbw, $id, $comment, true);
        $nullRevId = $nullRevision->insertOn($dbw);
        # Update page record
        $dbw->update('page', array('page_touched' => $dbw->timestamp(), 'page_restrictions' => '', 'page_latest' => $nullRevId), array('page_id' => $id), 'Article::protect');
        # Update the protection log
        $log = new LogPage('protect');
        if ($protect) {
            $log->addEntry($modified ? 'modify' : 'protect', $wgTitle, trim($reason . " [{$updated}]{$expiry_description}"));
        } else {
            $log->addEntry('unprotect', $wgTitle, $reason);
        }
    }
    # End "changed" check
    return true;
}
Esempio n. 19
0
 private static function AuthorProtectExpiry($value)
 {
     if ($value == 'infinite' || $value == 'indefinite' || $value == 'infinity' || $value == '') {
         $time = Block::infinity();
     } else {
         $unix = strtotime($value);
         if (!$unix || $unix === -1) {
             return false;
         }
         // Fixme: non-qualified absolute times are not in users specified timezone
         // and there isn't notice about it in the ui
         $time = wfTimestamp(TS_MW, $unix);
     }
     return $time;
 }
Esempio n. 20
0
 /**
  * Get the expiry time for a given action, by combining the relevant inputs.
  *
  * @return 14-char timestamp or "infinity", or false if the input was invalid
  */
 function getExpiry($action)
 {
     if ($this->mExpirySelection[$action] == 'existing') {
         return $this->mExistingExpiry[$action];
     } elseif ($this->mExpirySelection[$action] == 'othertime') {
         $value = $this->mExpiry[$action];
     } else {
         $value = $this->mExpirySelection[$action];
     }
     if ($value == 'infinite' || $value == 'indefinite' || $value == 'infinity') {
         $time = Block::infinity();
     } else {
         $unix = strtotime($value);
         if (!$unix || $unix === -1) {
             return false;
         }
         // Fixme: non-qualified absolute times are not in users specified timezone
         // and there isn't notice about it in the ui
         $time = wfTimestamp(TS_MW, $unix);
     }
     return $time;
 }
Esempio n. 21
0
 /** 
  * Decode expiry which has come from the DB
  */
 static function decodeExpiry($expiry, $timestampType = TS_MW)
 {
     if ($expiry == '' || $expiry == Block::infinity()) {
         return Block::infinity();
     } else {
         return wfTimestamp($timestampType, $expiry);
     }
 }
 function save()
 {
     global $wgRequest, $wgUser, $wgOut;
     if ($this->disabled) {
         $this->show();
         return false;
     }
     $token = $wgRequest->getVal('wpEditToken');
     if (!$wgUser->matchEditToken($token)) {
         $this->show(wfMsg('sessionfailure'));
         return false;
     }
     if (strlen($this->mExpiry) == 0) {
         $this->mExpiry = 'infinite';
     }
     if ($this->mExpiry == 'infinite' || $this->mExpiry == 'indefinite') {
         $expiry = Block::infinity();
     } else {
         # Convert GNU-style date, on error returns -1 for PHP <5.1 and false for PHP >=5.1
         $expiry = strtotime($this->mExpiry);
         if ($expiry < 0 || $expiry === false) {
             $this->show(wfMsg('protect_expiry_invalid'));
             return false;
         }
         $expiry = wfTimestamp(TS_MW, $expiry);
         if ($expiry < wfTimestampNow()) {
             $this->show(wfMsg('protect_expiry_old'));
             return false;
         }
     }
     # They shouldn't be able to do this anyway, but just to make sure, ensure that cascading restrictions aren't being applied
     #  to a semi-protected page.
     global $wgGroupPermissions;
     $edit_restriction = $this->mRestrictions['edit'];
     if ($this->mCascade && $edit_restriction != 'protect' && !(isset($wgGroupPermissions[$edit_restriction]['protect']) && $wgGroupPermissions[$edit_restriction]['protect'])) {
         $this->mCascade = false;
     }
     if ($this->mTitle->exists()) {
         $ok = $this->mArticle->updateRestrictions($this->mRestrictions, $this->mReason, $this->mCascade, $expiry);
     } else {
         $ok = $this->mTitle->updateTitleProtection($this->mRestrictions['create'], $this->mReason, $expiry);
     }
     if (!$ok) {
         throw new FatalError("Unknown error at restriction save time.");
     }
     if ($wgRequest->getCheck('mwProtectWatch')) {
         $this->mArticle->doWatch();
     } elseif ($this->mTitle->userIsWatching()) {
         $this->mArticle->doUnwatch();
     }
     return $ok;
 }
 function getQueryInfo()
 {
     $conds = $this->mConds;
     $conds[] = 'page_id = fpc_page_id';
     $conds['fpc_override'] = 1;
     if ($this->autoreview !== null) {
         $conds['fpc_level'] = $this->autoreview;
     }
     $conds['page_namespace'] = $this->namespace;
     // Be sure not to include expired items
     if ($this->indef) {
         $conds['fpc_expiry'] = Block::infinity();
     } else {
         $encCutoff = $this->mDb->addQuotes($this->mDb->timestamp());
         $conds[] = "fpc_expiry > {$encCutoff}";
     }
     return array('tables' => array('flaggedpage_config', 'page'), 'fields' => array('page_namespace', 'page_title', 'fpc_override', 'fpc_expiry', 'fpc_page_id', 'fpc_level'), 'conds' => $conds, 'options' => array());
 }
Esempio n. 24
0
 /**
  * Blocks the user specified in the parameters for the given expiry, with the
  * given reason, and with all other settings provided in the params. If the block
  * succeeds, produces a result containing the details of the block and notice
  * of success. If it fails, the result will specify the nature of the error.
  */
 public function execute()
 {
     global $wgUser, $wgBlockAllowsUTEdit;
     $params = $this->extractRequestParams();
     if ($params['gettoken']) {
         $res['blocktoken'] = $wgUser->editToken();
         $this->getResult()->addValue(null, $this->getModuleName(), $res);
         return;
     }
     if (is_null($params['user'])) {
         $this->dieUsageMsg(array('missingparam', 'user'));
     }
     if (is_null($params['token'])) {
         $this->dieUsageMsg(array('missingparam', 'token'));
     }
     if (!$wgUser->matchEditToken($params['token'])) {
         $this->dieUsageMsg(array('sessionfailure'));
     }
     if (!$wgUser->isAllowed('block')) {
         $this->dieUsageMsg(array('cantblock'));
     }
     if ($params['hidename'] && !$wgUser->isAllowed('hideuser')) {
         $this->dieUsageMsg(array('canthide'));
     }
     if ($params['noemail'] && !$wgUser->isAllowed('blockemail')) {
         $this->dieUsageMsg(array('cantblock-email'));
     }
     $form = new IPBlockForm('');
     $form->BlockAddress = $params['user'];
     $form->BlockReason = is_null($params['reason']) ? '' : $params['reason'];
     $form->BlockReasonList = 'other';
     $form->BlockExpiry = $params['expiry'] == 'never' ? 'infinite' : $params['expiry'];
     $form->BlockOther = '';
     $form->BlockAnonOnly = $params['anononly'];
     $form->BlockCreateAccount = $params['nocreate'];
     $form->BlockEnableAutoblock = $params['autoblock'];
     $form->BlockEmail = $params['noemail'];
     $form->BlockHideName = $params['hidename'];
     $form->BlockAllowUsertalk = $params['allowusertalk'] && $wgBlockAllowsUTEdit;
     $form->BlockReblock = $params['reblock'];
     $userID = $expiry = null;
     $retval = $form->doBlock($userID, $expiry);
     if (count($retval)) {
         // We don't care about multiple errors, just report one of them
         $this->dieUsageMsg($retval);
     }
     $res['user'] = $params['user'];
     $res['userID'] = intval($userID);
     $res['expiry'] = $expiry == Block::infinity() ? 'infinite' : wfTimestamp(TS_ISO_8601, $expiry);
     $res['reason'] = $params['reason'];
     if ($params['anononly']) {
         $res['anononly'] = '';
     }
     if ($params['nocreate']) {
         $res['nocreate'] = '';
     }
     if ($params['autoblock']) {
         $res['autoblock'] = '';
     }
     if ($params['noemail']) {
         $res['noemail'] = '';
     }
     if ($params['hidename']) {
         $res['hidename'] = '';
     }
     if ($params['allowusertalk']) {
         $res['allowusertalk'] = '';
     }
     $this->getResult()->addValue(null, $this->getModuleName(), $res);
 }
Esempio n. 25
0
 /**
  * Callback function to output a block
  */
 function formatRow($block)
 {
     global $wgUser, $wgLang;
     wfProfileIn(__METHOD__);
     static $sk = null, $msg = null;
     if (is_null($sk)) {
         $sk = $wgUser->getSkin();
     }
     if (is_null($msg)) {
         $msg = array();
         $keys = array('infiniteblock', 'expiringblock', 'contribslink', 'unblocklink', 'anononlyblock', 'createaccountblock');
         foreach ($keys as $key) {
             $msg[$key] = wfMsgHtml($key);
         }
         $msg['blocklistline'] = wfMsg('blocklistline');
         $msg['contribslink'] = wfMsg('contribslink');
     }
     # Prepare links to the blocker's user and talk pages
     $blocker_name = $block->getByName();
     $blocker = $sk->MakeLinkObj(Title::makeTitle(NS_USER, $blocker_name), $blocker_name);
     $blocker .= ' (' . $sk->makeLinkObj(Title::makeTitle(NS_USER_TALK, $blocker_name), $wgLang->getNsText(NS_TALK)) . ')';
     # Prepare links to the block target's user and contribs. pages (as applicable, don't do it for autoblocks)
     if ($block->mAuto) {
         $target = $block->getRedactedName();
         # Hide the IP addresses of auto-blocks; privacy
     } else {
         $target = $sk->makeLinkObj(Title::makeTitle(NS_USER, $block->mAddress), $block->mAddress);
         $target .= ' (' . $sk->makeKnownLinkObj(Title::makeTitle(NS_SPECIAL, 'Contributions'), $msg['contribslink'], 'target=' . urlencode($block->mAddress)) . ')';
     }
     $formattedTime = $wgLang->timeanddate($block->mTimestamp, true);
     $properties = array();
     if ($block->mExpiry === "" || $block->mExpiry === Block::infinity()) {
         $properties[] = $msg['infiniteblock'];
     } else {
         $properties[] = wfMsgReplaceArgs($msg['expiringblock'], array($wgLang->timeanddate($block->mExpiry, true)));
     }
     if ($block->mAnonOnly) {
         $properties[] = $msg['anononlyblock'];
     }
     if ($block->mCreateAccount) {
         $properties[] = $msg['createaccountblock'];
     }
     $properties = implode(', ', $properties);
     $line = wfMsgReplaceArgs($msg['blocklistline'], array($formattedTime, $blocker, $target, $properties));
     $s = "<li>{$line}";
     if ($wgUser->isAllowed('block')) {
         $titleObj = Title::makeTitle(NS_SPECIAL, "Ipblocklist");
         $s .= ' (' . $sk->makeKnownLinkObj($titleObj, $msg['unblocklink'], 'action=unblock&id=' . urlencode($block->mId)) . ')';
     }
     $s .= $sk->commentBlock($block->mReason);
     $s .= "</li>\n";
     wfProfileOut(__METHOD__);
     return $s;
 }
Esempio n. 26
0
 function doSubmit()
 {
     global $wgOut, $wgUser, $wgSysopUserBans, $wgSysopRangeBans;
     $userId = 0;
     $this->BlockAddress = trim($this->BlockAddress);
     $rxIP = '\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}';
     # Check for invalid specifications
     if (!preg_match("/^{$rxIP}\$/", $this->BlockAddress)) {
         if (preg_match("/^({$rxIP})\\/(\\d{1,2})\$/", $this->BlockAddress, $matches)) {
             if ($wgSysopRangeBans) {
                 if ($matches[2] > 31 || $matches[2] < 16) {
                     $this->showForm(wfMsg('ip_range_invalid'));
                     return;
                 }
                 $this->BlockAddress = Block::normaliseRange($this->BlockAddress);
             } else {
                 # Range block illegal
                 $this->showForm(wfMsg('range_block_disabled'));
                 return;
             }
         } else {
             # Username block
             if ($wgSysopUserBans) {
                 $user = User::newFromName($this->BlockAddress);
                 if (!is_null($user) && $user->getID()) {
                     # Use canonical name
                     $this->BlockAddress = $user->getName();
                     $userId = $user->getID();
                 } else {
                     $this->showForm(wfMsg('nosuchusershort', htmlspecialchars($this->BlockAddress)));
                     return;
                 }
             } else {
                 $this->showForm(wfMsg('badipaddress'));
                 return;
             }
         }
     }
     $expirestr = $this->BlockExpiry;
     if ($expirestr == 'other') {
         $expirestr = $this->BlockOther;
     }
     if (strlen($expirestr) == 0) {
         $this->showForm(wfMsg('ipb_expiry_invalid'));
         return;
     }
     if ($expirestr == 'infinite' || $expirestr == 'indefinite') {
         $expiry = Block::infinity();
     } else {
         # Convert GNU-style date, on error returns -1 for PHP <5.1 and false for PHP >=5.1
         $expiry = strtotime($expirestr);
         if ($expiry < 0 || $expiry === false) {
             $this->showForm(wfMsg('ipb_expiry_invalid'));
             return;
         }
         $expiry = wfTimestamp(TS_MW, $expiry);
     }
     # Create block
     # Note: for a user block, ipb_address is only for display purposes
     $block = new Block($this->BlockAddress, $userId, $wgUser->getID(), $this->BlockReason, wfTimestampNow(), 0, $expiry, $this->BlockAnonOnly, $this->BlockCreateAccount);
     if (wfRunHooks('BlockIp', array(&$block, &$wgUser))) {
         if (!$block->insert()) {
             $this->showForm(wfMsg('ipb_already_blocked', htmlspecialchars($this->BlockAddress)));
             return;
         }
         wfRunHooks('BlockIpComplete', array($block, $wgUser));
         # Make log entry
         $log = new LogPage('block');
         $log->addEntry('block', Title::makeTitle(NS_USER, $this->BlockAddress), $this->BlockReason, $expirestr);
         # Report to the user
         $titleObj = Title::makeTitle(NS_SPECIAL, 'Blockip');
         $wgOut->redirect($titleObj->getFullURL('action=success&ip=' . urlencode($this->BlockAddress)));
     }
 }
Esempio n. 27
0
 function testActionPermissions()
 {
     global $wgUser;
     $wgUser = $this->user;
     $this->setUserPerm(array("createpage"));
     $this->setTitle(NS_MAIN, "test page");
     $this->title->mTitleProtection['pt_create_perm'] = '';
     $this->title->mTitleProtection['pt_user'] = $this->user->getID();
     $this->title->mTitleProtection['pt_expiry'] = Block::infinity();
     $this->title->mTitleProtection['pt_reason'] = 'test';
     $this->title->mCascadeRestriction = false;
     $this->assertEquals(array(array('titleprotected', 'Useruser', 'test')), $this->title->getUserPermissionsErrors('create', $this->user));
     $this->assertEquals(false, $this->title->userCan('create'));
     $this->title->mTitleProtection['pt_create_perm'] = 'sysop';
     $this->setUserPerm(array('createpage', 'protect'));
     $this->assertEquals(array(), $this->title->getUserPermissionsErrors('create', $this->user));
     $this->assertEquals(true, $this->title->userCan('create'));
     $this->setUserPerm(array('createpage'));
     $this->assertEquals(array(array('titleprotected', 'Useruser', 'test')), $this->title->getUserPermissionsErrors('create', $this->user));
     $this->assertEquals(false, $this->title->userCan('create'));
     $this->setTitle(NS_MEDIA, "test page");
     $this->setUserPerm(array("move"));
     $this->assertEquals(false, $this->title->userCan('move'));
     $this->assertEquals(array(array('immobile-source-namespace', 'Media')), $this->title->getUserPermissionsErrors('move', $this->user));
     $this->setTitle(NS_MAIN, "test page");
     $this->assertEquals(array(), $this->title->getUserPermissionsErrors('move', $this->user));
     $this->assertEquals(true, $this->title->userCan('move'));
     $this->title->mInterwiki = "no";
     $this->assertEquals(array(array('immobile-page')), $this->title->getUserPermissionsErrors('move', $this->user));
     $this->assertEquals(false, $this->title->userCan('move'));
     $this->setTitle(NS_MEDIA, "test page");
     $this->assertEquals(false, $this->title->userCan('move-target'));
     $this->assertEquals(array(array('immobile-target-namespace', 'Media')), $this->title->getUserPermissionsErrors('move-target', $this->user));
     $this->setTitle(NS_MAIN, "test page");
     $this->assertEquals(array(), $this->title->getUserPermissionsErrors('move-target', $this->user));
     $this->assertEquals(true, $this->title->userCan('move-target'));
     $this->title->mInterwiki = "no";
     $this->assertEquals(array(array('immobile-target-page')), $this->title->getUserPermissionsErrors('move-target', $this->user));
     $this->assertEquals(false, $this->title->userCan('move-target'));
 }