Пример #1
0
 public function execute_fix_wpw_date_expires()
 {
     $dbw = wfGetDB(DB_MASTER);
     $dbw->begin();
     $this->output("looking for wikiplace records to fix...\n");
     $cond = 'wpw_date_expires > DATE_ADD(wpw_report_updated,INTERVAL 1 MONTH)';
     $wikiplaces = WpWikiplace::search($cond, true);
     foreach ($wikiplaces as $wikiplace) {
         $subscription = WpSubscription::newFromId($wikiplace->getSubscriptionId());
         $should_ends = WpWikiplace::calculateNextDateExpiresFromSubscription($subscription);
         if ($subscription->isActive() && $subscription->getTmrStatus() == 'OK' && $wikiplace->getDateExpires() != $should_ends) {
             $this->output("wpw_id=" . $wikiplace->getId() . "\tupdated=" . $wikiplace->getReportUpdated() . "\texpires=" . $wikiplace->getDateExpires() . "\n");
             $this->output(" > wps\t\tstarts=" . $subscription->getStart() . "\tends=" . $subscription->getEnd() . "\n");
             $this->output(" > should expire {$should_ends}\n");
             if (!$this->isTest()) {
                 $this->output(" > fixing...\n");
                 $success = $dbw->update('wp_wikiplace', array('wpw_date_expires' => $should_ends), array('wpw_id' => $wikiplace->getId()));
                 if (!$success) {
                     $this->error("Error while updating wikiplace id=" . $wikiplace->getId(), true);
                 }
                 $this->output(" > fixed :)\n");
             }
             $this->output("\n");
         }
     }
     $this->output("end\n");
     $dbw->commit();
 }
Пример #2
0
 /**
  * 
  * @return WpWikiplace
  */
 public function getWikiPlace()
 {
     if (is_null($this->wikiplace)) {
         $this->wikiplace = WpWikiplace::getById($this->wpm_wpw_id);
     }
     return $this->wikiplace;
 }
Пример #3
0
 public function execute()
 {
     $lifespan = intval($this->getOption('lifespan', 60));
     if ($lifespan < 1) {
         $lifespan = 60;
     }
     $this->output("[" . WpSubscription::now() . ": Updating usages, considering {$lifespan} minutes lifespan...]\n");
     // updates all users'wikiplaces having lifespan expired
     $ok = WpWikiplace::updateOutdatedUsages(null, $lifespan);
     if ($ok === false) {
         $this->output("ERROR: {$ok}\n");
     } else {
         // $this->output("OK: $ok record(s) updated\n");
     }
     // $this->output( "[".WpSubscription::now().": Archiving and resetting monthly usages...]\n" );
     $ok = WpWikiplace::archiveAndResetExpiredUsages();
     if ($ok === false) {
         $this->output("ERROR: {$ok}\n");
     } else {
         // $this->output("OK: $ok record(s) archived and reset\n");
     }
     $this->output("[" . WpSubscription::now() . ": END]\n");
 }
