Ejemplo n.º 1
0
 public function processAddedEvent(Event $event)
 {
     $logEvent = new \SystemEvent();
     $logEvent->user_id = 0;
     if (\Auth::check()) {
         $logEvent->user_id = \Auth::user()->id;
     }
     if (property_exists($event, 'eventName')) {
         $logEvent->event_name = $event->eventName;
     } else {
         $logEvent->event_name = get_class($event);
     }
     $logEvent->event_data = $event;
     if (isset($_SERVER['REMOTE_ADDR'])) {
         $logEvent->client_ip = $_SERVER['REMOTE_ADDR'];
     } else {
         $logEvent->client_ip = '::1';
     }
     if ($this->getContext()->hasSourceEvent()) {
         $sourceSystemEvent = $this->getContext()->getSourceEvent();
         $logEvent->sourceEvent()->associate($sourceSystemEvent);
     }
     $logEvent->source = 'front';
     if (\Request::is('cms*')) {
         $logEvent->source = 'cms';
     } else {
         if (\Request::is('api')) {
             $logEvent->source = 'api';
         }
     }
     $logEvent->save();
     $this->getContext()->setSourceEvent($logEvent);
 }
 private function executeSystemEvent(SystemEvent $sysevent)
 {
     $this->logger->info("Processing event #" . $sysevent->getId() . " " . $sysevent->getType() . "(" . $sysevent->getParameters() . ")");
     try {
         $sysevent->process();
     } catch (Exception $exception) {
         $sysevent->logException($exception);
     }
     $this->dao->close($sysevent);
     $sysevent->notify();
     $this->logger->info("Processing event #" . $sysevent->getId() . ": done.", Backend::LOG_INFO);
     // Output errors???
 }
Ejemplo n.º 3
0
 public static function logout()
 {
     $username = $GLOBALS['user']->getUsername();
     $GLOBALS['user'] = null;
     unset($GLOBALS['user']);
     session_destroy();
     SystemEvent::raise(SystemEvent::DEBUG, "User logged out. [ID={$username}]", __METHOD__);
     return true;
 }
Ejemplo n.º 4
0
 protected static function _expandStr($str, array &$context = array())
 {
     return preg_replace_callback('/\\$\\{(\\w*)\\}/', function ($matches) use(&$context) {
         if (isset($context['properties'][$matches[1]])) {
             return $context['properties'][$matches[1]];
         } else {
             SystemEvent::raise(SystemEvent::INFO, "Couldn't expand user variable {$matches[0]}, no such property was found. Assumed value '{$matches[1]}'.", __METHOD__);
             return $matches[1];
         }
     }, $str);
 }
Ejemplo n.º 5
0
 private static function _workersDir()
 {
     $result = false;
     $dir = dirname(dirname(dirname(__FILE__))) . '/workers';
     $dir = str_replace(array('\\', '//'), '/', $dir);
     if (is_dir($dir) && is_writable($dir)) {
         $result = $dir;
     } else {
         SystemEvent::raise(SystemEvent::ERROR, " The workers dir is not writable!", __METHOD__);
     }
     return $result;
 }
Ejemplo n.º 6
0
 public function toPhp(array &$context = array())
 {
     if (!$this->isActive()) {
         return '';
     }
     $php = '';
     if (!$this->getFilesets()) {
         SystemEvent::raise(SystemEvent::ERROR, 'No files not set for task Perl syntax.', __METHOD__);
         return false;
     }
     $php .= "\n\$GLOBALS['result']['task'] = 'perlsyntax';\noutput('Starting...');\n";
     if ($this->getFilesets()) {
         $filesets = $this->getFilesets();
         foreach ($filesets as $fileset) {
             $php .= "\n" . $fileset->toPhp($context) . "\n";
             //
             // In the following callback we assume that the fileset returns a
             // directory only *after* all it's content.
             //
             $php .= "\n\$callback = function (\$entry, \$baseDir) {\n  \$ret = true;\n  if (is_file(\$entry)) {\n    \$output = array();\n    exec(\"perl -c \$entry\", \$output, \$ret);\n    if (\$ret > 0) {\n      output('Errors parsing ' . substr(\$entry, strlen(\$baseDir)) . '.');\n      \$ret = false;\n    } else {\n      output('No syntax errors detected in ' . substr(\$entry, strlen(\$baseDir)) . '.');\n      \$ret = true;\n    }\n  }\n  return \$ret;\n};\nif (!fileset{$fileset->getId()}_{$context['id']}(\$callback) && {$this->getFailOnError()}) {\n  output('Failed.');\n  \$GLOBALS['result']['ok'] = false;\n  return false;\n} else {\n  \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n  output('Done.');\n}\n";
         }
     }
     return $php;
 }
