Ejemplo n.º 1
0
 function addWatermark($srcPath, $dstPath, $width, $height)
 {
     global $IP, $wgImageMagickConvertCommand, $wgImageMagickCompositeCommand;
     // do not add a watermark if the image is too small
     if (WatermarkSupport::validImageSize($width, $height) == false) {
         return;
     }
     $wm = $IP . '/skins/WikiHow/images/watermark.svg';
     $watermarkWidth = 1074.447;
     $targetWidth = $width / 8;
     $density = 72 * $targetWidth / $watermarkWidth;
     // we have a lower limit on density so the watermark is readable
     if ($density < 4.0) {
         $density = 4.0;
     }
     $cmd = "";
     // make sure image is rgb format so the watermark applies correctly
     if (WatermarkSupport::isCMYK($srcPath)) {
         $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) . " " . wfEscapeShellArg($srcPath) . " " . "-colorspace RGB " . wfEscapeShellArg($dstPath) . ";";
         $srcPath = $dstPath;
     }
     $cmd = $cmd . wfEscapeShellArg($wgImageMagickConvertCommand) . " -density {$density} -background none " . wfEscapeShellArg($wm) . " miff:- | " . wfEscapeShellArg($wgImageMagickCompositeCommand) . " -gravity southeast -quality 100 -geometry +8+10 - " . wfEscapeShellArg($srcPath) . " " . wfEscapeShellArg($dstPath) . " 2>&1";
     $beforeExists = file_exists($dstPath);
     wfDebug(__METHOD__ . ": running ImageMagick: {$cmd}\n");
     $err = wfShellExec($cmd, $retval);
     $afterExists = file_exists($dstPath);
     $currentDate = `date`;
     wfErrorLog(trim($currentDate) . " {$cmd} b:" . ($beforeExists ? 't' : 'f') . " a:" . ($afterExists ? 't' : 'f') . "\n", '/tmp/watermark.log');
     wfProfileOut('watermark');
 }
Ejemplo n.º 2
0
 function logToFile($msg, $file)
 {
     $header = '[' . date('d\\TH:i:s') . '] ' . wfHostname() . ' ' . posix_getpid();
     if ($this->slaveId !== false) {
         $header .= "({$this->slaveId})";
     }
     $header .= ' ' . wfWikiID();
     wfErrorLog(sprintf("%-50s %s\n", $header, $msg), $file);
 }
Ejemplo n.º 3
0
DeferredUpdates::doUpdates();
// Log what the user did, for book-keeping purposes.
$endtime = microtime(true);
wfProfileOut('api.php');
wfLogProfilingData();
// Log the request
if ($wgAPIRequestLog) {
    $items = array(wfTimestamp(TS_MW), $endtime - $starttime, $wgRequest->getIP(), $wgRequest->getHeader('User-agent'));
    $items[] = $wgRequest->wasPosted() ? 'POST' : 'GET';
    if ($processor) {
        try {
            $manager = $processor->getModuleManager();
            $module = $manager->getModule($wgRequest->getVal('action'), 'action');
        } catch (Exception $ex) {
            $module = null;
        }
        if (!$module || $module->mustBePosted()) {
            $items[] = "action=" . $wgRequest->getVal('action');
        } else {
            $items[] = wfArrayToCgi($wgRequest->getValues());
        }
    } else {
        $items[] = "failed in ApiBeforeMain";
    }
    wfErrorLog(implode(',', $items) . "\n", $wgAPIRequestLog);
    wfDebug("Logged API request to {$wgAPIRequestLog}\n");
}
// Shut down the database.  foo()->bar() syntax is not supported in PHP4: we won't ever actually
// get here to worry about whether this should be = or =&, but the file has to parse properly.
$lb = wfGetLBFactory();
$lb->shutdown();
Ejemplo n.º 4
0
/**
 * Log for database errors
 *
 * @param string $text Database error message.
 */