Пример #4
0
 /**
  * Fetch informations about the user uploading, prepare prefixes list content, and
  * set the default item to select. It also updates the special page DestFileName 
  * attribute. Attached to hooks:
  * <ul>
  * <li>$wgHooks['UploadForm:initial']</li>
  * <li>$wgHooks['UploadForm:BeforeProcessing']</li>
  * </ul>
  * @param SpecialPage $specialUploadObj current SpecialUpload page object
  * @todo if the user cannot upload a new file, maybe this function should
  * however return true, as seen in SpecialUpload page code comments (but if
  * true returned, the form is displayed with our error message on top)
  */
 public static function fetchRequestInformations($specialUploadObj)
 {
     $user = $specialUploadObj->getUser();
     self::$USER_IS_WP_ADMIN = $user->isAllowed(WP_ADMIN_RIGHT);
     if (self::$USER_IS_WP_ADMIN || !self::$DISPLAY_UPLOAD_MOD) {
         return true;
         // no informations to fetch and nothing to prepare, using standard form
     }
     $full_title = $specialUploadObj->getFullTitle();
     $request = $specialUploadObj->getRequest();
     // update special page DestFileName attribute
     $final_wp_filename = self::getDestinationFileName($request);
     if ($final_wp_filename != null) {
         $specialUploadObj->mDesiredDestName = $final_wp_filename;
         wfDebugLog('wikiplaces-debug', 'fetchRequestInformations, mDesiredDestName set to "' . $final_wp_filename . '"');
     }
     $final_wp_file_title = Title::newFromText($final_wp_filename, NS_FILE);
     // is the user re uploading a new version of an existing file or followed a "upload a file with this name" link ?
     if ($request->getText('wpDestFile') && !$request->getText('wpDestFileMainPart')) {
         $result = true;
         wfRunHooks('userCan', array(&$final_wp_file_title, &$user, 'upload', &$result));
         if ($result !== true) {
             wfDebugLog('wikiplaces-debug', 'WikiplaceUpload::fetchRequestInformations userCan returned ' . print_r($result, true));
             $specialUploadObj->getOutput()->showErrorPage('sorry', wfMessage('badaccess-group0'));
             // not allowed
             return false;
             // break SpecialUpload page init/processing
         }
         // Check getUserPermissionsErrors hook (this behavior is suitable for nonessential UI
         // controls because it skips potentially expensive cascading permission checks, but may
         // provide false positives)
         wfRunHooks('getUserPermissionsErrors', array(&$final_wp_file_title, &$user, 'upload', &$result));
         if ($result !== true) {
             wfDebugLog('wikiplaces-debug', print_r($result, true));
             // WikiplacesHooks::getUserPermissionsErrors($final_wp_file_title, $user, 'upload', $result);
             if (is_array($result) && !empty($result)) {
                 $key = array_shift($result);
                 $specialUploadObj->getOutput()->showErrorPage('sorry', wfMessage($key, $result));
                 return false;
                 // break SpecialUpload page init/processing
             } else {
                 $specialUploadObj->getOutput()->showErrorPage('sorry', wfMessage('badaccess-group0'));
                 // not allowed
                 return false;
                 // break SpecialUpload page init/processing
             }
         }
         // she is reuploading or has followed a "upload a file with this name" link
         wfDebugLog('wikiplaces-debug', 'fetchRequestInformations: reuploading, so disabling mod');
         self::$WPDESTFILE_READONLY = true;
         // ensure that the filename field is readonly when create link followed
         self::$DISPLAY_UPLOAD_MOD = false;
         return true;
         // no informations to fetch and nothing to prepare
     }
     // ( if we arrive here, we are uploading a new file )
     // is there a wikiplace specified in the url ?
     // search a GET parameter, as seen in SpecialPageFactory around line 408
     $db_key = $full_title->getDBkey();
     $bits = explode('/', $db_key, 2);
     $param = null;
     if (isset($bits[1])) {
         $param = $bits[1];
     }
     // is the user trying to upload a public file ?
     if ($param === WP_PUBLIC_FILE_PREFIX || $final_wp_file_title instanceof Title && WpPage::isPublic(NS_FILE, $final_wp_file_title->getDBkey())) {
         // there is a "Public" param, there will be only one choice in the listbox
         wfDebugLog('wikiplaces-debug', 'fetchRequestInformations: only public prefix will be visible');
         self::$FILE_PREFIXES[$param] = WP_PUBLIC_FILE_PREFIX;
         self::$FILE_PREFIXES_DEFAULT = $param;
     } else {
         // get all wikiplaces the user has access to
         $wikiplacesOwner = WpWikiplace::factoryAllOwnedByUserId($user->getId());
         $wikiplacesMember = WpWikiplace::factoryAllWhereUserIsMember($user->getId());
         // check if the user has access to at least one wikiplace
         if (count($wikiplacesOwner) + count($wikiplacesMember) == 0) {
             $specialUploadObj->getOutput()->showErrorPage('sorry', wfMessage('wp-create-wp-first'));
             return false;
             // break SpecialUpload page init/processing
         }
         // multiple choice: prepare full prefixes list
         foreach ($wikiplacesOwner as $wikiplace) {
             $wpw_name = $wikiplace->getName();
             self::$FILE_PREFIXES[$wpw_name] = $wpw_name;
         }
         foreach ($wikiplacesMember as $wikiplace) {
             $wpw_name = $wikiplace->getName();
             self::$FILE_PREFIXES[$wpw_name] = $wpw_name;
         }
         // do we have to set a default value ?
         if ($param != null && array_key_exists($param, self::$FILE_PREFIXES)) {
             if (!self::$FILE_PREFIXES_DEFAULT) {
                 self::$FILE_PREFIXES_DEFAULT = $param;
             }
         }
     }
     return true;
     // continue hook processing
 }