Ejemplo n.º 7
0
 public function toPhp(array &$context = array())
 {
     $php = '';
     //
     // Generic class to process the includes/excludes filters
     //
     //TODO: Implement $isCaseSensitive!!!!
     //TODO: Implement only a single top level class for this
     $php = "\nif (!class_exists('FilesetFilterIterator', false)) {\n  class FilesetFilterIterator extends FilterIterator\n  {\n    private \$_filesetId;\n    private \$_type;\n\n    public function __construct(\$o, \$filesetId, \$type = " . Build_BuilderElement_Type_Fileset::FILE . ")\n    {\n      \$this->_filesetId = \$filesetId;\n      \$this->_type = \$type;\n      parent::__construct(\$o);\n    }\n\n    public function accept()\n    {\n      // Check for type, first of all\n      if (\$this->_type == " . Build_BuilderElement_Type_Fileset::FILE . " && !is_file(\$this->current()) ||\n      \t\t\$this->_type == " . Build_BuilderElement_Type_Fileset::DIR . " && !is_dir(\$this->current()))\n      {\n        return false;\n      }\n\n      // if it is default excluded promptly return false\n      foreach (\$GLOBALS['filesets'][\$this->_filesetId]['defaultExcludes'] as \$exclude) {\n        if (\$this->_isMatch(\$exclude)) {\n          return false;\n        }\n      }\n      // if it is excluded promptly return false\n      foreach (\$GLOBALS['filesets'][\$this->_filesetId]['exclude'] as \$exclude) {\n        if (\$this->_isMatch(\$exclude)) {\n          return false;\n        }\n      }\n      // if it is included promptly return true\n      foreach (\$GLOBALS['filesets'][\$this->_filesetId]['include'] as \$include) {\n        if (\$this->_isMatch(\$include)) {\n          return true;\n        }\n      }\n    }\n\n    private function _isMatch(\$pattern)\n    {\n      \$current = \$this->current();\n      \$dir = \$GLOBALS['filesets'][\$this->_filesetId]['dir'];\n      /*if (substr(\$dir, -1) != DIRECTORY_SEPARATOR) {\n        \$dir .= DIRECTORY_SEPARATOR;\n      }\n      \$current = \$dir . \$current;*/\n      \$isCaseSensitive = true;\n      \$rePattern = preg_quote(\$GLOBALS['filesets'][\$this->_filesetId]['dir'] . \$pattern, '/');\n      \$dirSep = preg_quote(DIRECTORY_SEPARATOR, '/');\n      \$patternReplacements = array(\n        \$dirSep.'\\*\\*' => '\\/?.*',\n        '\\*\\*'.\$dirSep => '.*',\n        '\\*\\*' => '.*',\n        '\\*' => '[^'.\$dirSep.']*',\n        '\\?' => '[^'.\$dirSep.']'\n      );\n      \$rePattern = str_replace(array_keys(\$patternReplacements), array_values(\$patternReplacements), \$rePattern);\n      \$rePattern = '/^'.\$rePattern.'\$/'.(\$isCaseSensitive ? '' : 'i');\n      return (bool) preg_match(\$rePattern, \$current);\n    }\n  }\n}\n";
     if (!$this->getDir()) {
         SystemEvent::raise(SystemEvent::ERROR, 'Root dir not set for type fileset.', __METHOD__);
         return false;
     }
     $php .= "\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}'] = array();\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['dir'] = '';\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['defaultExcludes'] = array(\n  '**/*~',\n  '**/#*#',\n  '**/.#*',\n  '**/%*%',\n  '**/._*',\n  '**/CVS',\n  '**/CVS/**',\n  '**/.cvsignore',\n  '**/SCCS',\n  '**/SCCS/**',\n  '**/vssver.scc',\n  '**/.svn',\n  '**/.svn/**',\n  '**/.DS_Store',\n  '**/.git',\n  '**/.git/**',\n  '**/.gitattributes',\n  '**/.gitignore',\n  '**/.gitmodules',\n  '**/.hg',\n  '**/.hg/**',\n  '**/.hgignore',\n  '**/.hgsub',\n  '**/.hgsubstate',\n  '**/.hgtags',\n  '**/.bzr',\n  '**/.bzr/**',\n  '**/.bzrignore',\n);\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['exclude'] = array();\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['include'] = array();\n";
     if ($this->getDir()) {
         $php .= "\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['dir'] = expandStr('{$this->getDir()}');\n";
     }
     if ($this->getDefaultExcludes() === false) {
         $php .= "\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['defaultExcludes'] = array();\n";
     }
     if ($this->getInclude()) {
         $includes = $this->getInclude();
         foreach ($includes as $include) {
             $php .= "\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['include'][] = expandStr('{$include}');\n";
         }
     }
     if ($this->getExclude()) {
         $excludes = $this->getExclude();
         foreach ($excludes as $exclude) {
             $php .= "\n\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['exclude'][] = expandStr('{$exclude}');\n";
         }
     }
     $php .= "\nif (!function_exists('fileset{$this->getId()}_{$context['id']}')) {\n  function fileset{$this->getId()}_{$context['id']}(\$callback)\n  {\n    \$recursiveIt = false;\n    \$dirIt = 'DirectoryIterator';\n    \$itIt = 'IteratorIterator';\n    foreach (\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['include'] as \$include) {\n      /*if (strpos(\$include, '**') !== false ||\n         (substr_count(\$include, '/') > 1 && substr_count(\$include, '//') === 0) ||\n          substr_count(\$include, '/') == 1 && strpos(\$include, '/') !== 0)\n      {*/\n        \$recursiveIt = true;\n        \$dirIt = 'Recursive' . \$dirIt;\n        \$itIt = 'Recursive' . \$itIt;\n        break;\n      /*}*/\n    }\n    try {\n      foreach (new FilesetFilterIterator(new \$itIt(new \$dirIt(\$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['dir']), (!\$recursiveIt?:" . (!empty($context['iteratorMode']) ?: "\$itIt::CHILD_FIRST") . "), (!\$recursiveIt?:\$itIt::CATCH_GET_CHILD)), '{$this->getId()}_{$context['id']}', {$this->getType()}) as \$entry) {\n        if (!\$callback(\$entry, \$GLOBALS['filesets']['{$this->getId()}_{$context['id']}']['dir'])) {\n          //\$GLOBALS['result']['ok'] = false; // This should be relegated to the caller task\n          \$msg = 'Callback applied to fileset returned false [CALLBACK=\$callback] [FILESET={$this->getId()}_{$context['id']}]';\n          \$GLOBALS['result']['output'] = \$msg;\n          //output(\$msg);\n          return false;\n        }\n      }\n    } catch (UnexpectedValueException \$e) { // Typical permission denied\n      //\$GLOBALS['result']['ok'] = false; // This should be relegated to the caller task\n      \$GLOBALS['result']['output'] = \$e->getMessage();\n      output(\$e->getMessage());\n      return false;\n    }\n    return true;\n  }\n}\n";
     return $php;
 }
