Ejemplo n.º 1
0
 /**
  * This method will be called when the engine has finished the source
  * analysis phase. To remove file with violations from cache.
  *
  * @param Report $report
  * @return void
  */
 public function renderReport(Report $report)
 {
     foreach ($report->getRuleViolations() as $violation) {
         $fileName = $violation->getFileName();
         $this->cache->remove($fileName, null);
     }
 }
Ejemplo n.º 2
0
function s_element_replace(array $matches)
{
    if (isset($matches[1])) {
        $dD = new DataStore();
        $o_Element = new Element($dD->get_element_data($matches[1]));
        $o_Element->_set_full_element($dD->o_get_full_element($matches[1]));
        return $o_Element->render();
    }
}
Ejemplo n.º 3
0
 /**
  * Remove file from cache if contains errors
  *
  * @param array                $report      Prepared report data.
  * @param PHP_CodeSniffer_File $phpcsFile   The file being reported on.
  * @param boolean              $showSources Show sources?
  * @param int                  $width       Maximum allowed line width.
  *
  * @return boolean
  */
 public function generateFileReport($report, PHP_CodeSniffer_File $phpcsFile, $showSources = false, $width = 80)
 {
     if (!self::$cache || $report['errors'] === 0 && $report['warnings'] === 0) {
         // Nothing to do
         return false;
     }
     self::$cache->remove($report['filename']);
     return false;
 }
Ejemplo n.º 4
0
 private function connect()
 {
     if (self::$conn) {
         return true;
     }
     self::$conn = new PDO('sqlite:' . DIR_DATA . '/data.db');
 }
Ejemplo n.º 5
0
 protected function parseField($k, $v)
 {
     if ($k == "created") {
         return $v != "" ? new \DateTime($v) : null;
     } else {
         return parent::parseField($k, $v);
     }
 }
Ejemplo n.º 6
0
 /**
  * check that the nonce is not repeated
  */
 private function _checkNonce(Consumer $consumer, $nonce, $timestamp)
 {
     if (!$nonce) {
         throw new Exception('Missing nonce parameter. The parameter is required.', 400);
     }
     // verify that the nonce is uniqueish
     $found = $this->_dataStore->lookupNonce($consumer, $nonce, $timestamp);
     if ($found) {
         throw new Exception("Nonce already used: {$nonce}", 400);
     }
 }
Ejemplo n.º 7
0
 public function validatorUnique($name, $parameter)
 {
     if ($this->datastore->data[$name] == '' || $this->datastore->data[$name] === null) {
         return true;
     }
     $data = $this->getWithField($name, $this->escape($this->datastore->data[$name]));
     if (count($data) == 0 || $this->datastore->checkTemp($name, $this->datastore->data[$name])) {
         return true;
     } else {
         return "The value of the %field_name% field must be unique.";
     }
 }
Ejemplo n.º 8
0
<?php