Пример #5
0
 function formatPageTitle($value)
 {
     $title = Title::makeTitle($this->mCurrentRow->page_namespace, $value);
     $ns = $title->getNamespace();
     $explosion = WpWikiplace::explodeWikipageKey($title->getText(), $ns);
     $excount = count($explosion);
     $text = '';
     // Page is in NS_MAIN
     if ($ns == NS_MAIN || $ns == NS_WIKIPLACE) {
         if ($ns == NS_WIKIPLACE) {
             $text .= '<span class="wpp-ns">' . $title->getNsText() . ':</span>';
         }
         // Homepage
         if ($excount == 1) {
             if ($ns == NS_MAIN) {
                 $text .= '<span class="wpp-hp">' . $explosion[0] . '</span>';
             } else {
                 $text .= '<span class="wpp-sp">' . $explosion[0] . '</span>';
             }
             // Subpage
         } else {
             // Language variant
             if (strlen($explosion[$excount - 1]) == 2) {
                 $lang = $explosion[$excount - 1];
                 array_pop($explosion);
             }
             // Extracting wikiplace base
             $text .= '<span class="wpp-sp-hp">' . $explosion[0] . '</span>';
             array_shift($explosion);
             // Reconstructing Page title
             $text .= '<span class="wpp-sp">';
             foreach ($explosion as $atom) {
                 $text .= '/' . $atom;
             }
             $text .= '</span>';
             // Appending Lang variant
             if (isset($lang)) {
                 $text .= '<span class="wpp-sp-lg">/' . $lang . '</span>';
             }
         }
         // Page is NS_FILE
     } else {
         if ($title->getNamespace() == NS_FILE) {
             $text .= '<span class="wpp-ns">' . $title->getNsText() . ':</span>';
             // @TODO: Extract file extension and lang variant for prettyfying
             //
             // Extracting wikiplace base
             $text .= '<span class="wpp-sp-hp">' . $explosion[0] . '</span>';
             array_shift($explosion);
             // Reconstructing Page title
             $text .= '<span class="wpp-sp">';
             foreach ($explosion as $atom) {
                 $text .= '.' . $atom;
             }
             $text .= '</span>';
         } else {
             $text .= '<span class="wpp-ns">' . $title->getNsText() . ':</span>';
             $text .= '<span class="wpp-sp">' . $title->getText() . '</span>';
         }
     }
     return Linker::linkKnown($title, $text, array(), array('redirect' => 'no'));
 }
Пример #6
0
 /**
  * skinTemplateOutputPageBeforeExec hook
  * 
  * Cooks the skin template Seizam-Style!
  * 
  * @param SkinSkinzam $skin
  * @param SkinzamTemplate $tpl
  */
 public static function skinTemplateOutputPageBeforeExec(&$skin, &$tpl)
 {
     $background['url'] = false;
     $navigation['content'] = false;
     $title = $skin->getRelevantTitle();
     $ns = $title->getNamespace();
     if (WpPage::isInWikiplaceNamespaces($ns)) {
         $explosion = WpWikiplace::explodeWikipageKey($title->getText(), $ns);
         $wikiplaceKey = $explosion[0];
         // Wikiplace Background?g|png|gif)$/i';
         $background['url'] = self::getBackgroundUrlForWikiPlace($wikiplaceKey);
         // Wikiplace Navigation Menu
         $navigationKey = $wikiplaceKey . '/' . WPNAVIGATIONKEY;
         /** @todo i18n */
         $navigationTitle = Title::newFromText($navigationKey, NS_WIKIPLACE);
         $navigationPage = WikiPage::factory($navigationTitle);
         $navigationText = $navigationPage->getText();
         if ($navigationText) {
             $navigationArticle = Article::newFromTitle($navigationTitle, $skin->getContext());
             $navigation['content'] = $navigationArticle->getOutputFromWikitext($navigationText)->getText();
         }
     } else {
         $background['url'] = self::getBackgroundUrlForOther($title);
     }
     $tpl->set('wp_background', $background);
     $tpl->set('wp_navigation', $navigation);
     return true;
 }