function wfLogDBError($text)
{
    global $wgDBerrorLog, $wgDBerrorLogTZ;
    static $logDBErrorTimeZoneObject = null;
    if ($wgDBerrorLog) {
        $host = wfHostname();
        $wiki = wfWikiID();
        if ($wgDBerrorLogTZ && !$logDBErrorTimeZoneObject) {
            $logDBErrorTimeZoneObject = new DateTimeZone($wgDBerrorLogTZ);
        }
        // Workaround for https://bugs.php.net/bug.php?id=52063
        // Can be removed when min PHP > 5.3.2
        if ($logDBErrorTimeZoneObject === null) {
            $d = date_create("now");
        } else {
            $d = date_create("now", $logDBErrorTimeZoneObject);
        }
        $date = $d->format('D M j G:i:s T Y');
        $text = "{$date}\t{$host}\t{$wiki}\t" . trim($text) . "\n";
        wfErrorLog($text, $wgDBerrorLog);
    }
}
 /**
  * Move the uploaded image from the temporary location to the initial upload directory 
  */
 public function moveUploadToOriginalImagesDir($temp_path)
 {
     $initial_upload_dir_path = $this->getOriginalImagesFullPath();
     $upload_succesfull = move_uploaded_file($temp_path, $initial_upload_dir_path);
     if (!$upload_succesfull) {
         wfErrorLog($this->msg('newmanuscript-error-upload') . "\r\n", $web_root . '/' . 'ManuscriptDeskDebugLog.log');
         throw new \Exception('newmanuscript-error-upload');
     }
     return $this->image_uploaded = true;
 }
/**
 * @todo document
 */
function wfLogProfilingData()
{
    global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
    global $wgProfileLimit, $wgUser;
    $profiler = Profiler::instance();
    # Profiling must actually be enabled...
    if ($profiler->isStub()) {
        return;
    }
    // Get total page request time and only show pages that longer than
    // $wgProfileLimit time (default is 0)
    $now = wfTime();
    $elapsed = $now - $wgRequestTime;
    if ($elapsed <= $wgProfileLimit) {
        return;
    }
    $profiler->logData();
    // Check whether this should be logged in the debug file.
    if ($wgDebugLogFile == '' || !$wgDebugRawPage && wfIsDebugRawPage()) {
        return;
    }
    $forward = '';
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
    }
    if (!empty($_SERVER['HTTP_FROM'])) {
        $forward .= ' from ' . $_SERVER['HTTP_FROM'];
    }
    if ($forward) {
        $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
    }
    // Don't load $wgUser at this late stage just for statistics purposes
    // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
    if ($wgUser->isItemLoaded('id') && $wgUser->isAnon()) {
        $forward .= ' anon';
    }
    $log = sprintf("%s\t%04.3f\t%s\n", gmdate('YmdHis'), $elapsed, urldecode($wgRequest->getRequestURL() . $forward));
    wfErrorLog($log . $profiler->getOutput(), $wgDebugLogFile);
}
Ejemplo n.º 7
0
/**
 * @todo document
 */
