Ejemplo n.º 1
0
 /**
  * Returns true if uploads are enabled.
  * Can be override by subclasses.
  * @return bool
  */
 public static function isEnabled()
 {
     global $wgEnableUploads;
     if (!$wgEnableUploads) {
         return false;
     }
     # Check php's file_uploads setting
     return wfIsHHVM() || wfIniGetBool('file_uploads');
 }
 public static function provideGeneralEncoding()
 {
     // Sigh. Docs claim it's a boolean, but can have values 0, 1, or 2.
     // Fortunately wfIniGetBool does the right thing.
     if (wfIniGetBool('xdebug.overload_var_dump')) {
         return array(array(array(), 'Cannot test ApiFormatDump when xDebug overloads var_dump', array('SKIP' => true)));
     }
     $warning = "\n  [\"warnings\"]=>\n  array(1) {\n    [\"dump\"]=>\n    array(1) {\n      [\"*\"]=>\n" . "      string(64) \"format=dump has been deprecated. Please use format=json instead.\"\n" . "    }\n  }";
     return array(array(array(null), "array(2) {{$warning}\n  [0]=>\n  NULL\n}\n"), array(array(true), "array(2) {{$warning}\n  [0]=>\n  string(0) \"\"\n}\n"), array(array(false), "array(1) {{$warning}\n}\n"), array(array(true, ApiResult::META_BC_BOOLS => array(0)), "array(2) {{$warning}\n  [0]=>\n  bool(true)\n}\n"), array(array(false, ApiResult::META_BC_BOOLS => array(0)), "array(2) {{$warning}\n  [0]=>\n  bool(false)\n}\n"), array(array(42), "array(2) {{$warning}\n  [0]=>\n  int(42)\n}\n"), array(array(42.5), "array(2) {{$warning}\n  [0]=>\n  float(42.5)\n}\n"), array(array(1.0E+42), "array(2) {{$warning}\n  [0]=>\n  float(1.0E+42)\n}\n"), array(array('foo'), "array(2) {{$warning}\n  [0]=>\n  string(3) \"foo\"\n}\n"), array(array('fóo'), "array(2) {{$warning}\n  [0]=>\n  string(4) \"fóo\"\n}\n"), array(array(array()), "array(2) {{$warning}\n  [0]=>\n  array(0) {\n  }\n}\n"), array(array(array(1)), "array(2) {{$warning}\n  [0]=>\n  array(1) {\n    [0]=>\n    int(1)\n  }\n}\n"), array(array(array('x' => 1)), "array(2) {{$warning}\n  [0]=>\n  array(1) {\n    [\"x\"]=>\n    int(1)\n  }\n}\n"), array(array(array(2 => 1)), "array(2) {{$warning}\n  [0]=>\n  array(1) {\n    [2]=>\n    int(1)\n  }\n}\n"), array(array((object) array()), "array(2) {{$warning}\n  [0]=>\n  array(0) {\n  }\n}\n"), array(array(array(1, ApiResult::META_TYPE => 'assoc')), "array(2) {{$warning}\n  [0]=>\n  array(1) {\n    [0]=>\n    int(1)\n  }\n}\n"), array(array(array('x' => 1, ApiResult::META_TYPE => 'array')), "array(2) {{$warning}\n  [0]=>\n  array(1) {\n    [0]=>\n    int(1)\n  }\n}\n"), array(array(array('x' => 1, ApiResult::META_TYPE => 'kvp')), "array(2) {{$warning}\n  [0]=>\n  array(1) {\n    [\"x\"]=>\n    int(1)\n  }\n}\n"), array(array(array('x' => 1, ApiResult::META_TYPE => 'BCkvp', ApiResult::META_KVP_KEY_NAME => 'key')), "array(2) {{$warning}\n  [0]=>\n  array(1) {\n    [0]=>\n    array(2) {\n      [\"key\"]=>\n      string(1) \"x\"\n      [\"*\"]=>\n      int(1)\n    }\n  }\n}\n"), array(array(array('x' => 1, ApiResult::META_TYPE => 'BCarray')), "array(2) {{$warning}\n  [0]=>\n  array(1) {\n    [\"x\"]=>\n    int(1)\n  }\n}\n"), array(array(array('a', 'b', ApiResult::META_TYPE => 'BCassoc')), "array(2) {{$warning}\n  [0]=>\n  array(2) {\n    [0]=>\n    string(1) \"a\"\n    [1]=>\n    string(1) \"b\"\n  }\n}\n"), array(array('content' => 'foo', ApiResult::META_CONTENT => 'content'), "array(2) {{$warning}\n  [\"*\"]=>\n  string(3) \"foo\"\n}\n"), array(array('foo' => 'foo', ApiResult::META_BC_SUBELEMENTS => array('foo')), "array(2) {{$warning}\n  [\"foo\"]=>\n  array(1) {\n    [\"*\"]=>\n    string(3) \"foo\"\n  }\n}\n"));
 }
Ejemplo n.º 3
0
 /**
  * Returns true if uploads are enabled.
  * Can be override by subclasses.
  */
 public static function isEnabled()
 {
     global $wgEnableUploads;
     if (!$wgEnableUploads) {
         return false;
     }
     # Check php's file_uploads setting
     if (!wfIniGetBool('file_uploads')) {
         return false;
     }
     return true;
 }
Ejemplo n.º 4
0
 public static function factory($url, $options = null)
 {
     if (!Http::$httpEngine) {
         Http::$httpEngine = function_exists('curl_init') ? 'curl' : 'php';
     } elseif (Http::$httpEngine == 'curl' && !function_exists('curl_init')) {
         throw new MWException(__METHOD__ . ': curl (http://php.net/curl) is not installed, but' . 'Http::$httpEngine is set to "curl"');
     }
     switch (Http::$httpEngine) {
         case 'curl':
             return new CurlHttpRequestTester($url, $options);
         case 'php':
             if (!wfIniGetBool('allow_url_fopen')) {
                 throw new MWException(__METHOD__ . ': allow_url_fopen needs to be enabled for pure PHP' . ' http requests to work. If possible, curl should be used instead. See http://php.net/curl.');
             }
             return new PhpHttpRequestTester($url, $options);
         default:
     }
 }
Ejemplo n.º 5
0
 function setup()
 {
     putenv("http_proxy");
     /* Remove any proxy env var, so curl doesn't get confused */
     if (is_array(self::$content)) {
         return;
     }
     self::$has_curl = function_exists('curl_init');
     self::$has_fopen = wfIniGetBool('allow_url_fopen');
     if (!file_exists("/usr/bin/curl")) {
         $this->markTestIncomplete("This test requires the curl binary at /usr/bin/curl.\t If you have curl, please file a bug on this test, or, better yet, provide a patch.");
     }
     $content = tempnam(wfTempDir(), "");
     $headers = tempnam(wfTempDir(), "");
     if (!$content && !$headers) {
         die("Couldn't create temp file!");
     }
     // This probably isn't the best test for a proxy, but it works on my system!
     system("curl -0 -o {$content} -s " . self::$proxy);
     $out = file_get_contents($content);
     if ($out) {
         self::$has_proxy = true;
     }
     /* Maybe use wget instead of curl here ... just to use a different codebase? */
     foreach ($this->test_geturl as $u) {
         system("curl -0 -s -D {$headers} '{$u}' -o {$content}");
         self::$content["GET {$u}"] = file_get_contents($content);
         self::$headers["GET {$u}"] = file_get_contents($headers);
     }
     foreach ($this->test_requesturl as $u) {
         system("curl -0 -s -X POST -H 'Content-Length: 0' -D {$headers} '{$u}' -o {$content}");
         self::$content["POST {$u}"] = file_get_contents($content);
         self::$headers["POST {$u}"] = file_get_contents($headers);
     }
     foreach ($this->test_posturl as $u => $postData) {
         system("curl -0 -s -X POST -d '{$postData}' -D {$headers} '{$u}' -o {$content}");
         self::$content["POST {$u} => {$postData}"] = file_get_contents($content);
         self::$headers["POST {$u} => {$postData}"] = file_get_contents($headers);
     }
     unlink($content);
     unlink($headers);
 }