Пример #7
0
 public function validateRenewPlanId($id, $allData)
 {
     if (!preg_match('/^[0-9]{1,10}$/', $id)) {
         return 'Error: Invalid Renewal Plan ID';
     }
     if ($id == WPP_ID_NORENEW) {
         return true;
         // "no next plan"
     }
     $plan = WpPlan::newFromId($id);
     if ($plan == null) {
         return 'Error: Invalid Plan ID';
     }
     $user_id = $this->getUser()->getId();
     $curr_sub = WpSubscription::newActiveByUserId($user_id);
     if ($curr_sub == null) {
         return 'Error: No Active Subscription';
     }
     if (!$plan->isAvailableForRenewal($curr_sub->getEnd())) {
         return 'Error: Plan Not Available For Renewal';
     }
     if (!$plan->hasSufficientQuotas(WpWikiplace::countWikiplacesOwnedByUser($user_id), WpPage::countPagesOwnedByUser($user_id), WpPage::countDiskspaceUsageByUser($user_id))) {
         return 'Error: Plan Quotas Unsufficients';
     }
     return true;
 }
Пример #8
0
 /**
  * 
  * @param WpWikiplace $wikiplace
  */
 function setWikiPlace($wikiplace)
 {
     $this->wpNameText = $wikiplace->getName();
     $this->wpNameDb = Title::newFromText($this->wpNameText)->getDBkey();
 }
Пример #9
0
 public function processAddMember($formData)
 {
     if (!isset($formData['WpId']) || !isset($formData['UserName'])) {
         throw new MWException('Cannot add member, no data.');
     }
     $wikiplace = WpWikiplace::getById(intval($formData['WpId']));
     $user = User::newFromName($formData['UserName']);
     if (is_null($member = WpMember::Create($wikiplace, $user))) {
         return wfMessage('internalerror');
     }
     $user->invalidateCache();
     // necessary to update menus and link of the user
     $this->logActionMember('add', $wikiplace->getTitle(), $user);
     $this->name = $wikiplace->getName();
     return true;
 }