function wfLogProfilingData()
{
    global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
    global $wgProfileLimit, $wgUser;
    StatCounter::singleton()->flush();
    $profiler = Profiler::instance();
    # Profiling must actually be enabled...
    if ($profiler->isStub()) {
        return;
    }
    // Get total page request time and only show pages that longer than
    // $wgProfileLimit time (default is 0)
    $elapsed = microtime(true) - $wgRequestTime;
    if ($elapsed <= $wgProfileLimit) {
        return;
    }
    $profiler->logData();
    // Check whether this should be logged in the debug file.
    if ($wgDebugLogFile == '' || !$wgDebugRawPage && wfIsDebugRawPage()) {
        return;
    }
    $forward = '';
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
    }
    if (!empty($_SERVER['HTTP_FROM'])) {
        $forward .= ' from ' . $_SERVER['HTTP_FROM'];
    }
    if ($forward) {
        $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
    }
    // Don't load $wgUser at this late stage just for statistics purposes
    // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
    if ($wgUser->isItemLoaded('id') && $wgUser->isAnon()) {
        $forward .= ' anon';
    }
    // Command line script uses a FauxRequest object which does not have
    // any knowledge about an URL and throw an exception instead.
    try {
        $requestUrl = $wgRequest->getRequestURL();
    } catch (MWException $e) {
        $requestUrl = 'n/a';
    }
    $log = sprintf("%s\t%04.3f\t%s\n", gmdate('YmdHis'), $elapsed, urldecode($requestUrl . $forward));
    wfErrorLog($log . $profiler->getOutput(), $wgDebugLogFile);
}
Ejemplo n.º 8
0
 function doTransform($image, $dstPath, $dstUrl, $params, $flags = 0)
 {
     global $wgUseImageMagick, $wgImageMagickConvertCommand;
     global $wgCustomConvertCommand;
     global $wgSharpenParameter, $wgSharpenReductionThreshold;
     $oheight = $params['height'];
     $owidth = $params['width'];
     if (!$this->normaliseParams($image, $params)) {
         return new TransformParameterError($params);
     }
     $physicalWidth = $params['physicalWidth'];
     $physicalHeight = $params['physicalHeight'];
     $clientWidth = $params['width'];
     $clientHeight = $params['height'];
     $crop = $params['crop'] == 1 ? true : false;
     $srcWidth = $image->getWidth();
     $srcHeight = $image->getHeight();
     $mimeType = $image->getMimeType();
     $srcPath = $image->getPath();
     $retval = 0;
     wfDebug(__METHOD__ . ": creating {$physicalWidth}x{$physicalHeight} thumbnail at {$dstPath}\n");
     if ($physicalWidth == $srcWidth && $physicalHeight == $srcHeight) {
         if (wfRunHooks("ImageConvertNoScale", array($dstPath, $params))) {
             # normaliseParams (or the user) wants us to return the unscaled image
             wfDebug(__METHOD__ . ": returning unscaled image\n");
             return new ThumbnailImage($image, $image->getURL(), $clientWidth, $clientHeight, $srcPath);
         }
     }
     if (!$dstPath) {
         // No output path available, client side scaling only
         $scaler = 'client';
     } elseif ($wgUseImageMagick) {
         $scaler = 'im';
     } elseif ($wgCustomConvertCommand) {
         $scaler = 'custom';
     } elseif (function_exists('imagecreatetruecolor')) {
         $scaler = 'gd';
     } else {
         $scaler = 'client';
     }
     if ($scaler == 'client') {
         # Client-side image scaling, use the source URL
         # Using the destination URL in a TRANSFORM_LATER request would be incorrect
         return new ThumbnailImage($image, $image->getURL(), $clientWidth, $clientHeight, $srcPath);
     }
     if ($flags & self::TRANSFORM_LATER) {
         return new ThumbnailImage($image, $dstUrl, $clientWidth, $clientHeight, $dstPath);
     }
     if (!wfMkdirParents(dirname($dstPath))) {
         return new MediaTransformError('thumbnail_error', $clientWidth, $clientHeight, wfMsg('thumbnail_dest_directory'));
     }
     if ($scaler == 'im') {
         # use ImageMagick
         $sharpen = '';
         if ($mimeType == 'image/jpeg') {
             $quality = "-quality 80";
             // 80%
             # Sharpening, see bug 6193
             if (($physicalWidth + $physicalHeight) / ($srcWidth + $srcHeight) < $wgSharpenReductionThreshold) {
                 $sharpen = "-sharpen " . wfEscapeShellArg($wgSharpenParameter);
             }
         } elseif ($mimeType == 'image/png') {
             $quality = "-quality 95";
             // zlib 9, adaptive filtering
         } else {
             $quality = '';
             // default
         }
         # Specify white background color, will be used for transparent images
         # in Internet Explorer/Windows instead of default black.
         # Note, we specify "-size {$physicalWidth}" and NOT "-size {$physicalWidth}x{$physicalHeight}".
         # It seems that ImageMagick has a bug wherein it produces thumbnails of
         # the wrong size in the second case.
         if (!$crop) {
             $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) . " {$quality} -background white -size {$physicalWidth} " . wfEscapeShellArg($srcPath) . ' -coalesce ' . " -thumbnail " . wfEscapeShellArg("{$physicalWidth}x{$physicalHeight}!") . " -depth 8 {$sharpen} " . wfEscapeShellArg($dstPath) . " 2>&1";
         } else {
             $physicalWidth = $owidth;
             $physicalHeight = $oheight;
             if (isset($params['heightPreference']) && $params['heightPreference']) {
                 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) . " " . wfEscapeShellArg($srcPath) . " -thumbnail " . wfEscapeShellArg("x{$physicalHeight}") . " -gravity center -crop " . wfEscapeShellArg("{$physicalWidth}x{$physicalHeight}+0+0 ") . " -quality 100 " . wfEscapeShellArg($dstPath) . " 2>&1";
             } else {
                 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) . " " . wfEscapeShellArg($srcPath) . " -thumbnail " . wfEscapeShellArg("{$physicalWidth}x") . " -gravity center -crop " . wfEscapeShellArg("{$physicalWidth}x{$physicalHeight}+0+0 ") . " -quality 100 " . wfEscapeShellArg($dstPath) . " 2>&1";
             }
         }
         #print_r($params); echo wfBacktrace(); echo $cmd; exit;
         $beforeExists = file_exists($dstPath);
         wfDebug(__METHOD__ . ": running ImageMagick: {$cmd}\n");
         wfProfileIn('convert');
         if (wfRunHooks("ImageConvert", array($cmd, $image, $srcPath, $dstPath, $params))) {
             $err = wfShellExec($cmd, $retval);
             wfRunHooks("ImageConvertComplete", array($dstPath, $params));
         }
         $afterExists = file_exists($dstPath);
         $currentDate = `date`;
         wfErrorLog(trim($currentDate) . " {$cmd} b:" . ($beforeExists ? 't' : 'f') . " a:" . ($afterExists ? 't' : 'f') . "\n", '/tmp/convert.log');
         wfProfileOut('convert');
     } elseif ($scaler == 'custom') {
         # Use a custom convert command
         # Variables: %s %d %w %h
         $src = wfEscapeShellArg($srcPath);
         $dst = wfEscapeShellArg($dstPath);
         $cmd = $wgCustomConvertCommand;
         $cmd = str_replace('%s', $src, str_replace('%d', $dst, $cmd));
         # Filenames
         $cmd = str_replace('%h', $physicalHeight, str_replace('%w', $physicalWidth, $cmd));
         # Size
         wfDebug(__METHOD__ . ": Running custom convert command {$cmd}\n");
         wfProfileIn('convert');
         $err = wfShellExec($cmd, $retval);
         wfProfileOut('convert');
     } else {
         # Use PHP's builtin GD library functions.
         #
         # First find out what kind of file this is, and select the correct
         # input routine for this.
         $typemap = array('image/gif' => array('imagecreatefromgif', 'palette', 'imagegif'), 'image/jpeg' => array('imagecreatefromjpeg', 'truecolor', array(__CLASS__, 'imageJpegWrapper')), 'image/png' => array('imagecreatefrompng', 'bits', 'imagepng'), 'image/vnd.wap.wbmp' => array('imagecreatefromwbmp', 'palette', 'imagewbmp'), 'image/xbm' => array('imagecreatefromxbm', 'palette', 'imagexbm'));
         if (!isset($typemap[$mimeType])) {
             $err = 'Image type not supported';
             wfDebug("{$err}\n");
             return new MediaTransformError('thumbnail_error', $clientWidth, $clientHeight, $err);
         }
         list($loader, $colorStyle, $saveType) = $typemap[$mimeType];
         if (!function_exists($loader)) {
             $err = "Incomplete GD library configuration: missing function {$loader}";
             wfDebug("{$err}\n");
             return new MediaTransformError('thumbnail_error', $clientWidth, $clientHeight, $err);
         }
         $src_image = call_user_func($loader, $srcPath);
         $dst_image = imagecreatetruecolor($physicalWidth, $physicalHeight);
         // Initialise the destination image to transparent instead of
         // the default solid black, to support PNG and GIF transparency nicely
         $background = imagecolorallocate($dst_image, 0, 0, 0);
         imagecolortransparent($dst_image, $background);
         imagealphablending($dst_image, false);
         if ($colorStyle == 'palette') {
             // Don't resample for paletted GIF images.
             // It may just uglify them, and completely breaks transparency.
             imagecopyresized($dst_image, $src_image, 0, 0, 0, 0, $physicalWidth, $physicalHeight, imagesx($src_image), imagesy($src_image));
         } else {
             imagecopyresampled($dst_image, $src_image, 0, 0, 0, 0, $physicalWidth, $physicalHeight, imagesx($src_image), imagesy($src_image));
         }
         imagesavealpha($dst_image, true);
         call_user_func($saveType, $dst_image, $dstPath);
         imagedestroy($dst_image);
         imagedestroy($src_image);
         $retval = 0;
     }
     $removed = $this->removeBadFile($dstPath, $retval);
     if ($retval != 0 || $removed) {
         wfDebugLog('thumbnail', sprintf('thumbnail failed on %s: error %d "%s" from "%s"', wfHostname(), $retval, trim($err), $cmd));
         return new MediaTransformError('thumbnail_error', $clientWidth, $clientHeight, $err);
     } else {
         return new ThumbnailImage($image, $dstUrl, $clientWidth, $clientHeight, $dstPath);
     }
 }