Ejemplo n.º 6
0
 public function testInstall()
 {
     $reset = $this->getResetter($rProp);
     $rProp->setValue(null);
     session_write_close();
     ini_set('session.use_cookies', 1);
     ini_set('session.use_trans_sid', 1);
     $store = new \HashBagOStuff();
     $logger = new \TestLogger();
     $manager = new SessionManager(array('store' => $store, 'logger' => $logger));
     $this->assertFalse(PHPSessionHandler::isInstalled());
     PHPSessionHandler::install($manager);
     $this->assertTrue(PHPSessionHandler::isInstalled());
     $this->assertFalse(wfIniGetBool('session.use_cookies'));
     $this->assertFalse(wfIniGetBool('session.use_trans_sid'));
     $this->assertNotNull($rProp->getValue());
     $priv = \TestingAccessWrapper::newFromObject($rProp->getValue());
     $this->assertSame($manager, $priv->manager);
     $this->assertSame($store, $priv->store);
     $this->assertSame($logger, $priv->logger);
 }
Ejemplo n.º 7
0
 /**
  * Helper function fo UserMailer::send() which does the actual sending. It expects a $to
  * list which the UserMailerSplitTo hook would not split further.
  * @param MailAddress[] $to Array of recipients' email addresses
  * @param MailAddress $from Sender's email
  * @param string $subject Email's subject.
  * @param string $body Email's text or Array of two strings to be the text and html bodies
  * @param array $options:
  * 		'replyTo' MailAddress
  * 		'contentType' string default 'text/plain; charset=UTF-8'
  * 		'headers' array Extra headers to set
  *
  * @throws MWException
  * @throws Exception
  * @return Status
  */
 protected static function sendInternal(array $to, MailAddress $from, $subject, $body, $options = array())
 {
     global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams;
     $mime = null;
     $replyto = isset($options['replyTo']) ? $options['replyTo'] : null;
     $contentType = isset($options['contentType']) ? $options['contentType'] : 'text/plain; charset=UTF-8';
     $headers = isset($options['headers']) ? $options['headers'] : array();
     // Allow transformation of content, such as encrypting/signing
     $error = false;
     if (!Hooks::run('UserMailerTransformContent', array($to, $from, &$body, &$error))) {
         if ($error) {
             return Status::newFatal('php-mail-error', $error);
         } else {
             return Status::newFatal('php-mail-error-unknown');
         }
     }
     /**
      * Forge email headers
      * -------------------
      *
      * WARNING
      *
      * DO NOT add To: or Subject: headers at this step. They need to be
      * handled differently depending upon the mailer we are going to use.
      *
      * To:
      *  PHP mail() first argument is the mail receiver. The argument is
      *  used as a recipient destination and as a To header.
      *
      *  PEAR mailer has a recipient argument which is only used to
      *  send the mail. If no To header is given, PEAR will set it to
      *  to 'undisclosed-recipients:'.
      *
      *  NOTE: To: is for presentation, the actual recipient is specified
      *  by the mailer using the Rcpt-To: header.
      *
      * Subject:
      *  PHP mail() second argument to pass the subject, passing a Subject
      *  as an additional header will result in a duplicate header.
      *
      *  PEAR mailer should be passed a Subject header.
      *
      * -- hashar 20120218
      */
     $headers['From'] = $from->toString();
     $returnPath = $from->address;
     $extraParams = $wgAdditionalMailParams;
     // Hook to generate custom VERP address for 'Return-Path'
     Hooks::run('UserMailerChangeReturnPath', array($to, &$returnPath));
     // Add the envelope sender address using the -f command line option when PHP mail() is used.
     // Will default to the $from->address when the UserMailerChangeReturnPath hook fails and the
     // generated VERP address when the hook runs effectively.
     $extraParams .= ' -f ' . $returnPath;
     $headers['Return-Path'] = $returnPath;
     if ($replyto) {
         $headers['Reply-To'] = $replyto->toString();
     }
     $headers['Date'] = MWTimestamp::getLocalInstance()->format('r');
     $headers['Message-ID'] = self::makeMsgId();
     $headers['X-Mailer'] = 'MediaWiki mailer';
     $headers['List-Unsubscribe'] = '<' . SpecialPage::getTitleFor('Preferences')->getFullURL('', false, PROTO_CANONICAL) . '>';
     // Line endings need to be different on Unix and Windows due to
     // the bug described at http://trac.wordpress.org/ticket/2603
     if (wfIsWindows()) {
         $endl = "\r\n";
     } else {
         $endl = "\n";
     }
     if (is_array($body)) {
         // we are sending a multipart message
         wfDebug("Assembling multipart mime email\n");
         if (!stream_resolve_include_path('Mail/mime.php')) {
             wfDebug("PEAR Mail_Mime package is not installed. Falling back to text email.\n");
             // remove the html body for text email fall back
             $body = $body['text'];
         } else {
             // Check if pear/mail_mime is already loaded (via composer)
             if (!class_exists('Mail_mime')) {
                 require_once 'Mail/mime.php';
             }
             if (wfIsWindows()) {
                 $body['text'] = str_replace("\n", "\r\n", $body['text']);
                 $body['html'] = str_replace("\n", "\r\n", $body['html']);
             }
             $mime = new Mail_mime(array('eol' => $endl, 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8'));
             $mime->setTXTBody($body['text']);
             $mime->setHTMLBody($body['html']);
             $body = $mime->get();
             // must call get() before headers()
             $headers = $mime->headers($headers);
         }
     }
     if ($mime === null) {
         // sending text only, either deliberately or as a fallback
         if (wfIsWindows()) {
             $body = str_replace("\n", "\r\n", $body);
         }
         $headers['MIME-Version'] = '1.0';
         $headers['Content-type'] = is_null($contentType) ? 'text/plain; charset=UTF-8' : $contentType;
         $headers['Content-transfer-encoding'] = '8bit';
     }
     // allow transformation of MIME-encoded message
     if (!Hooks::run('UserMailerTransformMessage', array($to, $from, &$subject, &$headers, &$body, &$error))) {
         if ($error) {
             return Status::newFatal('php-mail-error', $error);
         } else {
             return Status::newFatal('php-mail-error-unknown');
         }
     }
     $ret = Hooks::run('AlternateUserMailer', array($headers, $to, $from, $subject, $body));
     if ($ret === false) {
         // the hook implementation will return false to skip regular mail sending
         return Status::newGood();
     } elseif ($ret !== true) {
         // the hook implementation will return a string to pass an error message
         return Status::newFatal('php-mail-error', $ret);
     }
     if (is_array($wgSMTP)) {
         // Check if pear/mail is already loaded (via composer)
         if (!class_exists('Mail')) {
             // PEAR MAILER
             if (!stream_resolve_include_path('Mail.php')) {
                 throw new MWException('PEAR mail package is not installed');
             }
             require_once 'Mail.php';
         }
         MediaWiki\suppressWarnings();
         // Create the mail object using the Mail::factory method
         $mail_object =& Mail::factory('smtp', $wgSMTP);
         if (PEAR::isError($mail_object)) {
             wfDebug("PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n");
             MediaWiki\restoreWarnings();
             return Status::newFatal('pear-mail-error', $mail_object->getMessage());
         }
         wfDebug("Sending mail via PEAR::Mail\n");
         $headers['Subject'] = self::quotedPrintable($subject);
         // When sending only to one recipient, shows it its email using To:
         if (count($to) == 1) {
             $headers['To'] = $to[0]->toString();
         }
         // Split jobs since SMTP servers tends to limit the maximum
         // number of possible recipients.
         $chunks = array_chunk($to, $wgEnotifMaxRecips);
         foreach ($chunks as $chunk) {
             $status = self::sendWithPear($mail_object, $chunk, $headers, $body);
             // FIXME : some chunks might be sent while others are not!
             if (!$status->isOK()) {
                 MediaWiki\restoreWarnings();
                 return $status;
             }
         }
         MediaWiki\restoreWarnings();
         return Status::newGood();
     } else {
         // PHP mail()
         if (count($to) > 1) {
             $headers['To'] = 'undisclosed-recipients:;';
         }
         $headers = self::arrayToHeaderString($headers, $endl);
         wfDebug("Sending mail via internal mail() function\n");
         self::$mErrorString = '';
         $html_errors = ini_get('html_errors');
         ini_set('html_errors', '0');
         set_error_handler('UserMailer::errorHandler');
         try {
             $safeMode = wfIniGetBool('safe_mode');
             foreach ($to as $recip) {
                 if ($safeMode) {
                     $sent = mail($recip, self::quotedPrintable($subject), $body, $headers);
                 } else {
                     $sent = mail($recip, self::quotedPrintable($subject), $body, $headers, $extraParams);
                 }
             }
         } catch (Exception $e) {
             restore_error_handler();
             throw $e;
         }
         restore_error_handler();
         ini_set('html_errors', $html_errors);
         if (self::$mErrorString) {
             wfDebug("Error sending mail: " . self::$mErrorString . "\n");
             return Status::newFatal('php-mail-error', self::$mErrorString);
         } elseif (!$sent) {
             // mail function only tells if there's an error
             wfDebug("Unknown error sending mail\n");
             return Status::newFatal('php-mail-error-unknown');
         } else {
             return Status::newGood();
         }
     }
 }
Ejemplo n.º 8
0
 /**
  * Start the PHP session. This may be called before execute() to start the PHP session.
  *
  * @return bool
  */
 public function startSession()
 {
     if (wfIniGetBool('session.auto_start') || session_id()) {
         // Done already
         return true;
     }
     $this->phpErrors = array();
     set_error_handler(array($this, 'errorHandler'));
     session_start();
     restore_error_handler();
     if ($this->phpErrors) {
         $this->showError('config-session-error', $this->phpErrors[0]);
         return false;
     }
     return true;
 }
Ejemplo n.º 9
0
 /**
  * Environment check for safe_mode.
  */
 protected function envCheckSafeMode()
 {
     if (wfIniGetBool('safe_mode')) {
         $this->setVar('_SafeMode', true);
         $this->showMessage('config-safe-mode');
     }
 }
Ejemplo n.º 10
0
 /**
  * Start doing stuff
  * @access public
  */
 function execute()
 {
     global $wgUser, $wgOut;
     global $wgEnableUploads;
     # Check php's file_uploads setting
     if (!wfIniGetBool('file_uploads')) {
         $wgOut->showErrorPage('uploaddisabled', 'php-uploaddisabledtext', array($this->mDesiredDestName));
         return;
     }
     # Check uploading enabled
     if (!$wgEnableUploads) {
         $wgOut->showErrorPage('uploaddisabled', 'uploaddisabledtext', array($this->mDesiredDestName));
         return;
     }
     # Check permissions
     if (!$wgUser->isAllowed('upload')) {
         if (!$wgUser->isLoggedIn()) {
             $wgOut->showErrorPage('uploadnologin', 'uploadnologintext');
         } else {
             $wgOut->permissionRequired('upload');
         }
         return;
     }
     # Check blocks
     if ($wgUser->isBlocked()) {
         $wgOut->blockedPage();
         return;
     }
     if (wfReadOnly()) {
         $wgOut->readOnlyPage();
         return;
     }
     if ($this->mReUpload) {
         if (!$this->unsaveUploadedFile()) {
             return;
         }
         # Because it is probably checked and shouldn't be
         $this->mIgnoreWarning = false;
         $this->mainUploadForm();
     } else {
         if ('submit' == $this->mAction || $this->mUploadClicked) {
             $this->processUpload();
         } else {
             $this->mainUploadForm();
         }
     }
     $this->cleanupTempFile();
 }
Ejemplo n.º 11
0
function getShellLocale($wikiLang)
{
    # Give up now if we're in safe mode or open_basedir
    # It's theoretically possible but tricky to work with
    if (wfIniGetBool("safe_mode") || ini_get('open_basedir') || !function_exists('exec')) {
        return false;
    }
    $os = php_uname('s');
    $supported = array('Linux', 'SunOS', 'HP-UX');
    # Tested these
    if (!in_array($os, $supported)) {
        return false;
    }
    # Get a list of available locales
    $lines = $ret = false;
    $lines = wfShellExec('/usr/bin/locale -a', $ret, true);
    if ($ret) {
        return false;
    }
    $lines = wfArrayMap('trim', explode("\n", $lines));
    $candidatesByLocale = array();
    $candidatesByLang = array();
    foreach ($lines as $line) {
        if ($line === '') {
            continue;
        }
        if (!preg_match('/^([a-zA-Z]+)(_[a-zA-Z]+|)\\.(utf8|UTF-8)(@[a-zA-Z_]*|)$/i', $line, $m)) {
            continue;
        }
        list($all, $lang, $territory, $charset, $modifier) = $m;
        $candidatesByLocale[$m[0]] = $m;
        $candidatesByLang[$lang][] = $m;
    }
    # Try the current value of LANG
    if (isset($candidatesByLocale[getenv('LANG')])) {
        return getenv('LANG');
    }
    # Try the most common ones
    $commonLocales = array('en_US.UTF-8', 'en_US.utf8', 'de_DE.UTF-8', 'de_DE.utf8');
    foreach ($commonLocales as $commonLocale) {
        if (isset($candidatesByLocale[$commonLocale])) {
            return $commonLocale;
        }
    }
    # Is there an available locale in the Wiki's language?
    if (isset($candidatesByLang[$wikiLang])) {
        $m = reset($candidatesByLang[$wikiLang]);
        return $m[0];
    }
    # Are there any at all?
    if (count($candidatesByLocale)) {
        $m = reset($candidatesByLocale);
        return $m[0];
    }
    # Give up
    return false;
}
Ejemplo n.º 12
0
    $wgAuth = new MediaWiki\Auth\AuthManagerAuthPlugin();
    Hooks::run('AuthPluginSetup', [&$wgAuth]);
}
if ($wgAuth && !$wgAuth instanceof MediaWiki\Auth\AuthManagerAuthPlugin) {
    MediaWiki\Auth\AuthManager::singleton()->forcePrimaryAuthenticationProviders([new MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider(['authoritative' => false]), new MediaWiki\Auth\AuthPluginPrimaryAuthenticationProvider($wgAuth), new MediaWiki\Auth\LocalPasswordPrimaryAuthenticationProvider(['authoritative' => true])], '$wgAuth is ' . get_class($wgAuth));
}
// Set up the session
$ps_session = Profiler::instance()->scopedProfileIn($fname . '-session');
/**
 * @var MediaWiki\Session\SessionId|null $wgInitialSessionId The persistent
 * session ID (if any) loaded at startup
 */
$wgInitialSessionId = null;
if (!defined('MW_NO_SESSION') && !$wgCommandLineMode) {
    // If session.auto_start is there, we can't touch session name
    if ($wgPHPSessionHandling !== 'disable' && !wfIniGetBool('session.auto_start')) {
        session_name($wgSessionName ? $wgSessionName : $wgCookiePrefix . '_session');
    }
    // Create the SessionManager singleton and set up our session handler,
    // unless we're specifically asked not to.
    if (!defined('MW_NO_SESSION_HANDLER')) {
        MediaWiki\Session\PHPSessionHandler::install(MediaWiki\Session\SessionManager::singleton());
    }
    // Initialize the session
    try {
        $session = MediaWiki\Session\SessionManager::getGlobalSession();
    } catch (OverflowException $ex) {
        if (isset($ex->sessionInfos) && count($ex->sessionInfos) >= 2) {
            // The exception is because the request had multiple possible
            // sessions tied for top priority. Report this to the user.
            $list = [];
Ejemplo n.º 13
0
 /**
  * Factory function referenced from DefaultSettings.php for CACHE_ACCEL.
  *
  * @param $params array
  * @throws MWException
  * @return ObjectCache
  */
 static function newAccelerator($params)
 {
     if (function_exists('apc_fetch')) {
         $id = 'apc';
     } elseif (function_exists('xcache_get') && wfIniGetBool('xcache.var_size')) {
         $id = 'xcache';
     } elseif (function_exists('wincache_ucache_get')) {
         $id = 'wincache';
     } else {
         throw new MWException("CACHE_ACCEL requested but no suitable object " . "cache is present. You may want to install APC.");
     }
     return self::newFromId($id);
 }
Ejemplo n.º 14
0
    }
    wfDebug($debug);
}
Profiler::instance()->scopedProfileOut($ps_misc);
$ps_memcached = Profiler::instance()->scopedProfileIn($fname . '-memcached');
$wgMemc = wfGetMainCache();
$messageMemc = wfGetMessageCacheStorage();
$parserMemc = wfGetParserCacheStorage();
wfDebugLog('caches', 'main: ' . get_class($wgMemc) . ', message: ' . get_class($messageMemc) . ', parser: ' . get_class($parserMemc));
Profiler::instance()->scopedProfileOut($ps_memcached);
// Most of the config is out, some might want to run hooks here.
Hooks::run('SetupAfterCache');
$ps_session = Profiler::instance()->scopedProfileIn($fname . '-session');
if (!defined('MW_NO_SESSION') && !$wgCommandLineMode) {
    // If session.auto_start is there, we can't touch session name
    if (!wfIniGetBool('session.auto_start')) {
        session_name($wgSessionName ? $wgSessionName : $wgCookiePrefix . '_session');
    }
    if ($wgRequest->checkSessionCookie() || isset($_COOKIE[$wgCookiePrefix . 'Token'])) {
        wfSetupSession();
    }
}
Profiler::instance()->scopedProfileOut($ps_session);
$ps_globals = Profiler::instance()->scopedProfileIn($fname . '-globals');
/**
 * @var Language $wgContLang
 */
$wgContLang = Language::factory($wgLanguageCode);
$wgContLang->initEncoding();
$wgContLang->initContLang();
// Now that variant lists may be available...
Ejemplo n.º 15
0
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 */
if (!defined('MEDIAWIKI')) {
    exit(1);
}
# make sure that everything that needs to be set/loaded is that way
$err = '';
if (!wfIniGetBool('allow_url_fopen') && !extension_loaded('curl')) {
    # we need allow_url_fopen or curl to be on in order for the Http::get() call to work on the amazon url
    $err .= "\n<li>allow_url_fopen or curl must be enabled in php.ini</li>";
}
if (!extension_loaded('simplexml')) {
    # we need the simplexml extension loaded to parse the xml string
    $err .= "\n<li>The SimpleXML extension for PHP must be loaded</li>";
}
# if there were errors found, die with the messages
if ($err) {
    $html = '<html><head><title>Error</title></head><body>
	The following errors were discovered with the AmazonPlus extension for MediaWiki:
	<ul>' . $err . '</ul></body></html>';
    echo $html;
    die(1);
}
Ejemplo n.º 16
0
function writeSuccessMessage()
{
    $script = defined('MW_INSTALL_PHP5_EXT') ? 'index.php5' : 'index.php';
    if (wfIniGetBool('safe_mode') && !ini_get('open_basedir')) {
        echo <<<EOT
<div class="success-box">
<p>Installation successful!</p>
<p>To complete the installation, please do the following:
<ol>
\t<li>Download config/LocalSettings.php with your FTP client or file manager</li>
\t<li>Upload it to the parent directory</li>
\t<li>Delete config/LocalSettings.php</li>
\t<li>Start using <a href='../{$script}'>your wiki</a>!
</ol>
<p>If you are in a shared hosting environment, do <strong>not</strong> just move LocalSettings.php
remotely. LocalSettings.php is currently owned by the user your webserver is running under,
which means that anyone on the same server can read your database password! Downloading
it and uploading it again will hopefully change the ownership to a user ID specific to you.</p>
</div>
EOT;
    } else {
        echo <<<EOT
<div class="success-box">
<p>
<span class="success-message">Installation successful!</span>
Move the <tt>config/LocalSettings.php</tt> file to the parent directory, then follow
<a href="../{$script}"> this link</a> to your wiki.</p>
<p>You should change file permissions for <tt>LocalSettings.php</tt> as required to
prevent other users on the server reading passwords and altering configuration data.</p>
</div>
EOT;
    }
}
Ejemplo n.º 17
0
 /**
  * Environment check for compiled object cache types.
  */
 protected function envCheckCache()
 {
     $caches = array();
     foreach ($this->objectCaches as $name => $function) {
         if (function_exists($function)) {
             if ($name == 'xcache' && !wfIniGetBool('xcache.var_size')) {
                 continue;
             }
             $caches[$name] = true;
         }
     }
     if (!$caches) {
         $key = 'config-no-cache';
         // PHP >=5.5 is called APCu, earlier versions use APC (T61998).
         if (!wfIsHHVM() && version_compare(PHP_VERSION, '5.5', '>=')) {
             // config-no-cache-apcu
             $key .= '-apcu';
         }
         $this->showMessage($key);
     }
     $this->setVar('_Caches', $caches);
 }
Ejemplo n.º 18
0
 /**
  * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
  *
  * This will look for any APC style server-local cache.
  * A fallback cache can be specified if none is found.
  *
  *     // Direct calls
  *     ObjectCache::getLocalServerInstance( $fallbackType );
  *
  *     // From $wgObjectCaches via newFromParams()
  *     ObjectCache::getLocalServerInstance( array( 'fallback' => $fallbackType ) );
  *
  * @param int|string|array $fallback Fallback cache or parameter map with 'fallback'
  * @return BagOStuff
  * @throws MWException
  * @since 1.27
  */
 public static function getLocalServerInstance($fallback = CACHE_NONE)
 {
     if (function_exists('apc_fetch')) {
         $id = 'apc';
     } elseif (function_exists('xcache_get') && wfIniGetBool('xcache.var_size')) {
         $id = 'xcache';
     } elseif (function_exists('wincache_ucache_get')) {
         $id = 'wincache';
     } else {
         if (is_array($fallback)) {
             $id = isset($fallback['fallback']) ? $fallback['fallback'] : CACHE_NONE;
         } else {
             $id = $fallback;
         }
     }
     return self::getInstance($id);
 }
Ejemplo n.º 19
0
 /**
  * Generate a new request object
  * @param string $url Url to use
  * @param array $options (optional) extra params to pass (see Http::request())
  * @param string $caller The method making this request, for profiling
  * @throws MWException
  * @return CurlHttpRequest|PhpHttpRequest
  * @see MWHttpRequest::__construct
  */
 public static function factory($url, $options = null, $caller = __METHOD__)
 {
     if (!Http::$httpEngine) {
         Http::$httpEngine = function_exists('curl_init') ? 'curl' : 'php';
     } elseif (Http::$httpEngine == 'curl' && !function_exists('curl_init')) {
         throw new MWException(__METHOD__ . ': curl (http://php.net/curl) is not installed, but' . ' Http::$httpEngine is set to "curl"');
     }
     if (!is_array($options)) {
         $options = [];
     }
     if (!isset($options['logger'])) {
         $options['logger'] = LoggerFactory::getInstance('http');
     }
     switch (Http::$httpEngine) {
         case 'curl':
             return new CurlHttpRequest($url, $options, $caller, Profiler::instance());
         case 'php':
             if (!wfIniGetBool('allow_url_fopen')) {
                 throw new MWException(__METHOD__ . ': allow_url_fopen ' . 'needs to be enabled for pure PHP http requests to ' . 'work. If possible, curl should be used instead. See ' . 'http://php.net/curl.');
             }
             return new PhpHttpRequest($url, $options, $caller, Profiler::instance());
         default:
             throw new MWException(__METHOD__ . ': The setting of Http::$httpEngine is not valid.');
     }
 }
Ejemplo n.º 20
0
 /**
  * This function will perform a direct (authenticated) login to
  * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
  * array of parameters. It requires PEAR:Mail to do that.
  * Otherwise it just uses the standard PHP 'mail' function.
  *
  * @param MailAddress $to : recipient's email (or an array of them)
  * @param MailAddress $from : sender's email
  * @param String $subject : email's subject.
  * @param String $body : email's text.
  * $body can be array with text and html version of email message, and also can contain attachements
  * $body = array('text' => 'Email text', 'html' => '<b>Email text</b>')
  * @param MailAddress $replyTo : optional reply-to email (default: null).
  * @param String $contentType : optional custom Content-Type
  * @param String $category : optional category for statistic
  * @param int $priority : optional priority for email
  * @param Array $attachments : optional list of files to send as attachments
  *
  * @return Status object
  * @throws MWException
  */
 public static function send(MailAddress $to, MailAddress $from, $subject, $body, MailAddress $replyTo = null, $contentType = null, $category = 'UserMailer', $priority = 0, $attachments = [])
 {
     if (!is_array($to)) {
         $to = [$to];
     }
     # Make sure we have at least one address
     $has_address = false;
     foreach ($to as $u) {
         if ($u->address) {
             $has_address = true;
             break;
         }
     }
     if (!$has_address) {
         return Status::newFatal('user-mail-no-addy');
     }
     wfRunHooks('UserMailerSend', [&$to]);
     # Forge email headers
     # -------------------
     #
     # WARNING
     #
     # DO NOT add To: or Subject: headers at this step. They need to be
     # handled differently depending upon the mailer we are going to use.
     #
     # To:
     #  PHP mail() first argument is the mail receiver. The argument is
     #  used as a recipient destination and as a To header.
     #
     #  PEAR mailer has a recipient argument which is only used to
     #  send the mail. If no To header is given, PEAR will set it to
     #  to 'undisclosed-recipients:'.
     #
     #  NOTE: To: is for presentation, the actual recipient is specified
     #  by the mailer using the Rcpt-To: header.
     #
     # Subject:
     #  PHP mail() second argument to pass the subject, passing a Subject
     #  as an additional header will result in a duplicate header.
     #
     #  PEAR mailer should be passed a Subject header.
     #
     # -- hashar 20120218
     $headers['From'] = $from->toString();
     $headers['Return-Path'] = $from->address;
     if ($replyTo && $replyTo instanceof MailAddress) {
         $headers['Reply-To'] = $replyTo->toString();
     }
     $headers['Date'] = date('r');
     $headers['MIME-Version'] = '1.0';
     if (empty($attachments)) {
         $headers['Content-Type'] = is_null($contentType) ? 'text/plain; charset=UTF-8' : $contentType;
         $headers['Content-Transfer-Encoding'] = '8bit';
     }
     $headers['Message-ID'] = self::makeMsgId();
     $headers['X-Mailer'] = 'MediaWiki mailer';
     $headers['X-Msg-Category'] = $category;
     if ($priority) {
         $headers['X-Priority'] = $priority;
     }
     $ret = wfRunHooks('AlternateUserMailer', [$headers, $to, $from, $subject, $body, $priority, $attachments]);
     if ($ret === false) {
         return Status::newGood();
     } elseif ($ret !== true) {
         return Status::newFatal('php-mail-error', $ret);
     }
     # MoLi: body can be an array with text and html message
     # MW core uses only text version of email message, so $body as array should be used only with AlternateUserMailer hook
     if (is_array($body) && isset($body['text'])) {
         $body = $body['text'];
     }
     if (is_array(F::app()->wg->SMTP)) {
         #
         # PEAR MAILER
         #
         if (function_exists('stream_resolve_include_path')) {
             $found = stream_resolve_include_path('Mail.php');
         } else {
             $found = Fallback::stream_resolve_include_path('Mail.php');
         }
         if (!$found) {
             throw new MWException('PEAR mail package is not installed');
         }
         require_once 'Mail.php';
         wfSuppressWarnings();
         // Create the mail object using the Mail::factory method
         $mail_object =& Mail::factory('smtp', F::app()->wg->SMTP);
         if (PEAR::isError($mail_object)) {
             wfDebug("PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n");
             wfRestoreWarnings();
             return Status::newFatal('pear-mail-error', $mail_object->getMessage());
         }
         wfDebug("Sending mail via PEAR::Mail\n");
         $headers['Subject'] = self::quotedPrintable($subject);
         # When sending only to one recipient, shows it its email using To:
         if (count($to) == 1) {
             $headers['To'] = $to[0]->toString();
         }
         # Split jobs since SMTP servers tends to limit the maximum
         # number of possible recipients.
         $chunks = array_chunk($to, F::app()->wg->EnotifMaxRecips);
         foreach ($chunks as $chunk) {
             if (!wfRunHooks('ComposeMail', [$chunk, &$body, &$headers])) {
                 continue;
             }
             $status = self::sendWithPear($mail_object, $chunk, $headers, $body);
             # FIXME : some chunks might be sent while others are not!
             if (!$status->isOK()) {
                 wfRestoreWarnings();
                 return $status;
             }
         }
         wfRestoreWarnings();
         return Status::newGood();
     } else {
         #
         # PHP mail()
         #
         # Line endings need to be different on Unix and Windows due to
         # the bug described at http://trac.wordpress.org/ticket/2603
         if (wfIsWindows()) {
             $body = str_replace("\n", "\r\n", $body);
             $endl = "\r\n";
         } else {
             $endl = "\n";
         }
         if (count($to) > 1) {
             $headers['To'] = 'undisclosed-recipients:;';
         }
         $headers = self::arrayToHeaderString($headers, $endl);
         wfDebug("Sending mail via internal mail() function\n");
         self::$mErrorString = '';
         $html_errors = ini_get('html_errors');
         ini_set('html_errors', '0');
         $safeMode = wfIniGetBool('safe_mode');
         foreach ($to as $recip) {
             if (!wfRunHooks('ComposeMail', array($recip, &$body, &$headers))) {
                 continue;
             }
             if ($safeMode) {
                 $sent = mail($recip, self::quotedPrintable($subject), $body, $headers);
             } else {
                 $sent = mail($recip, self::quotedPrintable($subject), $body, $headers, F::app()->wg->AdditionalMailParams);
             }
         }
         ini_set('html_errors', $html_errors);
         if (self::$mErrorString) {
             wfDebug("Error sending mail: " . self::$mErrorString . "\n");
             return Status::newFatal('php-mail-error', self::$mErrorString);
         } elseif (!$sent) {
             // mail function only tells if there's an error
             wfDebug("Unknown error sending mail\n");
             return Status::newFatal('php-mail-error-unknown');
         } else {
             return Status::newGood();
         }
     }
 }
Ejemplo n.º 21
0
	/**
	 * @return bool
	 */
	public function canFollowRedirects() {
		if ( strval( ini_get( 'open_basedir' ) ) !== '' || wfIniGetBool( 'safe_mode' ) ) {
			wfDebug( "Cannot follow redirects in safe mode\n" );
			return false;
		}

		if ( !defined( 'CURLOPT_REDIR_PROTOCOLS' ) ) {
			wfDebug( "Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n" );
			return false;
		}

		return true;
	}
Ejemplo n.º 22
0
 /**
  * @return bool
  */
 public function canFollowRedirects()
 {
     if (strval(ini_get('open_basedir')) !== '' || wfIniGetBool('safe_mode')) {
         wfDebug("Cannot follow redirects in safe mode\n");
         return false;
     }
     $curlVersionInfo = curl_version();
     if ($curlVersionInfo['version_number'] < 0x71304) {
         wfDebug("Cannot follow redirects with libcurl < 7.19.4 due to CVE-2009-0037\n");
         return false;
     }
     return true;
 }
Ejemplo n.º 23
0
 /**
  * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
  *
  * This will look for any APC style server-local cache.
  * A fallback cache can be specified if none is found.
  *
  * @param array $params [optional]
  * @param int|string $fallback Fallback cache, e.g. (CACHE_NONE, "hash") (since 1.24)
  * @return BagOStuff
  * @throws MWException
  */
 public static function newAccelerator($params = array(), $fallback = null)
 {
     if (!is_array($params) && $fallback === null) {
         $fallback = $params;
     }
     if (function_exists('apc_fetch')) {
         $id = 'apc';
     } elseif (function_exists('xcache_get') && wfIniGetBool('xcache.var_size')) {
         $id = 'xcache';
     } elseif (function_exists('wincache_ucache_get')) {
         $id = 'wincache';
     } else {
         if ($fallback === null) {
             throw new MWException('CACHE_ACCEL requested but no suitable object ' . 'cache is present. You may want to install APC.');
         }
         $id = $fallback;
     }
     return self::newFromId($id);
 }
 /**
  * @param Scribunto_LuaStandaloneEngine $engine
  * @param array $options
  * @throws MWException
  * @throws Scribunto_LuaInterpreterNotFoundError
  * @throws ScribuntoException
  */
 function __construct($engine, array $options)
 {
     $this->id = self::$nextInterpreterId++;
     if ($options['errorFile'] === null) {
         $options['errorFile'] = wfGetNull();
     }
     if ($options['luaPath'] === null) {
         $path = false;
         // Note, if you alter these, also alter getLuaVersion() below
         if (PHP_OS == 'Linux') {
             if (PHP_INT_SIZE == 4) {
                 $path = 'lua5_1_5_linux_32_generic/lua';
             } elseif (PHP_INT_SIZE == 8) {
                 $path = 'lua5_1_5_linux_64_generic/lua';
             }
         } elseif (PHP_OS == 'Windows' || PHP_OS == 'WINNT' || PHP_OS == 'Win32') {
             if (PHP_INT_SIZE == 4) {
                 $path = 'lua5_1_4_Win32_bin/lua5.1.exe';
             } elseif (PHP_INT_SIZE == 8) {
                 $path = 'lua5_1_4_Win64_bin/lua5.1.exe';
             }
         } elseif (PHP_OS == 'Darwin') {
             $path = 'lua5_1_5_mac_lion_fat_generic/lua';
         }
         if ($path === false) {
             throw new Scribunto_LuaInterpreterNotFoundError('No Lua interpreter was given in the configuration, ' . 'and no bundled binary exists for this platform.');
         }
         $options['luaPath'] = dirname(__FILE__) . "/binaries/{$path}";
         if (!is_executable($options['luaPath'])) {
             throw new MWException(sprintf('The lua binary (%s) is not executable.', $options['luaPath']));
         }
     }
     $this->engine = $engine;
     $this->enableDebug = !empty($options['debug']);
     $pipes = null;
     $cmd = wfEscapeShellArg($options['luaPath'], dirname(__FILE__) . '/mw_main.lua', dirname(dirname(dirname(__FILE__))), $this->id);
     if (php_uname('s') == 'Linux') {
         // Limit memory and CPU
         $cmd = wfEscapeShellArg('/bin/sh', dirname(__FILE__) . '/lua_ulimit.sh', $options['cpuLimit'], $options['cpuLimit'] + 1, intval($options['memoryLimit'] / 1024), $cmd);
     }
     if (php_uname('s') == 'Windows NT') {
         // Like the passthru() in older versions of PHP,
         // PHP's invokation of cmd.exe in proc_open() is broken:
         // http://news.php.net/php.internals/21796
         // Unlike passthru(), it is not fixed in any PHP version,
         // so we use the fix similar to one in wfShellExec()
         $cmd = '"' . $cmd . '"';
     }
     wfDebug(__METHOD__ . ": creating interpreter: {$cmd}\n");
     // Check whether proc_open is available before trying to call it (e.g.
     // PHP's disable_functions may have removed it)
     if (!function_exists('proc_open')) {
         throw $this->engine->newException('scribunto-luastandalone-proc-error-proc-open');
     }
     // Clear the "last error", so if proc_open fails we can know any
     // warning was generated by that.
     @trigger_error('');
     $this->proc = proc_open($cmd, array(array('pipe', 'r'), array('pipe', 'w'), array('file', $options['errorFile'], 'a')), $pipes);
     if (!$this->proc) {
         $err = error_get_last();
         if (!empty($err['message'])) {
             throw $this->engine->newException('scribunto-luastandalone-proc-error-msg', array('args' => array($err['message'])));
         } elseif (wfIniGetBool('safe_mode')) {
             /** @todo: Remove this case once we no longer support PHP 5.3 */
             throw $this->engine->newException('scribunto-luastandalone-proc-error-safe-mode');
         } else {
             throw $this->engine->newException('scribunto-luastandalone-proc-error');
         }
     }
     $this->writePipe = $pipes[0];
     $this->readPipe = $pipes[1];
 }
Ejemplo n.º 25
0
 /**
  * This function will perform a direct (authenticated) login to
  * a SMTP Server to use for mail relaying if 'wgSMTP' specifies an
  * array of parameters. It requires PEAR:Mail to do that.
  * Otherwise it just uses the standard PHP 'mail' function.
  *
  * @param MailAddress|MailAddress[] $to Recipient's email (or an array of them)
  * @param MailAddress $from Sender's email
  * @param string $subject Email's subject.
  * @param string $body Email's text or Array of two strings to be the text and html bodies
  * @param MailAddress $replyto Optional reply-to email (default: null).
  * @param string $contentType Optional custom Content-Type (default: text/plain; charset=UTF-8)
  * @throws MWException
  * @throws Exception
  * @return Status
  */
 public static function send($to, $from, $subject, $body, $replyto = null, $contentType = 'text/plain; charset=UTF-8')
 {
     global $wgSMTP, $wgEnotifMaxRecips, $wgAdditionalMailParams, $wgAllowHTMLEmail;
     $mime = null;
     if (!is_array($to)) {
         $to = array($to);
     }
     // mail body must have some content
     $minBodyLen = 10;
     // arbitrary but longer than Array or Object to detect casting error
     // body must either be a string or an array with text and body
     if (!(!is_array($body) && strlen($body) >= $minBodyLen) && !(is_array($body) && isset($body['text']) && isset($body['html']) && strlen($body['text']) >= $minBodyLen && strlen($body['html']) >= $minBodyLen)) {
         // if it is neither we have a problem
         return Status::newFatal('user-mail-no-body');
     }
     if (!$wgAllowHTMLEmail && is_array($body)) {
         // HTML not wanted.  Dump it.
         $body = $body['text'];
     }
     wfDebug(__METHOD__ . ': sending mail to ' . implode(', ', $to) . "\n");
     # Make sure we have at least one address
     $has_address = false;
     foreach ($to as $u) {
         if ($u->address) {
             $has_address = true;
             break;
         }
     }
     if (!$has_address) {
         return Status::newFatal('user-mail-no-addy');
     }
     # Forge email headers
     # -------------------
     #
     # WARNING
     #
     # DO NOT add To: or Subject: headers at this step. They need to be
     # handled differently depending upon the mailer we are going to use.
     #
     # To:
     #  PHP mail() first argument is the mail receiver. The argument is
     #  used as a recipient destination and as a To header.
     #
     #  PEAR mailer has a recipient argument which is only used to
     #  send the mail. If no To header is given, PEAR will set it to
     #  to 'undisclosed-recipients:'.
     #
     #  NOTE: To: is for presentation, the actual recipient is specified
     #  by the mailer using the Rcpt-To: header.
     #
     # Subject:
     #  PHP mail() second argument to pass the subject, passing a Subject
     #  as an additional header will result in a duplicate header.
     #
     #  PEAR mailer should be passed a Subject header.
     #
     # -- hashar 20120218
     $headers['From'] = $from->toString();
     $returnPath = $from->address;
     $extraParams = $wgAdditionalMailParams;
     // Hook to generate custom VERP address for 'Return-Path'
     Hooks::run('UserMailerChangeReturnPath', array($to, &$returnPath));
     # Add the envelope sender address using the -f command line option when PHP mail() is used.
     # Will default to the $from->address when the UserMailerChangeReturnPath hook fails and the
     # generated VERP address when the hook runs effectively.
     $extraParams .= ' -f ' . $returnPath;
     $headers['Return-Path'] = $returnPath;
     if ($replyto) {
         $headers['Reply-To'] = $replyto->toString();
     }
     $headers['Date'] = MWTimestamp::getLocalInstance()->format('r');
     $headers['Message-ID'] = self::makeMsgId();
     $headers['X-Mailer'] = 'MediaWiki mailer';
     # Line endings need to be different on Unix and Windows due to
     # the bug described at http://trac.wordpress.org/ticket/2603
     if (wfIsWindows()) {
         $endl = "\r\n";
     } else {
         $endl = "\n";
     }
     if (is_array($body)) {
         // we are sending a multipart message
         wfDebug("Assembling multipart mime email\n");
         if (!stream_resolve_include_path('Mail/mime.php')) {
             wfDebug("PEAR Mail_Mime package is not installed. Falling back to text email.\n");
             // remove the html body for text email fall back
             $body = $body['text'];
         } else {
             require_once 'Mail/mime.php';
             if (wfIsWindows()) {
                 $body['text'] = str_replace("\n", "\r\n", $body['text']);
                 $body['html'] = str_replace("\n", "\r\n", $body['html']);
             }
             $mime = new Mail_mime(array('eol' => $endl, 'text_charset' => 'UTF-8', 'html_charset' => 'UTF-8'));
             $mime->setTXTBody($body['text']);
             $mime->setHTMLBody($body['html']);
             $body = $mime->get();
             // must call get() before headers()
             $headers = $mime->headers($headers);
         }
     }
     if ($mime === null) {
         // sending text only, either deliberately or as a fallback
         if (wfIsWindows()) {
             $body = str_replace("\n", "\r\n", $body);
         }
         $headers['MIME-Version'] = '1.0';
         $headers['Content-type'] = is_null($contentType) ? 'text/plain; charset=UTF-8' : $contentType;
         $headers['Content-transfer-encoding'] = '8bit';
     }
     $ret = Hooks::run('AlternateUserMailer', array($headers, $to, $from, $subject, $body));
     if ($ret === false) {
         // the hook implementation will return false to skip regular mail sending
         return Status::newGood();
     } elseif ($ret !== true) {
         // the hook implementation will return a string to pass an error message
         return Status::newFatal('php-mail-error', $ret);
     }
     if (is_array($wgSMTP)) {
         #
         # PEAR MAILER
         #
         //start Eli Agbayani Nov 26, 2015
         $path = '/usr/local/Cellar/php53/5.3.29_2/lib/php';
         set_include_path(get_include_path() . PATH_SEPARATOR . $path);
         //end Eli Agbayani
         if (!stream_resolve_include_path('Mail.php')) {
             throw new MWException('PEAR mail package is not installed');
         }
         require_once 'Mail.php';
         wfSuppressWarnings();
         // Create the mail object using the Mail::factory method
         $mail_object =& Mail::factory('smtp', $wgSMTP);
         if (PEAR::isError($mail_object)) {
             wfDebug("PEAR::Mail factory failed: " . $mail_object->getMessage() . "\n");
             wfRestoreWarnings();
             return Status::newFatal('pear-mail-error', $mail_object->getMessage());
         }
         wfDebug("Sending mail via PEAR::Mail\n");
         $headers['Subject'] = self::quotedPrintable($subject);
         # When sending only to one recipient, shows it its email using To:
         if (count($to) == 1) {
             $headers['To'] = $to[0]->toString();
         }
         # Split jobs since SMTP servers tends to limit the maximum
         # number of possible recipients.
         $chunks = array_chunk($to, $wgEnotifMaxRecips);
         foreach ($chunks as $chunk) {
             $status = self::sendWithPear($mail_object, $chunk, $headers, $body);
             # FIXME : some chunks might be sent while others are not!
             if (!$status->isOK()) {
                 wfRestoreWarnings();
                 return $status;
             }
         }
         wfRestoreWarnings();
         return Status::newGood();
     } else {
         #
         # PHP mail()
         #
         if (count($to) > 1) {
             $headers['To'] = 'undisclosed-recipients:;';
         }
         $headers = self::arrayToHeaderString($headers, $endl);
         wfDebug("Sending mail via internal mail() function\n");
         self::$mErrorString = '';
         $html_errors = ini_get('html_errors');
         ini_set('html_errors', '0');
         set_error_handler('UserMailer::errorHandler');
         try {
             $safeMode = wfIniGetBool('safe_mode');
             foreach ($to as $recip) {
                 if ($safeMode) {
                     $sent = mail($recip, self::quotedPrintable($subject), $body, $headers);
                 } else {
                     $sent = mail($recip, self::quotedPrintable($subject), $body, $headers, $extraParams);
                 }
             }
         } catch (Exception $e) {
             restore_error_handler();
             throw $e;
         }
         restore_error_handler();
         ini_set('html_errors', $html_errors);
         if (self::$mErrorString) {
             wfDebug("Error sending mail: " . self::$mErrorString . "\n");
             return Status::newFatal('php-mail-error', self::$mErrorString);
         } elseif (!$sent) {
             // mail function only tells if there's an error
             wfDebug("Unknown error sending mail\n");
             return Status::newFatal('php-mail-error-unknown');
         } else {
             return Status::newGood();
         }
     }
 }
Ejemplo n.º 26
0
 /**
  * Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
  *
  * This will look for any APC style server-local cache.
  * A fallback cache can be specified if none is found.
  *
  *     // Direct calls
  *     ObjectCache::newAccelerator( $fallbackType );
  *
  *     // From $wgObjectCaches via newFromParams()
  *     ObjectCache::newAccelerator( array( 'fallback' => $fallbackType ) );
  *
  * @param array $params [optional] Array key 'fallback' for $fallback.
  * @param int|string $fallback Fallback cache, e.g. (CACHE_NONE, "hash") (since 1.24)
  * @return BagOStuff
  * @throws MWException
  */
 public static function newAccelerator($params = array(), $fallback = null)
 {
     if ($fallback === null) {
         // The is_array check here is needed because in PHP 5.3:
         // $a = 'hash'; isset( $params['fallback'] ); yields true
         if (is_array($params) && isset($params['fallback'])) {
             $fallback = $params['fallback'];
         } elseif (!is_array($params)) {
             $fallback = $params;
         }
     }
     if (function_exists('apc_fetch')) {
         $id = 'apc';
     } elseif (function_exists('xcache_get') && wfIniGetBool('xcache.var_size')) {
         $id = 'xcache';
     } elseif (function_exists('wincache_ucache_get')) {
         $id = 'wincache';
     } else {
         if ($fallback === null) {
             throw new MWException('CACHE_ACCEL requested but no suitable object ' . 'cache is present. You may want to install APC.');
         }
         $id = $fallback;
     }
     return self::newFromId($id);
 }
Ejemplo n.º 27
0
/**
 * Workaround for http://bugs.php.net/bug.php?id=45132
 * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
 */
function wfInitShellLocale()
{
    static $done = false;
    if ($done) {
        return;
    }
    $done = true;
    global $wgShellLocale;
    if (!wfIniGetBool('safe_mode')) {
        putenv("LC_CTYPE={$wgShellLocale}");
        setlocale(LC_CTYPE, $wgShellLocale);
    }
}
Ejemplo n.º 28
0
 /**
  * Start the PHP session. This may be called before execute() to start the PHP session.
  *
  * @throws Exception
  * @return bool
  */
 public function startSession()
 {
     if (wfIniGetBool('session.auto_start') || session_id()) {
         // Done already
         return true;
     }
     $this->phpErrors = array();
     set_error_handler(array($this, 'errorHandler'));
     try {
         session_start();
     } catch (Exception $e) {
         restore_error_handler();
         throw $e;
     }
     restore_error_handler();
     if ($this->phpErrors) {
         return false;
     }
     return true;
 }
Ejemplo n.º 29
0
 /**
  * Environment check for compiled object cache types.
  */
 protected function envCheckCache()
 {
     $caches = array();
     foreach ($this->objectCaches as $name => $function) {
         if (function_exists($function)) {
             if ($name == 'xcache' && !wfIniGetBool('xcache.var_size')) {
                 continue;
             }
             $caches[$name] = true;
         }
     }
     if (!$caches) {
         $this->showMessage('config-no-cache');
     }
     $this->setVar('_Caches', $caches);
 }
Ejemplo n.º 30
0
$wgOut = RequestContext::getMain()->getOutput();
# BackCompat
/**
 * @var Parser
 */
$wgParser = new StubObject('wgParser', $wgParserConf['class'], array($wgParserConf));
if (!is_object($wgAuth)) {
    $wgAuth = new StubObject('wgAuth', 'AuthPlugin');
    wfRunHooks('AuthPluginSetup', array(&$wgAuth));
}
# Placeholders in case of DB error
$wgTitle = null;
$wgDeferredUpdateList = array();
// We need to check for safe_mode, because mail() will throw an E_NOTICE
// on additional parameters
if (!is_null($wgAdditionalMailParams) && wfIniGetBool('safe_mode')) {
    $wgAdditionalMailParams = null;
}
wfProfileOut($fname . '-globals');
wfProfileIn($fname . '-extensions');
# Extension setup functions for extensions other than skins
# Entries should be added to this variable during the inclusion
# of the extension file. This allows the extension to perform
# any necessary initialisation in the fully initialised environment
foreach ($wgExtensionFunctions as $func) {
    # Allow closures in PHP 5.3+
    if (is_object($func) && $func instanceof Closure) {
        $profName = $fname . '-extensions-closure';
    } elseif (is_array($func)) {
        if (is_object($func[0])) {
            $profName = $fname . '-extensions-' . get_class($func[0]) . '::' . $func[1];