require_once 'lib/datastore.class.php';
require_once 'lib/datafetcher.class.php';
$store = new DataStore();
$fetcher = new DataFetcher();
$user = $_GET['user'];
if (!$user) {
    die("No user specified.");
}
$scrobbles = $store->getAllScrobbles($user);
$chart = array();
foreach ($scrobbles as $scrobble) {
    $address = $fetcher->fetchAddress($scrobble['latitude'] . ',' . $scrobble['longitude']);
    $address = preg_replace('/London.*?,/', 'London,', $address);
    if (!isset($chart[$address])) {
        $chart[$address] = array();
    }
    if (!isset($chart[$address][$scrobble['artist']])) {
        $chart[$address][$scrobble['artist']] = 0;
    }
    $chart[$address][$scrobble['artist']]++;
}
foreach ($chart as $place => $chart) {
    arsort($chart);
    print "<h4>{$place}</h4><ul>";
    foreach ($chart as $artist => $plays) {
        print "<li><b>{$plays}</b>. {$artist}</li>";
    }
    print "</ul><br>";
}
Ejemplo n.º 9
0
 /**
  * Performs the actual syntax check
  *
  * @param  string $file
  *
  * @throws BuildException
  *
  * @return bool|void
  */
 protected function lint($file)
 {
     $command = $this->executable . ' -output-format ' . escapeshellarg('file:__FILE__;line:__LINE__;message:__ERROR__') . ' ';
     if (isset($this->conf)) {
         $command .= '-conf ' . escapeshellarg($this->conf->getPath()) . ' ';
     }
     $command .= '-process ';
     if (file_exists($file)) {
         if (is_readable($file)) {
             if ($this->cache) {
                 $lastmtime = $this->cache->get($file);
                 if ($lastmtime >= filemtime($file)) {
                     $this->log("Not linting '" . $file . "' due to cache", Project::MSG_DEBUG);
                     return false;
                 }
             }
             $messages = array();
             exec($command . '"' . $file . '"', $messages, $return);
             if ($return > 100) {
                 throw new BuildException("Could not execute Javascript Lint executable '{$this->executable}'");
             }
             $summary = $messages[sizeof($messages) - 1];
             preg_match('/(\\d+)\\serror/', $summary, $matches);
             $errorCount = count($matches) > 1 ? $matches[1] : 0;
             preg_match('/(\\d+)\\swarning/', $summary, $matches);
             $warningCount = count($matches) > 1 ? $matches[1] : 0;
             $errors = array();
             $warnings = array();
             if ($errorCount > 0 || $warningCount > 0) {
                 $last = false;
                 foreach ($messages as $message) {
                     $matches = array();
                     if (preg_match('/^(\\.*)\\^$/', $message)) {
                         $column = strlen($message);
                         if ($last == 'error') {
                             $errors[count($errors) - 1]['column'] = $column;
                         } else {
                             if ($last == 'warning') {
                                 $warnings[count($warnings) - 1]['column'] = $column;
                             }
                         }
                         $last = false;
                     }
                     if (!preg_match('/^file:(.+);line:(\\d+);message:(.+)$/', $message, $matches)) {
                         continue;
                     }
                     $msg = $matches[3];
                     $data = array('filename' => $matches[1], 'line' => $matches[2], 'message' => $msg);
                     if (preg_match('/^.*error:.+$/i', $msg)) {
                         $errors[] = $data;
                         $last = 'error';
                     } else {
                         if (preg_match('/^.*warning:.+$/i', $msg)) {
                             $warnings[] = $data;
                             $last = 'warning';
                         }
                     }
                 }
             }
             if ($this->showWarnings && $warningCount > 0) {
                 $this->log($file . ': ' . $warningCount . ' warnings detected', Project::MSG_WARN);
                 foreach ($warnings as $warning) {
                     $this->log('- line ' . $warning['line'] . (isset($warning['column']) ? ' column ' . $warning['column'] : '') . ': ' . $warning['message'], Project::MSG_WARN);
                 }
                 $this->hasWarnings = true;
             }
             if ($errorCount > 0) {
                 $this->log($file . ': ' . $errorCount . ' errors detected', Project::MSG_ERR);
                 if (!isset($this->badFiles[$file])) {
                     $this->badFiles[$file] = array();
                 }
                 foreach ($errors as $error) {
                     $message = 'line ' . $error['line'] . (isset($error['column']) ? ' column ' . $error['column'] : '') . ': ' . $error['message'];
                     $this->log('- ' . $message, Project::MSG_ERR);
                     array_push($this->badFiles[$file], $message);
                 }
                 $this->hasErrors = true;
             } else {
                 if (!$this->showWarnings || $warningCount == 0) {
                     $this->log($file . ': No syntax errors detected', Project::MSG_VERBOSE);
                     if ($this->cache) {
                         $this->cache->put($file, filemtime($file));
                     }
                 }
             }
         } else {
             throw new BuildException('Permission denied: ' . $file);
         }
     } else {
         throw new BuildException('File not found: ' . $file);
     }
 }