Ejemplo n.º 8
0
 public static function redirectToUri($url)
 {
     SystemEvent::raise(SystemEvent::DEBUG, "Redirecting from [URI={$GLOBALS['uri']}] to [URL={$url}]");
     header('Location: ' . $url);
     exit;
 }
 /**
  * Filter the query by a related SystemEvent object
  *
  * @param   SystemEvent|PropelObjectCollection $systemEvent The related object(s) to use as filter
  * @param     string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
  *
  * @return   SystemEventInstanceQuery The current query, for fluid interface
  * @throws   PropelException - if the provided filter is invalid.
  */
 public function filterBySystemEvent($systemEvent, $comparison = null)
 {
     if ($systemEvent instanceof SystemEvent) {
         return $this->addUsingAlias(SystemEventInstancePeer::SYSTEM_EVENT_ID, $systemEvent->getId(), $comparison);
     } elseif ($systemEvent instanceof PropelObjectCollection) {
         if (null === $comparison) {
             $comparison = Criteria::IN;
         }
         return $this->addUsingAlias(SystemEventInstancePeer::SYSTEM_EVENT_ID, $systemEvent->toKeyValue('PrimaryKey', 'Id'), $comparison);
     } else {
         throw new PropelException('filterBySystemEvent() only accepts arguments of type SystemEvent or PropelCollection');
     }
 }
Ejemplo n.º 10
0
// Ajax related
//
if (!empty($GLOBALS['section'])) {
    $GLOBALS['ajaxMethod'] = $GLOBALS['subSection'];
    if (strpos($GLOBALS['subSection'], '-') !== false) {
        $subSectionPieces = explode('-', $GLOBALS['subSection']);
        array_walk($subSectionPieces, function (&$value) {
            $value = ucfirst($value);
        });
        $GLOBALS['ajaxMethod'] = lcfirst(implode($subSectionPieces));
    }
    if ($GLOBALS['section'] != 'default') {
        $GLOBALS['ajaxMethod'] = $GLOBALS['section'] . '_' . $GLOBALS['ajaxMethod'];
    }
    if (method_exists('AjaxManager', $GLOBALS['ajaxMethod'])) {
        #if DEBUG
        SystemEvent::raise(SystemEvent::DEBUG, "Routing to known ajax function. [FUNCTION=AjaxManager::{$GLOBALS['ajaxMethod']}] [URI={$GLOBALS['uri']}]", "ajaxHandler");
        #endif
        AjaxManager::$GLOBALS['ajaxMethod']();
        exit;
    }
    #if DEBUG
    SystemEvent::raise(SystemEvent::DEBUG, "Unknown ajax function. [FUNCTION=AjaxManager::{$GLOBALS['ajaxMethod']}] [URI={$GLOBALS['uri']}]", "ajaxHandler");
    #endif
}
/* +----------------------------------------------------------------+ *\
|* | RESTAURANT AT THE END OF THE UNIVERSE                          | *|
\* +----------------------------------------------------------------+ */
SystemEvent::raise(SystemEvent::INFO, "Not found. [URI={$GLOBALS['uri']}] [USER=" . ($GLOBALS['user'] instanceof User ? $GLOBALS['user']->getUsername() : 'N/A') . ']');
// TODO: send error here
exit;
Ejemplo n.º 11
0
 *  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 Cintient. If not, see <http://www.gnu.org/licenses/>.
 *
 */
// TODO: centralize the initalization stuff that is common to web, ajax
// and builder handlers. (this builder could be called by a crontab)
require_once dirname(__FILE__) . '/../config/cintient.conf.php';
SystemEvent::setSeverityLevel(CINTIENT_LOG_SEVERITY);
$GLOBALS['settings'] = SystemSettings::load();
// Pull up system settings
// Temporarily disable the background build handler in Windows, while
// binaries aren't being dealt with in the installer.
if (Framework_HostOs::isWindows()) {
    SystemEvent::raise(SystemEvent::INFO, "Background builds are temporarily disabled in Windows.", 'buildHandler');
    return false;
}
$buildProcess = new Framework_Process($GLOBALS['settings'][SystemSettings::EXECUTABLE_PHP]);
$buildProcess->addArg(CINTIENT_INSTALL_DIR . 'src/workers/runBuildWorker.php');
if (!$buildProcess->isRunning()) {
    if (!$buildProcess->run(true)) {
        SystemEvent::raise(SystemEvent::ERROR, "Problems starting up build worker.", 'buildHandler');
    } else {
        SystemEvent::raise(SystemEvent::INFO, "Build worker left running in the background.", 'buildHandler');
    }
} else {
    SystemEvent::raise(SystemEvent::DEBUG, "Build process already running.", 'buildHandler');
}
#endif
Ejemplo n.º 12
0
 public function toPhp(array &$context = array())
 {
     if (!$this->isActive()) {
         return true;
     }
     $php = '';
     if (!$this->getExecutable()) {
         SystemEvent::raise(SystemEvent::ERROR, 'Executable not set for exec task.', __METHOD__);
         return false;
     }
     $php .= "\n\$GLOBALS['result']['task'] = 'exec';\n\$getBaseDir = '';\n";
     if ($this->getBaseDir()) {
         $php .= "\n\$getBaseDir = \"cd \" . expandStr('{$this->getBaseDir()}') . \"; \";\n";
     }
     $php .= "\n\$args = '';\n";
     if ($this->getArgs()) {
         $php .= "\n\$getArgs = expandStr(' {$this->getArgs()}');\n";
     }
     $php .= "\n\$getExecutable = expandStr('{$this->getExecutable()}');\n\$GLOBALS['result']['task'] = 'exec';\noutput(\"Executing '\$getBaseDir\$getExecutable\$getArgs'.\");\n\$ret = exec(\"\$getBaseDir\$getExecutable\$getArgs\", \$lines, \$retval);\nforeach (\$lines as \$line) {\n  output(\$line);\n}\n";
     if ($this->getOutputProperty()) {
         $php .= "\n\$GLOBALS['properties']['{$this->getOutputProperty()}_{$context['id']}'] = \$ret;\n";
     }
     $php .= "\nif (\$retval > 0) {\n  output('Failed.');\n  if ({$this->getFailOnError()}) {\n    \$GLOBALS['result']['ok'] = false;\n    return false;\n  } else {\n    \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n  }\n} else {\n  \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n  output('Success.');\n}\n";
     //TODO: bullet proof this for boolean falses (they're not showing up)
     /*
         $php .= "if ({$this->getFailOnError()} && !\$ret) {
       \$GLOBALS['result']['ok'] = false;
       return false;
     }
     \$GLOBALS['result']['ok'] = true;
     return true;
     ";*/
     return $php;
 }