Ejemplo n.º 9
0
	/**
	 * Sends the notification to the specified host in a UDP packet.
	 * @see RCFeedEngine::send
	 */
	public function send( array $feed, $line ) {
		wfErrorLog( $line, $feed['uri'] );
	}
Ejemplo n.º 10
0
/**
 * @todo document
 */
function wfLogProfilingData()
{
    global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
    global $wgProfiler, $wgProfileLimit, $wgUser;
    # Profiling must actually be enabled...
    if (!isset($wgProfiler)) {
        return;
    }
    # Get total page request time
    $now = wfTime();
    $elapsed = $now - $wgRequestTime;
    # Only show pages that longer than $wgProfileLimit time (default is 0)
    if ($elapsed <= $wgProfileLimit) {
        return;
    }
    $prof = wfGetProfilingOutput($wgRequestTime, $elapsed);
    $forward = '';
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
    }
    if (!empty($_SERVER['HTTP_FROM'])) {
        $forward .= ' from ' . $_SERVER['HTTP_FROM'];
    }
    if ($forward) {
        $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
    }
    // Don't unstub $wgUser at this late stage just for statistics purposes
    if (StubObject::isRealObject($wgUser) && $wgUser->isAnon()) {
        $forward .= ' anon';
    }
    $log = sprintf("%s\t%04.3f\t%s\n", gmdate('YmdHis'), $elapsed, urldecode($wgRequest->getRequestURL() . $forward));
    if ('' != $wgDebugLogFile && ($wgRequest->getVal('action') != 'raw' || $wgDebugRawPage)) {
        wfErrorLog($log . $prof, $wgDebugLogFile);
    }
}
Ejemplo n.º 11
0
 public static function logging($level, $fileabsoluteName, $lineNumber, $format)
 {
     global $wgMoegirlRatingLogLevel, $wgMoegirlRatingLogDir;
     if ($level >= $wgMoegirlRatingLogLevel && isset($wgMoegirlRatingLogDir)) {
         $currentTime = (string) microtime();
         $dateString = date('Ymd', substr($currentTime, 11, 20));
         $timeString1 = date('Ymd H:i:s', substr($currentTime, 11, 20));
         $timeString2 = substr($currentTime, 1, 7);
         $fileName = basename($fileabsoluteName);
         $content = $format;
         if (func_num_args() > 4) {
             $array = array();
             for ($i = 4; $i < func_num_args(); $i++) {
                 $array[] = func_get_arg($i);
             }
             $content = vsprintf($format, $array);
         }
         $logEntry = sprintf("%s%s %s %s -- %s:%s\n", $timeString1, $timeString2, self::$logLevelStrings[$level], $content, $fileName, $lineNumber);
         $logFile = $wgMoegirlRatingLogDir . '/MoegirlRating-' . $dateString . '.log';
         wfErrorLog($logEntry, $logFile);
     }
 }