Пример #10
0
 public function execute()
 {
     $deadline = intval($this->getOption('deadline', 0));
     if ($deadline < 0) {
         $deadline = 0;
     }
     $when = WpSubscription::now(0, 0, 0, $deadline);
     $this->output("[" . WpSubscription::now() . ": Searching subscriptions to renew before {$when} which has not been notified ...]\n");
     $subs = WpSubscription::factoryActiveEndSoonToNotify($when);
     $this->output("[" . WpSubscription::now() . ": " . count($subs) . " subscription(s) to check...]\n");
     foreach ($subs as $sub) {
         $next_plan_id = $sub->getRenewalPlanId();
         $msg = "wps_id[{$sub->getId()}], ";
         if ($next_plan_id == WPP_ID_NORENEW) {
             $msg .= 'do not renew';
             $sub->sendOnNoRenewalSoon();
             $sub->setRenewalPlanNotified();
         } else {
             $msg .= "renew_wpp_id[{$next_plan_id}]: ";
             // a plan is defined has renewal, check if it's a good choice...
             $renewal_date = $sub->getEnd();
             $next_plan = $sub->getRenewalPlan();
             $user_id = $sub->getBuyerUserId();
             if ($next_plan == null) {
                 // should not occur, but ensure database is not corrupted, correct if needed
                 // change to the current plan suggested renewal one
                 $curr_plan = $sub->getPlan();
                 $new_next_plan;
                 if ($curr_plan == null) {
                     // should not occur, but ... just in case
                     $new_next_plan = WpPlan::newFromId(WP_FALLBACK_PLAN_ID);
                 } else {
                     $new_next_plan = $curr_plan->getRenewalPlan($renewal_date);
                 }
                 $new_next_plan_id = $new_next_plan->getId();
                 // update and flag as problem reported, as we will send an email to user
                 $sub->setRenewalPlanId($new_next_plan_id, true);
                 $msg .= "doesn't exist, changed to = {$new_next_plan_id}";
                 $sub->sendOnRenewalSoonWarning('wp-plan-not-available-renewal', $new_next_plan);
             } elseif (!$next_plan->hasSufficientQuotas(WpWikiplace::countWikiplacesOwnedByUser($user_id), WpPage::countPagesOwnedByUser($user_id), WpPage::countDiskspaceUsageByUser($user_id))) {
                 // change to the current plan suggested renewal one
                 $curr_plan = $sub->getPlan();
                 $new_next_plan = $curr_plan->getRenewalPlan($renewal_date);
                 $new_next_plan_id = $new_next_plan->getId();
                 // update and flag as problem reported, as we will send an email to user
                 $sub->setRenewalPlanId($new_next_plan_id, true);
                 $msg .= "unsufficient quotas, changed to = {$new_next_plan_id}";
                 $sub->sendOnRenewalSoonWarning('wp-insufficient-quota', $next_plan);
             } elseif (!$next_plan->isAvailableForRenewal($renewal_date)) {
                 // ensure the next plan will still be available
                 // change to the planned renwal plan suggested renewal one
                 $new_next_plan = $next_plan->getRenewalPlan($renewal_date);
                 $new_next_plan_id = $new_next_plan->getId();
                 // update and flag as problem reported, as we will send an email to user
                 $sub->setRenewalPlanId($new_next_plan_id, true);
                 $msg .= "will not be available, changed to = {$new_next_plan_id}";
                 $sub->sendOnRenewalSoonWarning('wp-plan-not-available-renewal', $next_plan);
             } else {
                 // it seems to be ok :)
                 $msg .= 'renewal will be ok';
                 $sub->sendOnRenewalSoonValid();
                 $sub->setRenewalPlanNotified();
             }
         }
         $this->output("{$msg}\n");
     }
     $this->output("[" . WpSubscription::now() . ": END]\n");
 }