Ejemplo n.º 13
0
    public function toPhp(array &$context = array())
    {
        if (!$this->isActive()) {
            return '';
        }
        $php = '';
        if (!$this->getMessage()) {
            SystemEvent::raise(SystemEvent::ERROR, 'Message not set for echo task.', __METHOD__);
            return false;
        }
        $php .= "\n\$GLOBALS['result']['task'] = 'echo';\n";
        $msg = addslashes($this->getMessage());
        $php .= "\n\$getMessage = expandStr('{$msg}');\n";
        if ($this->getFile()) {
            $append = 'w';
            // the same as append == false (default for Ant and Phing)
            if ($this->getAppend()) {
                $append = 'a';
            }
            $php .= <<<EOT
\$getFile = expandStr('{$this->getFile()}');
if (!(\$fp = @fopen(\$getFile, '{$append}'))) {
  output("Couldn't open file \$getFile for output.");
  if ({$this->getFailOnError()}) {
    \$GLOBALS['result']['ok'] = false;
    return false;
  } else {
    \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;
  }
}
\$res = (fwrite(\$fp, \$getMessage) === false ?:true);
fclose(\$fp);
if (!\$res) {
  output("Couldn't write message to file.");
  if ({$this->getFailOnError()}) {
    \$GLOBALS['result']['ok'] = false;
    return false;
  } else {
    \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;
  }
} else {
  \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;
}
EOT;
        } else {
            $php .= <<<EOT
\$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;
output(\$getMessage);
EOT;
        }
        return $php;
    }
Ejemplo n.º 14
0
    public function toPhp(array &$context = array())
    {
        if (!$this->isActive()) {
            return '';
        }
        $php = '';
        if (!$this->getName() || !$this->getValue()) {
            SystemEvent::raise(SystemEvent::ERROR, 'Name and value not set for type property.', __METHOD__);
            return false;
        }
        $context['properties'][self::_expandStr($this->getName(), $context)] = self::_expandStr($this->getValue(), $context);
        $php .= <<<EOT
\$GLOBALS['properties'][expandStr('{$this->getName()}') . '_{$context['id']}'] = expandStr('{$this->getValue()}');
\$GLOBALS['result']['ok'] = (\$GLOBALS['result']['ok'] & true);
EOT;
        return $php;
    }
Ejemplo n.º 15
0
 public static function setSeverityLevel($severityLevel = self::DEBUG)
 {
     self::$severityLevel = (int) $severityLevel;
 }