Ejemplo n.º 12
0
/**
 * @todo document
 */
function wfLogProfilingData()
{
    global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
    global $wgProfileLimit, $wgUser, $wgProfilingDataLogged;
    $wgProfilingDataLogged = true;
    $profiler = Profiler::instance();
    # Profiling must actually be enabled...
    if ($profiler->isStub()) {
        return;
    }
    // Get total page request time and only show pages that longer than
    // $wgProfileLimit time (default is 0)
    $elapsed = microtime(true) - $wgRequestTime;
    if ($elapsed <= $wgProfileLimit) {
        return;
    }
    $profiler->logData();
    // Check whether this should be logged in the debug file.
    if ($wgDebugLogFile == '' || !$wgDebugRawPage && wfIsDebugRawPage()) {
        return;
    }
    $forward = '';
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
    }
    if (!empty($_SERVER['HTTP_FROM'])) {
        $forward .= ' from ' . $_SERVER['HTTP_FROM'];
    }
    if ($forward) {
        $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
    }
    // Don't load $wgUser at this late stage just for statistics purposes
    // @todo FIXME: We can detect some anons even if it is not loaded. See User::getId()
    if ($wgUser->isItemLoaded('id') && $wgUser->isAnon()) {
        $forward .= ' anon';
    }
    // Wikia change - begin - FauxRequest::getRequestURL() is not implemented and throws exception
    // in maintenance scripts
    try {
        $log = sprintf("%s\t%04.3f\t%s\n", gmdate('YmdHis'), $elapsed, urldecode($wgRequest->getRequestURL() . $forward));
        wfErrorLog($log . $profiler->getOutput(), $wgDebugLogFile);
    } catch (MWException $e) {
        // double-check it is the case
        if ($e->getMessage() !== "FauxRequest::getRequestURL() not implemented") {
            throw $e;
        }
    }
    // Wikia change - end
}
 /**
  * Track particular event
  *
  * @param $sessionId String: unique session id for this editing sesion
  * @param $isLoggedIn Boolean: whether or not the user is logged in
  * @param $namespace Integer: namespace the user is editing
  * @param $eventName String: event type
  * @param $contribs Integer: contributions the user has made (or NULL if user not logged in)
  * @param $contribs_in_timespan1 Integer: number of contributions user has made in timespan of granularity 1
  * (defined by ClickTracking/$wgClickTrackContribGranularity1)
  * @param $contribs_in_timespan2 Integer: number of contributions user has made in timespan of granularity 2
  * (defined by ClickTracking/$wgClickTrackContribGranularity2)
  * @param $contribs_in_timespan3 Integer: number of contributions user has made in timespan of granularity 3
  * (defined by ClickTracking/$wgClickTrackContribGranularity3)
  * @param $additional String: catch-all for any additional information we want to record about this click
  * @param $relevantBucket String: name/index of the particular bucket we're concerned with for this event
  * @return Boolean: true if the event was stored in the DB
  */
 public static function trackEvent($sessionId, $isLoggedIn, $namespace, $eventName, $contribs = 0, $contribs_in_timespan1 = 0, $contribs_in_timespan2 = 0, $contribs_in_timespan3 = 0, $additional = null, $recordBucketInfo = true)
 {
     global $wgClickTrackingDatabase, $wgClickTrackingLog;
     $retval = true;
     if ($wgClickTrackingDatabase) {
         $eventId = self::getEventIDFromName($eventName);
         $dbw = wfGetDB(DB_MASTER);
         $dbw->begin();
         // Builds insert information
         $data = array('action_time' => $dbw->timestamp(), 'session_id' => (string) $sessionId, 'is_logged_in' => (bool) $isLoggedIn, 'user_total_contribs' => $isLoggedIn ? (int) $contribs : null, 'user_contribs_span1' => $isLoggedIn ? (int) $contribs_in_timespan1 : null, 'user_contribs_span2' => $isLoggedIn ? (int) $contribs_in_timespan2 : null, 'user_contribs_span3' => $isLoggedIn ? (int) $contribs_in_timespan3 : null, 'namespace' => (int) $namespace, 'event_id' => (int) $eventId, 'additional_info' => isset($additional) ? (string) $additional : null);
         $db_status_buckets = true;
         $db_status = $dbw->insert('click_tracking', $data, __METHOD__);
         $dbw->commit();
         if ($recordBucketInfo && $db_status) {
             $buckets = self::unpackBucketInfo();
             $dbw->begin();
             if ($buckets) {
                 foreach ($buckets as $bucketName => $bucketValue) {
                     $db_current_bucket_insert = $dbw->insert('click_tracking_user_properties', array('session_id' => (string) $sessionId, 'property_name' => (string) $bucketName, 'property_value' => (string) $bucketValue[0], 'property_version' => (int) $bucketValue[1]), __METHOD__, array('IGNORE'));
                     $db_status_buckets = $db_status_buckets && $db_current_bucket_insert;
                 }
             }
             //ifbuckets
             $dbw->commit();
         }
         //ifrecord
         $retval = $db_status && $db_status_buckets;
     }
     if ($wgClickTrackingLog) {
         $msg = implode("\t", array(str_replace("\t", ' ', $eventName), wfTimestampNow(), (int) $isLoggedIn, str_replace("\t", ' ', $sessionId), (int) $namespace, (int) $contribs, (int) $contribs_in_timespan1, (int) $contribs_in_timespan2, (int) $contribs_in_timespan3, str_replace("\t", ' ', $additional)));
         wfErrorLog($msg, $wgClickTrackingLog);
         // No need to mess with $retval here, doing
         // $retval == $retval && true is useless
     }
     return $retval;
 }