Пример #11
0
 private function changeWikiplaceOwner($wikiplace_name = null, $user_name = null, $confirm = false)
 {
     $output = $this->getOutput();
     $output->addWikiText("=== Change Wikiplace Owner ===");
     $this->prettyOutput($output, array('wikiplace' => $wikiplace_name, 'user' => $user_name));
     $output->addWikiText("----");
     if (empty($wikiplace_name)) {
         $output->addWikiText("=== Specify a wikiplace name. ===");
         return;
     }
     $wikiplace = WpWikiplace::newFromName($wikiplace_name);
     if (is_null($wikiplace)) {
         $output->addWikiText("== ERROR! No Wikiplace with that name was found. ==");
         return;
     }
     $output->addWikiText("=== Wikiplace ===");
     $this->prettyOutput($output, array('id' => $wikiplace->getId(), 'name' => $wikiplace->getName(), 'report_expires' => $wikiplace->getDateExpires(), 'report_updated' => $wikiplace->getReportUpdated()));
     $owner = User::newFromId($wikiplace->getOwnerUserId());
     if (!$owner->loadFromId()) {
         $output->addWikiText("== WARNING! Owner is not an existing user! ==");
     } else {
         $output->addWikiText("==== Current owner ====");
         $this->prettyOutput($output, array('id' => $owner->getId(), 'name' => $owner->getName(), 'email' => $owner->getEmail(), 'email confirmed' => $owner->isEmailConfirmed() ? 'yes' : 'no', 'timestamp of account creation' => $owner->getRegistration()));
     }
     $output->addWikiText("----");
     if (empty($user_name)) {
         $output->addWikiText("=== Specify a user name. ===");
         return;
     }
     $user = User::newFromName($user_name);
     if (!$user || $user->getId() == 0) {
         $output->addWikiText("== ERROR! The user doesn't exist ! ==");
         return;
     }
     $output->addWikiText("=== New Owner ===");
     $this->prettyOutput($output, array('id' => $user->getId(), 'name' => $user->getName(), 'email' => $user->getEmail(), 'email confirmed' => $user->isEmailConfirmed() ? 'yes' : 'no', 'timestamp of account creation' => $user->getRegistration()));
     if (!$user->isEmailConfirmed()) {
         $output->addWikiText("== WARNING! Email is not confirmed! ==");
     }
     $last_subscription = WpSubscription::newByUserId($user->getId());
     if (is_null($last_subscription)) {
         $output->addWikiText("== ERROR! The user doesn't have any subscription! ==");
         return;
     }
     $output->addWikiText("==== Last subscription ====");
     $this->prettyOutput($output, array('id' => $last_subscription->getId(), 'starts' => $last_subscription->getStart(), 'ends' => $last_subscription->getEnd(), 'active' => $last_subscription->isActive() ? "yes" : "no", 'transaction status' => $last_subscription->getTmrStatus()));
     if (!$last_subscription->isActive()) {
         $output->addWikiText("== WARNING! The subscription is not active! ==");
     }
     $plan = $last_subscription->getPlan();
     if (is_null($plan)) {
         $output->addWikiText("== ERROR! The subscribed plan doesn't exist! ==");
         return;
     }
     $output->addWikiText("==== Plan ====");
     $price = $plan->getPrice();
     $this->prettyOutput($output, array('id' => $plan->getId(), 'name' => $plan->getName(), 'period' => $plan->getPeriod() . ' month(s)', 'by invitation only' => $plan->isInvitationRequired() ? 'yes' : 'no', 'price' => $price['amount'] . ' ' . $price['currency']));
     $output->addWikiText("==== Membership ====");
     $member = WpMember::GetFromWikiPlaceAndUser($wikiplace, $user);
     if ($member instanceof WpMember) {
         $output->addWikiText("Target user, {$user->getName()}, is a member of {$wikiplace->getName()}.");
         $output->addWikiText("Membership will be removed for ownership change.");
     } else {
         $output->addWikiText("{$user->getName()} is <b>NOT</b> a member of {$wikiplace->getName()}.");
     }
     $output->addWikiText("----");
     if ($confirm !== true) {
         $output->addWikiText("=== To confirm ===");
         $output->addHTML($this->getLink(self::ACTION_CHANGE_WIKIPLACE_OWNER, array('wikiplace' => $wikiplace_name, 'user' => $user_name), true));
     } else {
         if ($member instanceof WpMember) {
             $member->delete();
         }
         $wikiplace->setOwnerUserId($user->getId());
         $output->addWikiText("== Done ! ==");
     }
 }
Пример #12
0
/**
 *
 * @global Output $wgOut
 * @global User $wgUser
 * @global Request $wgRequest
 * @global Boolean $wgProtectOwnDoProtect
 * @global Array $wgProtectOwnGroups
 * @param String $action
 * @param Wikipage $article
 * @return Boolean 
 */