Ejemplo n.º 10
0
 /**
  * Executes PHPMD against PhingFile or a FileSet
  *
  * @throws BuildException - if the phpmd classes can't be loaded.
  */
 public function main()
 {
     $className = $this->loadDependencies();
     if (!isset($this->file) and count($this->filesets) == 0) {
         throw new BuildException('Missing either a nested fileset or attribute "file" set');
     }
     if (count($this->formatters) == 0) {
         // turn legacy format attribute into formatter
         $fmt = new PHPMDFormatterElement();
         $fmt->setType($this->format);
         $fmt->setUseFile(false);
         $this->formatters[] = $fmt;
     }
     $reportRenderers = array();
     foreach ($this->formatters as $fe) {
         if ($fe->getType() == '') {
             throw new BuildException('Formatter missing required "type" attribute.');
         }
         if ($fe->getUsefile() && $fe->getOutfile() === null) {
             throw new BuildException('Formatter requires "outfile" attribute when "useFile" is true.');
         }
         $reportRenderers[] = $fe->getRenderer();
     }
     if ($this->newVersion && $this->cache) {
         $reportRenderers[] = new PHPMDRendererRemoveFromCache($this->cache);
     } else {
         $this->cache = null;
         // cache not compatible to old version
     }
     // Create a rule set factory
     if ($this->newVersion) {
         $ruleSetClass = '\\PHPMD\\RuleSetFactory';
         $ruleSetFactory = new $ruleSetClass();
         //php 5.2 parser compatibility
     } else {
         if (!class_exists("PHP_PMD_RuleSetFactory")) {
             @(include 'PHP/PMD/RuleSetFactory.php');
         }
         $ruleSetFactory = new PHP_PMD_RuleSetFactory();
     }
     $ruleSetFactory->setMinimumPriority($this->minimumPriority);
     /**
      * @var PHPMD\PHPMD $phpmd
      */
     $phpmd = new $className();
     $phpmd->setFileExtensions($this->allowedFileExtensions);
     $phpmd->setIgnorePattern($this->ignorePatterns);
     $filesToParse = $this->getFilesToParse();
     if (count($filesToParse) > 0) {
         $inputPath = implode(',', $filesToParse);
         $this->log('Processing files...');
         $phpmd->processFiles($inputPath, $this->rulesets, $reportRenderers, $ruleSetFactory);
         if ($this->cache) {
             $this->cache->commit();
         }
         $this->log('Finished processing files');
     } else {
         $this->log('No files to process');
     }
 }
 private static function register_cached_template($hashed_content, $parsed_content)
 {
     self::$parsing_cache->store($hashed_content, $parsed_content);
 }