Ejemplo n.º 16
0
        array_walk($subSectionPieces, function (&$value) {
            $value = ucfirst($value);
        });
        $GLOBALS['templateMethod'] = lcfirst(implode($subSectionPieces));
    }
    if ($GLOBALS['section'] != 'default') {
        $GLOBALS['templateFile'] = $GLOBALS['section'] . '/' . $GLOBALS['subSection'] . '.tpl';
        $GLOBALS['templateMethod'] = $GLOBALS['section'] . '_' . $GLOBALS['templateMethod'];
    }
    if (method_exists('TemplateManager', $GLOBALS['templateMethod'])) {
        #if DEBUG
        SystemEvent::raise(SystemEvent::DEBUG, "Routing to known template function. [FUNCTION=TemplateManager::{$GLOBALS['templateMethod']}] [URI={$GLOBALS['uri']}]", __METHOD__);
        #endif
        TemplateManager::$GLOBALS['templateMethod']();
        $GLOBALS['smarty']->assign('globals_settings', $GLOBALS['settings']);
        $GLOBALS['smarty']->assign('globals_section', $GLOBALS['section']);
        $GLOBALS['smarty']->assign('globals_subSection', $GLOBALS['subSection']);
        $GLOBALS['smarty']->assign('globals_user', $GLOBALS['user']);
        $GLOBALS['smarty']->assign('globals_project', $GLOBALS['project']);
        ob_end_clean();
        $GLOBALS['smarty']->display($GLOBALS['templateFile']);
        exit;
    }
    #if DEBUG
    SystemEvent::raise(SystemEvent::DEBUG, "Unknown template function. [FUNCTION=TemplateManager::{$GLOBALS['templateMethod']}] [URI={$GLOBALS['uri']}]", __METHOD__);
    #endif
}
/* +----------------------------------------------------------------+ *\
|* | RESTAURANT AT THE END OF THE UNIVERSE                          | *|
\* +----------------------------------------------------------------+ */
Redirector::redirectAndExit(Redirector::NOT_FOUND);
Ejemplo n.º 17
0
 public function toPhp(array &$context = array())
 {
     if (!$this->isActive()) {
         return '';
     }
     $php = '';
     if (!$this->getFiles()) {
         SystemEvent::raise(SystemEvent::ERROR, 'No files/dirs not set for task PHPCodeSniffer.', __METHOD__);
         return false;
     }
     if (!$this->getStandard()) {
         SystemEvent::raise(SystemEvent::ERROR, 'No standard defined for task PHPCodeSniffer.', __METHOD__);
         return false;
     }
     $php .= "\n\$GLOBALS['result']['task'] = 'phpcodesniffer';\n// To avoid the 'PHP Notice:  Undefined index: argc' that happens when\n// manually triggering a build\nif (!isset(\$_SERVER['argc'])) {\n  \$_SERVER['argc'] = 1;\n}\n\$getFailOnError = " . (int) $this->getFailOnError() . ";\nrequire_once '" . CINTIENT_PHPCODESNIFFER_INCLUDE_FILE . "';\n\$getFileExtensions = expandStr('{$this->getFileExtensions()}');\n\$getFiles = expandStr('{$this->getFiles()}');\n\$getSniffs = expandStr('{$this->getSniffs()}');\n\$phpcs = new PHP_CodeSniffer_CLI();\n\$values = \$phpcs->getDefaults();\n\$values['extensions'] = (empty(\$getFileExtensions)?array():explode(' ', \$getFileExtensions));\n\$values['files'] = (empty(\$getFiles)?array():explode(' ', \$getFiles));\n\$values['reports']['xml'] = '{$this->getReportXmlFile()}';\n\$values['reports']['full'] = '{$this->getReportFullFile()}';\n\$values['reports']['source'] = null; // null means cout it, instead of file\n\$values['sniffs'] = (empty(\$getSniffs)?array():explode(' ', \$getSniffs));\n\$values['standard'] = expandStr('{$this->getStandard()}');\n\$values['reportWidth'] = 110;\nob_start();\n\$numErrors = \$phpcs->process(\$values);\noutput(ob_get_contents());\nob_end_clean();\n// Try to clean up as much as we can\n\$phpcs = null;\nunset(\$phpcs);\nif (\$numErrors === 0) {\n  output(\"No code violations found. All code respects the '{\$values['standard']}' standard.\");\n  \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n} else {\n  output(\"Total of \$numErrors violation(s) found.\");\n  if (\$getFailOnError) {\n    \$GLOBALS['result']['ok'] = false;\n\t  return false;\n  } else {\n\t  \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n\t}\n}\n";
     return $php;
 }
Ejemplo n.º 18
0
    public function toPhp(array &$context = array())
    {
        if (!$this->isActive()) {
            return '';
        }
        $php = '';
        if (!$this->getText()) {
            SystemEvent::raise(SystemEvent::ERROR, 'Empty properties text.', __METHOD__);
            return false;
        }
        $properties = parse_ini_string($this->getText());
        foreach ($properties as $key => $value) {
            $context['properties'][self::_expandStr($key, $context)] = self::_expandStr($value, $context);
            $php .= <<<EOT
\$GLOBALS['properties'][expandStr('{$key}') . '_{$context['id']}'] = expandStr('{$value}');
EOT;
        }
        return $php;
    }
Ejemplo n.º 19
0
 public function toPhp(array &$context = array())
 {
     if (!$this->isActive()) {
         return '';
     }
     $php = '';
     $getFailedOnError = $this->getFailOnError() ? "true" : "false";
     if (!$this->getIncludeDirs()) {
         SystemEvent::raise(SystemEvent::ERROR, 'No include dirs set for task PhpDepend.', __METHOD__);
         return false;
     }
     $php .= "\n\$GLOBALS['result']['task'] = 'phpdepend';\n\$_SERVER['argv'] = array('dummyfirstentry');\n";
     if ($this->getJdependChartFile()) {
         $php .= "\n\$_SERVER['argv'][] = expandStr('--jdepend-chart={$this->getJdependChartFile()}');\n";
     }
     if ($this->getOverviewPyramidFile()) {
         $php .= "\n\$_SERVER['argv'][] = expandStr('--overview-pyramid={$this->getOverviewPyramidFile()}');\n";
     }
     if ($this->getSummaryFile()) {
         $php .= "\n\$_SERVER['argv'][] = expandStr('--summary-xml={$this->getSummaryFile()}');\n";
     }
     if ($this->getExcludeDirs()) {
         $php .= "\n\$_SERVER['argv'][] = expandStr('--ignore=" . str_replace(' ', ',', trim($this->getExcludeDirs())) . "');\n";
     }
     if ($this->getExcludePackages()) {
         $php .= "\n\$_SERVER['argv'][] = expandStr('--exclude=" . str_replace(' ', ',', trim($this->getExcludePackages())) . "');\n";
     }
     // Cintient's space separated to PHP_Depend's comma separated
     $php .= "\n\$_SERVER['argv'][] = expandStr('" . str_replace(' ', ',', trim($this->getIncludeDirs())) . "');\n";
     $php .= "\n// To avoid the 'PHP Notice:  Undefined index: argc' that happens when\n// manually triggering a build\n\$_SERVER['argc'] = count(\$_SERVER['argv']);\nrequire_once 'PHP/Depend/Autoload.php';\n\$autoload = new PHP_Depend_Autoload();\n\$autoload->register();\nPHP_Depend_Util_Log::setSeverity(-1); // to set PHP_Depend debug to false\nob_start();\n\$ret = PHP_Depend_TextUI_Command::main();\noutput(ob_get_contents());\nob_end_clean();\nunset(\$_SERVER['argv']);\nunset(\$_SERVER['argc']);\nif (\$ret > 0) {\n  output('PHP_Depend analysis failed.');\n  \$GLOBALS['result']['ok'] = false;\n  if (" . $getFailedOnError . ") {\n    return false;\n  }\n} else {\n  output('PHP_Depend analysis successful.');\n\t\$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n}\n";
     return $php;
 }