Ejemplo n.º 14
0
 /**
  * @param string $term
  * @public
  */
 function showResults($term)
 {
     $fname = 'SpecialSearch::showResults';
     wfProfileIn($fname);
     $this->setupPage($term);
     global $wgOut;
     $wgOut->addWikiMsg('searchresulttext');
     if ('' === trim($term)) {
         // Empty query -- straight view of search form
         $wgOut->setSubtitle('');
         $wgOut->addHTML($this->powerSearchBox($term));
         $wgOut->addHTML($this->powerSearchFocus());
         wfProfileOut($fname);
         return;
     }
     global $wgDisableTextSearch;
     if ($wgDisableTextSearch) {
         global $wgForwardSearchUrl;
         if ($wgForwardSearchUrl) {
             $url = str_replace('$1', urlencode($term), $wgForwardSearchUrl);
             $wgOut->redirect($url);
             return;
         }
         global $wgInputEncoding;
         $wgOut->addHTML(wfMsg('searchdisabled'));
         $wgOut->addHTML(wfMsg('googlesearch', htmlspecialchars($term), htmlspecialchars($wgInputEncoding), htmlspecialchars(wfMsg('searchbutton'))));
         wfProfileOut($fname);
         return;
     }
     // XXADDED temporary logging for Reuben
     wfErrorLog("{$term}\n", '/tmp/searches.txt');
     $search = SearchEngine::create();
     $search->setLimitOffset($this->limit, $this->offset);
     $search->setNamespaces($this->namespaces);
     $search->showRedirects = $this->searchRedirects;
     $titleMatches = $search->searchTitle($term);
     // Sometimes the search engine knows there are too many hits
     if ($titleMatches instanceof SearchResultTooMany) {
         $wgOut->addWikiText('==' . wfMsg('toomanymatches') . "==\n");
         $wgOut->addHTML($this->powerSearchBox($term));
         $wgOut->addHTML($this->powerSearchFocus());
         wfProfileOut($fname);
         return;
     }
     $textMatches = $search->searchText($term);
     $num = ($titleMatches ? $titleMatches->numRows() : 0) + ($textMatches ? $textMatches->numRows() : 0);
     if ($num > 0) {
         if ($num >= $this->limit) {
             $top = wfShowingResults($this->offset, $this->limit);
         } else {
             $top = wfShowingResultsNum($this->offset, $this->limit, $num);
         }
         $wgOut->addHTML("<p>{$top}</p>\n");
     }
     if ($num || $this->offset) {
         $prevnext = wfViewPrevNext($this->offset, $this->limit, SpecialPage::getTitleFor('Search'), wfArrayToCGI($this->powerSearchOptions(), array('search' => $term)), $num < $this->limit);
         $wgOut->addHTML("<br />{$prevnext}\n");
     }
     if ($titleMatches) {
         if ($titleMatches->numRows()) {
             $wgOut->wrapWikiMsg("==\$1==\n", 'titlematches');
             $wgOut->addHTML($this->showMatches($titleMatches));
         } else {
             $wgOut->wrapWikiMsg("==\$1==\n", 'notitlematches');
         }
         $titleMatches->free();
     }
     if ($textMatches) {
         if ($textMatches->numRows()) {
             $wgOut->wrapWikiMsg("==\$1==\n", 'textmatches');
             $wgOut->addHTML($this->showMatches($textMatches));
         } elseif ($num == 0) {
             # Don't show the 'no text matches' if we received title matches
             $wgOut->wrapWikiMsg("==\$1==\n", 'notextmatches');
         }
         $textMatches->free();
     }
     if ($num == 0) {
         $wgOut->addWikiMsg('nonefound');
     }
     if ($num || $this->offset) {
         $wgOut->addHTML("<p>{$prevnext}</p>\n");
     }
     $wgOut->addHTML($this->powerSearchBox($term));
     wfProfileOut($fname);
 }