Ejemplo n.º 12
0
 /**
  * Executes PHP code sniffer against PhingFile or a FileSet
  */
 public function main()
 {
     if (!class_exists('PHP_CodeSniffer')) {
         @(include_once 'PHP/CodeSniffer.php');
         if (!class_exists('PHP_CodeSniffer')) {
             throw new BuildException("This task requires the PHP_CodeSniffer package installed and available on the include path", $this->getLocation());
         }
     }
     /**
      * Determine PHP_CodeSniffer version number
      */
     if (!$this->skipversioncheck) {
         if (defined('PHP_CodeSniffer::VERSION')) {
             preg_match('/\\d\\.\\d\\.\\d/', PHP_CodeSniffer::VERSION, $version);
         } else {
             preg_match('/\\d\\.\\d\\.\\d/', shell_exec('phpcs --version'), $version);
         }
         if (version_compare($version[0], '1.2.2') < 0) {
             throw new BuildException('PhpCodeSnifferTask requires PHP_CodeSniffer version >= 1.2.2', $this->getLocation());
         }
     }
     if (!isset($this->file) and count($this->filesets) == 0) {
         throw new BuildException("Missing either a nested fileset or attribute 'file' set");
     }
     if (count($this->formatters) == 0) {
         // turn legacy format attribute into formatter
         $fmt = new PhpCodeSnifferTask_FormatterElement();
         $fmt->setType($this->format);
         $fmt->setUseFile(false);
         $this->formatters[] = $fmt;
     }
     $fileList = $this->getFilesToParse();
     $cwd = getcwd();
     // Save command line arguments because it confuses PHPCS (version 1.3.0)
     $oldArgs = $_SERVER['argv'];
     $_SERVER['argv'] = array();
     $_SERVER['argc'] = 0;
     include_once 'phing/tasks/ext/phpcs/PhpCodeSnifferTask_Wrapper.php';
     $codeSniffer = new PhpCodeSnifferTask_Wrapper($this->verbosity, $this->tabWidth, $this->encoding);
     $codeSniffer->setAllowedFileExtensions($this->allowedFileExtensions);
     if ($this->allowedTypes) {
         PhpCodeSnifferTask_Wrapper::$allowedTypes = $this->allowedTypes;
     }
     if (is_array($this->ignorePatterns)) {
         $codeSniffer->setIgnorePatterns($this->ignorePatterns);
     }
     foreach ($this->configData as $configData) {
         $codeSniffer->setConfigData($configData->getName(), $configData->getValue(), true);
     }
     /*
      * Verifying if standard is installed only after setting config data.
      * Custom standard paths could be provided via installed_paths config parameter.
      */
     foreach ($this->standards as $standard) {
         if (PHP_CodeSniffer::isInstalledStandard($standard) === false) {
             // They didn't select a valid coding standard, so help them
             // out by letting them know which standards are installed.
             $installedStandards = PHP_CodeSniffer::getInstalledStandards();
             $numStandards = count($installedStandards);
             $errMsg = '';
             if ($numStandards === 0) {
                 $errMsg = 'No coding standards are installed.';
             } else {
                 $lastStandard = array_pop($installedStandards);
                 if ($numStandards === 1) {
                     $errMsg = 'The only coding standard installed is ' . $lastStandard;
                 } else {
                     $standardList = implode(', ', $installedStandards);
                     $standardList .= ' and ' . $lastStandard;
                     $errMsg = 'The installed coding standards are ' . $standardList;
                 }
             }
             throw new BuildException('ERROR: the "' . $standard . '" coding standard is not installed. ' . $errMsg, $this->getLocation());
         }
     }
     if (!$this->showWarnings) {
         $codeSniffer->cli->warningSeverity = 0;
     }
     // nasty integration hack
     $values = $codeSniffer->cli->getDefaults();
     $_SERVER['argv'] = array('t');
     $_SERVER['argc'] = 1;
     foreach ($this->formatters as $fe) {
         $output = $fe->getUseFile() ? $fe->getOutFile() : null;
         $_SERVER['argv'][] = '--report-' . $fe->getType() . '=' . $output;
         $_SERVER['argc']++;
     }
     if ($this->cache) {
         require_once 'phing/tasks/ext/phpcs/Reports_PhingRemoveFromCache.php';
         PHP_CodeSniffer_Reports_PhingRemoveFromCache::setCache($this->cache);
         // add a fake report to remove from cache
         $_SERVER['argv'][] = '--report-phingRemoveFromCache=';
         $_SERVER['argc']++;
     }
     $codeSniffer->process($fileList, $this->standards, $this->sniffs, $this->noSubdirectories);
     $_SERVER['argv'] = array();
     $_SERVER['argc'] = 0;
     if ($this->cache) {
         PHP_CodeSniffer_Reports_PhingRemoveFromCache::setCache(null);
         $this->cache->commit();
     }
     $this->printErrorReport($codeSniffer);
     // generate the documentation
     if ($this->docGenerator !== '' && $this->docFile !== null) {
         ob_start();
         $codeSniffer->generateDocs($this->standards, $this->sniffs, $this->docGenerator);
         $output = ob_get_contents();
         ob_end_clean();
         // write to file
         $outputFile = $this->docFile->getPath();
         $check = file_put_contents($outputFile, $output);
         if (is_bool($check) && !$check) {
             throw new BuildException('Error writing doc to ' . $outputFile);
         }
     } elseif ($this->docGenerator !== '' && $this->docFile === null) {
         $codeSniffer->generateDocs($this->standards, $this->sniffs, $this->docGenerator);
     }
     if ($this->haltonerror && $codeSniffer->reporting->totalErrors > 0) {
         throw new BuildException('phpcodesniffer detected ' . $codeSniffer->reporting->totalErrors . ' error' . ($codeSniffer->reporting->totalErrors > 1 ? 's' : ''));
     }
     if ($this->haltonwarning && $codeSniffer->reporting->totalWarnings > 0) {
         throw new BuildException('phpcodesniffer detected ' . $codeSniffer->reporting->totalWarnings . ' warning' . ($codeSniffer->reporting->totalWarnings > 1 ? 's' : ''));
     }
     $_SERVER['argv'] = $oldArgs;
     $_SERVER['argc'] = count($oldArgs);
     chdir($cwd);
 }