Ejemplo n.º 20
0
 public function itProperlyEncodesAndDecodesData()
 {
     $data = array('coin' => 'String that contains :: (the param separator)');
     $this->assertEqual($data, SystemEvent::decode(SystemEvent::encode($data)));
 }
Ejemplo n.º 21
0
 public static function uninstall(Project $project)
 {
     $sql = "DROP TABLE projectlog{$project->getId()}";
     if (!Database::execute($sql)) {
         SystemEvent::raise(SystemEvent::ERROR, "Couldn't delete project log table. [TABLE={$project->getId()}]", __METHOD__);
         return false;
     }
     return true;
 }
Ejemplo n.º 22
0
 public function toPhp(array &$context = array())
 {
     if (!$this->isActive()) {
         return '';
     }
     $php = '';
     if (!$this->getFile() && !$this->getFilesets()) {
         SystemEvent::raise(SystemEvent::ERROR, 'No files not set for task chmod.', __METHOD__);
         return false;
     }
     $mode = $this->getMode();
     if (empty($mode) || !preg_match('/^(?:\\d{3}|\\$\\{\\w*\\})$/', $mode)) {
         // It must be a 3 digit decimal or a property
         SystemEvent::raise(SystemEvent::ERROR, 'No mode set for chmod.', __METHOD__);
         return false;
     }
     $php .= "\n\$GLOBALS['result']['task'] = 'chmod';\n\$callback = function (\$entry) {\n  \$getModeInt = expandStr('{$this->getMode()}');\n  \$getModeOctal = intval(\$getModeInt, 8); // Casts the decimal string representation into an octal (8 is for base 8 conversion)\n  \$ret = @chmod(\$entry, \$getModeOctal);\n  if (!\$ret) {\n    output(\"Failed setting \$getModeInt on \$entry.\");\n  } else {\n    output(\"Ok setting \$getModeInt on \$entry.\");\n  }\n  return \$ret;\n};";
     if ($this->getFile()) {
         $php .= "\n\$getFile = expandStr('{$this->getFile()}');\nif (!\$callback(\$getFile) && {$this->getFailOnError()}) { // failonerror\n  \$GLOBALS['result']['ok'] = false;\n  return false;\n} else {\n  \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n}\n";
     } elseif ($this->getFilesets()) {
         // If file exists, it takes precedence over filesets
         $filesets = $this->getFilesets();
         foreach ($filesets as $fileset) {
             $php .= "\n" . $fileset->toPhp($context) . "\nif (!fileset{$fileset->getId()}_{$context['id']}(\$callback) && {$this->getFailOnError()}) {\n  \$GLOBALS['result']['ok'] = false;\n  return false;\n} else {\n  \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n}\n";
         }
     }
     return $php;
 }
Ejemplo n.º 23
0
    public static function install()
    {
        SystemEvent::raise(SystemEvent::INFO, "Creating systemsettings table...", __METHOD__);
        $tableName = 'systemsettings';
        $sql = <<<EOT
DROP TABLE IF EXISTS {$tableName}NEW;
CREATE TABLE IF NOT EXISTS {$tableName}NEW(
  key VARCHAR(255) PRIMARY KEY,
  value TEXT NOT NULL DEFAULT ''
);
EOT;
        if (!Database::setupTable($tableName, $sql)) {
            SystemEvent::raise(SystemEvent::ERROR, "Problems setting up {$tableName} table.", __METHOD__);
            return false;
        }
        $self = new SystemSettings();
        $self->_save(true);
        // This allows us to save the default system settings values at install time.
        SystemEvent::raise(SystemEvent::INFO, "{$tableName} table created.", __METHOD__);
        return true;
    }
Ejemplo n.º 24
0
 public static function project_history()
 {
     if (!isset($GLOBALS['project']) || !$GLOBALS['project'] instanceof Project) {
         SystemEvent::raise(SystemEvent::ERROR, "Problems fetching requested project.", __METHOD__);
         //
         // TODO: Notification
         //
         //
         // TODO: this should really be a redirect to the previous page.
         //
         return false;
     }
     //
     // Viewing project build details
     //
     $build = null;
     // It's possible that no build was triggered yet.
     if (isset($_GET['bid']) && !empty($_GET['bid'])) {
         $build = Project_Build::getById($_GET['bid'], $GLOBALS['project'], $GLOBALS['user']);
     } else {
         $build = Project_Build::getLatest($GLOBALS['project'], $GLOBALS['user']);
     }
     //
     // TODO: don't let user access the build history of a still unfinished build!
     //
     if ($build instanceof Project_Build) {
         //
         // Special tasks. This is post build, so we're fetching an existing special task (never creating it)
         //
         $specialTasks = $build->getSpecialTasks();
         $GLOBALS['smarty']->assign('project_specialTasks', $specialTasks);
         if (!empty($specialTasks)) {
             foreach ($specialTasks as $task) {
                 if (!class_exists($task)) {
                     SystemEvent::raise(SystemEvent::ERROR, "Unexisting special task. [PID={$GLOBALS['project']->getId()}] [BUILD={$build->getId()}] [TASK={$task}]", __METHOD__);
                     continue;
                 }
                 $o = $task::getById($build, $GLOBALS['user'], Access::READ);
                 //$GLOBALS['smarty']->assign($task, $o); // Register for s
                 if (!$o instanceof Build_SpecialTaskInterface) {
                     SystemEvent::raise(SystemEvent::ERROR, "Unexisting special task ID. [PID={$GLOBALS['project']->getId()}] [BUILD={$build->getId()}] [TASK={$task}] [TASKID={$build->getId()}]", __METHOD__);
                     continue;
                 }
                 $viewData = $o->getViewData();
                 if (is_array($viewData)) {
                     foreach ($viewData as $key => $value) {
                         $GLOBALS['smarty']->assign($key, $value);
                     }
                 }
                 $o = null;
                 unset($o);
             }
         }
     }
     // Last assignments
     $GLOBALS['smarty']->assign('project_buildList', Project_Build::getList($GLOBALS['project'], $GLOBALS['user']));
     $GLOBALS['smarty']->assign('project_build', $build);
 }