/**
 * @todo document
 */
function wfLogProfilingData()
{
    global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
    global $wgProfiling, $wgUser;
    if ($wgProfiling) {
        $now = wfTime();
        $elapsed = $now - $wgRequestTime;
        $prof = wfGetProfilingOutput($wgRequestTime, $elapsed);
        $forward = '';
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
        }
        if (!empty($_SERVER['HTTP_FROM'])) {
            $forward .= ' from ' . $_SERVER['HTTP_FROM'];
        }
        if ($forward) {
            $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
        }
        // Don't unstub $wgUser at this late stage just for statistics purposes
        if (StubObject::isRealObject($wgUser) && $wgUser->isAnon()) {
            $forward .= ' anon';
        }
        $log = sprintf("%s\t%04.3f\t%s\n", gmdate('YmdHis'), $elapsed, urldecode($wgRequest->getRequestURL() . $forward));
        if ('' != $wgDebugLogFile && ($wgRequest->getVal('action') != 'raw' || $wgDebugRawPage)) {
            wfErrorLog($log . $prof, $wgDebugLogFile);
        }
    }
}
Ejemplo n.º 16
0
/**
 * Writes an event to a file descriptor or socket.
 * Takes an event ID and an event, encodes it as query string,
 * and writes it to the UDP / TCP address or file specified by
 * $wgEventLoggingFile. If $wgEventLoggingFile is not set, returns
 * false without logging anything.
 *
 * @see wfErrorLog
 *
 * @param string $schema: Schema name.
 * @param integer $revId: revision ID of schema
 * @param array $event: Map of event keys/vals.
 * @return bool: Whether the event was logged.
 */