Ejemplo n.º 13
0
 public function testGet()
 {
     $rolesTestData = $this->roles->get()->toArray();
     $this->assertContains(array('id' => '1', 'name' => 'System Administrator'), $rolesTestData);
     $this->assertContains(array('id' => '2', 'name' => 'System Auditor'), $rolesTestData);
     $this->assertContains(array('id' => '3', 'name' => 'Content Author'), $rolesTestData);
     $this->assertContains(array('id' => '4', 'name' => 'Site Member'), $rolesTestData);
     $this->assertEquals(true, is_object($this->roles->get()));
     $this->assertObjectHasAttribute('belongsTo', $this->roles->get());
     $this->assertEquals($this->roles->get('count'), '4');
     $filteredRolesData = array(array('id' => '1', 'name' => 'System Administrator'), array('id' => '2', 'name' => 'System Auditor'));
     $this->assertEquals($filteredRolesData, $this->roles->get('all', array('conditions' => array('id<' => 3)))->toArray());
     $filteredRolesData = array(array('id' => '3', 'name' => 'Content Author'), array('id' => '4', 'name' => 'Site Member'));
     $this->assertEquals($filteredRolesData, $this->roles->get('all', array('conditions' => array('id>' => 2)))->toArray());
     $filteredRolesData = array(array('id' => '3', 'name' => 'Content Author'), array('id' => '4', 'name' => 'Site Member'));
     $this->assertEquals($filteredRolesData, $this->roles->get('all', array('conditions' => array('id>=' => 3)))->toArray());
     $filteredRolesData = array(array('id' => '1', 'name' => 'System Administrator'), array('id' => '2', 'name' => 'System Auditor'), array('id' => '4', 'name' => 'Site Member'));
     $this->assertEquals($filteredRolesData, $this->roles->get('all', array('conditions' => array('id<>' => 3), 'sort' => array('id')))->toArray());
     $filteredRolesData = array(array('id' => '4', 'name' => 'Site Member'), array('id' => '2', 'name' => 'System Auditor'), array('id' => '1', 'name' => 'System Administrator'));
     $this->assertEquals($filteredRolesData, $this->roles->get('all', array('conditions' => array('id<>' => 3), 'sort' => 'id DESC'))->toArray());
     $filteredRolesData = array('id' => '1', 'name' => 'System Administrator');
     $this->assertEquals($filteredRolesData, $this->roles->getJustFirstWithId(1)->toArray());
     $roles = $this->roles->getFirstWithId(1)->toArray();
     $this->assertInternalType('array', $roles['users']);
     $this->assertEquals(3, count($roles['users']));
     $this->assertArrayHasKey('username', $roles['users'][0]);
     $this->assertArrayHasKey('password', $roles['users'][0]);
     $this->assertArrayHasKey('id', $roles['users'][0]);
     $this->assertArrayHasKey('role_id', $roles['users'][0]);
     $this->assertArrayHasKey('is_admin', $roles['users'][0]);
     $roles = $this->roles->getJustAll(array('fields' => array('name')))->toArray();
     $this->assertContains(array('name' => 'System Administrator'), $roles);
     $this->assertContains(array('name' => 'System Auditor'), $roles);
     $this->assertContains(array('name' => 'Content Author'), $roles);
     $this->assertContains(array('name' => 'Site Member'), $roles);
     $roles = $this->roles->getFirstWithId(1, array('fields' => array('id', 'name', 'users.username')))->toArray();
     $this->assertEquals(3, count($roles['users']));
     $this->assertContains(array('username' => 'odadzie'), $roles['users']);
     $this->assertContains(array('username' => 'mwembley'), $roles['users']);
     $this->assertContains(array('username' => 'eabaka'), $roles['users']);
     $roles = $this->roles->getJust2(array('sort' => 'id'))->toArray();
     $this->assertCount(2, $roles);
     $this->assertContains(array('id' => '2', 'name' => 'System Auditor'), $roles);
     $this->assertContains(array('id' => '1', 'name' => 'System Administrator'), $roles);
     $user = $this->users->getFirstWithId(1);
     $this->assertInstanceOf('tests\\modules\\users\\Users', $user);
     $this->assertEquals('odadzie', $user->username);
     $this->assertInstanceOf('tests\\modules\\roles\\Roles', $user->role);
     $user = $user->toArray();
     $this->assertContains(array('name' => 'System Administrator', 'id' => '1'), $user);
     $this->assertContains(array('name' => 'Software Developers', 'id' => '1'), $user);
     $user = $this->users->getFirstWithId(1, array('fields' => array('id', 'username', 'role.name', 'department.name')));
     $this->assertInstanceOf('tests\\modules\\roles\\Roles', $user->role);
     $this->assertInstanceOf('tests\\modules\\departments\\Departments', $user->office);
     $user = $user->toArray();
     $this->assertCount(1, $user['role']);
     $this->assertCount(1, $user['office']);
     $users = $this->users->getWithIsAdmin(null, array('fields' => array('username'), 'sort' => array('id')));
     $filteredUsersData = array(array('username' => 'edonkor'), array('username' => 'rcommey'), array('username' => 'gaddo'), array('username' => 'fforson'), array('username' => 'eabaka'));
     $this->assertEquals($filteredUsersData, $users->toArray());
     $roles = $this->roles->getJustAll(array('conditions' => array('id' => array('1', '2'))));
     $this->assertEquals(array(array('id' => '1', 'name' => 'System Administrator'), array('id' => '2', 'name' => 'System Auditor')), $roles->toArray());
     $roles = $this->roles->getAll(array('fields' => array('id', 'name', 'users.username'), 'conditions' => array('users.username' => 'eabaka'), 'sort' => array('id')));
     $this->assertEquals(array(array('id' => '1', 'name' => 'System Administrator', 'users' => array(array('username' => 'eabaka'))), array('id' => '2', 'name' => 'System Auditor', 'users' => array()), array('id' => '3', 'name' => 'Content Author', 'users' => array()), array('id' => '4', 'name' => 'Site Member', 'users' => array())), $roles->toArray());
     $roles = $this->roles->getJustAll(array('conditions' => array('OR' => array('name' => 'System Administrator', 'id' => '2'))));
     $this->assertEquals(array(array('id' => '1', 'name' => 'System Administrator'), array('id' => '2', 'name' => 'System Auditor')), $roles->toArray());
 }