Ejemplo n.º 25
0
 public function update(&$rev)
 {
     if (!$this->_connector->update($rev)) {
         SystemEvent::raise(SystemEvent::INFO, "Could not update local working copy, trying a few tricks before quiting. [DIR={$this->_connector->getLocal()}]", __METHOD__);
         if (!is_writable($this->_connector->getLocal()) && !@mkdir($this->_connector->getLocal(), DEFAULT_DIR_MASK, true)) {
             SystemEvent::raise(SystemEvent::INFO, "Could not update local working copy, dir was either not writable or didn't exist. [DIR={$this->_connector->getLocal()}]", __METHOD__);
             return false;
         }
         if (!$this->checkout()) {
             SystemEvent::raise(SystemEvent::INFO, "Could not update local working copy, trying 'checking out' the sources again, but couldn't. [DIR={$this->_connector->getLocal()}]", __METHOD__);
             return false;
         }
         if (!$this->_connector->update($rev)) {
             SystemEvent::raise(SystemEvent::INFO, "Definitely could not update local working copy. [DIR={$this->_connector->getLocal()}]", __METHOD__);
             return false;
         }
     }
     SystemEvent::raise(SystemEvent::DEBUG, "Updated local working copy. [DIR={$this->_connector->getLocal()}]", __METHOD__);
     return true;
 }
Ejemplo n.º 26
0
 /**
  * Adds an object to the instance pool.
  *
  * Propel keeps cached copies of objects in an instance pool when they are retrieved
  * from the database.  In some cases -- especially when you override doSelect*()
  * methods in your stub classes -- you may need to explicitly add objects
  * to the cache in order to ensure that the same objects are always returned by doSelect*()
  * and retrieveByPK*() calls.
  *
  * @param      SystemEvent $obj A SystemEvent object.
  * @param      string $key (optional) key to use for instance map (for performance boost if key was already calculated externally).
  */
 public static function addInstanceToPool($obj, $key = null)
 {
     if (Propel::isInstancePoolingEnabled()) {
         if ($key === null) {
             $key = (string) $obj->getId();
         }
         // if key === null
         self::$instances[$key] = $obj;
     }
 }
Ejemplo n.º 27
0
 /**
  * Declares an association between this object and a SystemEvent object.
  *
  * @param                  SystemEvent $v
  * @return                 SystemEventInstance The current object (for fluent API support)
  * @throws PropelException
  */
 public function setSystemEvent(SystemEvent $v = null)
 {
     if ($v === null) {
         $this->setSystemEventId(NULL);
     } else {
         $this->setSystemEventId($v->getId());
     }
     $this->aSystemEvent = $v;
     // Add binding for other direction of this n:n relationship.
     // If this object has already been added to the SystemEvent object, it will not be re-added.
     if ($v !== null) {
         $v->addSystemEventInstance($this);
     }
     return $this;
 }
Ejemplo n.º 28
0
 /**
  *
  * Enter description here ...
  * @param unknown_type $dir
  */
 public static function emptyDir($dir)
 {
     $ret = true;
     $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
     foreach ($iterator as $path) {
         if ($path->isDir() && !$path->isLink()) {
             if ($res = @rmdir($path->getPathName())) {
                 SystemEvent::raise(SystemEvent::DEBUG, "Removed dir {$path->getPathName()}", __METHOD__);
             } else {
                 SystemEvent::raise(SystemEvent::ERROR, "Couldn't remove dir {$path->getPathName()}", __METHOD__);
             }
             $ret = $ret & $res;
         } else {
             if ($res = @unlink($path->getPathName())) {
                 SystemEvent::raise(SystemEvent::DEBUG, "Removed file {$path->getPathName()}", __METHOD__);
             } else {
                 SystemEvent::raise(SystemEvent::ERROR, "Couldn't remove file {$path->getPathName()}", __METHOD__);
             }
             $ret = $ret & $res;
         }
     }
     return $ret;
 }