function poForm($action, $article)
{
    if ($action != PROTECTOWN_ACTION) {
        // not our extension
        return true;
        //don't stop processing
    }
    global $wgOut, $wgUser, $wgRequest, $wgProtectOwnDoProtect;
    // is the user allowed to use ProtectOwn
    if (!$wgUser->isAllowed(PROTECTOWN_ACTION)) {
        $wgOut->permissionRequired(PROTECTOWN_ACTION);
        return false;
        //stop processing
    }
    # user is allowed to use ProtectOwn
    $title = $article->getTitle();
    // is the user the owner?
    if (!poIsOwner($title, $wgUser)) {
        // user is not the owner of the page
        $wgOut->setPageTitle(wfMsg('errorpagetitle'));
        $wgOut->addHTML(wfMessage('po-notowner')->parse());
        return false;
        //stop processing
    }
    # user is the owner
    // start displaying page
    $wgOut->setPageTitle(wfMsg('collaborate-title', $title->getPrefixedText()));
    // as defined in Title.php, around lines 1550 (mw1.18.1),
    // being authorized to 'protect' require being authorized to 'edit'
    /* Title.php >>
     *  private function checkActionPermissions( $action, $user, $errors, $doExpensiveQueries, $short ) {
     * 	if ( $action == 'protect' ) {
     * 		if ( $this->getUserPermissionsErrors( 'edit', $user ) != array() ) {
     *  ...
     */
    # temporary assign protect right, in order to update the restricitons
    $wgProtectOwnDoProtect = true;
    // tells spSetProtectionAssignDynamicRights 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;
    # check that the user can protect (check also write right)
    $readonly = $title->getUserPermissionsErrors('protect', $wgUser);
    $readonly = !empty($readonly);
    # remove temporary assigned protect right by reloading rights with $wgProtectOwnDoProtect = 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
    wfDebugLog('ProtectOwn', 'Form: ' . ($readonly ? 'READ-ONLY' : 'READ/WRITE'));
    // can we AND do we have a request to handle?
    if ($readonly || !$wgRequest->wasPosted()) {
        // readonly OR no data submitted, so construct the form (maybe readonly)
        // display the header.
        if (!$readonly) {
            $wgOut->addHTML(Html::rawElement('div', array('class' => 'form_header informations'), wfMessage('po-header', $title->getPrefixedText(), WpWikiplace::extractWikiplaceRoot($title->getDBkey(), $title->getNamespace()))->parse()));
        } else {
            $wgOut->addHTML(Html::rawElement('div', array('class' => 'form_header informations'), wfMsg('po-locked')));
        }
        $wgOut->addHTML(poMakeForm($title, $readonly));
        return false;
        //stop processing
    }
    // ensure that the form was submitted from the user's own login session
    if (!$wgUser->matchEditToken($wgRequest->getText('wpToken'))) {
        // hummm.... how did this case happen?
        $wgOut->setPageTitle(wfMsg('errorpagetitle'));
        $wgOut->addWikiMsg('sessionfailure');
        return false;
        // stop processing
    }
    # ok, so let's change restrictions!
    $new_restrictions = array();
    $expiration = array();
    $expiry = Block::infinity();
    // the restriction will never expire
    // we load the title specific available restrictions
    $applicableRestrictionTypes = $title->getRestrictionTypes();
    // for each of theses available restrictions
    foreach ($applicableRestrictionTypes as $action) {
        // 'read', 'upload', ...
        $current_restrictions = $title->getRestrictions($action);
        //'sysop', 'owner', ...
        wfDebugLog('ProtectOwn', 'Form: current title, action "' . $action . '" restricted to level(s) "' . implode(',', $current_restrictions) . '"');
        // ensure that we have not to keep the previous restrictions
        $keep_old_restriction_for_this_action = false;
        // does the title have already a restriction ?
        if ($current_restrictions !== array()) {
            // check that the user can change the current restriction(s)
            // so, if there is multiple restrictions (for one action), user need to
            // satisfy all current restrictions in order to change at least on of them
            // (maybe, this behviour can be improved)
            // (the mediawiki check that the user satisfy all to allow an action... that's it)
            foreach ($current_restrictions as $current_restriction) {
                if (!poCanTheUserSetToThisLevel($wgUser, $title, $current_restriction)) {
                    // if the user cannot set this restriction, we keep the previous restrictions
                    // if giving few restrictions, MW core raises a warning:
                    //   mysql_real_escape_string() expects parameter 1 to be string,
                    //   array given in /var/seizam/seizamcore/WikiZam/includes/db/DatabaseMysql.php on line 331
                    // so, only one restriction per action
                    $new_restrictions[$action] = $current_restriction;
                    $keep_old_restriction_for_this_action = true;
                    break;
                    // end $current_restrictions foreach
                }
            }
        }
        if ($keep_old_restriction_for_this_action) {
            continue;
        }
        // end $applicableRestrictionTypes current iteration foreach
        // set expiry
        $expiration[$action] = $expiry;
        # we arrive here if user can change the restrictions
        // by default, restricted to owner
        $new_restrictions[$action] = 'owner';
        // check what's checked, taking account $wgProtectOwnGroups order
        global $wgProtectOwnGroups;
        foreach ($wgProtectOwnGroups as $current_level) {
            // convert from BACK-END to FRONT-END: 'everyone' = ''
            $current_level = $current_level == '' ? 'everyone' : $current_level;
            // is the checkbox $action/$current_level checked ?
            if ($wgRequest->getText("radio-{$action}") == $current_level) {
                // convert from FRONT-END to BACK-END
                $current_level = $current_level == 'everyone' ? '' : $current_level;
                // can the user set to this level?
                if (poCanTheUserSetToThisLevel($wgUser, $title, $current_level)) {
                    wfDebugLog('ProtectOwn', 'Form: restricting ' . $action . ' to ' . $current_level);
                    // so we can set the restriction to it
                    $new_restrictions[$action] = $current_level;
                } else {
                    # the user wanted to restrict the action to a level, in which she is not
                    # what to do? diplay an error message?
                    # if no code in this block, we will resume checkboxes getting values,
                    # and set to restriction level 'owner' if no one else checked
                }
            }
        }
    }
    // END foreach $applicableRestrictionTypes
    // don't cascade the owner restriction, because a subpage may not have the same owner
    // so casacing won't make sens, and can be very problematic
    // don't change this unless you know serioulsy what you are doing !!!
    // display the header.
    // display error/succes message
    if (poUpdateRestrictions($article, $new_restrictions)) {
        $wgOut->addHTML(Html::rawElement('div', array('class' => 'informations success'), wfMessage('po-success')->text()));
    } else {
        $wgOut->addHTML(Html::rawElement('div', array('class' => 'informations error'), wfMessage('po-failure')->text()));
    }
    if (!$readonly) {
        $wgOut->addHTML(Html::rawElement('div', array('class' => 'form_header informations'), wfMessage('po-header', $title->getPrefixedText(), WpWikiplace::extractWikiplaceRoot($title->getDBkey(), $title->getNamespace()))->parse()));
    } else {
        $wgOut->addHTML(Html::rawElement('div', array('class' => 'form_header informations'), wfMsg('po-locked')));
    }
    // re-display the ProtectOwn form with the current restrictions (reloaded above)
    $wgOut->addHTML(poMakeForm($article->getTitle()));
    // stop hook processing, and doesn't throw an error message
    return false;
}
Пример #13
0
 /**
  * Check the user has an active subscription and 
  * wikiplace creation quota is not exceeded and 
  * page creation quota is not exceeded
  * @param type $user_id
  * @return boolean/string True if user can, string message explaining why she can't:
  * <ul>
  * <li><b>wp-no-active-sub</b> user has no active subscription</li>
  * <li><b>wp-wikiplace-quota-exceeded</b> wikiplace creation quota exceeded</li>
  * <li><b>wp-page-quota-exceeded</b> page creation quota exceeded</li>
  * </ul>
  */
 public static function userCanCreateWikiplace($user_id)
 {
     if (!is_int($user_id) || $user_id < 1) {
         throw new MWException('Cannot check if user can create a Wikiplace, invalid user identifier.');
     }
     $sub = self::newActiveByUserId($user_id);
     if ($sub == null) {
         return 'wp-no-active-sub';
     }
     $plan = $sub->getPlan();
     $max_wikiplaces = $plan->getNbWikiplaces();
     $user_wikiplaces_nb = WpWikiplace::countWikiplacesOwnedByUser($user_id);
     if ($user_wikiplaces_nb >= $max_wikiplaces) {
         return 'wp-wikiplace-quota-exceeded';
     }
     $max_pages = $plan->getNbWikiplacePages();
     $user_pages_nb = WpPage::countPagesOwnedByUser($user_id);
     if ($user_pages_nb >= $max_pages) {
         return 'wp-page-quota-exceeded';
     }
     return true;
     // all ok
 }
Пример #14
0
 /**
  *
  * @param int $namespace
  * @param string $db_key
  * @return boolean 
  */
 public static function isAdmin($namespace, $db_key)
 {
     if (!($namespace == NS_FILE) && !($namespace == NS_FILE_TALK)) {
         return false;
     }
     $exploded = WpWikiplace::explodeWikipageKey($db_key, $namespace);
     return $exploded[0] == WP_ADMIN_FILE_PREFIX;
 }