Ejemplo n.º 14
0
        $response->getBody()->write(json_encode("Missing password"));
        return $response->withStatus(400);
    }
    $dataStore = DataStore::getInstance();
    $user = $dataStore->getUser($email);
    if ($user) {
        $response->getBody()->write(json_encode("User with the same email already exists"));
        return $response->withStatus(400);
    }
    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    $dataStore->createUser($email, $passwordHash, $name, "dutings");
    $user = $dataStore->getUser($email);
    unset($user['password']);
    $response->getBody()->write(json_encode($user));
});
$hasAuthToken = function (Request $request, Response $response, $next) use($app, $settings) {
    $authTokens = $request->getHeader('AUTH_TOKEN');
    if (count($authTokens) === 0) {
        return $response->withStatus(401);
    }
    $authToken = $authTokens[0];
    $dataStore = DataStore::getInstance();
    $token = $dataStore->getAuthToken($authToken);
    if (!$token) {
        return $response->withStatus(401);
    }
    $dataStore->cache["user_id"] = $token['user_id'];
    return $next($request, $response);
};
$app->group("/api", function () use($app, $settings) {
})->add($hasAuthToken);
Ejemplo n.º 15
0
<?php

include 'Services/Twilio.php';
include "config.php";
include "datastore.class.php";
include "functions.php";
$client = new Services_Twilio($accountsid, $authtoken);
$datastore = new DataStore('check_sites');
foreach ($sites as $url => $name) {
    if (!check_site($url)) {
        $datastore->Set($url, 'down', 0);
        $message = "Oops! The site found at {$url} seems to be down!";
        foreach ($people as $number => $person) {
            send_sms($number, $message);
        }
    } else {
        $last = $datastore->Get($url);
        if ($last == 'down') {
            $message = "Yay! The site found at {$url} seems to be back up!";
            foreach ($people as $number => $person) {
                send_sms($number, $message);
            }
        }
        $datastore->Set($url, 'up', 0);
    }
}