Ejemplo n.º 29
0
 public function toPhp(array &$context = array())
 {
     if (!$this->isActive()) {
         return '';
     }
     $php = '';
     if (!$this->getFile() && !$this->getFilesets()) {
         SystemEvent::raise(SystemEvent::ERROR, 'No source files set for task copy.', __METHOD__);
         return false;
     }
     if (!$this->getToFile() && !$this->getToDir()) {
         SystemEvent::raise(SystemEvent::ERROR, 'No destination set for task copy.', __METHOD__);
         return false;
     }
     $php .= "\n\$GLOBALS['result']['task'] = 'copy';\n\$baseToFilename = '';\n";
     if ($this->getToFile()) {
         $php .= "\n\$path = pathinfo(expandStr('{$this->getToFile()}'));\n\$baseToDir = \$path['dirname'];\n\$baseToFilename = '/' . \$path['basename']; // pathinfo's dirname *always* returns the dirname without the trailing slash.\n";
     } elseif ($this->getToDir()) {
         $php .= "\n\$baseToDir = expandStr('{$this->getToDir()}');\n";
     }
     //
     // TODO: Potential bug here. If the following generated mkdir does
     // indeed fail and failOnError == true, the execution will continue
     // because we are not returning true... A return true here would
     // halt the generated script execution (that's what return false does
     // in case of error...)
     //
     // Wrapping this whole element into a generated auto-executing closure
     // a la Javascript would be awesome, because that way we could just
     // force a return and not risk shutting down the whole builder script
     //
     $php .= "\nif (!file_exists(\$baseToDir) && !@mkdir(\$baseToDir, 0755, true)) {\n  output(\"Failed creating dir \$baseToDir.\");\n\tif ({$this->getFailOnError()}) {\n    \$GLOBALS['result']['ok'] = false;\n    return false;\n  } else {\n\t  \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n  }\n}";
     //
     // Internally treat $this->getFile() as a fileset.
     //
     $filesets = array();
     if ($this->getFile()) {
         $getFile = self::_expandStr($this->getFile(), $context);
         $pathFrom = pathinfo($getFile);
         $fileset = new Build_BuilderElement_Type_Fileset();
         if (!file_exists($getFile)) {
             $php .= "\noutput(\"No such file or directory {$getFile}.\");\nif ({$this->getFailOnError()}) { // failonerror\n  \$GLOBALS['result']['ok'] = false;\n  return false;\n} else {\n  \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n}\n";
         } elseif (is_file($getFile)) {
             $fileset->addInclude($pathFrom['basename']);
             $fileset->setDir($pathFrom['dirname']);
             $fileset->setType(Build_BuilderElement_Type_Fileset::FILE);
             $php .= "\n\$baseFromDir = '{$pathFrom['dirname']}';\n";
         } else {
             // It's a directory
             $fileset->addInclude('**/*');
             $fileset->setDir($getFile);
             $fileset->setType(Build_BuilderElement_Type_Fileset::BOTH);
             // Very important default!!!
             $php .= "\n\$baseFromDir = '{$getFile}';\n";
         }
         $filesets[] = $fileset;
     } elseif ($this->getFilesets()) {
         // If file exists, it takes precedence over filesets
         $realFilesets = $this->getFilesets();
         // Not to be overwritten
         if (!$realFilesets[0]->getDir() || !$realFilesets[0]->getInclude()) {
             SystemEvent::raise(SystemEvent::ERROR, 'No source files set for task copy.', __METHOD__);
             return false;
         }
         // Iterator mode for copy() must enforce parent dirs before their children,
         // so that we can mkdir the parent without first trying to copy in the children
         // on a non-existing dir.
         $fileset = new Build_BuilderElement_Type_Fileset();
         $fileset->setDir(self::_expandStr($realFilesets[0]->getDir(), $context));
         $fileset->setInclude(explode(' ', self::_expandStr(implode(' ', $realFilesets[0]->getInclude()), $context)));
         $fileset->setExclude(explode(' ', self::_expandStr(implode(' ', $realFilesets[0]->getExclude()), $context)));
         $filesets[] = $fileset;
         $php .= "\n\$baseFromDir = '{$fileset->getDir()}';\n";
     }
     $php .= "\n\$callback = function (\$entry) use (\$baseToDir, \$baseFromDir, \$baseToFilename) {\n  \$dest = \$baseToDir . (!empty(\$baseToFilename)?\$baseToFilename:substr(\$entry, strlen(\$baseFromDir)));\n  if (is_file(\$entry)) {\n    \$ret = @copy(\$entry, \$dest);\n  } elseif (is_dir(\$entry)) {\n  \tif (!file_exists(\$dest) && !@mkdir(\$dest, 0755, true)) {\n  \t  \$ret = false;\n  \t} else {\n  \t  \$ret = true;\n    }\n  } else {\n    \$ret = false;\n  }\n  if (!\$ret) {\n    output(\"Failed copy of \$entry to \$dest.\");\n  } else {\n    output(\"Copied \$entry to \$dest.\");\n  }\n  return \$ret;\n};\n";
     $context['iteratorMode'] = RecursiveIteratorIterator::SELF_FIRST;
     // Make sure dirs come before their children, in order to be created first
     foreach ($filesets as $fileset) {
         $php .= "\n" . $fileset->toPhp($context) . "\nif (!fileset{$fileset->getId()}_{$context['id']}(\$callback) && {$this->getFailOnError()}) {\n  \$GLOBALS['result']['ok'] = false;\n  return false;\n} else {\n  \$GLOBALS['result']['ok'] = \$GLOBALS['result']['ok'] & true;\n}\n";
     }
     return $php;
 }
Ejemplo n.º 30
0
 public static function settings_notificationsSave()
 {
     SystemEvent::raise(SystemEvent::DEBUG, "Called.", __METHOD__);
     if (empty($GLOBALS['user']) || !$GLOBALS['user'] instanceof User) {
         $msg = 'Invalid request';
         SystemEvent::raise(SystemEvent::INFO, $msg, __METHOD__);
         echo json_encode(array('success' => false, 'error' => $msg));
         exit;
     }
     $notifications = array();
     foreach ($_REQUEST as $handler => $payload) {
         $notificationClass = $handler;
         if (!class_exists($notificationClass)) {
             SystemEvent::raise(SystemEvent::INFO, "Invalid notification handler specified for save. [METHOD={$handler}]", __METHOD__);
             continue;
         }
         $notification = new $notificationClass();
         foreach ($payload as $attribute => $data) {
             $setter = 'set' . ucfirst($attribute);
             if (!is_callable(array($notification, $setter))) {
                 // method_exists() does not invoke __call() to check the method exists
                 SystemEvent::raise(SystemEvent::INFO, "Invalid notification handler attribute specified for save. [METHOD={$handler}] [ATTRIBUTE={$attribute}]", __METHOD__);
                 continue;
             }
             $notification->{$setter}($data['value']);
         }
         $notifications[$handler] = $notification;
     }
     $GLOBALS['user']->setNotifications($notifications);
     SystemEvent::raise(SystemEvent::DEBUG, "Notification settings changed for user {$GLOBALS['user']->getUsername()}.", __METHOD__);
     echo json_encode(array('success' => true, 'error' => 'Notification settings successfully changed.'));
     exit;
 }