function efLogServerSideEvent($schemaName, $revId, $event)
{
    global $wgDBname, $wgEventLoggingFile;
    if (!$wgEventLoggingFile) {
        return false;
    }
    wfProfileIn(__FUNCTION__);
    $remoteSchema = new RemoteSchema($schemaName, $revId);
    $schema = $remoteSchema->get();
    try {
        $isValid = is_array($schema) && efSchemaValidate($event, $schema);
    } catch (JsonSchemaException $e) {
        $isValid = false;
    }
    $encapsulated = array('event' => $event, 'schema' => $schemaName, 'revision' => $revId, 'clientValidated' => $isValid, 'wiki' => $wgDBname, 'recvFrom' => gethostname(), 'timestamp' => $_SERVER['REQUEST_TIME']);
    if (isset($_SERVER['HTTP_HOST'])) {
        $encapsulated['webHost'] = $_SERVER['HTTP_HOST'];
    }
    // To make the resultant JSON easily extracted from a row of
    // space-separated values, we replace literal spaces with unicode
    // escapes. This is permitted by the JSON specs.
    $json = str_replace(' ', '\\u0020', FormatJson::encode($encapsulated));
    wfErrorLog($json . "\n", $wgEventLoggingFile);
    wfProfileOut(__FUNCTION__);
    return true;
}