repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
Freeeaky/VIngameConsole | src/D3D11/FW1FontWrapper/src/FW1Precompiled.cpp | 52 | // FW1Precompiled.cpp
#include "FW1Precompiled.h"
| gpl-2.0 |
TheTypoMaster/Scaper | openjdk/langtools/test/com/sun/javadoc/testNewLanguageFeatures/pkg/Coin.java | 1451 | /*
* Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package pkg;
/**
* This is a sample Enum.
*
* @author Jamie Ho
*/
public enum Coin {
Penny, Nickel, Dime;
/**
* Overloaded valueOf() method has correct documentation.
*/
public static Coin valueOf(int foo) {
return null;
}
/**
* Overloaded values method has correct documentation.
*/
public static final Coin[] values(int foo) {
return null;
}
}
| gpl-2.0 |
dantman/mediawiki-core | includes/specials/SpecialRevisiondelete.php | 21348 | <?php
/**
* Implements Special:Revisiondelete
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup SpecialPage
*/
/**
* Special page allowing users with the appropriate permissions to view
* and hide revisions. Log items can also be hidden.
*
* @ingroup SpecialPage
*/
class SpecialRevisionDelete extends UnlistedSpecialPage {
/** True if the submit button was clicked, and the form was posted */
var $submitClicked;
/** Target ID list */
var $ids;
/** Archive name, for reviewing deleted files */
var $archiveName;
/** Edit token for securing image views against XSS */
var $token;
/** Title object for target parameter */
var $targetObj;
/** Deletion type, may be revision, archive, oldimage, filearchive, logging. */
var $typeName;
/** Array of checkbox specs (message, name, deletion bits) */
var $checks;
/** Information about the current type */
var $typeInfo;
/** The RevDel_List object, storing the list of items to be deleted/undeleted */
var $list;
/**
* Assorted information about each type, needed by the special page.
* TODO Move some of this to the list class
*/
static $allowedTypes = array(
'revision' => array(
'check-label' => 'revdelete-hide-text',
'deletion-bits' => Revision::DELETED_TEXT,
'success' => 'revdelete-success',
'failure' => 'revdelete-failure',
'list-class' => 'RevDel_RevisionList',
'permission' => 'deleterevision',
),
'archive' => array(
'check-label' => 'revdelete-hide-text',
'deletion-bits' => Revision::DELETED_TEXT,
'success' => 'revdelete-success',
'failure' => 'revdelete-failure',
'list-class' => 'RevDel_ArchiveList',
'permission' => 'deleterevision',
),
'oldimage' => array(
'check-label' => 'revdelete-hide-image',
'deletion-bits' => File::DELETED_FILE,
'success' => 'revdelete-success',
'failure' => 'revdelete-failure',
'list-class' => 'RevDel_FileList',
'permission' => 'deleterevision',
),
'filearchive' => array(
'check-label' => 'revdelete-hide-image',
'deletion-bits' => File::DELETED_FILE,
'success' => 'revdelete-success',
'failure' => 'revdelete-failure',
'list-class' => 'RevDel_ArchivedFileList',
'permission' => 'deleterevision',
),
'logging' => array(
'check-label' => 'revdelete-hide-name',
'deletion-bits' => LogPage::DELETED_ACTION,
'success' => 'logdelete-success',
'failure' => 'logdelete-failure',
'list-class' => 'RevDel_LogList',
'permission' => 'deletelogentry',
),
);
/** Type map to support old log entries */
static $deprecatedTypeMap = array(
'oldid' => 'revision',
'artimestamp' => 'archive',
'oldimage' => 'oldimage',
'fileid' => 'filearchive',
'logid' => 'logging',
);
public function __construct() {
parent::__construct( 'Revisiondelete', 'deletedhistory' );
}
public function execute( $par ) {
$this->checkPermissions();
$this->checkReadOnly();
$output = $this->getOutput();
$user = $this->getUser();
$this->setHeaders();
$this->outputHeader();
$request = $this->getRequest();
$this->submitClicked = $request->wasPosted() && $request->getBool( 'wpSubmit' );
# Handle our many different possible input types.
$ids = $request->getVal( 'ids' );
if ( !is_null( $ids ) ) {
# Allow CSV, for backwards compatibility, or a single ID for show/hide links
$this->ids = explode( ',', $ids );
} else {
# Array input
$this->ids = array_keys( $request->getArray( 'ids', array() ) );
}
// $this->ids = array_map( 'intval', $this->ids );
$this->ids = array_unique( array_filter( $this->ids ) );
if ( $request->getVal( 'action' ) == 'historysubmit' || $request->getVal( 'action' ) == 'revisiondelete' ) {
// For show/hide form submission from history page
// Since we are access through index.php?title=XXX&action=historysubmit
// getFullTitle() will contain the target title and not our title
$this->targetObj = $this->getFullTitle();
$this->typeName = 'revision';
} else {
$this->typeName = $request->getVal( 'type' );
$this->targetObj = Title::newFromText( $request->getText( 'target' ) );
if ( $this->targetObj && $this->targetObj->isSpecial( 'Log' ) && count( $this->ids ) !== 0 ) {
$result = wfGetDB( DB_SLAVE )->select( 'logging',
'log_type',
array( 'log_id' => $this->ids ),
__METHOD__,
array( 'DISTINCT' )
);
if ( $result->numRows() == 1 ) {
// If there's only one type, the target can be set to include it.
$this->targetObj = SpecialPage::getTitleFor( 'Log', $result->current()->log_type );
}
}
}
# For reviewing deleted files...
$this->archiveName = $request->getVal( 'file' );
$this->token = $request->getVal( 'token' );
if ( $this->archiveName && $this->targetObj ) {
$this->tryShowFile( $this->archiveName );
return;
}
if ( isset( self::$deprecatedTypeMap[$this->typeName] ) ) {
$this->typeName = self::$deprecatedTypeMap[$this->typeName];
}
# No targets?
if ( !isset( self::$allowedTypes[$this->typeName] ) || count( $this->ids ) == 0 ) {
throw new ErrorPageError( 'revdelete-nooldid-title', 'revdelete-nooldid-text' );
}
$this->typeInfo = self::$allowedTypes[$this->typeName];
$this->mIsAllowed = $user->isAllowed( $this->typeInfo['permission'] );
# If we have revisions, get the title from the first one
# since they should all be from the same page. This allows
# for more flexibility with page moves...
if ( $this->typeName == 'revision' ) {
$rev = Revision::newFromId( $this->ids[0] );
$this->targetObj = $rev ? $rev->getTitle() : $this->targetObj;
}
$this->otherReason = $request->getVal( 'wpReason' );
# We need a target page!
if ( is_null( $this->targetObj ) ) {
$output->addWikiMsg( 'undelete-header' );
return;
}
# Give a link to the logs/hist for this page
$this->showConvenienceLinks();
# Initialise checkboxes
$this->checks = array(
array( $this->typeInfo['check-label'], 'wpHidePrimary', $this->typeInfo['deletion-bits'] ),
array( 'revdelete-hide-comment', 'wpHideComment', Revision::DELETED_COMMENT ),
array( 'revdelete-hide-user', 'wpHideUser', Revision::DELETED_USER )
);
if ( $user->isAllowed( 'suppressrevision' ) ) {
$this->checks[] = array( 'revdelete-hide-restricted',
'wpHideRestricted', Revision::DELETED_RESTRICTED );
}
# Either submit or create our form
if ( $this->mIsAllowed && $this->submitClicked ) {
$this->submit( $request );
} else {
$this->showForm();
}
$qc = $this->getLogQueryCond();
# Show relevant lines from the deletion log
$deleteLogPage = new LogPage( 'delete' );
$output->addHTML( "<h2>" . $deleteLogPage->getName()->escaped() . "</h2>\n" );
LogEventsList::showLogExtract( $output, 'delete',
$this->targetObj, '', array( 'lim' => 25, 'conds' => $qc ) );
# Show relevant lines from the suppression log
if ( $user->isAllowed( 'suppressionlog' ) ) {
$suppressLogPage = new LogPage( 'suppress' );
$output->addHTML( "<h2>" . $suppressLogPage->getName()->escaped() . "</h2>\n" );
LogEventsList::showLogExtract( $output, 'suppress',
$this->targetObj, '', array( 'lim' => 25, 'conds' => $qc ) );
}
}
/**
* Show some useful links in the subtitle
*/
protected function showConvenienceLinks() {
# Give a link to the logs/hist for this page
if ( $this->targetObj ) {
$links = array();
$links[] = Linker::linkKnown(
SpecialPage::getTitleFor( 'Log' ),
$this->msg( 'viewpagelogs' )->escaped(),
array(),
array( 'page' => $this->targetObj->getPrefixedText() )
);
if ( !$this->targetObj->isSpecialPage() ) {
# Give a link to the page history
$links[] = Linker::linkKnown(
$this->targetObj,
$this->msg( 'pagehist' )->escaped(),
array(),
array( 'action' => 'history' )
);
# Link to deleted edits
if ( $this->getUser()->isAllowed( 'undelete' ) ) {
$undelete = SpecialPage::getTitleFor( 'Undelete' );
$links[] = Linker::linkKnown(
$undelete,
$this->msg( 'deletedhist' )->escaped(),
array(),
array( 'target' => $this->targetObj->getPrefixedDBkey() )
);
}
}
# Logs themselves don't have histories or archived revisions
$this->getOutput()->addSubtitle( $this->getLanguage()->pipeList( $links ) );
}
}
/**
* Get the condition used for fetching log snippets
* @return array
*/
protected function getLogQueryCond() {
$conds = array();
// Revision delete logs for these item
$conds['log_type'] = array( 'delete', 'suppress' );
$conds['log_action'] = $this->getList()->getLogAction();
$conds['ls_field'] = RevisionDeleter::getRelationType( $this->typeName );
$conds['ls_value'] = $this->ids;
return $conds;
}
/**
* Show a deleted file version requested by the visitor.
* TODO Mostly copied from Special:Undelete. Refactor.
*/
protected function tryShowFile( $archiveName ) {
$repo = RepoGroup::singleton()->getLocalRepo();
$oimage = $repo->newFromArchiveName( $this->targetObj, $archiveName );
$oimage->load();
// Check if user is allowed to see this file
if ( !$oimage->exists() ) {
$this->getOutput()->addWikiMsg( 'revdelete-no-file' );
return;
}
$user = $this->getUser();
if ( !$oimage->userCan( File::DELETED_FILE, $user ) ) {
if ( $oimage->isDeleted( File::DELETED_RESTRICTED ) ) {
throw new PermissionsError( 'suppressrevision' );
} else {
throw new PermissionsError( 'deletedtext' );
}
}
if ( !$user->matchEditToken( $this->token, $archiveName ) ) {
$lang = $this->getLanguage();
$this->getOutput()->addWikiMsg( 'revdelete-show-file-confirm',
$this->targetObj->getText(),
$lang->userDate( $oimage->getTimestamp(), $user ),
$lang->userTime( $oimage->getTimestamp(), $user ) );
$this->getOutput()->addHTML(
Xml::openElement( 'form', array(
'method' => 'POST',
'action' => $this->getTitle()->getLocalURL( array(
'target' => $this->targetObj->getPrefixedDBkey(),
'file' => $archiveName,
'token' => $user->getEditToken( $archiveName ),
) )
)
) .
Xml::submitButton( $this->msg( 'revdelete-show-file-submit' )->text() ) .
'</form>'
);
return;
}
$this->getOutput()->disable();
# We mustn't allow the output to be Squid cached, otherwise
# if an admin previews a deleted image, and it's cached, then
# a user without appropriate permissions can toddle off and
# nab the image, and Squid will serve it
$this->getRequest()->response()->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
$this->getRequest()->response()->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
$this->getRequest()->response()->header( 'Pragma: no-cache' );
$key = $oimage->getStorageKey();
$path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
$repo->streamFile( $path );
}
/**
* Get the list object for this request
*/
protected function getList() {
if ( is_null( $this->list ) ) {
$class = $this->typeInfo['list-class'];
$this->list = new $class( $this->getContext(), $this->targetObj, $this->ids );
}
return $this->list;
}
/**
* Show a list of items that we will operate on, and show a form with checkboxes
* which will allow the user to choose new visibility settings.
*/
protected function showForm() {
$UserAllowed = true;
if ( $this->typeName == 'logging' ) {
$this->getOutput()->addWikiMsg( 'logdelete-selected', $this->getLanguage()->formatNum( count( $this->ids ) ) );
} else {
$this->getOutput()->addWikiMsg( 'revdelete-selected',
$this->targetObj->getPrefixedText(), count( $this->ids ) );
}
$this->getOutput()->addHTML( "<ul>" );
$numRevisions = 0;
// Live revisions...
$list = $this->getList();
for ( $list->reset(); $list->current(); $list->next() ) {
$item = $list->current();
if ( !$item->canView() ) {
if ( !$this->submitClicked ) {
throw new PermissionsError( 'suppressrevision' );
}
$UserAllowed = false;
}
$numRevisions++;
$this->getOutput()->addHTML( $item->getHTML() );
}
if ( !$numRevisions ) {
throw new ErrorPageError( 'revdelete-nooldid-title', 'revdelete-nooldid-text' );
}
$this->getOutput()->addHTML( "</ul>" );
// Explanation text
$this->addUsageText();
// Normal sysops can always see what they did, but can't always change it
if ( !$UserAllowed ) {
return;
}
// Show form if the user can submit
if ( $this->mIsAllowed ) {
$out = Xml::openElement( 'form', array( 'method' => 'post',
'action' => $this->getTitle()->getLocalURL( array( 'action' => 'submit' ) ),
'id' => 'mw-revdel-form-revisions' ) ) .
Xml::fieldset( $this->msg( 'revdelete-legend' )->text() ) .
$this->buildCheckBoxes() .
Xml::openElement( 'table' ) .
"<tr>\n" .
'<td class="mw-label">' .
Xml::label( $this->msg( 'revdelete-log' )->text(), 'wpRevDeleteReasonList' ) .
'</td>' .
'<td class="mw-input">' .
Xml::listDropDown( 'wpRevDeleteReasonList',
$this->msg( 'revdelete-reason-dropdown' )->inContentLanguage()->text(),
$this->msg( 'revdelete-reasonotherlist' )->inContentLanguage()->text(),
'', 'wpReasonDropDown', 1
) .
'</td>' .
"</tr><tr>\n" .
'<td class="mw-label">' .
Xml::label( $this->msg( 'revdelete-otherreason' )->text(), 'wpReason' ) .
'</td>' .
'<td class="mw-input">' .
Xml::input( 'wpReason', 60, $this->otherReason, array( 'id' => 'wpReason', 'maxlength' => 100 ) ) .
'</td>' .
"</tr><tr>\n" .
'<td></td>' .
'<td class="mw-submit">' .
Xml::submitButton( $this->msg( 'revdelete-submit', $numRevisions )->text(),
array( 'name' => 'wpSubmit' ) ) .
'</td>' .
"</tr>\n" .
Xml::closeElement( 'table' ) .
Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() ) .
Html::hidden( 'target', $this->targetObj->getPrefixedText() ) .
Html::hidden( 'type', $this->typeName ) .
Html::hidden( 'ids', implode( ',', $this->ids ) ) .
Xml::closeElement( 'fieldset' ) . "\n";
} else {
$out = '';
}
if ( $this->mIsAllowed ) {
$out .= Xml::closeElement( 'form' ) . "\n";
// Show link to edit the dropdown reasons
if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
$title = Title::makeTitle( NS_MEDIAWIKI, 'Revdelete-reason-dropdown' );
$link = Linker::link(
$title,
$this->msg( 'revdelete-edit-reasonlist' )->escaped(),
array(),
array( 'action' => 'edit' )
);
$out .= Xml::tags( 'p', array( 'class' => 'mw-revdel-editreasons' ), $link ) . "\n";
}
}
$this->getOutput()->addHTML( $out );
}
/**
* Show some introductory text
* @todo FIXME: Wikimedia-specific policy text
*/
protected function addUsageText() {
$this->getOutput()->addWikiMsg( 'revdelete-text' );
if ( $this->getUser()->isAllowed( 'suppressrevision' ) ) {
$this->getOutput()->addWikiMsg( 'revdelete-suppress-text' );
}
if ( $this->mIsAllowed ) {
$this->getOutput()->addWikiMsg( 'revdelete-confirm' );
}
}
/**
* @return String: HTML
*/
protected function buildCheckBoxes() {
$html = '<table>';
// If there is just one item, use checkboxes
$list = $this->getList();
if ( $list->length() == 1 ) {
$list->reset();
$bitfield = $list->current()->getBits(); // existing field
if ( $this->submitClicked ) {
$bitfield = $this->extractBitfield( $this->extractBitParams(), $bitfield );
}
foreach ( $this->checks as $item ) {
list( $message, $name, $field ) = $item;
$innerHTML = Xml::checkLabel( $this->msg( $message )->text(), $name, $name, $bitfield & $field );
if ( $field == Revision::DELETED_RESTRICTED ) {
$innerHTML = "<b>$innerHTML</b>";
}
$line = Xml::tags( 'td', array( 'class' => 'mw-input' ), $innerHTML );
$html .= "<tr>$line</tr>\n";
}
// Otherwise, use tri-state radios
} else {
$html .= '<tr>';
$html .= '<th class="mw-revdel-checkbox">' . $this->msg( 'revdelete-radio-same' )->escaped() . '</th>';
$html .= '<th class="mw-revdel-checkbox">' . $this->msg( 'revdelete-radio-unset' )->escaped() . '</th>';
$html .= '<th class="mw-revdel-checkbox">' . $this->msg( 'revdelete-radio-set' )->escaped() . '</th>';
$html .= "<th></th></tr>\n";
foreach ( $this->checks as $item ) {
list( $message, $name, $field ) = $item;
// If there are several items, use third state by default...
if ( $this->submitClicked ) {
$selected = $this->getRequest()->getInt( $name, 0 /* unchecked */ );
} else {
$selected = -1; // use existing field
}
$line = '<td class="mw-revdel-checkbox">' . Xml::radio( $name, -1, $selected == -1 ) . '</td>';
$line .= '<td class="mw-revdel-checkbox">' . Xml::radio( $name, 0, $selected == 0 ) . '</td>';
$line .= '<td class="mw-revdel-checkbox">' . Xml::radio( $name, 1, $selected == 1 ) . '</td>';
$label = $this->msg( $message )->escaped();
if ( $field == Revision::DELETED_RESTRICTED ) {
$label = "<b>$label</b>";
}
$line .= "<td>$label</td>";
$html .= "<tr>$line</tr>\n";
}
}
$html .= '</table>';
return $html;
}
/**
* UI entry point for form submission.
* @throws PermissionsError
* @return bool
*/
protected function submit() {
# Check edit token on submission
$token = $this->getRequest()->getVal( 'wpEditToken' );
if ( $this->submitClicked && !$this->getUser()->matchEditToken( $token ) ) {
$this->getOutput()->addWikiMsg( 'sessionfailure' );
return false;
}
$bitParams = $this->extractBitParams();
$listReason = $this->getRequest()->getText( 'wpRevDeleteReasonList', 'other' ); // from dropdown
$comment = $listReason;
if ( $comment != 'other' && $this->otherReason != '' ) {
// Entry from drop down menu + additional comment
$comment .= $this->msg( 'colon-separator' )->inContentLanguage()->text() . $this->otherReason;
} elseif ( $comment == 'other' ) {
$comment = $this->otherReason;
}
# Can the user set this field?
if ( $bitParams[Revision::DELETED_RESTRICTED] == 1 && !$this->getUser()->isAllowed( 'suppressrevision' ) ) {
throw new PermissionsError( 'suppressrevision' );
}
# If the save went through, go to success message...
$status = $this->save( $bitParams, $comment, $this->targetObj );
if ( $status->isGood() ) {
$this->success();
return true;
# ...otherwise, bounce back to form...
} else {
$this->failure( $status );
}
return false;
}
/**
* Report that the submit operation succeeded
*/
protected function success() {
$this->getOutput()->setPageTitle( $this->msg( 'actioncomplete' ) );
$this->getOutput()->wrapWikiMsg( "<span class=\"success\">\n$1\n</span>", $this->typeInfo['success'] );
$this->list->reloadFromMaster();
$this->showForm();
}
/**
* Report that the submit operation failed
*/
protected function failure( $status ) {
$this->getOutput()->setPageTitle( $this->msg( 'actionfailed' ) );
$this->getOutput()->addWikiText( $status->getWikiText( $this->typeInfo['failure'] ) );
$this->showForm();
}
/**
* Put together an array that contains -1, 0, or the *_deleted const for each bit
*
* @return array
*/
protected function extractBitParams() {
$bitfield = array();
foreach ( $this->checks as $item ) {
list( /* message */, $name, $field ) = $item;
$val = $this->getRequest()->getInt( $name, 0 /* unchecked */ );
if ( $val < -1 || $val > 1 ) {
$val = -1; // -1 for existing value
}
$bitfield[$field] = $val;
}
if ( !isset( $bitfield[Revision::DELETED_RESTRICTED] ) ) {
$bitfield[Revision::DELETED_RESTRICTED] = 0;
}
return $bitfield;
}
/**
* Put together a rev_deleted bitfield
* @param array $bitPars extractBitParams() params
* @param int $oldfield current bitfield
* @return array
*/
public static function extractBitfield( $bitPars, $oldfield ) {
// Build the actual new rev_deleted bitfield
$newBits = 0;
foreach ( $bitPars as $const => $val ) {
if ( $val == 1 ) {
$newBits |= $const; // $const is the *_deleted const
} elseif ( $val == -1 ) {
$newBits |= ( $oldfield & $const ); // use existing
}
}
return $newBits;
}
/**
* Do the write operations. Simple wrapper for RevDel_*List::setVisibility().
* @param $bitfield
* @param $reason
* @param $title
* @return
*/
protected function save( $bitfield, $reason, $title ) {
return $this->getList()->setVisibility(
array( 'value' => $bitfield, 'comment' => $reason )
);
}
protected function getGroupName() {
return 'pagetools';
}
}
| gpl-2.0 |
hoa32811/wp_thanhtrung_hotel | wp-content/themes/hotelmaster-v2-01/header.php | 5446 | <!DOCTYPE html>
<!--[if IE 7]><html class="ie ie7 ltie8 ltie9" <?php language_attributes(); ?>><![endif]-->
<!--[if IE 8]><html class="ie ie8 ltie9" <?php language_attributes(); ?>><![endif]-->
<!--[if !(IE 7) | !(IE 8) ]><!-->
<html <?php language_attributes(); ?>>
<!--<![endif]-->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>" />
<?php
global $theme_option, $gdlr_post_option;
$body_wrapper = '';
if(empty($theme_option['enable-responsive-mode']) || $theme_option['enable-responsive-mode'] == 'enable'){
echo '<meta name="viewport" content="initial-scale=1.0" />';
}else{
$body_wrapper .= 'gdlr-no-responsive ';
}
?>
<?php if( !function_exists( '_wp_render_title_tag' ) ){ ?>
<title><?php wp_title(); ?></title>
<?php } ?>
<link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" />
<?php
if( !empty($gdlr_post_option) ){ $gdlr_post_option = json_decode($gdlr_post_option, true); }
wp_head();
?>
</head>
<body <?php body_class(); ?>>
<?php
if($theme_option['enable-boxed-style'] == 'boxed-style'){
$body_wrapper .= 'gdlr-boxed-style';
if( !empty($theme_option['boxed-background-image']) && is_numeric($theme_option['boxed-background-image']) ){
$alt_text = get_post_meta($theme_option['boxed-background-image'] , '_wp_attachment_image_alt', true);
$image_src = wp_get_attachment_image_src($theme_option['boxed-background-image'], 'full');
echo '<img class="gdlr-full-boxed-background" src="' . $image_src[0] . '" alt="' . $alt_text . '" />';
}else if( !empty($theme_option['boxed-background-image']) ){
echo '<img class="gdlr-full-boxed-background" src="' . $theme_option['boxed-background-image'] . '" />';
}
}
global $header_style;
if( !empty($gdlr_post_option['header-style']) && $gdlr_post_option['header-style'] != 'default' ){
$header_style = $gdlr_post_option['header-style'];
}else{
$header_style = empty($theme_option['default-header-style'])? 'solid': $theme_option['default-header-style'];
}
$body_wrapper .= ($theme_option['enable-float-menu'] != 'disable')? ' float-menu': '';
$body_wrapper .= empty($theme_option['body-icon-color'])? ' gdlr-icon-dark': ' gdlr-icon-' . $theme_option['body-icon-color'];
$body_wrapper .= ' gdlr-header-' . $header_style;
?>
<div class="body-wrapper <?php echo esc_attr($body_wrapper); ?>" data-home="<?php echo home_url(); ?>" >
<?php
// page style
if( empty($gdlr_post_option) || empty($gdlr_post_option['page-style']) ||
$gdlr_post_option['page-style'] == 'normal' ||
$gdlr_post_option['page-style'] == 'no-footer'){
?>
<header class="gdlr-header-wrapper">
<!-- top navigation -->
<?php if( empty($theme_option['enable-top-bar']) || $theme_option['enable-top-bar'] == 'enable' ){ ?>
<div class="top-navigation-wrapper">
<div class="top-navigation-container container">
<div class="top-navigation-left">
<div class="top-navigation-left-text">
<?php
if( !empty($theme_option['top-bar-left-text']) )
echo gdlr_text_filter(gdlr_escape_string($theme_option['top-bar-left-text']));
?>
</div>
</div>
<div class="top-navigation-right">
<div class="top-social-wrapper">
<?php gdlr_print_header_social(); ?>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="top-navigation-divider"></div>
<?php } ?>
<!-- logo -->
<div class="gdlr-header-inner">
<div class="gdlr-header-container container">
<!-- logo -->
<div class="gdlr-logo">
<div class="gdlr-logo-inner">
<a href="<?php echo home_url(); ?>" >
<?php
if($header_style != 'transparent'){
if(empty($theme_option['logo-id'])){
echo gdlr_get_image(GDLR_PATH . '/images/logo.png');
}else{
echo gdlr_get_image($theme_option['logo-id']);
}
}else{
if(empty($theme_option['logo-id'])){
$theme_option['logo-id'] = GDLR_PATH . '/images/logo.png';
}else if(is_numeric($theme_option['logo-id'])){
$image_src = wp_get_attachment_image_src($theme_option['logo-id'], 'full');
$theme_option['logo-id'] = $image_src[0];
}
$attr = ' data-normal="' . $theme_option['logo-id'] . '" ';
if(empty($theme_option['logot-id'])){
echo gdlr_get_image(GDLR_PATH . '/images/logot.png', 'full', array(), $attr);
}else{
echo gdlr_get_image($theme_option['logot-id'], 'full', array(), $attr);
}
}
?>
</a>
<?php
// mobile navigation
if( class_exists('gdlr_dlmenu_walker') && has_nav_menu('main_menu') &&
( empty($theme_option['enable-responsive-mode']) || $theme_option['enable-responsive-mode'] == 'enable' ) ){
echo '<div class="gdlr-responsive-navigation dl-menuwrapper" id="gdlr-responsive-navigation" >';
echo '<button class="dl-trigger">Open Menu</button>';
wp_nav_menu( array(
'theme_location'=>'main_menu',
'container'=> '',
'menu_class'=> 'dl-menu gdlr-main-mobile-menu',
'walker'=> new gdlr_dlmenu_walker()
) );
echo '</div>';
}
?>
</div>
</div>
<!-- navigation -->
<?php get_template_part( 'header', 'nav' ); ?>
<div class="clear"></div>
</div>
</div>
</header>
<div id="gdlr-header-substitute" ></div>
<?php get_template_part( 'header', 'title' );
} // page style ?>
<div class="content-wrapper"> | gpl-2.0 |
kobliha/yast-network | src/include/network/lan/hardware.rb | 38328 | # encoding: utf-8
# ***************************************************************************
#
# Copyright (c) 2012 Novell, Inc.
# All Rights Reserved.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public License as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, contact Novell, Inc.
#
# To contact Novell about this file by physical or electronic mail,
# you may find current contact information at www.novell.com
#
# **************************************************************************
# File: include/network/lan/hardware.ycp
# Package: Network configuration
# Summary: Hardware dialogs
# Authors: Michal Svec <msvec@suse.cz>
#
require "network/edit_nic_name"
module Yast
module NetworkLanHardwareInclude
def initialize_network_lan_hardware(include_target)
Yast.import "UI"
textdomain "network"
Yast.import "Arch"
Yast.import "CWM"
Yast.import "Label"
Yast.import "Lan"
Yast.import "NetworkInterfaces"
Yast.import "Popup"
Yast.import "Wizard"
Yast.import "LanItems"
Yast.include include_target, "network/summary.rb"
Yast.include include_target, "network/routines.rb"
Yast.include include_target, "network/lan/cards.rb"
@hardware = nil
@widget_descr_hardware = {
"HWDIALOG" => {
"widget" => :custom,
"custom_widget" => ReplacePoint(Id(:hw_content), Empty()),
"init" => fun_ref(method(:initHwDialog), "void (string)"),
"handle" => fun_ref(method(:handleHW), "symbol (string, map)"),
"store" => fun_ref(method(:storeHW), "void (string, map)"),
"validate_type" => :function,
"validate_function" => fun_ref(method(:validate_hw), "boolean (string, map)"),
"help" => initHelp
}
}
end
# Determines if the dialog is used for adding new device or for editing existing one.
#
# Some widgets are disabled when creating new device. Also, when editing existing device, it is not possible
# to e.g. change device type.
#
# @return false if hardware widgets are embedded into another dialog, otherwise true.
def isNewDevice
LanItems.operation == :add
end
# Dynamic initialization of help text.
#
# @return content of the help
def initHelp
# Manual network card setup help 1/4
hw_help = _(
"<p>Set up hardware-specific options for \nyour network device here.</p>\n"
)
if isNewDevice
# Manual network card setup help 2/4
# translators: do not translated udev, MAC, BusID
hw_help = Ops.add(
hw_help,
_(
"<p><b>Device Type</b>. Various device types are available, select \none according your needs.</p>"
)
)
else
hw_help = Ops.add(
Ops.add(
hw_help,
_(
"<p><b>Udev Rules</b> are rules for the kernel device manager that allow\n" \
"associating the MAC address or BusID of the network device with its name (for\n" \
"example, eth1, wlan0 ) and assures a persistent device name upon reboot.\n"
)
),
_(
"<p><b>Show visible port identification</b> allows you to physically identify now configured NIC. \n" \
"Set appropriate time, click <b>Blink</b> and LED diodes on you NIC will start blinking for selected time.\n" \
"</p>"
)
)
end
# Manual network card setup help 2/4
hw_help = Ops.add(
Ops.add(
Ops.add(
hw_help,
_(
"<p><b>Kernel Module</b>. Enter the kernel module (driver) name \n" \
"for your network device here. If the device is already configured, see if there is more than one driver available for\n" \
"your device in the drop-down list. If necessary, choose a driver from the list, but usually the default value works.</p>\n"
)
),
# Manual networ card setup help 3/4
_(
"<p>Additionally, specify <b>Options</b> for the kernel module. Use this\n" \
"format: <i>option</i>=<i>value</i>. Each entry should be space-separated, for example: <i>io=0x300 irq=5</i>. <b>Note:</b> If two cards are \n" \
"configured with the same module name, the options will be merged while saving.</p>\n"
)
),
_(
"<p>If you specify options via <b>Ethtool options</b>, ifup will call ethtool with these options.</p>\n"
)
)
if isNewDevice && !Arch.s390
# Manual dialog help 4/4
hw_help = Ops.add(
hw_help,
_(
"<p>If you have a <b>PCMCIA</b> network card, select PCMCIA.\nIf you have a <b>USB</b> network card, select USB.</p>\n"
)
)
end
if Arch.s390
# overwrite help
# Manual dialog help 5/4
hw_help = _(
"<p>Here, set up your networking device. The values will be\nwritten to <i>/etc/modprobe.conf</i> or <i>/etc/chandev.conf</i>.</p>\n"
) +
# Manual dialog help 6/4
_(
"<p>Options for the module should be written in the format specified\nin the <b>IBM Device Drivers and Installation Commands</b> manual.</p>"
)
end
hw_help
end
def initHardware
@hardware = {}
Ops.set(@hardware, "hotplug", LanItems.hotplug)
Builtins.y2milestone("hotplug=%1", LanItems.hotplug)
Ops.set(
@hardware,
"modules_from_hwinfo",
LanItems.GetItemModules(Ops.get_string(@hardware, "modul", ""))
)
Ops.set(@hardware, "type", LanItems.type)
if Ops.get_string(@hardware, "type", "") == ""
Builtins.y2error("Shouldn't happen -- type is empty. Assuming eth.")
Ops.set(@hardware, "type", "eth")
end
Ops.set(
@hardware,
"realtype",
NetworkInterfaces.RealType(
Ops.get_string(@hardware, "type", ""),
Ops.get_string(@hardware, "hotplug", "")
)
)
# Use rather LanItems::device, so that device number is initialized correctly at all times (#308763)
Ops.set(@hardware, "device", LanItems.device)
driver = Ops.get_string(LanItems.getCurrentItem, ["udev", "driver"], "")
Ops.set(
@hardware,
"default_device",
if IsNotEmpty(driver)
driver
else
Ops.get_string(LanItems.getCurrentItem, ["hwinfo", "module"], "")
end
)
Ops.set(
@hardware,
"options",
Ops.get_string(
LanItems.driver_options,
Ops.get_string(@hardware, "default_device", ""),
""
)
)
# #38213, remember device id when we switch back from pcmcia/usb
Ops.set(
@hardware,
"non_hotplug_device_id",
Ops.get_string(@hardware, "device", "")
)
# FIXME: duplicated in address.ycp
Ops.set(@hardware, "device_types", NetworkInterfaces.GetDeviceTypes)
if Builtins.issubstring(
Ops.get_string(@hardware, "device", ""),
"bus-pcmcia"
)
Ops.set(@hardware, "hotplug", "pcmcia")
elsif Builtins.issubstring(
Ops.get_string(@hardware, "device", ""),
"bus-usb"
)
Ops.set(@hardware, "hotplug", "usb")
end
Builtins.y2milestone("hotplug=%1", LanItems.hotplug)
Ops.set(
@hardware,
"devices",
LanItems.FreeDevices(Ops.get_string(@hardware, "realtype", ""))
) # TODO: id-, bus-, ... here
if !Builtins.contains(
Ops.get_list(@hardware, "devices", []),
Ops.get_string(@hardware, "device", "")
)
Ops.set(
@hardware,
"devices",
Builtins.prepend(
Ops.get_list(@hardware, "devices", []),
Ops.get_string(@hardware, "device", "")
)
)
end
Ops.set(
@hardware,
"no_hotplug",
Ops.get_string(@hardware, "hotplug", "") == ""
)
Ops.set(
@hardware,
"no_hotplug_dummy",
Ops.get_boolean(@hardware, "no_hotplug", false) &&
Ops.get_string(@hardware, "type", "") != "dummy"
)
Ops.set(@hardware, "ethtool_options", LanItems.ethtool_options)
nil
end
def initHwDialog(_text)
initHardware
hotplug_type = @hardware["hotplug"] || ""
hw_type = @hardware["type"] || ""
check_boxes = HBox(
HSpacing(1.5),
# CheckBox label
CheckBox(
Id(:pcmcia),
Opt(:notify),
_("&PCMCIA"),
hotplug_type == "pcmcia"
),
HSpacing(1.5),
# CheckBox label
CheckBox(
Id(:usb),
Opt(:notify),
_("&USB"),
hotplug_type == "usb"
),
HSpacing(1.5)
)
# Disable PCMCIA and USB checkboxex on Edit and s390
check_boxes = VSpacing(0) if !isNewDevice || Arch.s390
# #116211 - allow user to change modules from list
# Frame label
kernel_box = Frame(
_("&Kernel Module"),
HBox(
HSpacing(0.5),
VBox(
VSpacing(0.4),
HBox(
# Text entry label
ComboBox(
Id(:modul),
Opt(:editable),
_("&Module Name"),
@hardware["modules_from_hwinfo"] || []
),
HSpacing(0.5),
InputField(
Id(:options),
Opt(:hstretch),
Label.Options,
@hardware["options"] || ""
)
),
VSpacing(0.4),
check_boxes,
VSpacing(0.4)
),
HSpacing(0.5)
)
)
device_number_box = ReplacePoint(
Id(:rnum),
# TextEntry label
ComboBox(
Id(:ifcfg_name),
Opt(:editable, :hstretch),
_("&Configuration Name"),
[@hardware["device"] || ""]
)
)
# Manual dialog contents
type_name_widgets = VBox(
VSpacing(0.2),
HBox(
HSpacing(0.5),
ComboBox(
Id(:type),
Opt(:hstretch, :notify),
# ComboBox label
_("&Device Type"),
BuildTypesList(
@hardware["device_types"] || [],
hw_type
)
),
HSpacing(1.5),
device_number_box,
HSpacing(0.5)
)
)
udev_widget =
Frame(
_("Udev Rules"),
HBox(
InputField(Id(:device_name), Opt(:hstretch), _("Device Name"), ""),
PushButton(Id(:change_udev), _("Change"))
)
)
if !isNewDevice
type_name_widgets = Empty()
else
udev_widget = Empty()
end
blink_card = Frame(
_("Show Visible Port Identification"),
HBox(
# translators: how many seconds will card be blinking
IntField(
Id(:blink_time),
format("%s:", _("Seconds")),
0,
100,
5
),
PushButton(Id(:blink), _("Blink"))
)
)
ethtool_widget = Frame(
_("Ethtool Options"),
HBox(
InputField(
Id(:ethtool_opts),
Opt(:hstretch),
_("Options"),
@hardware["ethtool_options"] || ""
)
)
)
contents = VBox(
HBox(udev_widget, HStretch(), isNewDevice ? Empty() : blink_card),
type_name_widgets,
kernel_box,
ethtool_widget,
VStretch()
)
UI.ReplaceWidget(:hw_content, contents)
UI.ChangeWidget(
:modul,
:Value,
@hardware["default_device"] || ""
)
UI.ChangeWidget(
Id(:modul),
:Enabled,
@hardware["no_hotplug_dummy"] == true # convert tri state boolean to two state
)
ChangeWidgetIfExists(
Id(:list),
:Enabled,
@hardware["no_hotplug_dummy"] == true # convert tri state boolean to two state
)
ChangeWidgetIfExists(
Id(:hwcfg),
:Enabled,
@hardware["no_hotplug"] == true # convert tri state boolean to two state
)
ChangeWidgetIfExists(
Id(:usb),
:Enabled,
(hotplug_type == "usb" || hotplug_type == "") &&
hw_type != "dummy"
)
ChangeWidgetIfExists(
Id(:pcmcia),
:Enabled,
(hotplug_type == "pcmcia" || hotplug_type == "") &&
hw_type != "dummy"
)
device_name = LanItems.current_udev_name
ChangeWidgetIfExists(Id(:device_name), :Enabled, false)
ChangeWidgetIfExists(Id(:device_name), :Value, device_name)
ChangeWidgetIfExists(Id(:type), :Enabled, false) if !isNewDevice
ChangeWidgetIfExists(
Id(:ifcfg_name),
:ValidChars,
NetworkInterfaces.ValidCharsIfcfg
)
nil
end
# Call back for a manual selection from the list
# @return dialog result
def SelectionDialog
type = LanItems.type
selected = 0
hwlist = Ops.get_list(@NetworkCards, type, [])
cards = hwlist2items(hwlist, 0)
# Manual selection caption
caption = _("Manual Network Card Selection")
# Manual selection help
helptext = _(
"<p>Select the network card to configure. Search\nfor a particular network card by entering the name in the search entry.</p>"
)
# Manual selection contents
contents = VBox(
VSpacing(0.5),
# Selection box label
ReplacePoint(
Id(:rp),
SelectionBox(Id(:cards), _("&Network Card"), cards)
),
VSpacing(0.5),
# Text entry field
InputField(Id(:search), Opt(:hstretch, :notify), _("&Search")),
VSpacing(0.5)
)
Wizard.SetContentsButtons(
caption,
contents,
helptext,
Label.BackButton,
Label.OKButton
)
UI.SetFocus(Id(:cards))
ret = nil
loop do
ret = UI.UserInput
if ret == :abort || ret == :cancel
if ReallyAbort()
break
else
next
end
elsif ret == :search
entry = Convert.to_string(UI.QueryWidget(Id(:search), :Value))
l = Builtins.filter(
Convert.convert(cards, from: "list", to: "list <term>")
) do |e|
Builtins.tolower(
Builtins.substring(
Ops.get_string(e, 1, ""),
0,
Builtins.size(entry)
)
) ==
Builtins.tolower(entry)
end
selected = 0 if Builtins.size(entry) == 0
if Ops.greater_than(Builtins.size(l), 0)
selected = Ops.get_integer(l, [0, 0, 0], 0)
end
cards = []
cards = hwlist2items(hwlist, selected)
# Selection box title
UI.ReplaceWidget(
Id(:rp),
SelectionBox(Id(:cards), _("&Network Card"), cards)
)
elsif ret == :back
break
elsif ret == :next
# FIXME: check_*
break
else
Builtins.y2error("Unexpected return code: %1", ret)
next
end
end
if ret == :next
selected = Convert.to_integer(UI.QueryWidget(Id(:cards), :CurrentItem))
selected = 0 if selected.nil?
card = Ops.get(hwlist, selected, {})
LanItems.description = Ops.get_string(card, "name", "")
end
deep_copy(ret)
end
# Dialog for editing nic's udev rules.
#
# @return nic name. New one if `ok, old one otherwise.
def EditUdevRulesDialog
edit_name_dlg = EditNicName.new
edit_name_dlg.run
end
def handleHW(_key, event)
event = deep_copy(event)
LanItems.Rollback if Ops.get(event, "ID") == :cancel
ret = nil
if Ops.get_string(event, "EventReason", "") == "ValueChanged" ||
Ops.get_string(event, "EventReason", "") == "Activated"
ret = Ops.get_symbol(event, "WidgetID")
end
SelectionDialog() if ret == :list
if ret == :pcmcia || ret == :usb || ret == :type
if UI.WidgetExists(Id(:pcmcia)) || UI.WidgetExists(Id(:usb))
if UI.QueryWidget(Id(:pcmcia), :Value) == true
Ops.set(@hardware, "hotplug", "pcmcia")
elsif UI.QueryWidget(Id(:usb), :Value) == true
Ops.set(@hardware, "hotplug", "usb")
else
Ops.set(@hardware, "hotplug", "")
end
end
Builtins.y2debug("hotplug=%1", Ops.get_string(@hardware, "hotplug", ""))
if UI.WidgetExists(Id(:type))
Ops.set(
@hardware,
"type",
Convert.to_string(UI.QueryWidget(Id(:type), :Value))
)
Ops.set(
@hardware,
"realtype",
NetworkInterfaces.RealType(
Ops.get_string(@hardware, "type", ""),
Ops.get_string(@hardware, "hotplug", "")
)
)
UI.ChangeWidget(
Id(:ifcfg_name),
:Items,
LanItems.FreeDevices(@hardware["realtype"]).map do |index|
@hardware["realtype"] + index
end
)
end
Builtins.y2debug("type=%1", Ops.get_string(@hardware, "type", ""))
Builtins.y2debug(
"realtype=%1",
Ops.get_string(@hardware, "realtype", "")
)
if Ops.get_string(@hardware, "type", "") == "usb"
UI.ChangeWidget(Id(:usb), :Value, true)
Ops.set(@hardware, "hotplug", "usb")
end
Ops.set(
@hardware,
"no_hotplug",
Ops.get_string(@hardware, "hotplug", "") == ""
)
Ops.set(
@hardware,
"no_hotplug_dummy",
Ops.get_boolean(@hardware, "no_hotplug", false) &&
Ops.get_string(@hardware, "type", "") != "dummy"
)
UI.ChangeWidget(
Id(:modul),
:Enabled,
Ops.get_boolean(@hardware, "no_hotplug_dummy", false)
)
UI.ChangeWidget(
Id(:options),
:Enabled,
Ops.get_boolean(@hardware, "no_hotplug_dummy", false)
)
ChangeWidgetIfExists(
Id(:list),
:Enabled,
Ops.get_boolean(@hardware, "no_hotplug_dummy", false)
)
ChangeWidgetIfExists(
Id(:hwcfg),
:Enabled,
Ops.get_boolean(@hardware, "no_hotplug", false)
)
ChangeWidgetIfExists(
Id(:usb),
:Enabled,
(Ops.get_string(@hardware, "hotplug", "") == "usb" ||
Ops.get_string(@hardware, "hotplug", "") == "") &&
Ops.get_string(@hardware, "type", "") != "dummy"
)
ChangeWidgetIfExists(
Id(:pcmcia),
:Enabled,
(Ops.get_string(@hardware, "hotplug", "") == "pcmcia" ||
Ops.get_string(@hardware, "hotplug", "") == "") &&
Ops.get_string(@hardware, "type", "") != "dummy"
)
Ops.set(
@hardware,
"device",
Convert.to_string(UI.QueryWidget(Id(:ifcfg_name), :Value))
)
if Ops.get_string(@hardware, "device", "") != "bus-usb" &&
Ops.get_string(@hardware, "device", "") != "bus-pcmcia"
Ops.set(
@hardware,
"non_hotplug_device_id",
Ops.get_string(@hardware, "device", "")
)
end
if Ops.get_string(@hardware, "hotplug", "") == "usb"
Ops.set(@hardware, "device", "bus-usb")
elsif Ops.get_string(@hardware, "hotplug", "") == "pcmcia"
Ops.set(@hardware, "device", "bus-pcmcia")
else
Ops.set(
@hardware,
"device",
Ops.get_string(@hardware, "non_hotplug_device_id", "")
)
end
UI.ChangeWidget(
Id(:ifcfg_name),
:Value,
Ops.get_string(@hardware, "device", "")
)
if Arch.s390
drvtype = DriverType(Ops.get_string(@hardware, "type", ""))
if Builtins.contains(["lcs", "qeth", "ctc"], drvtype)
Ops.set(@hardware, "modul", drvtype)
elsif drvtype == "iucv"
Ops.set(@hardware, "modul", "netiucv")
end
UI.ChangeWidget(
Id(:modul),
:Value,
Ops.get_string(@hardware, "modul", "")
)
end
if Ops.get_string(@hardware, "type", "") == "xp"
Ops.set(@hardware, "modul", "xpnet")
UI.ChangeWidget(
Id(:modul),
:Value,
Ops.get_string(@hardware, "modul", "")
)
elsif Ops.get_string(@hardware, "type", "") == "dummy" # #44582
Ops.set(@hardware, "modul", "dummy")
if UI.WidgetExists(Id(:hwcfg)) # bnc#767946
Ops.set(
@hardware,
"hwcfg",
Convert.to_string(UI.QueryWidget(Id(:hwcfg), :Value))
)
Ops.set(
@hardware,
"options",
Builtins.sformat(
"-o dummy-%1",
Ops.get_string(@hardware, "hwcfg", "")
)
)
end
UI.ChangeWidget(
Id(:modul),
:Value,
Ops.get_string(@hardware, "modul", "")
)
UI.ChangeWidget(
Id(:options),
:Value,
Ops.get_string(@hardware, "options", "")
)
elsif Builtins.contains(
["bond", "vlan", "br", "tun", "tap"],
Ops.get_string(@hardware, "type", "")
)
UI.ChangeWidget(Id(:hwcfg), :Enabled, false)
UI.ChangeWidget(Id(:modul), :Enabled, false)
UI.ChangeWidget(Id(:options), :Enabled, false)
UI.ChangeWidget(Id(:pcmcia), :Enabled, false)
UI.ChangeWidget(Id(:usb), :Enabled, false)
UI.ChangeWidget(Id(:list), :Enabled, false)
UI.ChangeWidget(Id(:hwcfg), :Value, "")
UI.ChangeWidget(Id(:modul), :Value, "")
UI.ChangeWidget(Id(:options), :Value, "")
end
end
if ret == :change_udev
UI.ChangeWidget(:device_name, :Value, EditUdevRulesDialog())
end
if ret == :blink
device = LanItems.device
timeout = Builtins.tointeger(UI.QueryWidget(:blink_time, :Value))
Builtins.y2milestone(
"blink, blink ... %1 seconds on %2 device",
timeout,
device
)
cmd = Builtins.sformat("ethtool -p %1 %2", device, timeout)
Builtins.y2milestone(
"%1 : %2",
cmd,
SCR.Execute(path(".target.bash_output"), cmd)
)
end
nil
end
def devname_from_hw_dialog
UI.QueryWidget(Id(:ifcfg_name), :Value)
end
def validate_hw(_key, _event)
nm = devname_from_hw_dialog
if UsedNicName(nm)
Popup.Error(
Builtins.sformat(
_(
"Configuration name %1 already exists.\nChoose a different one."
),
nm
)
)
UI.SetFocus(Id(:ifcfg_name))
return false
end
true
end
def storeHW(_key, _event)
if isNewDevice
nm = devname_from_hw_dialog
LanItems.type = UI.QueryWidget(Id(:type), :Value)
LanItems.device = nm
NetworkInterfaces.Name = nm
Ops.set(LanItems.Items, [LanItems.current, "ifcfg"], nm)
# Initialize udev map, so that setDriver (see below) sets correct module
Ops.set(LanItems.Items, [LanItems.current, "udev"], {})
# FIXME: for interfaces with no hwinfo don't propose ifplugd
if Builtins.size(Ops.get_map(LanItems.getCurrentItem, "hwinfo", {})) == 0
Builtins.y2milestone(
"interface without hwinfo, proposing STARTMODE=auto"
)
LanItems.startmode = "auto"
end
if LanItems.type == "vlan"
# for vlan devices named vlanN pre-set vlan_id to N, otherwise default to 0
LanItems.vlan_id = "#{nm["vlan".size].to_i}"
end
end
driver = Convert.to_string(UI.QueryWidget(:modul, :Value))
LanItems.setDriver(driver)
Ops.set(
LanItems.driver_options,
driver,
Convert.to_string(UI.QueryWidget(:options, :Value))
)
LanItems.ethtool_options = Convert.to_string(
UI.QueryWidget(:ethtool_opts, :Value)
)
nil
end
# S/390 devices configuration dialog
# @return dialog result
def S390Dialog
# S/390 dialog caption
caption = _("S/390 Network Card Configuration")
drvtype = DriverType(LanItems.type)
helptext = ""
contents = Empty()
if Builtins.contains(["qeth", "hsi"], LanItems.type)
# CHANIDS
tmp_list = Builtins.splitstring(LanItems.qeth_chanids, " ")
chanids_map = {
"read" => Ops.get(tmp_list, 0, ""),
"write" => Ops.get(tmp_list, 1, ""),
"control" => Ops.get(tmp_list, 2, "")
}
contents = HBox(
HSpacing(6),
# Frame label
Frame(
_("S/390 Device Settings"),
HBox(
HSpacing(2),
VBox(
VSpacing(1),
HBox(
# TextEntry label
InputField(
Id(:qeth_portname),
Opt(:hstretch),
_("&Port Name"),
LanItems.qeth_portname
),
ComboBox(
Id(:qeth_portnumber),
_("Port Number"),
[Item(Id("0"), "0", true), Item(Id("1"), "1")]
)
),
VSpacing(1),
# TextEntry label
InputField(
Id(:qeth_options),
Opt(:hstretch),
Label.Options,
LanItems.qeth_options
),
VSpacing(1),
# CheckBox label
Left(CheckBox(Id(:ipa_takeover), _("&Enable IPA Takeover"))),
VSpacing(1),
# CheckBox label
Left(
CheckBox(
Id(:qeth_layer2),
Opt(:notify),
_("Enable &Layer 2 Support")
)
),
# TextEntry label
InputField(
Id(:qeth_macaddress),
Opt(:hstretch),
_("Layer2 &MAC Address"),
LanItems.qeth_macaddress
),
VSpacing(1),
HBox(
InputField(
Id(:qeth_chan_read),
Opt(:hstretch),
_("Read Channel"),
Ops.get_string(chanids_map, "read", "")
),
InputField(
Id(:qeth_chan_write),
Opt(:hstretch),
_("Write Channel"),
Ops.get_string(chanids_map, "write", "")
),
InputField(
Id(:qeth_chan_control),
Opt(:hstretch),
_("Control Channel"),
Ops.get_string(chanids_map, "control", "")
)
)
),
HSpacing(2)
)
),
HSpacing(6)
)
# S/390 dialog help: QETH Port name
helptext = _(
"<p>Enter the <b>Port Name</b> for this interface (case-sensitive).</p>"
) +
# S/390 dialog help: QETH Options
_(
"<p>Enter any additional <b>Options</b> for this interface (separated by spaces).</p>"
) +
_(
"<p>Select <b>Enable IPA Takeover</b> if IP address takeover should be enabled for this interface.</p>"
) +
_(
"<p>Select <b>Enable Layer 2 Support</b> if this card has been configured with layer 2 support.</p>"
) +
_(
"<p>Enter the <b>Layer 2 MAC Address</b> if this card has been configured with layer 2 support.</p>"
)
end
if drvtype == "lcs"
tmp_list = Builtins.splitstring(LanItems.qeth_chanids, " ")
chanids_map = {
"read" => Ops.get(tmp_list, 0, ""),
"write" => Ops.get(tmp_list, 1, "")
}
contents = HBox(
HSpacing(6),
# Frame label
Frame(
_("S/390 Device Settings"),
HBox(
HSpacing(2),
VBox(
VSpacing(1),
# TextEntry label
InputField(
Id(:chan_mode),
Opt(:hstretch),
_("&Port Number"),
LanItems.chan_mode
),
VSpacing(1),
# TextEntry label
InputField(
Id(:lcs_timeout),
Opt(:hstretch),
_("&LANCMD Time-Out"),
LanItems.lcs_timeout
),
VSpacing(1),
HBox(
InputField(
Id(:qeth_chan_read),
Opt(:hstretch),
_("Read Channel"),
Ops.get_string(chanids_map, "read", "")
),
InputField(
Id(:qeth_chan_write),
Opt(:hstretch),
_("Write Channel"),
Ops.get_string(chanids_map, "write", "")
)
)
),
HSpacing(2)
)
),
HSpacing(6)
)
# S/390 dialog help: LCS
helptext = _("<p>Choose the <b>Port Number</b> for this interface.</p>") +
_("<p>Specify the <b>LANCMD Time-Out</b> for this interface.</p>")
end
ctcitems = [
# ComboBox item: CTC device protocol
Item(Id("0"), _("Compatibility Mode")),
# ComboBox item: CTC device protocol
Item(Id("1"), _("Extended Mode")),
# ComboBox item: CTC device protocol
Item(Id("2"), _("CTC-Based tty (Linux to Linux Connections)")),
# ComboBox item: CTC device protocol
Item(Id("3"), _("Compatibility Mode with OS/390 and z/OS"))
]
if drvtype == "ctc"
tmp_list = Builtins.splitstring(LanItems.qeth_chanids, " ")
chanids_map = {
"read" => Ops.get(tmp_list, 0, ""),
"write" => Ops.get(tmp_list, 1, "")
}
contents = HBox(
HSpacing(6),
# Frame label
Frame(
_("S/390 Device Settings"),
HBox(
HSpacing(2),
VBox(
VSpacing(1),
# TextEntry label
ComboBox(Id(:chan_mode), _("&Protocol"), ctcitems),
VSpacing(1),
HBox(
InputField(
Id(:qeth_chan_read),
Opt(:hstretch),
_("Read Channel"),
Ops.get_string(chanids_map, "read", "")
),
InputField(
Id(:qeth_chan_write),
Opt(:hstretch),
_("Write Channel"),
Ops.get_string(chanids_map, "write", "")
)
)
),
HSpacing(2)
)
),
HSpacing(6)
)
# S/390 dialog help: CTC
helptext = _("<p>Choose the <b>Protocol</b> for this interface.</p>")
end
if drvtype == "iucv"
contents = HBox(
HSpacing(6),
# Frame label
Frame(
_("S/390 Device Settings"),
HBox(
HSpacing(2),
VBox(
VSpacing(1),
# TextEntry label, #42789
InputField(
Id(:iucv_user),
Opt(:hstretch),
_("&Peer Name"),
LanItems.iucv_user
),
VSpacing(1)
),
HSpacing(2)
)
),
HSpacing(6)
)
# S/390 dialog help: IUCV, #42789
helptext = _(
"<p>Enter the name of the IUCV peer,\nfor example, the z/VM user name with which to connect (case-sensitive).</p>\n"
)
end
Wizard.SetContentsButtons(
caption,
contents,
helptext,
Label.BackButton,
Label.NextButton
)
if drvtype == "ctc"
UI.ChangeWidget(Id(:chan_mode), :Value, LanItems.chan_mode)
end
if drvtype == "lcs"
UI.ChangeWidget(Id(:chan_mode), :Value, LanItems.chan_mode)
UI.ChangeWidget(Id(:lcs_timeout), :Value, LanItems.lcs_timeout)
end
if drvtype == "qeth"
UI.ChangeWidget(Id(:ipa_takeover), :Value, LanItems.ipa_takeover)
UI.ChangeWidget(Id(:qeth_layer2), :Value, LanItems.qeth_layer2)
UI.ChangeWidget(
Id(:qeth_macaddress),
:ValidChars,
":0123456789abcdefABCDEF"
)
end
id = case LanItems.type
when "hsi" then :qeth_options
when "qeth" then :qeth_portname
when "iucv" then :iucv_user
else :chan_mode
end
UI.SetFocus(Id(id))
ret = nil
loop do
if drvtype == "qeth"
mac_enabled = Convert.to_boolean(
UI.QueryWidget(Id(:qeth_layer2), :Value)
)
UI.ChangeWidget(Id(:qeth_macaddress), :Enabled, mac_enabled)
end
ret = UI.UserInput
if ret == :abort || ret == :cancel
if ReallyAbort()
break
else
next
end
elsif ret == :back
break
elsif ret == :next
if LanItems.type == "iucv"
# #176330, must be static
LanItems.nm_name = Ops.add(
"static-iucv-id-",
Convert.to_string(UI.QueryWidget(Id(:iucv_user), :Value))
)
LanItems.device = Ops.add(
"id-",
Convert.to_string(UI.QueryWidget(Id(:iucv_user), :Value))
)
LanItems.iucv_user = Convert.to_string(
UI.QueryWidget(Id(:iucv_user), :Value)
)
end
if LanItems.type == "ctc"
LanItems.chan_mode = Convert.to_string(
UI.QueryWidget(Id(:chan_mode), :Value)
)
end
if LanItems.type == "lcs"
LanItems.lcs_timeout = Convert.to_string(
UI.QueryWidget(Id(:lcs_timeout), :Value)
)
LanItems.chan_mode = Convert.to_string(
UI.QueryWidget(Id(:chan_mode), :Value)
)
end
if LanItems.type == "qeth" || LanItems.type == "hsi"
LanItems.qeth_options = Convert.to_string(
UI.QueryWidget(Id(:qeth_options), :Value)
)
LanItems.ipa_takeover = Convert.to_boolean(
UI.QueryWidget(Id(:ipa_takeover), :Value)
)
LanItems.qeth_layer2 = Convert.to_boolean(
UI.QueryWidget(Id(:qeth_layer2), :Value)
)
LanItems.qeth_macaddress = Convert.to_string(
UI.QueryWidget(Id(:qeth_macaddress), :Value)
)
LanItems.qeth_portnumber = Convert.to_string(
UI.QueryWidget(Id(:qeth_portnumber), :Value)
)
LanItems.qeth_portname = Convert.to_string(
UI.QueryWidget(Id(:qeth_portname), :Value)
)
end
read = Convert.to_string(UI.QueryWidget(Id(:qeth_chan_read), :Value))
write = Convert.to_string(
UI.QueryWidget(Id(:qeth_chan_write), :Value)
)
control = Convert.to_string(
UI.QueryWidget(Id(:qeth_chan_control), :Value)
)
control = "" if control.nil?
LanItems.qeth_chanids = String.CutBlanks(
Builtins.sformat("%1 %2 %3", read, write, control)
)
if !LanItems.createS390Device
Popup.Error(
_(
"An error occurred while creating device.\nSee YaST log for details."
)
)
ret = nil
next
end
break
elsif ret == :qeth_layer2
next
else
Builtins.y2error("Unexpected return code: %1", ret)
next
end
end
deep_copy(ret)
end
# Manual network card configuration dialog
# @return dialog result
def HardwareDialog
caption = _("Hardware Dialog")
w = CWM.CreateWidgets(["HWDIALOG"], @widget_descr_hardware)
contents = VBox(
VStretch(),
HBox(
HStretch(),
HSpacing(1),
VBox(Ops.get_term(w, [0, "widget"]) { VSpacing(1) }),
HSpacing(1),
HStretch()
),
VStretch()
)
contents = CWM.PrepareDialog(contents, w)
Wizard.OpenNextBackDialog
Wizard.SetContents(caption, contents, initHelp, false, true)
Wizard.SetAbortButton(:cancel, Label.CancelButton)
ret = CWM.Run(w, {})
Wizard.CloseDialog
ret
end
end
end
| gpl-2.0 |
tbs-sct/gcpedia | extensions/MobileFrontend/resources/mobile.loggingSchemas/SchemaEdit.js | 1774 | ( function ( M, $ ) {
var SchemaEdit,
Schema = M.require( 'mobile.startup/Schema' ),
user = M.require( 'mobile.user/user' );
/**
* @class SchemaEdit
* @extends Schema
*/
SchemaEdit = Schema.extend( {
/** @inheritdoc **/
name: 'Edit',
/**
* https://meta.wikimedia.org/wiki/Schema:Edit
* @inheritdoc
* @cfg {Object} defaults The options hash.
*/
defaults: $.extend( {}, Schema.prototype.defaults, {
'page.id': mw.config.get( 'wgArticleId' ),
'page.revid': mw.config.get( 'wgRevisionId' ),
'page.title': mw.config.get( 'wgPageName' ),
'page.ns': mw.config.get( 'wgNamespaceNumber' ),
'user.id': user.getId(),
'user.class': user.isAnon() ? 'IP' : undefined,
'user.editCount': mw.config.get( 'wgUserEditCount', 0 ),
'mediawiki.version': mw.config.get( 'wgVersion' ),
platform: 'phone',
integration: 'page',
version: 1
} ),
/**
* @inheritdoc
*/
log: function ( data ) {
if ( mw.loader.getState( 'schema.Edit' ) === null ) {
// Only route any events into the Edit schema if the module is actually available.
// It won't be if EventLogging is installed but WikimediaEvents is not.
return $.Deferred().reject( 'schema.Edit not loaded.' );
}
data['action.' + data.action + '.type'] = data.type;
delete data.type;
data['action.' + data.action + '.mechanism'] = data.mechanism;
delete data.mechanism;
// data['action.' + data.action + '.timing'] = Math.round( computeDuration( ... ) );
data['action.' + data.action + '.message'] = data.message;
delete data.message;
mw.track( 'event.Edit', $.extend( {}, this.defaults, data ) );
return $.Deferred().resolve();
}
} );
M.define( 'loggingSchemas/SchemaEdit', SchemaEdit );
} )( mw.mobileFrontend, jQuery );
| gpl-2.0 |
tuyenln/femmefatalelashes | wp-content/plugins/portfolio/bws_menu/bws_menu.php | 54800 | <?php
/*
* Function for displaying BestWebSoft menu
* Version: 1.2.3
*/
if ( ! function_exists( 'bws_add_menu_render' ) ) {
function bws_add_menu_render() {
global $wpdb, $wpmu, $wp_version, $bws_plugin_info;
$error = $message = $bwsmn_form_email = '';
$bws_donate_link = 'https://www.2checkout.com/checkout/purchase?sid=1430388&quantity=10&product_id=13';
if ( ! function_exists( 'is_plugin_active_for_network' ) )
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
$bws_plugins = array(
'captcha/captcha.php' => array(
'name' => 'Captcha',
'description' => 'Plugin intended to prove that the visitor is a human being and not a spam robot.',
'link' => 'http://bestwebsoft.com/plugin/captcha-plugin/?k=d678516c0990e781edfb6a6c874f0b8a&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/captcha-plugin/?k=d678516c0990e781edfb6a6c874f0b8a&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Captcha+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=captcha.php',
'pro_version' => 'captcha-pro/captcha_pro.php'
),
'contact-form-plugin/contact_form.php' => array(
'name' => 'Contact form',
'description' => 'Add Contact Form to your WordPress website.',
'link' => 'http://bestwebsoft.com/plugin/contact-form/?k=012327ef413e5b527883e031d43b088b&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/contact-form/?k=012327ef413e5b527883e031d43b088b&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Contact+Form+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=contact_form.php',
'pro_version' => 'contact-form-pro/contact_form_pro.php'
),
'facebook-button-plugin/facebook-button-plugin.php' => array(
'name' => 'Facebook Like Button',
'description' => 'Allows you to add the Follow and Like buttons the easiest way.',
'link' => 'http://bestwebsoft.com/plugin/facebook-like-button-plugin/?k=05ec4f12327f55848335802581467d55&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/facebook-like-button-plugin/?k=05ec4f12327f55848335802581467d55&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Facebook+Like+Button+Plugin+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=facebook-button-plugin.php',
'pro_version' => 'facebook-button-pro/facebook-button-pro.php'
),
'twitter-plugin/twitter.php' => array(
'name' => 'Twitter',
'description' => 'Allows you to add the Twitter "Follow" and "Like" buttons the easiest way.',
'link' => 'http://bestwebsoft.com/plugin/twitter-plugin/?k=f8cb514e25bd7ec4974d64435c5eb333&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/twitter-plugin/?k=f8cb514e25bd7ec4974d64435c5eb333&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Twitter+Plugin+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=twitter.php',
'pro_version' => 'twitter-pro/twitter-pro.php'
),
'portfolio/portfolio.php' => array(
'name' => 'Portfolio',
'description' => 'Allows you to create a page with the information about your past projects.',
'link' => 'http://bestwebsoft.com/plugin/portfolio-plugin/?k=1249a890c5b7bba6bda3f528a94f768b&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/portfolio-plugin/?k=1249a890c5b7bba6bda3f528a94f768b&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Portfolio+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=portfolio.php'
),
'gallery-plugin/gallery-plugin.php' => array(
'name' => 'Gallery',
'description' => 'Allows you to implement a Gallery page into your website.',
'link' => 'http://bestwebsoft.com/plugin/gallery-plugin/?k=2da21c0a64eec7ebf16337fa134c5f78&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/gallery-plugin/?k=2da21c0a64eec7ebf16337fa134c5f78&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Gallery+Plugin+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=gallery-plugin.php',
'pro_version' => 'gallery-plugin-pro/gallery-plugin-pro.php'
),
'adsense-plugin/adsense-plugin.php'=> array(
'name' => 'Google AdSense',
'description' => 'Allows Google AdSense implementation to your website.',
'link' => 'http://bestwebsoft.com/plugin/google-adsense-plugin/?k=60e3979921e354feb0347e88e7d7b73d&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/google-adsense-plugin/?k=60e3979921e354feb0347e88e7d7b73d&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Adsense+Plugin+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=adsense-plugin.php'
),
'custom-search-plugin/custom-search-plugin.php'=> array(
'name' => 'Custom Search',
'description' => 'Allows to extend your website search functionality by adding a custom post type.',
'link' => 'http://bestwebsoft.com/plugin/custom-search-plugin/?k=933be8f3a8b8719d95d1079d15443e29&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/custom-search-plugin/?k=933be8f3a8b8719d95d1079d15443e29&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Custom+Search+plugin+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=custom_search.php'
),
'quotes-and-tips/quotes-and-tips.php'=> array(
'name' => 'Quotes and Tips',
'description' => 'Allows you to implement quotes & tips block into your web site.',
'link' => 'http://bestwebsoft.com/plugin/quotes-and-tips/?k=5738a4e85a798c4a5162240c6515098d&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/quotes-and-tips/?k=5738a4e85a798c4a5162240c6515098d&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Quotes+and+Tips+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=quotes-and-tips.php'
),
'google-sitemap-plugin/google-sitemap-plugin.php'=> array(
'name' => 'Google Sitemap',
'description' => 'Allows you to add sitemap file to Google Webmaster Tools.',
'link' => 'http://bestwebsoft.com/plugin/google-sitemap-plugin/?k=5202b2f5ce2cf85daee5e5f79a51d806&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/google-sitemap-plugin/?k=5202b2f5ce2cf85daee5e5f79a51d806&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Google+sitemap+plugin+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=google-sitemap-plugin.php',
'pro_version' => 'google-sitemap-pro/google-sitemap-pro.php'
),
'updater/updater.php'=> array(
'name' => 'Updater',
'description' => 'Allows you to update plugins and WP core.',
'link' => 'http://bestwebsoft.com/plugin/updater-plugin/?k=66f3ecd4c1912009d395c4bb30f779d1&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/updater-plugin/?k=66f3ecd4c1912009d395c4bb30f779d1&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=updater+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=updater-options',
'pro_version' => 'updater-pro/updater_pro.php'
),
'custom-fields-search/custom-fields-search.php'=> array(
'name' => 'Custom Fields Search',
'description' => 'Allows you to add website search any existing custom fields.',
'link' => 'http://bestwebsoft.com/plugin/custom-fields-search/?k=f3f8285bb069250c42c6ffac95ed3284&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/custom-fields-search/?k=f3f8285bb069250c42c6ffac95ed3284&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Custom+Fields+Search+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=custom_fields_search.php'
),
'google-one/google-plus-one.php' => array(
'name' => 'Google +1',
'description' => 'Allows you to celebrate liked the article.',
'link' => 'http://bestwebsoft.com/plugin/google-plus-one/?k=ce7a88837f0a857b3a2bb142f470853c&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/google-plus-one/?k=ce7a88837f0a857b3a2bb142f470853c&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&type=term&s=Google+%2B1+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=google-plus-one.php',
'pro_version' => 'google-one-pro/google-plus-one-pro.php'
),
'relevant/related-posts-plugin.php' => array(
'name' => 'Relevant - Related Posts',
'description' => 'Allows you to display related posts with similar words in category, tags, title or by adding special meta key for posts.',
'link' => 'http://bestwebsoft.com/plugin/related-posts-plugin/?k=73fb737037f7141e66415ec259f7e426&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/related-posts-plugin/?k=73fb737037f7141e66415ec259f7e426&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=Related+Posts+Plugin+Bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=related-posts-plugin.php'
),
'contact-form-to-db/contact_form_to_db.php' => array(
'name' => 'Contact Form To DB',
'description' => 'Allows you to manage the messages that have been sent from your site.',
'link' => 'http://bestwebsoft.com/plugin/contact-form-to-db/?k=ba3747d317c2692e4136ca096a8989d6&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/contact-form-to-db/?k=ba3747d317c2692e4136ca096a8989d6&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=Contact+Form+to+DB+bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=cntctfrmtdb_settings',
'pro_version' => 'contact-form-to-db-pro/contact_form_to_db_pro.php'
),
'pdf-print/pdf-print.php' => array(
'name' => 'PDF & Print',
'description' => 'Allows you to create PDF and Print page with adding appropriate buttons to the content.',
'link' => 'http://bestwebsoft.com/plugin/pdf-print/?k=bfefdfb522a4c0ff0141daa3f271840c&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/pdf-print/?k=bfefdfb522a4c0ff0141daa3f271840c&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=PDF+Print+Bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=pdf-print.php',
'pro_version' => 'pdf-print-pro/pdf-print-pro.php'
),
'donate-button/donate.php' => array(
'name' => 'Donate',
'description' => 'Makes it possible to place donation buttons of various payment systems on your web page.',
'link' => 'http://bestwebsoft.com/plugin/donate/?k=a8b2e2a56914fb1765dd20297c26401b&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/donate/?k=a8b2e2a56914fb1765dd20297c26401b&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=Donate+Bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=donate.php'
),
'post-to-csv/post-to-csv.php' => array(
'name' => 'Post To CSV',
'description' => 'The plugin allows to export posts of any types to a csv file.',
'link' => 'http://bestwebsoft.com/plugin/post-to-csv/?k=653aa55518ae17409293a7a894268b8f&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/post-to-csv/?k=653aa55518ae17409293a7a894268b8f&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=Post+To+CSV+Bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=post-to-csv.php'
),
'google-shortlink/google-shortlink.php' => array(
'name' => 'Google Shortlink',
'description' => 'Allows you to get short links from goo.gl servise without leaving your site.',
'link' => 'http://bestwebsoft.com/plugin/google-shortlink/?k=afcf3eaed021bbbbeea1090e16bc22db&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/google-shortlink/?k=afcf3eaed021bbbbeea1090e16bc22db&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=Google+Shortlink+Bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=gglshrtlnk_options'
),
'htaccess/htaccess.php' => array(
'name' => 'Htaccess',
'description' => 'Allows controlling access to your website using the directives Allow and Deny.',
'link' => 'http://bestwebsoft.com/plugin/htaccess/?k=2b865fcd56a935d22c5c4f1bba52ed46&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/htaccess/?k=2b865fcd56a935d22c5c4f1bba52ed46&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=Htaccess+Bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=htaccess.php'
),
'google-captcha/google-captcha.php' => array(
'name' => 'Google Captcha (reCAPTCHA)',
'description' => 'Plugin intended to prove that the visitor is a human being and not a spam robot.',
'link' => 'http://bestwebsoft.com/plugin/google-captcha/?k=7b59fbe542acf950b29f3e020d5ad735&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/google-captcha/?k=7b59fbe542acf950b29f3e020d5ad735&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=Google+Captcha+Bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=google-captcha.php'
),
'sender/sender.php' => array(
'name' => 'Sender',
'description' => 'You can send mails to all users or to certain categories of users.',
'link' => 'http://bestwebsoft.com/plugin/sender/?k=89c297d14ba85a8417a0f2fc05e089c7&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/sender/?k=89c297d14ba85a8417a0f2fc05e089c7&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=Sender+Bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=sndr_settings'
),
'subscriber/subscriber.php' => array(
'name' => 'Subscriber',
'description' => 'This plugin allows you to subscribe users for newsletters from your website.',
'link' => 'http://bestwebsoft.com/plugin/subscriber/?k=a4ecc1b7800bae7329fbe8b4b04e9c88&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/subscriber/?k=a4ecc1b7800bae7329fbe8b4b04e9c88&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=Subscriber+Bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=sbscrbr_settings_page'
),
'contact-form-multi/contact-form-multi.php' => array(
'name' => 'Contact Form Multi',
'description' => 'This plugin allows you to subscribe users for newsletters from your website.',
'link' => 'http://bestwebsoft.com/plugin/contact-form-multi/?k=83cdd9e72a9f4061122ad28a67293c72&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/contact-form-multi/?k=83cdd9e72a9f4061122ad28a67293c72&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=Contact+Form+Multi+Bestwebsoft&plugin-search-input=Search+Plugins',
'settings' => ''
),
'bws-google-maps/bws-google-maps.php' => array(
'name' => 'BestWebSoft Google Maps',
'description' => 'Easy to set up and insert Google Maps to your website.',
'link' => 'http://bestwebsoft.com/plugin/bws-google-maps/?k=d8fac412d7359ebaa4ff53b46572f9f7&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/bws-google-maps/?k=d8fac412d7359ebaa4ff53b46572f9f7&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=BestWebSoft+Google+Maps&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=bws-google-maps.php'
),
'bws-google-analytics/bws-google-analytics.php' => array(
'name' => 'BestWebSoft Google Analytics',
'description' => 'Allows you to retrieve basic stats from Google Analytics account and add the tracking code to your blog.',
'link' => 'http://bestwebsoft.com/plugin/bws-google-analytics/?k=261c74cad753fb279cdf5a5db63fbd43&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'download' => 'http://bestwebsoft.com/plugin/bws-google-analytics/?k=261c74cad753fb279cdf5a5db63fbd43&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#download',
'wp_install' => '/wp-admin/plugin-install.php?tab=search&s=BestWebSoft+Google+Analytics&plugin-search-input=Search+Plugins',
'settings' => 'admin.php?page=bws-google-analytics.php'
)
);
$bws_plugins_pro = array(
'gallery-plugin-pro/gallery-plugin-pro.php' => array(
'name' => 'Gallery Pro',
'description' => 'Allows you to implement as many galleries as you want into your website.',
'link' => 'http://bestwebsoft.com/plugin/gallery-pro/?k=382e5ce7c96a6391f5ffa5e116b37fe0&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'purchase' => 'http://bestwebsoft.com/plugin/gallery-pro/?k=382e5ce7c96a6391f5ffa5e116b37fe0&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#purchase',
'settings' => 'admin.php?page=gallery-plugin-pro.php'
),
'contact-form-pro/contact_form_pro.php' => array(
'name' => 'Contact form Pro',
'description' => 'Allows you to implement a feedback form to a web-page or a post in no time.',
'link' => 'http://bestwebsoft.com/plugin/contact-form-pro/?k=773dc97bb3551975db0e32edca1a6d71&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'purchase' => 'http://bestwebsoft.com/plugin/contact-form-pro/?k=773dc97bb3551975db0e32edca1a6d71&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#purchase',
'settings' => 'admin.php?page=contact_form_pro.php'
),
'captcha-pro/captcha_pro.php' => array(
'name' => 'Captcha Pro',
'description' => 'Allows you to implement a super security captcha form into web forms.',
'link' => 'http://bestwebsoft.com/plugin/captcha-pro/?k=ff7d65e55e5e7f98f219be9ed711094e&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'purchase' => 'http://bestwebsoft.com/plugin/captcha-pro/?k=ff7d65e55e5e7f98f219be9ed711094e&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#purchase',
'settings' => 'admin.php?page=captcha_pro.php'
),
'updater-pro/updater_pro.php' => array(
'name' => 'Updater Pro',
'description' => 'Allows you to update plugins and WordPress core on your website.',
'link' => 'http://bestwebsoft.com/plugin/updater-pro/?k=cf633acbefbdff78545347fe08a3aecb&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'purchase' => 'http://bestwebsoft.com/plugin/updater-pro?k=cf633acbefbdff78545347fe08a3aecb&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#purchase',
'settings' => 'admin.php?page=updater-pro-options'
),
'contact-form-to-db-pro/contact_form_to_db_pro.php' => array(
'name' => 'Contact form to DB Pro',
'description' => 'The plugin provides a unique opportunity to manage messages sent from your site via the contact form.',
'link' => 'http://bestwebsoft.com/plugin/contact-form-to-db-pro/?k=6ce5f4a9006ec906e4db643669246c6a&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'purchase' => 'http://bestwebsoft.com/plugin/contact-form-to-db-pro/?k=6ce5f4a9006ec906e4db643669246c6a&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#purchase',
'settings' => 'admin.php?page=cntctfrmtdbpr_settings'
),
'google-sitemap-pro/google-sitemap-pro.php'=> array(
'name' => 'Google Sitemap Pro',
'description' => 'Allows you to add sitemap file to Google Webmaster Tools.',
'link' => 'http://bestwebsoft.com/plugin/google-sitemap-pro/?k=7ea384a5cc36cb4c22741caa20dcd56d&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'purchase' => 'http://bestwebsoft.com/plugin/google-sitemap-pro/?k=7ea384a5cc36cb4c22741caa20dcd56d&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#purchase',
'settings' => 'admin.php?page=google-sitemap-pro.php'
),
'twitter-pro/twitter-pro.php' => array(
'name' => 'Twitter Pro',
'description' => 'Allows you to add the Twitter "Follow" and "Like" buttons the easiest way.',
'link' => 'http://bestwebsoft.com/plugin/twitter-pro/?k=63ecbf0cc9cebf060b5a3c9362299700&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'purchase' => 'http://bestwebsoft.com/plugin/twitter-pro?k=63ecbf0cc9cebf060b5a3c9362299700&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#purchase',
'settings' => 'admin.php?page=twitter-pro.php'
),
'google-one-pro/google-plus-one-pro.php' => array(
'name' => 'Google +1 Pro',
'description' => 'Allows you to celebrate liked the article.',
'link' => 'http://bestwebsoft.com/plugin/google-plus-one-pro/?k=f4b0a62d155c9df9601a0531ad5bd832&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'purchase' => 'http://bestwebsoft.com/plugin/google-plus-one-pro?k=f4b0a62d155c9df9601a0531ad5bd832&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#purchase',
'settings' => 'admin.php?page=google-plus-one-pro.php'
),
'facebook-button-pro/facebook-button-pro.php' => array(
'name' => 'Facebook Like Button Pro',
'description' => 'Allows you to add the Follow and Like buttons the easiest way.',
'link' => 'http://bestwebsoft.com/plugin/facebook-like-button-pro/?k=8da168e60a831cfb3525417c333ad275&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'purchase' => 'http://bestwebsoft.com/plugin/facebook-like-button-pro?k=8da168e60a831cfb3525417c333ad275&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#purchase',
'settings' => 'admin.php?page=facebook-button-pro.php'
),
'pdf-print-pro/pdf-print-pro.php' => array(
'name' => 'PDF & Print Pro',
'description' => 'Allows you to create PDF and Print page with adding appropriate buttons to the content.',
'link' => 'http://bestwebsoft.com/plugin/pdf-print-pro/?k=fd43a0e659ddc170a9060027cbfdcc3a&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version,
'purchase' => 'http://bestwebsoft.com/plugin/pdf-print-pro?k=fd43a0e659ddc170a9060027cbfdcc3a&pn=' . $bws_plugin_info["id"] . '&v=' . $bws_plugin_info["version"] . '&wp_v=' . $wp_version . '#purchase',
'settings' => 'admin.php?page=pdf-print-pro.php'
)
);
$all_plugins = get_plugins();
$active_plugins = get_option( 'active_plugins' );
$recommend_plugins = array_diff_key( $bws_plugins, $all_plugins );
foreach ( $bws_plugins as $key_plugin => $value_plugin ) {
if ( ! isset( $all_plugins[ $key_plugin ] ) && isset( $bws_plugins[ $key_plugin ]['pro_version'] ) && isset( $all_plugins[ $bws_plugins[ $key_plugin ]['pro_version'] ] ) ) {
unset( $recommend_plugins[ $key_plugin ] );
}
}
foreach ( $all_plugins as $key_plugin => $value_plugin ) {
if ( ! isset( $bws_plugins[ $key_plugin ] ) && ! isset( $bws_plugins_pro[ $key_plugin ] ) )
unset( $all_plugins[ $key_plugin ] );
if ( isset( $bws_plugins[ $key_plugin ] ) && isset( $bws_plugins[ $key_plugin ]['pro_version'] ) && isset( $all_plugins[ $bws_plugins[ $key_plugin ]['pro_version'] ] ) ) {
unset( $all_plugins[ $key_plugin ] );
}
}
if ( isset( $_GET['action'] ) && 'system_status' == $_GET['action'] ) {
$all_plugins = get_plugins();
$active_plugins = get_option( 'active_plugins' );
$sql_version = $wpdb->get_var( "SELECT VERSION() AS version" );
$mysql_info = $wpdb->get_results( "SHOW VARIABLES LIKE 'sql_mode'" );
if ( is_array( $mysql_info) )
$sql_mode = $mysql_info[0]->Value;
if ( empty( $sql_mode ) )
$sql_mode = __( 'Not set', 'bestwebsoft' );
if ( ini_get( 'safe_mode' ) )
$safe_mode = __( 'On', 'bestwebsoft' );
else
$safe_mode = __( 'Off', 'bestwebsoft' );
if ( ini_get( 'allow_url_fopen' ) )
$allow_url_fopen = __( 'On', 'bestwebsoft' );
else
$allow_url_fopen = __( 'Off', 'bestwebsoft' );
if ( ini_get( 'upload_max_filesize' ) )
$upload_max_filesize = ini_get( 'upload_max_filesize' );
else
$upload_max_filesize = __( 'N/A', 'bestwebsoft' );
if ( ini_get('post_max_size') )
$post_max_size = ini_get('post_max_size');
else
$post_max_size = __( 'N/A', 'bestwebsoft' );
if ( ini_get( 'max_execution_time' ) )
$max_execution_time = ini_get( 'max_execution_time' );
else
$max_execution_time = __( 'N/A', 'bestwebsoft' );
if ( ini_get( 'memory_limit' ) )
$memory_limit = ini_get( 'memory_limit' );
else
$memory_limit = __( 'N/A', 'bestwebsoft' );
if ( function_exists( 'memory_get_usage' ) )
$memory_usage = round( memory_get_usage() / 1024 / 1024, 2 ) . __( ' Mb', 'bestwebsoft' );
else
$memory_usage = __( 'N/A', 'bestwebsoft' );
if ( is_callable( 'exif_read_data' ) )
$exif_read_data = __( 'Yes', 'bestwebsoft' ) . " ( V" . substr( phpversion( 'exif' ), 0,4 ) . ")" ;
else
$exif_read_data = __( 'No', 'bestwebsoft' );
if ( is_callable( 'iptcparse' ) )
$iptcparse = __( 'Yes', 'bestwebsoft' );
else
$iptcparse = __( 'No', 'bestwebsoft' );
if ( is_callable( 'xml_parser_create' ) )
$xml_parser_create = __( 'Yes', 'bestwebsoft' );
else
$xml_parser_create = __( 'No', 'bestwebsoft' );
if ( function_exists( 'wp_get_theme' ) )
$theme = wp_get_theme();
else
$theme = get_theme( get_current_theme() );
if ( function_exists( 'is_multisite' ) ) {
if ( is_multisite() ) {
$multisite = __( 'Yes', 'bestwebsoft' );
} else {
$multisite = __( 'No', 'bestwebsoft' );
}
} else
$multisite = __( 'N/A', 'bestwebsoft' );
$site_url = get_option( 'siteurl' );
$home_url = get_option( 'home' );
$db_version = get_option( 'db_version' );
$system_info = array(
'system_info' => '',
'active_plugins' => '',
'inactive_plugins' => ''
);
$system_info['system_info'] = array(
__( 'Operating System', 'bestwebsoft' ) => PHP_OS,
__( 'Server', 'bestwebsoft' ) => $_SERVER["SERVER_SOFTWARE"],
__( 'Memory usage', 'bestwebsoft' ) => $memory_usage,
__( 'MYSQL Version', 'bestwebsoft' ) => $sql_version,
__( 'SQL Mode', 'bestwebsoft' ) => $sql_mode,
__( 'PHP Version', 'bestwebsoft' ) => PHP_VERSION,
__( 'PHP Safe Mode', 'bestwebsoft' ) => $safe_mode,
__( 'PHP Allow URL fopen', 'bestwebsoft' ) => $allow_url_fopen,
__( 'PHP Memory Limit', 'bestwebsoft' ) => $memory_limit,
__( 'PHP Max Upload Size', 'bestwebsoft' ) => $upload_max_filesize,
__( 'PHP Max Post Size', 'bestwebsoft' ) => $post_max_size,
__( 'PHP Max Script Execute Time', 'bestwebsoft' ) => $max_execution_time,
__( 'PHP Exif support', 'bestwebsoft' ) => $exif_read_data,
__( 'PHP IPTC support', 'bestwebsoft' ) => $iptcparse,
__( 'PHP XML support', 'bestwebsoft' ) => $xml_parser_create,
__( 'Site URL', 'bestwebsoft' ) => $site_url,
__( 'Home URL', 'bestwebsoft' ) => $home_url,
'$_SERVER[HTTP_HOST]' => $_SERVER['HTTP_HOST'],
'$_SERVER[SERVER_NAME]' => $_SERVER['SERVER_NAME'],
__( 'WordPress Version', 'bestwebsoft' ) => $wp_version,
__( 'WordPress DB Version', 'bestwebsoft' ) => $db_version,
__( 'Multisite', 'bestwebsoft' ) => $multisite,
__( 'Active Theme', 'bestwebsoft' ) => $theme['Name'] . ' ' . $theme['Version']
);
foreach ( $all_plugins as $path => $plugin ) {
if ( is_plugin_active( $path ) ) {
$system_info['active_plugins'][ $plugin['Name'] ] = $plugin['Version'];
} else {
$system_info['inactive_plugins'][ $plugin['Name'] ] = $plugin['Version'];
}
}
}
if ( ( isset( $_REQUEST['bwsmn_form_submit'] ) && check_admin_referer( plugin_basename(__FILE__), 'bwsmn_nonce_submit' ) ) ||
( isset( $_REQUEST['bwsmn_form_submit_custom_email'] ) && check_admin_referer( plugin_basename(__FILE__), 'bwsmn_nonce_submit_custom_email' ) ) ) {
if ( isset( $_REQUEST['bwsmn_form_email'] ) ) {
$bwsmn_form_email = trim( $_REQUEST['bwsmn_form_email'] );
if ( $bwsmn_form_email == "" || !preg_match( "/^((?:[a-z0-9']+(?:[a-z0-9\-_\.']+)?@[a-z0-9]+(?:[a-z0-9\-\.]+)?\.[a-z]{2,5})[, ]*)+$/i", $bwsmn_form_email ) ) {
$error = __( "Please enter a valid email address.", 'bestwebsoft' );
} else {
$email = $bwsmn_form_email;
$bwsmn_form_email = '';
$message = __( 'Email with system info is sent to ', 'bestwebsoft' ) . $email;
}
} else {
$email = 'plugin_system_status@bestwebsoft.com';
$message = __( 'Thank you for contacting us.', 'bestwebsoft' );
}
if ( $error == '' ) {
$headers = 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\n";
$headers .= 'From: ' . get_option( 'admin_email' );
$message_text = '<html><head><title>System Info From ' . $home_url . '</title></head><body>
<h4>Environment</h4>
<table>';
foreach ( $system_info['system_info'] as $key => $value ) {
$message_text .= '<tr><td>'. $key .'</td><td>'. $value .'</td></tr>';
}
$message_text .= '</table>
<h4>Active Plugins</h4>
<table>';
foreach ( $system_info['active_plugins'] as $key => $value ) {
$message_text .= '<tr><td scope="row">'. $key .'</td><td scope="row">'. $value .'</td></tr>';
}
$message_text .= '</table>
<h4>Inactive Plugins</h4>
<table>';
foreach ( $system_info['inactive_plugins'] as $key => $value ) {
$message_text .= '<tr><td scope="row">'. $key .'</td><td scope="row">'. $value .'</td></tr>';
}
$message_text .= '</table></body></html>';
$result = wp_mail( $email, 'System Info From ' . $home_url, $message_text, $headers );
if ( $result != true )
$error = __( "Sorry, email message could not be delivered.", 'bestwebsoft' );
}
}
?>
<div class="wrap">
<div class="icon32 icon32-bws" id="icon-options-general"></div>
<h2>BestWebSoft</h2>
<h2 class="nav-tab-wrapper">
<a class="nav-tab<?php if ( !isset( $_GET['action'] ) ) echo ' nav-tab-active'; ?>" href="admin.php?page=bws_plugins"><?php _e( 'Plugins', 'bestwebsoft' ); ?></a>
<?php if ( $wp_version >= '3.4' ) { ?>
<a class="nav-tab<?php if ( isset( $_GET['action'] ) && 'themes' == $_GET['action'] ) echo ' nav-tab-active'; ?>" href="admin.php?page=bws_plugins&action=themes"><?php _e( 'Themes', 'bestwebsoft' ); ?></a>
<?php } ?>
<a class="nav-tab<?php if ( isset( $_GET['action'] ) && 'system_status' == $_GET['action'] ) echo ' nav-tab-active'; ?>" href="admin.php?page=bws_plugins&action=system_status"><?php _e( 'System status', 'bestwebsoft' ); ?></a>
</h2>
<?php if ( !isset( $_GET['action'] ) ) { ?>
<ul class="subsubsub">
<li><a <?php if ( !isset( $_GET['sub'] ) ) echo 'class="current" '; ?>href="admin.php?page=bws_plugins"><?php _e( 'All', 'bestwebsoft' ); ?></a></li> |
<li><a <?php if ( isset( $_GET['sub'] ) && 'installed' == $_GET['sub'] ) echo 'class="current" '; ?>href="admin.php?page=bws_plugins&sub=installed"><?php _e( 'Installed', 'bestwebsoft' ); ?></a></li> |
<li><a <?php if ( isset( $_GET['sub'] ) && 'recommended' == $_GET['sub'] ) echo 'class="current" '; ?>href="admin.php?page=bws_plugins&sub=recommended"><?php _e( 'Recommended', 'bestwebsoft' ); ?></a></li>
</ul>
<div class="clear"></div>
<?php if ( ( isset( $_GET['sub'] ) && 'installed' == $_GET['sub'] ) || !isset( $_GET['sub'] ) ) { ?>
<h4 class="bws_installed"><?php _e( 'Installed plugins', 'bestwebsoft' ); ?></h4>
<?php foreach ( $all_plugins as $key_plugin => $value_plugin ) {
if ( isset( $bws_plugins_pro[ $key_plugin ] ) ) {
$key_plugin_explode = explode( '-plugin-pro/', $key_plugin );
if ( isset( $key_plugin_explode[1] ) )
$icon = $key_plugin_explode[0];
else {
$key_plugin_explode = explode( '-pro/', $key_plugin );
$icon = $key_plugin_explode[0];
}
} elseif ( isset( $bws_plugins[ $key_plugin ] ) ) {
$key_plugin_explode = explode( '-plugin/', $key_plugin );
if ( isset( $key_plugin_explode[1] ) )
$icon = $key_plugin_explode[0];
else {
$key_plugin_explode = explode( '/', $key_plugin );
$icon = $key_plugin_explode[0];
}
}
if ( in_array( $key_plugin, $active_plugins ) || is_plugin_active_for_network( $key_plugin ) ) { ?>
<?php if ( isset( $bws_plugins_pro[ $key_plugin ] ) ) { ?>
<div class="bws_product_box bws_exist_overlay">
<div class="bws_product">
<div class="bws_product_title"><?php echo $value_plugin["Name"]; ?></div>
<div class="bws_product_content">
<div class="bws_product_icon">
<div class="bws_product_icon_pro"></div>
<img src="<?php echo plugins_url( "icons/" , __FILE__ ) . $icon . '.png'; ?>"/>
</div>
<div class="bws_product_description"><?php echo $value_plugin["Description"]; ?></div>
</div>
<div class="clear"></div>
</div>
<div class="bws_product_links">
<a href="<?php echo $bws_plugins_pro[ $key_plugin ]["link"]; ?>" target="_blank"><?php _e( "Learn more", 'bestwebsoft' ); ?></a>
<span> | </span>
<a href="<?php echo $bws_plugins_pro[ $key_plugin ]["settings"]; ?>" target="_blank"><?php _e( "Settings", 'bestwebsoft' ); ?></a>
</div>
</div>
<?php } elseif ( isset( $bws_plugins[ $key_plugin ] ) ) { ?>
<div class="bws_product_box bws_product_free">
<div class="bws_product">
<div class="bws_product_title"><?php echo $value_plugin["Name"]; ?></div>
<div class="bws_product_content">
<div class="bws_product_icon">
<img src="<?php echo plugins_url( "icons/" , __FILE__ ) . $icon . '.png'; ?>"/>
</div>
<div class="bws_product_description"><?php echo $bws_plugins[ $key_plugin ]["description"]; ?></div>
</div>
<?php if ( isset( $bws_plugins[ $key_plugin ]['pro_version'] ) && isset( $bws_plugins_pro[ $bws_plugins[ $key_plugin ]['pro_version'] ] ) ) { ?>
<a class="bws_product_button" href="<?php echo $bws_plugins_pro[ $bws_plugins[ $key_plugin ]['pro_version'] ]["purchase"]; ?>" target="_blank">
<?php _e( 'Go', 'bestwebsoft' );?> <strong>PRO</strong>
</a>
<?php } else { ?>
<a class="bws_product_button bws_donate_button" href="<?php echo $bws_donate_link; ?>" target="_blank">
<strong><?php _e( 'DONATE', 'bestwebsoft' );?></strong>
</a>
<?php } ?>
<div class="clear"></div>
</div>
<div class="bws_product_links">
<a href="<?php echo $bws_plugins[ $key_plugin ]["link"]; ?>" target="_blank"><?php _e( "Learn more", 'bestwebsoft' ); ?></a>
<span> | </span>
<a href="<?php echo $bws_plugins[ $key_plugin ]["settings"]; ?>" target="_blank"><?php _e( "Settings", 'bestwebsoft' ); ?></a>
</div>
</div>
<?php }
} else {
if ( isset( $bws_plugins_pro[ $key_plugin ] ) ) { ?>
<div class="bws_product_box bws_product_deactivated">
<div class="bws_product">
<div class="bws_product_title"><?php echo $value_plugin["Name"]; ?></div>
<div class="bws_product_content">
<div class="bws_product_icon">
<div class="bws_product_icon_pro"></div>
<img src="<?php echo plugins_url( "icons/" , __FILE__ ) . $icon . '.png'; ?>"/>
</div>
<div class="bws_product_description"><?php echo $bws_plugins_pro[ $key_plugin ]["description"]; ?></div>
</div>
<div class="clear"></div>
</div>
<div class="bws_product_links">
<a href="<?php echo $bws_plugins_pro[ $key_plugin ]["link"]; ?>" target="_blank"><?php _e( "Learn more", 'bestwebsoft' ); ?></a>
<span> | </span>
<a class="bws_activate" href="plugins.php" title="<?php _e( "Activate this plugin", 'bestwebsoft' ); ?>" target="_blank"><?php _e( "Activate", 'bestwebsoft' ); ?></a>
</div>
</div>
<?php } elseif ( isset( $bws_plugins[ $key_plugin ] ) ) { ?>
<div class="bws_product_box bws_product_deactivated bws_product_free">
<div class="bws_product">
<div class="bws_product_title"><?php echo $value_plugin["Name"]; ?></div>
<div class="bws_product_content">
<div class="bws_product_icon">
<img src="<?php echo plugins_url( "icons/" , __FILE__ ) . $icon . '.png'; ?>"/>
</div>
<div class="bws_product_description"><?php echo $bws_plugins[ $key_plugin ]["description"]; ?></div>
</div>
<?php if ( isset( $bws_plugins[ $key_plugin ]['pro_version'] ) && isset( $bws_plugins_pro[ $bws_plugins[ $key_plugin ]['pro_version'] ] ) ) { ?>
<a class="bws_product_button" href="<?php echo $bws_plugins_pro[ $bws_plugins[ $key_plugin ]['pro_version'] ]["purchase"]; ?>" target="_blank">
<?php _e( 'Go', 'bestwebsoft' );?> <strong>PRO</strong>
</a>
<?php } else { ?>
<a class="bws_product_button bws_donate_button" href="<?php echo $bws_donate_link; ?>" target="_blank">
<strong><?php _e( 'DONATE', 'bestwebsoft' );?></strong>
</a>
<?php } ?>
<div class="clear"></div>
</div>
<div class="bws_product_links">
<a href="<?php echo $bws_plugins[ $key_plugin ]["link"]; ?>" target="_blank"><?php _e( "Learn more", 'bestwebsoft' ); ?></a>
<span> | </span>
<a class="bws_activate" href="plugins.php" title="<?php _e( "Activate this plugin", 'bestwebsoft' ); ?>" target="_blank"><?php _e( "Activate", 'bestwebsoft' ); ?></a>
</div>
</div>
<?php }
}
}
} ?>
<div class="clear"></div>
<?php if ( ( isset( $_GET['sub'] ) && 'recommended' == $_GET['sub'] ) || !isset( $_GET['sub'] ) ) { ?>
<h4 class="bws_recommended"><?php _e( 'Recommended plugins', 'bestwebsoft' ); ?></h4>
<?php foreach ( $recommend_plugins as $key_plugin => $value_plugin ) {
if ( isset( $bws_plugins_pro[ $key_plugin ] ) ) {
$key_plugin_explode = explode( '-plugin-pro/', $key_plugin );
if ( isset( $key_plugin_explode[1] ) )
$icon = $key_plugin_explode[0];
else {
$key_plugin_explode = explode( '-pro/', $key_plugin );
$icon = $key_plugin_explode[0];
}
} elseif ( isset( $bws_plugins[ $key_plugin ] ) ) {
$key_plugin_explode = explode( '-plugin/', $key_plugin );
if ( isset( $key_plugin_explode[1] ) )
$icon = $key_plugin_explode[0];
else {
$key_plugin_explode = explode( '/', $key_plugin );
$icon = $key_plugin_explode[0];
}
}
?>
<div class="bws_product_box">
<div class="bws_product">
<div class="bws_product_title"><?php echo $value_plugin["name"]; ?></div>
<div class="bws_product_content">
<div class="bws_product_icon">
<?php if ( isset( $bws_plugins[ $key_plugin ]['pro_version'] ) && isset( $bws_plugins_pro[ $bws_plugins[ $key_plugin ]['pro_version'] ] ) ) { ?>
<div class="bws_product_icon_pro"></div>
<?php } ?>
<img src="<?php echo plugins_url( "icons/" , __FILE__ ) . $icon . '.png'; ?>"/>
</div>
<div class="bws_product_description"><?php echo $bws_plugins[ $key_plugin ]["description"]; ?></div>
</div>
<?php if ( isset( $bws_plugins[ $key_plugin ]['pro_version'] ) && isset( $bws_plugins_pro[ $bws_plugins[ $key_plugin ]['pro_version'] ] ) ) { ?>
<a class="bws_product_button" href="<?php echo $bws_plugins_pro[ $bws_plugins[ $key_plugin ]['pro_version'] ]["link"]; ?>" target="_blank">
<?php echo _e( 'Go', 'bestwebsoft' );?> <strong>PRO</strong>
</a>
<?php } else { ?>
<a class="bws_product_button bws_donate_button" href="<?php echo $bws_donate_link; ?>" target="_blank">
<strong><?php echo _e( 'DONATE', 'bestwebsoft' );?></strong>
</a>
<?php } ?>
</div>
<div class="clear"></div>
<div class="bws_product_links">
<a href="<?php echo $bws_plugins[ $key_plugin ]["link"]; ?>" target="_blank"><?php echo __( "Learn more", 'bestwebsoft' ); ?></a>
<span> | </span>
<a href="<?php echo $bws_plugins[ $key_plugin ]["wp_install"]; ?>" target="_blank"><?php echo __( "Install now", 'bestwebsoft' ); ?></a>
</div>
</div>
<?php }
} ?>
<?php } elseif ( 'themes' == $_GET['action'] ) { ?>
<div id="availablethemes">
<?php
global $tabs, $tab, $paged, $type, $theme_field_defaults;
include( ABSPATH . 'wp-admin/includes/theme-install.php' );
include( ABSPATH . 'wp-admin/includes/class-wp-themes-list-table.php' );
include( ABSPATH . 'wp-admin/includes/class-wp-theme-install-list-table.php' );
$theme_class = new WP_Theme_Install_List_Table();
$paged = $theme_class->get_pagenum();
$per_page = 36;
$args = array( 'page' => $paged, 'per_page' => $per_page, 'fields' => $theme_field_defaults );
$args['author'] = 'bestwebsoft';
$args = apply_filters( 'install_themes_table_api_args_search', $args );
$api = themes_api( 'query_themes', $args );
if ( is_wp_error( $api ) )
wp_die( $api->get_error_message() . '</p> <p><a href="#" onclick="document.location.reload(); return false;">' . __( 'Try again' ) . '</a>' );
$theme_class->items = $api->themes;
$theme_class->set_pagination_args( array(
'total_items' => $api->info['results'],
'per_page' => $per_page,
'infinite_scroll' => true,
) );
$themes = $theme_class->items;
foreach ( $themes as $theme ) {
?><div class="available-theme installable-theme"><?php
global $themes_allowedtags;
if ( empty( $theme ) )
return;
$name = wp_kses( $theme->name, $themes_allowedtags );
$author = wp_kses( $theme->author, $themes_allowedtags );
$preview_title = sprintf( __('Preview “%s”'), $name );
$preview_url = add_query_arg( array(
'tab' => 'theme-information',
'theme' => $theme->slug,
), self_admin_url( 'theme-install.php' ) );
$actions = array();
$install_url = add_query_arg( array(
'action' => 'install-theme',
'theme' => $theme->slug,
), self_admin_url( 'update.php' ) );
$update_url = add_query_arg( array(
'action' => 'upgrade-theme',
'theme' => $theme->slug,
), self_admin_url( 'update.php' ) );
$status = 'install';
$installed_theme = wp_get_theme( $theme->slug );
if ( $installed_theme->exists() ) {
if ( version_compare( $installed_theme->get('Version'), $theme->version, '=' ) )
$status = 'latest_installed';
elseif ( version_compare( $installed_theme->get('Version'), $theme->version, '>' ) )
$status = 'newer_installed';
else
$status = 'update_available';
}
switch ( $status ) {
default:
case 'install':
$actions[] = '<a class="install-now" href="' . esc_url( wp_nonce_url( $install_url, 'install-theme_' . $theme->slug ) ) . '" title="' . esc_attr( sprintf( __( 'Install %s' ), $name ) ) . '">' . __( 'Install Now' ) . '</a>';
break;
case 'update_available':
$actions[] = '<a class="install-now" href="' . esc_url( wp_nonce_url( $update_url, 'upgrade-theme_' . $theme->slug ) ) . '" title="' . esc_attr( sprintf( __( 'Update to version %s' ), $theme->version ) ) . '">' . __( 'Update' ) . '</a>';
break;
case 'newer_installed':
case 'latest_installed':
$actions[] = '<span class="install-now" title="' . esc_attr__( 'This theme is already installed and is up to date' ) . '">' . _x( 'Installed', 'theme' ) . '</span>';
break;
}
$actions[] = '<a class="install-theme-preview" href="' . esc_url( $preview_url ) . '" title="' . esc_attr( sprintf( __( 'Preview %s' ), $name ) ) . '">' . __( 'Preview' ) . '</a>';
$actions = apply_filters( 'theme_install_actions', $actions, $theme );
?>
<a class="screenshot install-theme-preview" href="<?php echo esc_url( $preview_url ); ?>" title="<?php echo esc_attr( $preview_title ); ?>">
<img src='<?php echo esc_url( $theme->screenshot_url ); ?>' width='150' />
</a>
<h3><?php echo $name; ?></h3>
<div class="theme-author"><?php printf( __( 'By %s' ), $author ); ?></div>
<div class="action-links">
<ul>
<?php foreach ( $actions as $action ): ?>
<li><?php echo $action; ?></li>
<?php endforeach; ?>
<li class="hide-if-no-js"><a href="#" class="theme-detail"><?php _e('Details') ?></a></li>
</ul>
</div>
<?php $theme_class->install_theme_info( $theme );
?></div>
<?php }
// end foreach $theme_names
$theme_class->theme_installer();
?>
</div>
<?php } elseif ( 'system_status' == $_GET['action'] ) { ?>
<div class="updated fade" <?php if ( ! ( isset( $_REQUEST['bwsmn_form_submit'] ) || isset( $_REQUEST['bwsmn_form_submit_custom_email'] ) ) || $error != "" ) echo "style=\"display:none\""; ?>><p><strong><?php echo $message; ?></strong></p></div>
<div class="error" <?php if ( "" == $error ) echo "style=\"display:none\""; ?>><p><strong><?php echo $error; ?></strong></p></div>
<h3><?php _e( 'System status', 'bestwebsoft' ); ?></h3>
<div class="inside">
<table class="bws_system_info">
<thead><tr><th><?php _e( 'Environment', 'bestwebsoft' ); ?></th><td></td></tr></thead>
<tbody>
<?php foreach ( $system_info['system_info'] as $key => $value ) { ?>
<tr>
<td scope="row"><?php echo $key; ?></td>
<td scope="row"><?php echo $value; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<table class="bws_system_info">
<thead><tr><th><?php _e( 'Active Plugins', 'bestwebsoft' ); ?></th><th></th></tr></thead>
<tbody>
<?php foreach ( $system_info['active_plugins'] as $key => $value ) { ?>
<tr>
<td scope="row"><?php echo $key; ?></td>
<td scope="row"><?php echo $value; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<table class="bws_system_info">
<thead><tr><th><?php _e( 'Inactive Plugins', 'bestwebsoft' ); ?></th><th></th></tr></thead>
<tbody>
<?php
if ( ! empty( $system_info['inactive_plugins'] ) ) {
foreach ( $system_info['inactive_plugins'] as $key => $value ) { ?>
<tr>
<td scope="row"><?php echo $key; ?></td>
<td scope="row"><?php echo $value; ?></td>
</tr>
<?php }
} ?>
</tbody>
</table>
<div class="clear"></div>
<form method="post" action="admin.php?page=bws_plugins&action=system_status">
<p>
<input type="hidden" name="bwsmn_form_submit" value="submit" />
<input type="submit" class="button-primary" value="<?php _e( 'Send to support', 'bestwebsoft' ) ?>" />
<?php wp_nonce_field( plugin_basename(__FILE__), 'bwsmn_nonce_submit' ); ?>
</p>
</form>
<form method="post" action="admin.php?page=bws_plugins&action=system_status">
<p>
<input type="hidden" name="bwsmn_form_submit_custom_email" value="submit" />
<input type="submit" class="button" value="<?php _e( 'Send to custom email »', 'bestwebsoft' ) ?>" />
<input type="text" value="<?php echo $bwsmn_form_email; ?>" name="bwsmn_form_email" />
<?php wp_nonce_field( plugin_basename(__FILE__), 'bwsmn_nonce_submit_custom_email' ); ?>
</p>
</form>
</div>
<?php } ?>
</div>
<?php }
}
if ( ! function_exists ( 'bws_plugin_init' ) ) {
function bws_plugin_init() {
// Internationalization, first(!)
load_plugin_textdomain( 'bestwebsoft', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
}
}
if ( ! function_exists ( 'bws_admin_head' ) ) {
function bws_admin_head() {
global $wp_version;
if ( $wp_version < 3.8 )
wp_enqueue_style( 'pdfprnt-stylesheet', plugins_url( 'css/general_style_wp_before_3.8.css', __FILE__ ) );
else
wp_enqueue_style( 'pdfprnt-stylesheet', plugins_url( 'css/general_style.css', __FILE__ ) );
if ( isset( $_GET['page'] ) && $_GET['page'] == "bws_plugins" ) {
wp_enqueue_style( 'bws_menu_style', plugins_url( 'css/style.css', __FILE__ ) );
wp_enqueue_script( 'bws_menu_script', plugins_url( 'js/bws_menu.js' , __FILE__ ) );
if ( $wp_version >= '3.8' )
wp_enqueue_script( 'theme-install' );
elseif ( $wp_version >= '3.4' )
wp_enqueue_script( 'theme' );
}
}
}
add_action( 'init', 'bws_plugin_init' );
add_action( 'admin_enqueue_scripts', 'bws_admin_head' );
?> | gpl-2.0 |
GoogleChromeLabs/pwa-wp | wp-includes/theme-compat/offline.php | 482 | <?php
/**
* Contains the offline base template
*
* When the client's internet connection goes down, this template is served as the response
* instead of the service worker. This template can be overridden by including an offline.php
* in the theme.
*
* @package PWA
* @since 0.2.0
*/
pwa_get_header( 'error' );
?>
<main>
<h1><?php esc_html_e( 'Offline', 'pwa' ); ?></h1>
<?php wp_service_worker_error_message_placeholder(); ?>
</main>
<?php
pwa_get_footer( 'error' );
| gpl-2.0 |
frabarz/DRTrial | src/hud/NSDCylinder.js | 522 | import BaseElement from './Element.js';
export default class NSDCylinder extends BaseElement
{
constructor(ctx)
{
super(ctx);
this.type = 'HUD.NSD.Cylinder';
this.bullets = [];
this.giro = 0;
}
setScale()
{
this.r = this.H * 0.45 * 0.8;
this.x = this.r * -0.1;
this.y = this.H * 0.58;
var n = this.bullets.length;
while (n--)
this.bullets[n].setScale(this.r / 200);
}
loadBullet(bullet)
{
this.bullets.push(bullet);
bullet.setScale(this.r / 200);
}
} | gpl-2.0 |
Hourglass-Resurrection/Hourglass-Resurrection | source/hooks/hooks/inputhooks.cpp | 89172 | /* Copyright (C) 2011 nitsuja and contributors
Hourglass is licensed under GPL v2. Full notice is in COPYING.txt. */
#include <vector>
#include <algorithm>
#include "../wintasee.h"
//#include "../tls.h"
DEFINE_LOCAL_GUID(IID_IDirectInputA, 0x89521360, 0xAA8A, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(IID_IDirectInputW, 0x89521361, 0xAA8A, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(IID_IDirectInput2A, 0x5944E662, 0xAA8A, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(IID_IDirectInput2W, 0x5944E663, 0xAA8A, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(IID_IDirectInput7A, 0x9A4CB684, 0x236D, 0x11D3, 0x8E, 0x9D, 0x00, 0xC0, 0x4F, 0x68, 0x44, 0xAE);
DEFINE_LOCAL_GUID(IID_IDirectInput7W, 0x9A4CB685, 0x236D, 0x11D3, 0x8E, 0x9D, 0x00, 0xC0, 0x4F, 0x68, 0x44, 0xAE);
DEFINE_LOCAL_GUID(IID_IDirectInput8A, 0xBF798030, 0x483A, 0x4DA2, 0xAA, 0x99, 0x5D, 0x64, 0xED, 0x36, 0x97, 0x00);
DEFINE_LOCAL_GUID(IID_IDirectInput8W, 0xBF798031, 0x483A, 0x4DA2, 0xAA, 0x99, 0x5D, 0x64, 0xED, 0x36, 0x97, 0x00);
DEFINE_LOCAL_GUID(IID_IDirectInputDeviceA, 0x5944E680, 0xC92E, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(IID_IDirectInputDeviceW, 0x5944E681, 0xC92E, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(IID_IDirectInputDevice2A, 0x5944E682, 0xC92E, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(IID_IDirectInputDevice2W, 0x5944E683, 0xC92E, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(IID_IDirectInputDevice7A, 0x57D7C6BC, 0x2356, 0x11D3, 0x8E, 0x9D, 0x00, 0xC0, 0x4F, 0x68, 0x44, 0xAE);
DEFINE_LOCAL_GUID(IID_IDirectInputDevice7W, 0x57D7C6BD, 0x2356, 0x11D3, 0x8E, 0x9D, 0x00, 0xC0, 0x4F, 0x68, 0x44, 0xAE);
DEFINE_LOCAL_GUID(IID_IDirectInputDevice8A, 0x54D41080, 0xDC15, 0x4833, 0xA4, 0x1B, 0x74, 0x8F, 0x73, 0xA3, 0x81, 0x79);
DEFINE_LOCAL_GUID(IID_IDirectInputDevice8W, 0x54D41081, 0xDC15, 0x4833, 0xA4, 0x1B, 0x74, 0x8F, 0x73, 0xA3, 0x81, 0x79);
// Device GUIDs, re-defined as local GUIDs to avoid linker errors.
DEFINE_LOCAL_GUID(GUID_SysMouse, 0x6F1D2B60, 0xD5A0, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(GUID_SysKeyboard, 0x6F1D2B61, 0xD5A0, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
// DeviceObject GUIDs, re-defined as local GUIDs to avoid linker errors.
DEFINE_LOCAL_GUID(GUID_XAxis, 0xA36D02E0, 0xC9F3, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(GUID_YAxis, 0xA36D02E1, 0xC9F3, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(GUID_ZAxis, 0xA36D02E2, 0xC9F3, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(GUID_RxAxis, 0xA36D02F4, 0xC9F3, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(GUID_RyAxis, 0xA36D02F5, 0xC9F3, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(GUID_RzAxis, 0xA36D02E3, 0xC9F3, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(GUID_Slider, 0xA36D02E4, 0xC9F3, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(GUID_Button, 0xA36D02F0, 0xC9F3, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(GUID_Key, 0x55728220, 0xD33C, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(GUID_POV, 0xA36D02F2, 0xC9F3, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
DEFINE_LOCAL_GUID(GUID_Unknown, 0xA36D02F3, 0xC9F3, 0x11CF, 0xBF, 0xC7, 0x44, 0x45, 0x53, 0x54, 0x00, 0x00);
namespace Hooks
{
namespace DirectInput
{
using Log = DebugLog<LogCategory::DINPUT>;
template<typename IDirectInputDeviceN> struct IDirectInputDeviceTraits {};
template<> struct IDirectInputDeviceTraits<IDirectInputDeviceA> { typedef LPDIENUMDEVICEOBJECTSCALLBACKA LPDIENUMDEVICEOBJECTSCALLBACKN; typedef LPDIDEVICEINSTANCEA LPDIDEVICEINSTANCEN; typedef LPDIDEVICEOBJECTINSTANCEA LPDIDEVICEOBJECTINSTANCEN; typedef LPDIENUMEFFECTSCALLBACKA LPDIENUMEFFECTSCALLBACKN; typedef LPDIEFFECTINFOA LPDIEFFECTINFON; typedef LPDIACTIONFORMATA LPDIACTIONFORMATN; typedef LPDIDEVICEIMAGEINFOHEADERA LPDIDEVICEIMAGEINFOHEADERN; typedef LPCSTR LPCNSTR; typedef CHAR NCHAR; enum { defaultDIDEVICEOBJECTDATAsize = 16 }; };
template<> struct IDirectInputDeviceTraits<IDirectInputDeviceW> { typedef LPDIENUMDEVICEOBJECTSCALLBACKW LPDIENUMDEVICEOBJECTSCALLBACKN; typedef LPDIDEVICEINSTANCEW LPDIDEVICEINSTANCEN; typedef LPDIDEVICEOBJECTINSTANCEW LPDIDEVICEOBJECTINSTANCEN; typedef LPDIENUMEFFECTSCALLBACKW LPDIENUMEFFECTSCALLBACKN; typedef LPDIEFFECTINFOW LPDIEFFECTINFON; typedef LPDIACTIONFORMATW LPDIACTIONFORMATN; typedef LPDIDEVICEIMAGEINFOHEADERW LPDIDEVICEIMAGEINFOHEADERN; typedef LPCWSTR LPCNSTR; typedef WCHAR NCHAR; enum { defaultDIDEVICEOBJECTDATAsize = 16 }; };
template<> struct IDirectInputDeviceTraits<IDirectInputDevice2A> { typedef LPDIENUMDEVICEOBJECTSCALLBACKA LPDIENUMDEVICEOBJECTSCALLBACKN; typedef LPDIDEVICEINSTANCEA LPDIDEVICEINSTANCEN; typedef LPDIDEVICEOBJECTINSTANCEA LPDIDEVICEOBJECTINSTANCEN; typedef LPDIENUMEFFECTSCALLBACKA LPDIENUMEFFECTSCALLBACKN; typedef LPDIEFFECTINFOA LPDIEFFECTINFON; typedef LPDIACTIONFORMATA LPDIACTIONFORMATN; typedef LPDIDEVICEIMAGEINFOHEADERA LPDIDEVICEIMAGEINFOHEADERN; typedef LPCSTR LPCNSTR; typedef CHAR NCHAR; enum { defaultDIDEVICEOBJECTDATAsize = 16 }; };
template<> struct IDirectInputDeviceTraits<IDirectInputDevice2W> { typedef LPDIENUMDEVICEOBJECTSCALLBACKW LPDIENUMDEVICEOBJECTSCALLBACKN; typedef LPDIDEVICEINSTANCEW LPDIDEVICEINSTANCEN; typedef LPDIDEVICEOBJECTINSTANCEW LPDIDEVICEOBJECTINSTANCEN; typedef LPDIENUMEFFECTSCALLBACKW LPDIENUMEFFECTSCALLBACKN; typedef LPDIEFFECTINFOW LPDIEFFECTINFON; typedef LPDIACTIONFORMATW LPDIACTIONFORMATN; typedef LPDIDEVICEIMAGEINFOHEADERW LPDIDEVICEIMAGEINFOHEADERN; typedef LPCWSTR LPCNSTR; typedef WCHAR NCHAR; enum { defaultDIDEVICEOBJECTDATAsize = 16 }; };
template<> struct IDirectInputDeviceTraits<IDirectInputDevice7A> { typedef LPDIENUMDEVICEOBJECTSCALLBACKA LPDIENUMDEVICEOBJECTSCALLBACKN; typedef LPDIDEVICEINSTANCEA LPDIDEVICEINSTANCEN; typedef LPDIDEVICEOBJECTINSTANCEA LPDIDEVICEOBJECTINSTANCEN; typedef LPDIENUMEFFECTSCALLBACKA LPDIENUMEFFECTSCALLBACKN; typedef LPDIEFFECTINFOA LPDIEFFECTINFON; typedef LPDIACTIONFORMATA LPDIACTIONFORMATN; typedef LPDIDEVICEIMAGEINFOHEADERA LPDIDEVICEIMAGEINFOHEADERN; typedef LPCSTR LPCNSTR; typedef CHAR NCHAR; enum { defaultDIDEVICEOBJECTDATAsize = 16 }; };
template<> struct IDirectInputDeviceTraits<IDirectInputDevice7W> { typedef LPDIENUMDEVICEOBJECTSCALLBACKW LPDIENUMDEVICEOBJECTSCALLBACKN; typedef LPDIDEVICEINSTANCEW LPDIDEVICEINSTANCEN; typedef LPDIDEVICEOBJECTINSTANCEW LPDIDEVICEOBJECTINSTANCEN; typedef LPDIENUMEFFECTSCALLBACKW LPDIENUMEFFECTSCALLBACKN; typedef LPDIEFFECTINFOW LPDIEFFECTINFON; typedef LPDIACTIONFORMATW LPDIACTIONFORMATN; typedef LPDIDEVICEIMAGEINFOHEADERW LPDIDEVICEIMAGEINFOHEADERN; typedef LPCWSTR LPCNSTR; typedef WCHAR NCHAR; enum { defaultDIDEVICEOBJECTDATAsize = 16 }; };
template<> struct IDirectInputDeviceTraits<IDirectInputDevice8A> { typedef LPDIENUMDEVICEOBJECTSCALLBACKA LPDIENUMDEVICEOBJECTSCALLBACKN; typedef LPDIDEVICEINSTANCEA LPDIDEVICEINSTANCEN; typedef LPDIDEVICEOBJECTINSTANCEA LPDIDEVICEOBJECTINSTANCEN; typedef LPDIENUMEFFECTSCALLBACKA LPDIENUMEFFECTSCALLBACKN; typedef LPDIEFFECTINFOA LPDIEFFECTINFON; typedef LPDIACTIONFORMATA LPDIACTIONFORMATN; typedef LPDIDEVICEIMAGEINFOHEADERA LPDIDEVICEIMAGEINFOHEADERN; typedef LPCSTR LPCNSTR; typedef CHAR NCHAR; enum { defaultDIDEVICEOBJECTDATAsize = 20 }; };
template<> struct IDirectInputDeviceTraits<IDirectInputDevice8W> { typedef LPDIENUMDEVICEOBJECTSCALLBACKW LPDIENUMDEVICEOBJECTSCALLBACKN; typedef LPDIDEVICEINSTANCEW LPDIDEVICEINSTANCEN; typedef LPDIDEVICEOBJECTINSTANCEW LPDIDEVICEOBJECTINSTANCEN; typedef LPDIENUMEFFECTSCALLBACKW LPDIENUMEFFECTSCALLBACKN; typedef LPDIEFFECTINFOW LPDIEFFECTINFON; typedef LPDIACTIONFORMATW LPDIACTIONFORMATN; typedef LPDIDEVICEIMAGEINFOHEADERW LPDIDEVICEIMAGEINFOHEADERN; typedef LPCWSTR LPCNSTR; typedef WCHAR NCHAR; enum { defaultDIDEVICEOBJECTDATAsize = 20 }; };
// The DIDEVICEOBJECTINSTANCE struct has to be locally re-implemented thanks to it being defined in dinput.h as 2 different structs,
// this creates a conflict for our catch-all model since only the *A-implementation gets used if we use the normal struct due to our
// compiler being set to MultiByte which undefines UNICODE.
// This templated implementation lets the struct become anamorphic and it can take the shape of either version of the struct.
// NCHAR will take the form of a CHAR or WCHAR depending on which version of the IDirectInputDevice that is created by the game.
// Since the struct will become an exact replica of either the ANSI or Unicode version, the game should experience no problems in
// accessing the data from this struct compared to a "real" one.
// -- Warepire
template<typename NCHAR>
struct MyDIDEVICEOBJECTINSTANCE {
DWORD dwSize;
GUID guidType;
DWORD dwOfs;
DWORD dwType;
DWORD dwFlags;
NCHAR tszName[MAX_PATH];
DWORD dwFFMaxForce;
DWORD dwFFForceResolution;
WORD wCollectionNumber;
WORD wDesignatorIndex;
WORD wUsagePage;
WORD wUsage;
DWORD dwDimension;
WORD wExponent;
WORD wReportId;
};
// Due to NCHAR being able to take the shape of both a CHAR and WCHAR we cannot assign it data in string format.
// This is caused by the difference in length of the 2 datatypes. We are however lucky enough that the values we
// want to assign are the same, so we will just initiate tszName as an array using hexadecimal values.
// To make the code somewhat easier to read I added these defines.
// -- Warepire
#define XAXIS { 0x58, 0x2D, 0x61, 0x78, 0x69, 0x73, 0x00 } // "X-axis\0"
#define YAXIS { 0x59, 0x2D, 0x61, 0x78, 0x69, 0x73, 0x00 } // "Y-axis\0"
#define WHEEL { 0x57, 0x68, 0x65, 0x65, 0x6C, 0x00 } // "Wheel\0"
#define BUTTON0 { 0x42, 0x75, 0x74, 0x74, 0x6F, 0x6E, 0x20, 0x30, 0x00 }// "Button 0\0"
#define BUTTON1 { 0x42, 0x75, 0x74, 0x74, 0x6F, 0x6E, 0x20, 0x31, 0x00 }// "Button 1\0"
#define BUTTON2 { 0x42, 0x75, 0x74, 0x74, 0x6F, 0x6E, 0x20, 0x32, 0x00 }// "Button 2\0"
typedef std::vector<struct BufferedInput*> BufferedInputList;
static BufferedInputList s_bufferedKeySlots;
struct BufferedInput
{
DIDEVICEOBJECTDATA* data;
DWORD size;
DWORD used;
DWORD startOffset; // circular buffer
BOOL overflowed; // for DI_BUFFEROVERFLOW
HANDLE event;
BufferedInputList& bufferList;
BufferedInput(BufferedInputList& buflist) : data(NULL), size(0), used(0), startOffset(0), overflowed(FALSE), event(NULL), bufferList(buflist)
{
LOG() << "(" << this << ") adding self to list.";
bufferList.push_back(this);
}
~BufferedInput()
{
Resize(0);
LOG() << "(" << this << ") removing self from list.";
bufferList.erase(std::remove(bufferList.begin(), bufferList.end(), this), bufferList.end());
}
void Resize(DWORD newSize)
{
ENTER(newSize);
DWORD oldSize = size;
size = newSize;
if (oldSize != newSize)
{
LOG() << "allocating " << oldSize << " -> " << newSize;
data = (DIDEVICEOBJECTDATA*)realloc(data, newSize * sizeof(DIDEVICEOBJECTDATA));
if (used > newSize)
{
used = newSize;
overflowed = TRUE;
}
}
LOG() << "done.";
}
HRESULT GetData(DWORD elemSize, LPDIDEVICEOBJECTDATA dataOut, LPDWORD numElements, DWORD flags)
{
ENTER(elemSize, dataOut, numElements, flags);
if (!numElements)
return DIERR_INVALIDPARAM;
LOG() << "size=" << size << ", used=" << used << "*numElements=" << *numElements;
DWORD retrieved = 0;
DWORD requested = *numElements;
DWORD newUsed = used;
if (elemSize == sizeof(DIDEVICEOBJECTDATA))
{
while (requested && newUsed)
{
LOG() << "assigning " << elemSize << " bytes to "
<< &dataOut[retrieved] << " from " << &data[(startOffset + retrieved) % size];
if (dataOut)
dataOut[retrieved] = data[(startOffset + retrieved) % size];
retrieved++;
requested--;
newUsed--;
}
}
else
{
while (requested && newUsed)
{
LOG() << "copying " << elemSize << " bytes to "
<< &dataOut[retrieved] << " from " << &data[(startOffset + retrieved) % size];
if (dataOut)
memcpy(((char*)dataOut) + elemSize * retrieved, &data[(startOffset + retrieved) % size], elemSize);
// if memcpy doesn't work
//if(dataOut)
//{
// DIDEVICEOBJECTDATA& to = *(DIDEVICEOBJECTDATA*)(((char*)dataOut) + elemSize * retrieved);
// DIDEVICEOBJECTDATA& from = data[(startOffset + retrieved) % size];
// if(elemSize >= 4)
// to.dwOfs = from.dwOfs;
// if(elemSize >= 8)
// to.dwData = from.dwData;
// if(elemSize >= 12)
// to.dwSequence = from.dwSequence;
// if(elemSize >= 16)
// to.dwTimeStamp = from.dwTimeStamp;
//}
DIDEVICEOBJECTDATA& to = *(DIDEVICEOBJECTDATA*)(((char*)dataOut) + elemSize * retrieved);
LOG() << "BufferedInput::GotEvent(VK=0x??, DIK=" << to.dwOfs << ", data="
<< to.dwData << ", id=" << to.dwSequence << ") (used=" << newUsed << ")";
retrieved++;
requested--;
newUsed--;
LOG() << "BufferedInput::GotEvent(VK=0x??, DIK=" << to.dwOfs << ", data="
<< to.dwData << ", id=" << to.dwSequence << ") (used=" << newUsed << ")";
}
}
HRESULT rv = overflowed ? DI_BUFFEROVERFLOW : DI_OK;
*numElements = retrieved;
if (!(flags & DIGDD_PEEK))
{
used = newUsed;
startOffset += retrieved;
if (retrieved)
{
overflowed = FALSE;
if (used && event)
SetEvent(event); // tells app that we still have more input, otherwise it will lag behind weirdly
}
}
return rv;
}
void AddEvent(DIDEVICEOBJECTDATA inputEvent)
{
ENTER();
if (used >= size)
overflowed = TRUE;
else
{
// FIXME: this should only happen for the keyboard device
// convert event from VK to DIK
HKL keyboardLayout = MyGetKeyboardLayout(0);
int VK = inputEvent.dwOfs;
int DIK = MapVirtualKeyEx(VK, /*MAPVK_VK_TO_VSC*/0, keyboardLayout) & 0xFF;
inputEvent.dwOfs = DIK;
LOG() << "(VK=" << VK << ", DIK=" << DIK << ", data=" << inputEvent.dwData
<< ", id=" << inputEvent.dwSequence << ") (used=" << used << ")";
data[(startOffset + used) % size] = inputEvent;
used++;
LOG() << "(VK=" << VK << ", DIK=" << DIK << ", data=" << inputEvent.dwData
<< ", id=" << inputEvent.dwSequence << ") (used=" << used << ")";
}
if (event)
SetEvent(event);
}
static void AddEventToAllDevices(DIDEVICEOBJECTDATA inputEvent, BufferedInputList& bufferList)
{
ENTER();
for (int i = (int)bufferList.size() - 1; i >= 0; i--)
bufferList[i]->AddEvent(inputEvent);
}
void AddMouseEvent(DIDEVICEOBJECTDATA inputEvent)
{
ENTER();
if (used >= size)
overflowed = TRUE;
else
{
LOG() << "(dwOfs=" << inputEvent.dwOfs << ", data=" << inputEvent.dwData
<< ", id=" << inputEvent.dwSequence << ") (used=" << used << ")";
data[(startOffset + used) % size] = inputEvent;
used++;
}
if (event)
SetEvent(event);
}
static void AddMouseEventToAllDevices(DIDEVICEOBJECTDATA inputEvent, BufferedInputList& bufferList)
{
ENTER();
for (int i = (int)bufferList.size() - 1; i >= 0; i--)
bufferList[i]->AddMouseEvent(inputEvent);
}
};
// HACK: Something to init GUID to if it's not passed as a param to the class
// TODO: Implement the hooking in such a way that GUID is ALWAYS needed for this hook.
static const GUID emptyGUID = { 0, 0, 0, { 0, 0, 0, 0, 0, 0, 0, 0 } };
// TODO: more than keyboard
template<typename IDirectInputDeviceN>
class MyDirectInputDevice : public IDirectInputDeviceN
{
public:
typedef typename IDirectInputDeviceTraits<IDirectInputDeviceN>::LPCNSTR LPCNSTR;
typedef typename IDirectInputDeviceTraits<IDirectInputDeviceN>::LPDIENUMDEVICEOBJECTSCALLBACKN LPDIENUMDEVICEOBJECTSCALLBACKN;
typedef typename IDirectInputDeviceTraits<IDirectInputDeviceN>::LPDIDEVICEOBJECTINSTANCEN LPDIDEVICEOBJECTINSTANCEN;
typedef typename IDirectInputDeviceTraits<IDirectInputDeviceN>::LPDIDEVICEINSTANCEN LPDIDEVICEINSTANCEN;
typedef typename IDirectInputDeviceTraits<IDirectInputDeviceN>::LPDIENUMEFFECTSCALLBACKN LPDIENUMEFFECTSCALLBACKN;
typedef typename IDirectInputDeviceTraits<IDirectInputDeviceN>::LPDIEFFECTINFON LPDIEFFECTINFON;
typedef typename IDirectInputDeviceTraits<IDirectInputDeviceN>::LPDIACTIONFORMATN LPDIACTIONFORMATN;
typedef typename IDirectInputDeviceTraits<IDirectInputDeviceN>::LPDIDEVICEIMAGEINFOHEADERN LPDIDEVICEIMAGEINFOHEADERN;
typedef typename IDirectInputDeviceTraits<IDirectInputDeviceN>::NCHAR NCHAR;
MyDirectInputDevice(IDirectInputDeviceN* device) : m_device(device), m_type(emptyGUID), m_acquired(FALSE), m_bufferedInput(s_bufferedKeySlots)
{
LOG() << "created without GUID.";
}
MyDirectInputDevice(IDirectInputDeviceN* device, REFGUID guid) : m_device(device), m_type(guid), m_acquired(FALSE), m_bufferedInput(s_bufferedKeySlots)
{
LOG() << "created, received GUID: " << guid.Data1 << " " << guid.Data2
<< " " << guid.Data3 << " " << guid.Data4;
}
/*** IUnknown methods ***/
STDMETHOD(QueryInterface)(REFIID riid, void** ppvObj)
{
ENTER();
HRESULT rv = m_device->QueryInterface(riid, ppvObj);
if (SUCCEEDED(rv))
HookCOMInterface(riid, ppvObj);
return rv;
}
STDMETHOD_(ULONG, AddRef)()
{
ENTER();
ULONG count = m_device->AddRef();
LEAVE(count);
return count;
}
STDMETHOD_(ULONG, Release)()
{
ENTER();
ULONG count = m_device->Release();
LEAVE(count);
if (0 == count)
delete this;
return count;
}
/*** IDirectInputDevice methods ***/
STDMETHOD(GetCapabilities)(LPDIDEVCAPS lpDIDevCaps)
{
ENTER();
if (m_type == GUID_SysMouse)
{
// This function requires that lpDIDevCaps exists and that it's dwSize member is initialized to either
// sizeof(DIDEVCAPS_DX3) which is 24 bytes or sizeof(DIDEVCAPS) which is 44 bytes.
if (lpDIDevCaps == NULL) return E_POINTER;
if (lpDIDevCaps->dwSize != 24 && lpDIDevCaps->dwSize != 44) return DIERR_INVALIDPARAM;
lpDIDevCaps->dwFlags = (DIDC_ATTACHED | DIDC_EMULATED);
lpDIDevCaps->dwDevType = 0x112;
lpDIDevCaps->dwAxes = 3;
lpDIDevCaps->dwButtons = 3;
lpDIDevCaps->dwPOVs = 0;
if (lpDIDevCaps->dwSize == 44 /*sizeof(DIDEVCAPS)*/) // These are only defined in structs for DX-versions 5+
{
lpDIDevCaps->dwFFSamplePeriod = 0;
lpDIDevCaps->dwFFMinTimeResolution = 0;
lpDIDevCaps->dwFirmwareRevision = 0;
lpDIDevCaps->dwHardwareRevision = 0;
lpDIDevCaps->dwFFDriverVersion = 0;
}
return DI_OK;
}
//return rvfilter(m_device->GetCapabilities(devCaps));
return DIERR_INVALIDPARAM; // NYI! for keyboard or gamepads
}
STDMETHOD(EnumObjects)(LPDIENUMDEVICEOBJECTSCALLBACKN lpCallback, LPVOID pvRef, DWORD dwFlags)
{
ENTER(dwFlags);
if (m_type == GUID_SysMouse)
{
// A SysMouse device follows a defined standard, this data is the same for any pointer device loaded in DI as a SysMouse.
// Mice with more buttons/wheels may look differently after these objects, however, the array below represents a regular
// 3 button mouse with a scroll wheel, and that is what we choose to emulate as mice without scroll wheels are very rare
// in todays world, as far as I know anyway. This should be compatible with any mouse as long as it is loaded as SysMouse.
// -- Warepire
DWORD size = (sizeof(NCHAR) > sizeof(CHAR)) ? 576 : 316;
struct MyDIDEVICEOBJECTINSTANCE<NCHAR> EmulatedSysMouse[6] = {
{ size, GUID_XAxis, 0x0, 0x001, DIDOI_ASPECTPOSITION, XAXIS, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ size, GUID_YAxis, 0x4, 0x101, DIDOI_ASPECTPOSITION, YAXIS, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ size, GUID_ZAxis, 0x8, 0x201, DIDOI_ASPECTPOSITION, WHEEL, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ size, GUID_Button, 0xC, 0x301, 0, BUTTON0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ size, GUID_Button, 0xD, 0x401, 0, BUTTON1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ size, GUID_Button, 0xE, 0x501, 0, BUTTON2, 0, 0, 0, 0, 0, 0, 0, 0, 0 } };
// Requests that will return all the objects of our emulated mouse.
// The if statement checks for these flags: DIDFT_ALL || DIDFT_ENUMCOLLECTION(0) || DIDFT_NOCOLLECTION
// ALL is quite self-describing, the other 2 will both return all objects in HID collection 0 for this device.
// Which means all objects since they all belong to HID collection 0.
if ((dwFlags == DIDFT_ALL) || (((dwFlags >> 8) & 0xFFFF) == 0x0000) || ((dwFlags & DIDFT_NOCOLLECTION) == DIDFT_NOCOLLECTION))
{
for (unsigned int i = 0; i < 6; i++)
{
if (lpCallback((LPDIDEVICEOBJECTINSTANCEN)(&(EmulatedSysMouse[i])), pvRef) == DIENUM_STOP) break;
}
}
else // Requests that will return subsets of the objects.
{
if ((dwFlags & DIDFT_RELAXIS) == DIDFT_RELAXIS)
{
for (unsigned int i = 0; i < 3; i++)
{
if (lpCallback((LPDIDEVICEOBJECTINSTANCEN)(&(EmulatedSysMouse[i])), pvRef) == DIENUM_STOP) break;
}
}
if ((dwFlags & DIDFT_PSHBUTTON) == DIDFT_PSHBUTTON)
{
for (unsigned int i = 3; i < 6; i++)
{
if (lpCallback((LPDIDEVICEOBJECTINSTANCEN)(&(EmulatedSysMouse[i])), pvRef) == DIENUM_STOP) break;
}
}
// The flags DIDFT_AXIS and DIDFT_BUTTON can be ignored since they are pre-defined combinations of
// DIDFT_ABSAXIS & DIDFT_RELAXIS and DIDFT_PSHBUTTON & DIDFT_TGLBUTTON respectively.
// Objects our emulated mouse do not have, for these we will do nothing:
// DIDFT_ABSAXIS
// DIDFT_ALIAS
// DIDFT_COLLECTION
// DIDFT_FFACTUATOR
// DIDFT_FFEFFECTTRIGGER
// DIDFT_NODATA
// DIDFT_OUTPUT
// DIDFT_TGLBUTTON
// DIDFT_VENDORDEFINED
}
return DI_OK;
}
if (m_type == GUID_SysKeyboard)
{
return DIERR_INVALIDPARAM; // TODO: NYI ... EnumObjects is relatively useless for keyboards since you cannot use it to check for available keyboard keys or LEDs.
}
return DIERR_INVALIDPARAM; // TODO: NYI ... Gamepads, wheels, joysticks etc, how do we handle this? There aren't any real standards for these...
//return m_device->EnumObjects(callback, ref, flags);
//return DIERR_INVALIDPARAM; // NYI!
}
STDMETHOD(GetProperty)(REFGUID rguid, LPDIPROPHEADER ph)
{
ENTER();
//return rvfilter(m_device->GetProperty(rguid, ph));
if (&rguid == &DIPROP_BUFFERSIZE)
{
DWORD& size = *(DWORD*)(ph + 1);
size = m_bufferedInput.size;
return DI_OK;
}
else
{
return DIERR_UNSUPPORTED;
}
}
STDMETHOD(SetProperty)(REFGUID rguid, LPCDIPROPHEADER ph)
{
ENTER();
//return m_device->SetProperty(rguid, ph);
if (&rguid == &DIPROP_BUFFERSIZE)
{
DWORD size = *(DWORD*)(ph + 1);
if (size > 1024)
size = 1024;
m_bufferedInput.Resize(size);
return DI_OK;
}
else
{
return DIERR_UNSUPPORTED;
}
}
STDMETHOD(Acquire)()
{
ENTER();
//return m_device->Acquire();
if (m_acquired)
return DI_NOEFFECT;
m_acquired = TRUE;
return DI_OK;
}
STDMETHOD(Unacquire)()
{
ENTER();
//return m_device->Unacquire();
if (!m_acquired)
return DI_NOEFFECT;
m_acquired = FALSE;
return DI_OK;
}
STDMETHOD(GetDeviceState)(DWORD size, LPVOID data)
{
ENTER();
//return rvfilter(m_device->GetDeviceState(size, data));
if (!m_acquired)
return DIERR_NOTACQUIRED;
// not-so-direct input
// since the movie already has to store the VK constants,
// try to convert those to DIK key state
if (m_type == GUID_SysKeyboard)
{
HKL keyboardLayout = MyGetKeyboardLayout(0);
if (size > 256)
size = 256;
BYTE* keys = (BYTE*)data;
DEBUG_LOG() << "TODO: Should really send DIK keys instead, but that breaks VK input....";
for (unsigned int i = 0; i < size; i++)
{
int DIK = i;
int VK = MapVirtualKeyEx(DIK, /*MAPVK_VSC_TO_VK_EX*/3, keyboardLayout) & 0xFF;
// unfortunately MapVirtualKeyEx is slightly broken, so patch up the results ourselves...
// (note that some of the left/right modifier keys get lost too despite MAPVK_VSC_TO_VK_EX)
switch (DIK)
{
case DIK_LEFT: VK = VK_LEFT; break;
case DIK_RIGHT: VK = VK_RIGHT; break;
case DIK_UP: VK = VK_UP; break;
case DIK_DOWN: VK = VK_DOWN; break;
case DIK_PRIOR: VK = VK_PRIOR; break;
case DIK_NEXT: VK = VK_NEXT; break;
case DIK_HOME: VK = VK_HOME; break;
case DIK_END: VK = VK_END; break;
case DIK_INSERT: VK = VK_INSERT; break;
case DIK_DELETE: VK = VK_DELETE; break;
case DIK_DIVIDE: VK = VK_DIVIDE; break;
case DIK_NUMLOCK: VK = VK_NUMLOCK; break;
case DIK_LWIN: VK = VK_LWIN; break;
case DIK_RWIN: VK = VK_RWIN; break;
case DIK_RMENU: VK = VK_RMENU; break;
case DIK_RCONTROL:VK = VK_RCONTROL; break;
// these work for me, but are here in case other layouts need them
case DIK_RSHIFT: VK = VK_RSHIFT; break;
case DIK_LMENU: VK = VK_LMENU; break;
case DIK_LCONTROL:VK = VK_LCONTROL; break;
case DIK_LSHIFT: VK = VK_LSHIFT; break;
}
keys[DIK] = (BYTE)(::Hooks::WinInput::MyGetKeyState(VK) & 0xFF);
if (keys[DIK] & 0x80)
LOG() << "PRESSED: DIK " << DIK << " -> VK " << VK;
}
return DI_OK;
}
if (m_type == GUID_SysMouse)
{
// In the case of the game using DIMOUSESTATE2 we need to make sure the extra buttons are set to "idle" to avoid weird problems.
if (size == sizeof(DIMOUSESTATE2))
{
((LPDIMOUSESTATE2)data)->rgbButtons[4] = 0;
((LPDIMOUSESTATE2)data)->rgbButtons[5] = 0;
((LPDIMOUSESTATE2)data)->rgbButtons[6] = 0;
((LPDIMOUSESTATE2)data)->rgbButtons[7] = 0;
}
memcpy(data, &curinput.mouse.di, sizeof(DIMOUSESTATE));
return DI_OK;
}
return E_PENDING;
}
STDMETHOD(GetDeviceData)(DWORD size, LPDIDEVICEOBJECTDATA data, LPDWORD numElements, DWORD flags)
{
ENTER();
//return m_device->GetDeviceData(size, data, numElements, flags);
if (!m_acquired)
return DIERR_NOTACQUIRED;
if (m_bufferedInput.size == 0)
return DIERR_NOTBUFFERED;
if (!size)
size = IDirectInputDeviceTraits<IDirectInputDeviceN>::defaultDIDEVICEOBJECTDATAsize;
return m_bufferedInput.GetData(size, data, numElements, flags);
}
STDMETHOD(SetDataFormat)(LPCDIDATAFORMAT lpdf)
{
ENTER();
//return rvfilter(m_device->SetDataFormat(df));
//debugprintf("df = 0x%X\n", df); // can't get at c_dfDIKeyboard... so do it at a lower level
//debugprintf("dfnumobjs = %d\n", df->dwNumObjs);
//for(unsigned int i = 0; i < df->dwNumObjs; i++)
//{
// debugprintf("i = %d\n", i);
// debugprintf("ofs = 0x%X\n", df->rgodf[i].dwOfs);
// debugprintf("type = 0x%X\n", DIDFT_GETTYPE(df->rgodf[i].dwType));
// debugprintf("inst = 0x%X\n", DIDFT_GETINSTANCE(df->rgodf[i].dwType));
// debugprintf("guid = 0x%X\n", df->rgodf[i].pguid->Data1); // GUID_Key
// debugprintf("flags = 0x%X\n", df->rgodf[i].dwFlags);
//}
if (m_acquired)
return DIERR_ACQUIRED;
// NYI... assume 256 byte keyboard for now
return DI_OK;
}
STDMETHOD(SetEventNotification)(HANDLE event)
{
ENTER();
//return rvfilter(m_device->SetEventNotification(event));
if (m_acquired)
return DIERR_ACQUIRED;
m_bufferedInput.event = event;
return DI_OK;
}
STDMETHOD(SetCooperativeLevel)(HWND window, DWORD level)
{
ENTER();
if (IsWindow(window))
gamehwnd = window;
if (m_type == GUID_SysMouse) {
IPC::SendIPCMessage(IPC::Command::CMD_MOUSE_REG, &window, sizeof(&window));
}
//return rvfilter(m_device->SetCooperativeLevel(window, level));
return DI_OK;
}
STDMETHOD(GetObjectInfo)(LPDIDEVICEOBJECTINSTANCEN pdidoi, DWORD dwObj, DWORD dwHow)
{
ENTER(dwObj, dwHow);
if (m_type == GUID_SysMouse)
{
// This function requires that pdidoi is created by the game, and has it's dwSize member inited to the size of the struct,
// if the game passes a NULL pointer or a struct without the size member inited we cannot continue.
if (pdidoi == NULL) return E_POINTER;
DWORD zero = 0;
if (memcmp(pdidoi, &zero, 4) == 0) return DIERR_INVALIDPARAM;
switch (dwHow)
{
// Due to games being able to pass wrong values (either through bad code or bad coders) we cannot merge
// DIPH_BYOFFSET & DIPH_BYID and handle them at the same time. So this massive block of code is required.
case DIPH_BYOFFSET:
{
DWORD size;
// Since our typedef system doesn't let us access the members of pdidoi, nor let us cast it to our struct, we have no choice but
// to memcpy the data out of and into the struct, grabbing the size like this is mandatory because we need to leave it "untouched"
// when we fill the rest of the struct.
memcpy(&size, pdidoi, 4);
switch (dwObj)
{
// Sadly the compiler does not support creating the object outside of the switch statement,
// and then assigning all the values depending on case...
case 0x0:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> xaxis = { size, GUID_XAxis, 0x0, 0x001, DIDOI_ASPECTPOSITION, XAXIS, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &xaxis, xaxis.dwSize);
break;
}
case 0x4:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> yaxis = { size, GUID_YAxis, 0x4, 0x101, DIDOI_ASPECTPOSITION, YAXIS, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &yaxis, yaxis.dwSize);
break;
}
case 0x8:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> wheel = { size, GUID_ZAxis, 0x8, 0x201, DIDOI_ASPECTPOSITION, WHEEL, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &wheel, wheel.dwSize);
break;
}
case 0xC:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> button0 = { size, GUID_Button, 0xC, 0x304, 0, BUTTON0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &button0, button0.dwSize);
break;
}
case 0xD:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> button1 = { size, GUID_Button, 0xD, 0x404, 0, BUTTON1, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &button1, button1.dwSize);
break;
}
case 0xE:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> button2 = { size, GUID_Button, 0xE, 0x504, 0, BUTTON2, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &button2, button2.dwSize);
break;
}
default: return DIERR_OBJECTNOTFOUND;
}
break;
}
case DIPH_BYID:
{
DWORD size;
memcpy(&size, pdidoi, 4);
switch (dwObj)
{
case 0x001:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> xaxis = { size, GUID_XAxis, 0x0, 0x001, DIDOI_ASPECTPOSITION, XAXIS, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &xaxis, xaxis.dwSize);
break;
}
case 0x101:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> yaxis = { size, GUID_YAxis, 0x4, 0x101, DIDOI_ASPECTPOSITION, YAXIS, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &yaxis, yaxis.dwSize);
break;
}
case 0x201:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> wheel = { size, GUID_ZAxis, 0x8, 0x201, DIDOI_ASPECTPOSITION, WHEEL, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &wheel, wheel.dwSize);
break;
}
case 0x304:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> button0 = { size, GUID_Button, 0xC, 0x304, 0, BUTTON0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &button0, button0.dwSize);
break;
}
case 0x404:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> button1 = { size, GUID_Button, 0xD, 0x404, 0, BUTTON1, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &button1, button1.dwSize);
break;
}
case 0x504:
{
MyDIDEVICEOBJECTINSTANCE<NCHAR> button2 = { size, GUID_Button, 0xE, 0x504, 0, BUTTON2, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
memcpy(pdidoi, &button2, button2.dwSize);
break;
}
default: return DIERR_OBJECTNOTFOUND;
}
break;
}
case DIPH_BYUSAGE:
{
/*
* Despite MSDN giving a very detailed explanation on how to use this dwHow
* method it seems that for SysMouse it is not even closely supported, and
* this is what the function returns for this case when I call it on every
* PC I own.
* -- Warepire
*/
return E_NOTIMPL;
}
}
return DI_OK;
}
if (m_type == GUID_SysKeyboard)
{
return DIERR_INVALIDPARAM; // NYI!
}
//return rvfilter(m_device->GetObjectInfo(object, objId, objHow));
return DIERR_INVALIDPARAM; // NYI!
}
STDMETHOD(GetDeviceInfo)(LPDIDEVICEINSTANCEN di)
{
ENTER();
//return rvfilter(m_device->GetDeviceInfo(di));
return DIERR_INVALIDPARAM; // NYI!
}
STDMETHOD(RunControlPanel)(HWND owner, DWORD flags)
{
ENTER();
//return rvfilter(m_device->RunControlPanel(owner, flags));
return DI_OK;
}
STDMETHOD(Initialize)(HINSTANCE instance, DWORD version, REFGUID rguid)
{
ENTER();
//return rvfilter(m_device->Initialize(instance, version, rguid));
return DI_OK;
}
// DirectInputDevice2 methods
STDMETHOD(CreateEffect)(REFGUID a, LPCDIEFFECT b, LPDIRECTINPUTEFFECT * c, LPUNKNOWN d)
{
ENTER();
//return m_device->CreateEffect(a,b,c,d);
return DIERR_DEVICEFULL;
}
STDMETHOD(EnumEffects)(LPDIENUMEFFECTSCALLBACKN a, LPVOID b, DWORD c)
{
ENTER();
//return m_device->EnumEffects(a,b,c);
return DI_OK;
}
STDMETHOD(GetEffectInfo)(LPDIEFFECTINFON a, REFGUID b)
{
ENTER();
//return m_device->GetEffectInfo(a,b);
return E_POINTER;
}
STDMETHOD(GetForceFeedbackState)(LPDWORD a)
{
ENTER();
//return m_device->GetForceFeedbackState(a);
return DIERR_UNSUPPORTED;
}
STDMETHOD(SendForceFeedbackCommand)(DWORD a)
{
ENTER();
//return m_device->SendForceFeedbackCommand(a);
return DIERR_UNSUPPORTED;
}
STDMETHOD(EnumCreatedEffectObjects)(LPDIENUMCREATEDEFFECTOBJECTSCALLBACK a, LPVOID b, DWORD c)
{
ENTER();
//return m_device->EnumCreatedEffectObjects(a,b,c);
return DI_OK;
}
STDMETHOD(Escape)(LPDIEFFESCAPE a)
{
ENTER();
//return m_device->Escape(a);
return DI_OK;
}
STDMETHOD(Poll)()
{
ENTER();
//return rvfilter(m_device->Poll());
if (!m_acquired)
return DIERR_NOTACQUIRED;
return DI_NOEFFECT;
}
STDMETHOD(SendDeviceData)(DWORD a, LPCDIDEVICEOBJECTDATA b, LPDWORD c, DWORD d)
{
ENTER();
//return rvfilter(m_device->SendDeviceData(a,b,c,d));
return DI_OK; // according to the documentation, this function never does anything anyway and should not be called
}
// IDirectInputDevice7 methods
STDMETHOD(EnumEffectsInFile)(LPCNSTR a, LPDIENUMEFFECTSINFILECALLBACK b, LPVOID c, DWORD d)
{
ENTER();
//return m_device->EnumEffectsInFile(a,b,c,d);
return DI_OK;
}
STDMETHOD(WriteEffectToFile)(LPCNSTR a, DWORD b, LPDIFILEEFFECT c, DWORD d)
{
ENTER();
//return m_device->WriteEffectToFile(a,b,c,d);
return DIERR_INVALIDPARAM; // more like DIERR_NYI
}
// IDirectInputDevice8 methods
STDMETHOD(BuildActionMap)(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c)
{
ENTER();
//return m_device->BuildActionMap(a,b,c);
return DIERR_MAPFILEFAIL; // more like DIERR_NYI
}
STDMETHOD(SetActionMap)(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c)
{
ENTER();
//return m_device->SetActionMap(a,b,c);
return DIERR_INVALIDPARAM; // more like DIERR_NYI
}
STDMETHOD(GetImageInfo)(LPDIDEVICEIMAGEINFOHEADERN a)
{
ENTER();
//return m_device->GetImageInfo(a);
return DIERR_MAPFILEFAIL; // more like DIERR_NYI
}
//HRESULT rvfilter(HRESULT rv)
//{
//// if(rv == DIERR_INPUTLOST)
//// return DI_OK;
// return rv;
//}
private:
IDirectInputDeviceN* m_device;
REFGUID m_type;
BufferedInput m_bufferedInput;
BOOL m_acquired;
};
// methods DirectInputDevice doesn't implement
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::CreateEffect(REFGUID a, LPCDIEFFECT b, LPDIRECTINPUTEFFECT * c, LPUNKNOWN d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::EnumEffects(LPDIENUMEFFECTSCALLBACKN a, LPVOID b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::GetEffectInfo(LPDIEFFECTINFON a, REFGUID b) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::GetForceFeedbackState(LPDWORD a) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::SendForceFeedbackCommand(DWORD a) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::EnumCreatedEffectObjects(LPDIENUMCREATEDEFFECTOBJECTSCALLBACK a, LPVOID b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::Escape(LPDIEFFESCAPE a) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::Poll() IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::SendDeviceData(DWORD a, LPCDIDEVICEOBJECTDATA b, LPDWORD c, DWORD d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::CreateEffect(REFGUID a, LPCDIEFFECT b, LPDIRECTINPUTEFFECT * c, LPUNKNOWN d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::EnumEffects(LPDIENUMEFFECTSCALLBACKN a, LPVOID b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::GetEffectInfo(LPDIEFFECTINFON a, REFGUID b) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::GetForceFeedbackState(LPDWORD a) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::SendForceFeedbackCommand(DWORD a) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::EnumCreatedEffectObjects(LPDIENUMCREATEDEFFECTOBJECTSCALLBACK a, LPVOID b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::Escape(LPDIEFFESCAPE a) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::Poll() IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::SendDeviceData(DWORD a, LPCDIDEVICEOBJECTDATA b, LPDWORD c, DWORD d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::EnumEffectsInFile(LPCNSTR a, LPDIENUMEFFECTSINFILECALLBACK b, LPVOID c, DWORD d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::WriteEffectToFile(LPCNSTR a, DWORD b, LPDIFILEEFFECT c, DWORD d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::BuildActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::SetActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceA>::GetImageInfo(LPDIDEVICEIMAGEINFOHEADERN a) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::EnumEffectsInFile(LPCNSTR a, LPDIENUMEFFECTSINFILECALLBACK b, LPVOID c, DWORD d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::WriteEffectToFile(LPCNSTR a, DWORD b, LPDIFILEEFFECT c, DWORD d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::BuildActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::SetActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDeviceW>::GetImageInfo(LPDIDEVICEIMAGEINFOHEADERN a) IMPOSSIBLE_IMPL
// methods DirectInputDevice2 doesn't implement
template<> HRESULT MyDirectInputDevice<IDirectInputDevice2A>::EnumEffectsInFile(LPCNSTR a, LPDIENUMEFFECTSINFILECALLBACK b, LPVOID c, DWORD d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice2A>::WriteEffectToFile(LPCNSTR a, DWORD b, LPDIFILEEFFECT c, DWORD d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice2A>::BuildActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice2A>::SetActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice2A>::GetImageInfo(LPDIDEVICEIMAGEINFOHEADERN a) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice2W>::EnumEffectsInFile(LPCNSTR a, LPDIENUMEFFECTSINFILECALLBACK b, LPVOID c, DWORD d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice2W>::WriteEffectToFile(LPCNSTR a, DWORD b, LPDIFILEEFFECT c, DWORD d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice2W>::BuildActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice2W>::SetActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice2W>::GetImageInfo(LPDIDEVICEIMAGEINFOHEADERN a) IMPOSSIBLE_IMPL
// methods DirectInputDevice7 doesn't implement
template<> HRESULT MyDirectInputDevice<IDirectInputDevice7W>::BuildActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice7W>::SetActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice7W>::GetImageInfo(LPDIDEVICEIMAGEINFOHEADERN a) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice7A>::BuildActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice7A>::SetActionMap(LPDIACTIONFORMATN a, LPCNSTR b, DWORD c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInputDevice<IDirectInputDevice7A>::GetImageInfo(LPDIDEVICEIMAGEINFOHEADERN a) IMPOSSIBLE_IMPL
template<typename IDirectInputN> struct IDirectInputTraits {};
template<> struct IDirectInputTraits<IDirectInputA> { typedef IDirectInputDeviceA IDirectInputDeviceN; typedef LPCDIDEVICEINSTANCEA LPCDIDEVICEINSTANCEN; typedef LPDIACTIONFORMATA LPDIACTIONFORMATN; typedef LPDIENUMDEVICESBYSEMANTICSCBA LPDIENUMDEVICESBYSEMANTICSCBN; typedef LPDICONFIGUREDEVICESPARAMSA LPDICONFIGUREDEVICESPARAMSN; typedef LPCSTR LPCNSTR; };
template<> struct IDirectInputTraits<IDirectInputW> { typedef IDirectInputDeviceW IDirectInputDeviceN; typedef LPCDIDEVICEINSTANCEW LPCDIDEVICEINSTANCEN; typedef LPDIACTIONFORMATW LPDIACTIONFORMATN; typedef LPDIENUMDEVICESBYSEMANTICSCBW LPDIENUMDEVICESBYSEMANTICSCBN; typedef LPDICONFIGUREDEVICESPARAMSW LPDICONFIGUREDEVICESPARAMSN; typedef LPCWSTR LPCNSTR; };
template<> struct IDirectInputTraits<IDirectInput2A> { typedef IDirectInputDeviceA IDirectInputDeviceN; typedef LPCDIDEVICEINSTANCEA LPCDIDEVICEINSTANCEN; typedef LPDIACTIONFORMATA LPDIACTIONFORMATN; typedef LPDIENUMDEVICESBYSEMANTICSCBA LPDIENUMDEVICESBYSEMANTICSCBN; typedef LPDICONFIGUREDEVICESPARAMSA LPDICONFIGUREDEVICESPARAMSN; typedef LPCSTR LPCNSTR; };
template<> struct IDirectInputTraits<IDirectInput2W> { typedef IDirectInputDeviceW IDirectInputDeviceN; typedef LPCDIDEVICEINSTANCEW LPCDIDEVICEINSTANCEN; typedef LPDIACTIONFORMATW LPDIACTIONFORMATN; typedef LPDIENUMDEVICESBYSEMANTICSCBW LPDIENUMDEVICESBYSEMANTICSCBN; typedef LPDICONFIGUREDEVICESPARAMSW LPDICONFIGUREDEVICESPARAMSN; typedef LPCWSTR LPCNSTR; };
template<> struct IDirectInputTraits<IDirectInput7A> { typedef IDirectInputDeviceA IDirectInputDeviceN; typedef LPCDIDEVICEINSTANCEA LPCDIDEVICEINSTANCEN; typedef LPDIACTIONFORMATA LPDIACTIONFORMATN; typedef LPDIENUMDEVICESBYSEMANTICSCBA LPDIENUMDEVICESBYSEMANTICSCBN; typedef LPDICONFIGUREDEVICESPARAMSA LPDICONFIGUREDEVICESPARAMSN; typedef LPCSTR LPCNSTR; };
template<> struct IDirectInputTraits<IDirectInput7W> { typedef IDirectInputDeviceW IDirectInputDeviceN; typedef LPCDIDEVICEINSTANCEW LPCDIDEVICEINSTANCEN; typedef LPDIACTIONFORMATW LPDIACTIONFORMATN; typedef LPDIENUMDEVICESBYSEMANTICSCBW LPDIENUMDEVICESBYSEMANTICSCBN; typedef LPDICONFIGUREDEVICESPARAMSW LPDICONFIGUREDEVICESPARAMSN; typedef LPCWSTR LPCNSTR; };
template<> struct IDirectInputTraits<IDirectInput8A> { typedef IDirectInputDevice8A IDirectInputDeviceN; typedef LPCDIDEVICEINSTANCEA LPCDIDEVICEINSTANCEN; typedef LPDIACTIONFORMATA LPDIACTIONFORMATN; typedef LPDIENUMDEVICESBYSEMANTICSCBA LPDIENUMDEVICESBYSEMANTICSCBN; typedef LPDICONFIGUREDEVICESPARAMSA LPDICONFIGUREDEVICESPARAMSN; typedef LPCSTR LPCNSTR; };
template<> struct IDirectInputTraits<IDirectInput8W> { typedef IDirectInputDevice8W IDirectInputDeviceN; typedef LPCDIDEVICEINSTANCEW LPCDIDEVICEINSTANCEN; typedef LPDIACTIONFORMATW LPDIACTIONFORMATN; typedef LPDIENUMDEVICESBYSEMANTICSCBW LPDIENUMDEVICESBYSEMANTICSCBN; typedef LPDICONFIGUREDEVICESPARAMSW LPDICONFIGUREDEVICESPARAMSN; typedef LPCWSTR LPCNSTR; };
template<typename IDirectInputN>
class MyDirectInput : public IDirectInputN
{
public:
typedef typename IDirectInputTraits<IDirectInputN>::IDirectInputDeviceN IDirectInputDeviceN;
typedef typename IDirectInputTraits<IDirectInputN>::LPCNSTR LPCNSTR;
typedef typename IDirectInputTraits<IDirectInputN>::LPCDIDEVICEINSTANCEN LPCDIDEVICEINSTANCEN;
typedef typename IDirectInputTraits<IDirectInputN>::LPDIACTIONFORMATN LPDIACTIONFORMATN;
typedef typename IDirectInputTraits<IDirectInputN>::LPDIENUMDEVICESBYSEMANTICSCBN LPDIENUMDEVICESBYSEMANTICSCBN;
typedef typename IDirectInputTraits<IDirectInputN>::LPDICONFIGUREDEVICESPARAMSN LPDICONFIGUREDEVICESPARAMSN;
typedef BOOL(FAR PASCAL * LPDIENUMDEVICESCALLBACKN)(LPCDIDEVICEINSTANCEN, LPVOID);
static const GUID IID_IDirectInputDeviceN;
MyDirectInput(IDirectInputN* di) : m_di(di)
{
ENTER();
}
~MyDirectInput()
{
ENTER();
}
/*** IUnknown methods ***/
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObj)
{
ENTER();
HRESULT rv = m_di->QueryInterface(riid, ppvObj);
if (SUCCEEDED(rv))
HookCOMInterface(riid, ppvObj);
return rv;
}
ULONG STDMETHODCALLTYPE AddRef()
{
ENTER();
return m_di->AddRef();
}
ULONG STDMETHODCALLTYPE Release()
{
ENTER();
ULONG count = m_di->Release();
if (0 == count)
delete this;
return count;
}
/*** IDirectInputN methods ***/
STDMETHOD(CreateDevice)(REFGUID rguid, IDirectInputDeviceN** device, LPUNKNOWN unknown)
{
ENTER();
HRESULT hr = m_di->CreateDevice(rguid, device, unknown);
if (SUCCEEDED(hr))
{
LOG() << "Hooking input device with GUID: " << rguid.Data1 << ", " << rguid.Data2 << ", " << rguid.Data3 << ", " << rguid.Data4;
// Return our own keyboard device that checks for injected keypresses
// (at least if rguid == GUID_SysKeyboard that's what it'll do)
HookCOMInterfaceEx(IID_IDirectInputDeviceN, (LPVOID*)device, rguid);
}
return hr;
}
STDMETHOD(EnumDevices)(DWORD devType, LPDIENUMDEVICESCALLBACKN callback, LPVOID ref, DWORD flags)
{
ENTER();
// FIXME: NYI.
// this is leaking data to the game!
// for now, let's at least untrust it.
HRESULT rv = m_di->EnumDevices(devType, callback, ref, flags);
return rv;
}
STDMETHOD(GetDeviceStatus)(REFGUID rguid)
{
ENTER();
return m_di->GetDeviceStatus(rguid);
}
STDMETHOD(RunControlPanel)(HWND owner, DWORD flags)
{
ENTER();
return m_di->RunControlPanel(owner, flags);
}
STDMETHOD(Initialize)(HINSTANCE instance, DWORD version)
{
ENTER();
return m_di->Initialize(instance, version);
}
STDMETHOD(CreateDeviceEx)(REFGUID a, REFIID b, LPVOID* c, LPUNKNOWN d)
{
ENTER(a.Data1, b.Data1);
HRESULT hr = m_di->CreateDeviceEx(a, b, c, d);
if (SUCCEEDED(hr))
HookCOMInterface(b, c);
return hr;
}
STDMETHOD(FindDevice)(REFGUID a, LPCNSTR b, LPGUID c)
{
ENTER();
return m_di->FindDevice(a, b, c);
}
STDMETHOD(EnumDevicesBySemantics)(LPCNSTR a, LPDIACTIONFORMATN b, LPDIENUMDEVICESBYSEMANTICSCBN c, LPVOID d, DWORD e)
{
ENTER();
return m_di->EnumDevicesBySemantics(a, b, c, d, e);
}
STDMETHOD(ConfigureDevices)(LPDICONFIGUREDEVICESCALLBACK a, LPDICONFIGUREDEVICESPARAMSN b, DWORD c, LPVOID d)
{
ENTER();
return m_di->ConfigureDevices(a, b, c, d);
}
private:
IDirectInputN* m_di;
};
// unimplemented methods for old versions of DirectInput that didn't have them
template<> HRESULT MyDirectInput<IDirectInputA>::FindDevice(REFGUID a, LPCNSTR b, LPGUID c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInputW>::FindDevice(REFGUID a, LPCNSTR b, LPGUID c) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInputA>::EnumDevicesBySemantics(LPCNSTR a, LPDIACTIONFORMATN b, LPDIENUMDEVICESBYSEMANTICSCBN c, LPVOID d, DWORD e) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInputW>::EnumDevicesBySemantics(LPCNSTR a, LPDIACTIONFORMATN b, LPDIENUMDEVICESBYSEMANTICSCBN c, LPVOID d, DWORD e) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInputA>::ConfigureDevices(LPDICONFIGUREDEVICESCALLBACK a, LPDICONFIGUREDEVICESPARAMSN b, DWORD c, LPVOID d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInputW>::ConfigureDevices(LPDICONFIGUREDEVICESCALLBACK a, LPDICONFIGUREDEVICESPARAMSN b, DWORD c, LPVOID d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInputA>::CreateDeviceEx(REFGUID a, REFIID b, LPVOID* c, LPUNKNOWN d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInputW>::CreateDeviceEx(REFGUID a, REFIID b, LPVOID* c, LPUNKNOWN d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput2A>::EnumDevicesBySemantics(LPCNSTR a, LPDIACTIONFORMATN b, LPDIENUMDEVICESBYSEMANTICSCBN c, LPVOID d, DWORD e) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput2W>::EnumDevicesBySemantics(LPCNSTR a, LPDIACTIONFORMATN b, LPDIENUMDEVICESBYSEMANTICSCBN c, LPVOID d, DWORD e) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput2A>::ConfigureDevices(LPDICONFIGUREDEVICESCALLBACK a, LPDICONFIGUREDEVICESPARAMSN b, DWORD c, LPVOID d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput2W>::ConfigureDevices(LPDICONFIGUREDEVICESCALLBACK a, LPDICONFIGUREDEVICESPARAMSN b, DWORD c, LPVOID d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput2A>::CreateDeviceEx(REFGUID a, REFIID b, LPVOID* c, LPUNKNOWN d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput2W>::CreateDeviceEx(REFGUID a, REFIID b, LPVOID* c, LPUNKNOWN d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput7A>::EnumDevicesBySemantics(LPCNSTR a, LPDIACTIONFORMATN b, LPDIENUMDEVICESBYSEMANTICSCBN c, LPVOID d, DWORD e) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput7W>::EnumDevicesBySemantics(LPCNSTR a, LPDIACTIONFORMATN b, LPDIENUMDEVICESBYSEMANTICSCBN c, LPVOID d, DWORD e) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput7A>::ConfigureDevices(LPDICONFIGUREDEVICESCALLBACK a, LPDICONFIGUREDEVICESPARAMSN b, DWORD c, LPVOID d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput7W>::ConfigureDevices(LPDICONFIGUREDEVICESCALLBACK a, LPDICONFIGUREDEVICESPARAMSN b, DWORD c, LPVOID d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput8A>::CreateDeviceEx(REFGUID a, REFIID b, LPVOID* c, LPUNKNOWN d) IMPOSSIBLE_IMPL
template<> HRESULT MyDirectInput<IDirectInput8W>::CreateDeviceEx(REFGUID a, REFIID b, LPVOID* c, LPUNKNOWN d) IMPOSSIBLE_IMPL
template<> const GUID MyDirectInput<IDirectInputA>::IID_IDirectInputDeviceN = IID_IDirectInputDeviceA;
template<> const GUID MyDirectInput<IDirectInputW>::IID_IDirectInputDeviceN = IID_IDirectInputDeviceW;
template<> const GUID MyDirectInput<IDirectInput2A>::IID_IDirectInputDeviceN = IID_IDirectInputDeviceA;
template<> const GUID MyDirectInput<IDirectInput2W>::IID_IDirectInputDeviceN = IID_IDirectInputDeviceW;
template<> const GUID MyDirectInput<IDirectInput7A>::IID_IDirectInputDeviceN = IID_IDirectInputDeviceA;
template<> const GUID MyDirectInput<IDirectInput7W>::IID_IDirectInputDeviceN = IID_IDirectInputDeviceW;
template<> const GUID MyDirectInput<IDirectInput8A>::IID_IDirectInputDeviceN = IID_IDirectInputDevice8A;
template<> const GUID MyDirectInput<IDirectInput8W>::IID_IDirectInputDeviceN = IID_IDirectInputDevice8W;
}
int g_midFrameAsyncKeyRequests = 0;
namespace WinInput
{
using Log = DebugLog<LogCategory::WINPUT>;
HOOK_FUNCTION(SHORT, WINAPI, GetAsyncKeyState, int vKey);
HOOKFUNC SHORT WINAPI MyGetAsyncKeyState(int vKey)
{
// return GetAsyncKeyState(vKey);
ENTER(vKey);
if (vKey < 0 || vKey > 255)
return 0;
g_midFrameAsyncKeyRequests++;
if (g_midFrameAsyncKeyRequests >= 4096 && g_midFrameAsyncKeyRequests < 4096 + 512)
return 0; // prevent freezing in games that pause until a key is released (e.g. IWBTG)
if (vKey == VK_CAPITAL || vKey == VK_NUMLOCK || vKey == VK_SCROLL)
{
// special case for these because curinput stores the toggle status of these keys
// whereas GetAsyncKeyState treats them like other keys
unsigned char curbit = asynckeybit[vKey];
if (curbit)
{
//if(s_frameThreadId == GetCurrentThreadId())
//if(tls.isFrameThread)
if (tls_IsPrimaryThread())
{
if (curbit < 16)
asynckeybit[vKey]++;
else
asynckeybit[vKey] = 0;
}
return (curbit == 1) ? 0x8001 : 0x8000;
}
return 0;
}
if (asynckeybit[vKey]) // if the key has been pressed since the last call to this function
{
//if(s_frameThreadId == GetCurrentThreadId())
//if(tls.isFrameThread)
if (tls_IsPrimaryThread())
asynckeybit[vKey] = 0;
if (curinput.keys[vKey])
return (SHORT)0x8001; // key is just now pressed
return 1; // key is not held, but was pressed earlier
}
if (curinput.keys[vKey])
return (SHORT)0x8000; // key is held
return 0; // key is not held
}
static bool disableGetKeyStateLogging = false;
HOOK_FUNCTION(SHORT, WINAPI, GetKeyState, int vKey);
HOOKFUNC SHORT WINAPI MyGetKeyState(int vKey)
{
/*
* TODO: The returned state should only update when the game reads the relevant WM_ messages
* (WM_KEYDOWN, WM_KEYUP, etc.), just as if the state only knew about these messages.
*
* Currently the whole state is instantly updated on frame boundary.
* -- YaLTeR
*/
// WARNING: PeekMessage SOMETIMES internally calls this function (both directly and indirectly),
// so we must not change the state of anything in here.
if (!disableGetKeyStateLogging)
{
ENTER(vKey);
}
// return GetKeyState(vKey);
SHORT rv;
if (vKey == VK_CAPITAL || vKey == VK_NUMLOCK || vKey == VK_SCROLL)
{
// special case for these because curinput stores the toggle status of these keys
// whereas GetKeyState (perhaps surprisingly) treats them like other keys
if (curinput.keys[vKey] != previnput.keys[vKey])
rv = curinput.keys[vKey] ? (SHORT)0xFF81 : (SHORT)0xFF80;
else
rv = curinput.keys[vKey] ? 1 : 0;
}
else
{
if (curinput.keys[vKey])
rv = synckeybit[vKey] ? (SHORT)0xFF81 : (SHORT)0xFF80;
else
rv = synckeybit[vKey] ? 1 : 0;
}
if (!disableGetKeyStateLogging)
{
LEAVE(rv);
}
return rv;
}
HOOK_FUNCTION(BOOL, WINAPI, GetKeyboardState, PBYTE lpKeyState);
HOOKFUNC BOOL WINAPI MyGetKeyboardState(PBYTE lpKeyState)
{
// WARNING: PeekMessage SOMETIMES internally calls this function,
// so we must not change the state of anything in here.
// (MyPeekMessageA -> _PeekMessageA@20 -> _NtUserPeekMessage@20 -> _KiUserExceptionDispatcher@8 -> ___ClientImmProcessKey@4 -> _ImmProcessKey@20 -> MyGetKeyboardState)
// return GetKeyboardState(lpKeyState);
ENTER();
if (!lpKeyState)
return FALSE;
disableGetKeyStateLogging = true;
for (int i = 0; i < 256; i++)
lpKeyState[i] = (BYTE)(MyGetKeyState(i) & 0xFF);
disableGetKeyStateLogging = false;
return TRUE;
}
static LASTINPUTINFO s_lii = { sizeof(LASTINPUTINFO) };
HOOK_FUNCTION(BOOL, WINAPI, GetLastInputInfo, PLASTINPUTINFO plii);
HOOKFUNC BOOL WINAPI MyGetLastInputInfo(PLASTINPUTINFO plii)
{
ENTER();
//return GetLastInputInfo(plii);
if (plii)
{
plii->dwTime = s_lii.dwTime;
return TRUE;
}
return FALSE;
}
void ProcessFrameInput()
{
static DWORD inputEventSequenceID = 0;
// do some processing per key that changed states.
// this is so MyGetAsyncKeyState can properly mimic GetAsyncKeyState's
// return value pattern of 0x0000 -> 0x8001 -> 0x8000 when a key is pressed,
// and also so directinput buffered keyboard input can work.
for (DWORD i = 1; i < 256; i++)
{
if (curinput.keys[i] != previnput.keys[i])
{
LOG() << "key " << i << ": " << previnput.keys[i] << " -> " << curinput.keys[i];
if (i == VK_CAPITAL || i == VK_NUMLOCK || i == VK_SCROLL)
{
asynckeybit[i] = 1;
synckeybit[i] = 1;
}
else
{
asynckeybit[i] = curinput.keys[i];
synckeybit[i] = !synckeybit[i];
}
DWORD timeStamp = detTimer.GetTicks();
s_lii.dwTime = timeStamp;
__declspec(noinline) SHORT WINAPI MyGetKeyState(int vKey);
DIDEVICEOBJECTDATA keyEvent = { i, static_cast<DWORD>(MyGetKeyState(i) & 0xFF), timeStamp, inputEventSequenceID++ };
DirectInput::BufferedInput::AddEventToAllDevices(keyEvent, DirectInput::s_bufferedKeySlots);
}
}
// Send mouse events.
if (curinput.mouse.di.lX != 0) {
DWORD timeStamp = detTimer.GetTicks();
s_lii.dwTime = timeStamp;
DIDEVICEOBJECTDATA mouseEvent = { DIMOFS_X, static_cast<DWORD>(curinput.mouse.di.lX), timeStamp, inputEventSequenceID++ };
DirectInput::BufferedInput::AddMouseEventToAllDevices(mouseEvent, DirectInput::s_bufferedKeySlots);
}
if (curinput.mouse.di.lY != 0) {
DWORD timeStamp = detTimer.GetTicks();
s_lii.dwTime = timeStamp;
DIDEVICEOBJECTDATA mouseEvent = { DIMOFS_Y, static_cast<DWORD>(curinput.mouse.di.lY), timeStamp, inputEventSequenceID++ };
DirectInput::BufferedInput::AddMouseEventToAllDevices(mouseEvent, DirectInput::s_bufferedKeySlots);
}
if (curinput.mouse.di.lZ != 0) {
DWORD timeStamp = detTimer.GetTicks();
s_lii.dwTime = timeStamp;
DIDEVICEOBJECTDATA mouseEvent = { DIMOFS_Z, static_cast<DWORD>(curinput.mouse.di.lZ), timeStamp, inputEventSequenceID++ };
DirectInput::BufferedInput::AddMouseEventToAllDevices(mouseEvent, DirectInput::s_bufferedKeySlots);
}
if (curinput.mouse.di.rgbButtons[0] != previnput.mouse.di.rgbButtons[0]) {
DWORD timeStamp = detTimer.GetTicks();
s_lii.dwTime = timeStamp;
DIDEVICEOBJECTDATA mouseEvent = { DIMOFS_BUTTON0, static_cast<DWORD>(curinput.mouse.di.rgbButtons[0] ? 0x80 : 0x00), timeStamp, inputEventSequenceID++ };
DirectInput::BufferedInput::AddMouseEventToAllDevices(mouseEvent, DirectInput::s_bufferedKeySlots);
}
if (curinput.mouse.di.rgbButtons[1] != previnput.mouse.di.rgbButtons[1]) {
DWORD timeStamp = detTimer.GetTicks();
s_lii.dwTime = timeStamp;
DIDEVICEOBJECTDATA mouseEvent = { DIMOFS_BUTTON1, static_cast<DWORD>(curinput.mouse.di.rgbButtons[1] ? 0x80 : 0x00), timeStamp, inputEventSequenceID++ };
DirectInput::BufferedInput::AddMouseEventToAllDevices(mouseEvent, DirectInput::s_bufferedKeySlots);
}
if (curinput.mouse.di.rgbButtons[2] != previnput.mouse.di.rgbButtons[2]) {
DWORD timeStamp = detTimer.GetTicks();
s_lii.dwTime = timeStamp;
DIDEVICEOBJECTDATA mouseEvent = { DIMOFS_BUTTON2, static_cast<DWORD>(curinput.mouse.di.rgbButtons[2] ? 0x80 : 0x00), timeStamp, inputEventSequenceID++ };
DirectInput::BufferedInput::AddMouseEventToAllDevices(mouseEvent, DirectInput::s_bufferedKeySlots);
}
/*if (curinput.mouse.rgbButtons[3] && !previnput.mouse.rgbButtons[3]){
DWORD timeStamp = detTimer.GetTicks();
s_lii.dwTime = timeStamp;
DIDEVICEOBJECTDATA mouseEvent = {DIMOFS_BUTTON3, static_cast<DWORD>(0x80), timeStamp, inputEventSequenceID++};
BufferedInput::AddMouseEventToAllDevices(mouseEvent, s_bufferedKeySlots);
}*/
/* Pass mouse cursor absolute coords.
* If no mouse event were recorded during the current frame,
* we have to pass the previous absolute coords into the current frame.
*/
bool isMouseUsed = (curinput.mouse.di.lX != 0) || (curinput.mouse.di.lY != 0) || (curinput.mouse.di.lZ != 0);
for (int i = 0; i < 4; i++)
isMouseUsed |= ((curinput.mouse.di.rgbButtons[i] & MOUSE_PRESSED_FLAG) != 0);
if (!isMouseUsed)
curinput.mouse.coords = previnput.mouse.coords;
}
HOOK_FUNCTION(MMRESULT, WINAPI, joyReleaseCapture, UINT uJoyID);
HOOKFUNC MMRESULT WINAPI MyjoyReleaseCapture(UINT uJoyID)
{
ENTER(uJoyID);
return MMSYSERR_NODRIVER; // NYI
//cmdprintf("WAITING: %u", 1);
MMRESULT rv = joyReleaseCapture(uJoyID);
//cmdprintf("WAITED: %u", 1);
return rv;
}
HOOK_FUNCTION(MMRESULT, WINAPI, joySetCapture, HWND hwnd, UINT uJoyID, UINT uPeriod, BOOL fChanged);
HOOKFUNC MMRESULT WINAPI MyjoySetCapture(HWND hwnd, UINT uJoyID, UINT uPeriod, BOOL fChanged)
{
ENTER(hwnd, uJoyID, uPeriod, fChanged);
return MMSYSERR_NODRIVER; // NYI
MMRESULT rv = joySetCapture(hwnd, uJoyID, uPeriod, fChanged);
return rv;
}
HOOK_FUNCTION(MMRESULT, WINAPI, joyGetPosEx, UINT uJoyID, LPJOYINFOEX pji);
HOOKFUNC MMRESULT WINAPI MyjoyGetPosEx(UINT uJoyID, LPJOYINFOEX pji)
{
ENTER(uJoyID);
return MMSYSERR_NODRIVER; // NYI
char threadTypeName[64];
sprintf(threadTypeName, "JoypadThread(%d)", uJoyID);
tls.curThreadCreateName = threadTypeName;
LOG() << "tls.curThreadCreateName = " << tls.curThreadCreateName;
MMRESULT rv = joyGetPosEx(uJoyID, pji);
tls.curThreadCreateName = NULL;
return rv;
// return MMSYSERR_NODRIVER ;
}
HOOK_FUNCTION(MMRESULT, WINAPI, joyGetPos, UINT uJoyID, LPJOYINFO pji);
HOOKFUNC MMRESULT WINAPI MyjoyGetPos(UINT uJoyID, LPJOYINFO pji)
{
ENTER(uJoyID);
return MMSYSERR_NODRIVER; // NYI
char threadTypeName[64];
sprintf(threadTypeName, "JoypadThread(%d)", uJoyID);
tls.curThreadCreateName = threadTypeName;
MMRESULT rv = joyGetPos(uJoyID, pji);
tls.curThreadCreateName = NULL;
return rv;
}
HOOK_FUNCTION(UINT, WINAPI, joyGetNumDevs);
HOOKFUNC UINT WINAPI MyjoyGetNumDevs()
{
ENTER();
return 0; // NYI
UINT rv = joyGetNumDevs();
return rv;
}
HOOK_FUNCTION(MMRESULT, WINAPI, joyGetDevCapsA, UINT_PTR uJoyID, LPJOYCAPSA pjc, UINT cbjc);
HOOKFUNC MMRESULT WINAPI MyjoyGetDevCapsA(UINT_PTR uJoyID, LPJOYCAPSA pjc, UINT cbjc)
{
ENTER();
return MMSYSERR_NODRIVER; // NYI
MMRESULT rv = joyGetDevCapsA(uJoyID, pjc, cbjc);
return rv;
}
HOOK_FUNCTION(MMRESULT, WINAPI, joyGetDevCapsW, UINT_PTR uJoyID, LPJOYCAPSW pjc, UINT cbjc);
HOOKFUNC MMRESULT WINAPI MyjoyGetDevCapsW(UINT_PTR uJoyID, LPJOYCAPSW pjc, UINT cbjc)
{
ENTER();
return MMSYSERR_NODRIVER; // NYI
MMRESULT rv = joyGetDevCapsW(uJoyID, pjc, cbjc);
return rv;
}
HOOK_FUNCTION(BOOL, WINAPI, GetCursorPos, LPPOINT lpPoint);
HOOKFUNC BOOL WINAPI MyGetCursorPos(LPPOINT lpPoint)
{
if (!lpPoint) { return FALSE; }
lpPoint->x = curinput.mouse.coords.x;
lpPoint->y = curinput.mouse.coords.y;
ClientToScreen(gamehwnd, lpPoint);
//return GetCursorPos(lpPoint);
return TRUE;
}
HOOK_FUNCTION(BOOL, WINAPI, GetCursorInfo, PCURSORINFO pci);
HOOKFUNC BOOL WINAPI MyGetCursorInfo(PCURSORINFO pci)
{
if (!GetCursorInfo(pci)) { return FALSE; }
return MyGetCursorPos(&pci->ptScreenPos);
}
}
namespace DirectInput
{
HOOK_FUNCTION(HRESULT, WINAPI, DirectInputCreateA, HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTA *ppDI, LPUNKNOWN punkOuter);
HOOKFUNC HRESULT WINAPI MyDirectInputCreateA(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTA *ppDI, LPUNKNOWN punkOuter)
{
ENTER();
ThreadLocalStuff& curtls = tls;
const char* oldName = curtls.curThreadCreateName;
curtls.curThreadCreateName = "DirectInput";
HRESULT rv = DirectInputCreateA(hinst, dwVersion, ppDI, punkOuter);
if (SUCCEEDED(rv))
{
if (dwVersion < 0x500)
HookCOMInterface(IID_IDirectInputA, (LPVOID*)ppDI);
else if (dwVersion < 0x700)
HookCOMInterface(IID_IDirectInput2A, (LPVOID*)ppDI);
else if (dwVersion < 0x800)
HookCOMInterface(IID_IDirectInput7A, (LPVOID*)ppDI);
else if (dwVersion < 0x900)
HookCOMInterface(IID_IDirectInput8A, (LPVOID*)ppDI);
}
else
{
LOG() << "DirectInputCreateA FAILED, all on its own. Returned " << rv;
}
curtls.curThreadCreateName = oldName;
return rv;
}
HOOK_FUNCTION(HRESULT, WINAPI, DirectInputCreateW, HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTW *ppDI, LPUNKNOWN punkOuter);
HOOKFUNC HRESULT WINAPI MyDirectInputCreateW(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTW *ppDI, LPUNKNOWN punkOuter)
{
ENTER();
ThreadLocalStuff& curtls = tls;
const char* oldName = curtls.curThreadCreateName;
curtls.curThreadCreateName = "DirectInput";
HRESULT rv = DirectInputCreateW(hinst, dwVersion, ppDI, punkOuter);
if (SUCCEEDED(rv))
{
if (dwVersion < 0x500)
HookCOMInterface(IID_IDirectInputW, (LPVOID*)ppDI);
else if (dwVersion < 0x700)
HookCOMInterface(IID_IDirectInput2W, (LPVOID*)ppDI);
else if (dwVersion < 0x800)
HookCOMInterface(IID_IDirectInput7W, (LPVOID*)ppDI);
else if (dwVersion < 0x900)
HookCOMInterface(IID_IDirectInput8W, (LPVOID*)ppDI);
}
else
{
LOG() << "DirectInputCreateW FAILED, all on its own. Returned " << rv;
}
curtls.curThreadCreateName = oldName;
return rv;
}
HOOK_FUNCTION(HRESULT, WINAPI, DirectInputCreateEx, HINSTANCE hinst, DWORD dwVersion, REFIID riidltf, LPVOID *ppvOut, LPUNKNOWN punkOuter);
HOOKFUNC HRESULT WINAPI MyDirectInputCreateEx(HINSTANCE hinst, DWORD dwVersion, REFIID riidltf, LPVOID *ppvOut, LPUNKNOWN punkOuter)
{
ENTER();
ThreadLocalStuff& curtls = tls;
const char* oldName = curtls.curThreadCreateName;
curtls.curThreadCreateName = "directinputex";
HRESULT rv = DirectInputCreateEx(hinst, dwVersion, riidltf, ppvOut, punkOuter);
if (SUCCEEDED(rv))
{
HookCOMInterface(riidltf, ppvOut);
}
else
{
LOG() << "DirectInputCreateEx FAILED, all on its own. Returned " << rv;
}
curtls.curThreadCreateName = oldName;
return rv;
}
HOOK_FUNCTION(HRESULT, WINAPI, DirectInput8Create, HINSTANCE hinst, DWORD dwVersion, REFIID riidltf, LPVOID *ppvOut, LPUNKNOWN punkOuter);
HOOKFUNC HRESULT WINAPI MyDirectInput8Create(HINSTANCE hinst, DWORD dwVersion, REFIID riidltf, LPVOID *ppvOut, LPUNKNOWN punkOuter)
{
ENTER();
ThreadLocalStuff& curtls = tls;
const char* oldName = curtls.curThreadCreateName;
curtls.curThreadCreateName = "directinput8";
HRESULT rv = DirectInput8Create(hinst, dwVersion, riidltf, ppvOut, punkOuter);
if (SUCCEEDED(rv))
{
HookCOMInterface(riidltf, ppvOut);
}
else
{
LOG() << "DirectInput8Create FAILED, all on its own. Returned " << rv;
}
curtls.curThreadCreateName = oldName;
return rv;
}
bool HookCOMInterfaceInput(REFIID riid, LPVOID* ppvOut, bool uncheckedFastNew)
{
switch (riid.Data1)
{
HOOKRIID(DirectInput, A);
HOOKRIID(DirectInput, W);
HOOKRIID(DirectInput, 2A);
HOOKRIID(DirectInput, 2W);
HOOKRIID(DirectInput, 7A);
HOOKRIID(DirectInput, 7W);
HOOKRIID(DirectInput, 8A);
HOOKRIID(DirectInput, 8W);
HOOKRIID2(DirectInputDeviceA, MyDirectInputDevice);
HOOKRIID2(DirectInputDeviceW, MyDirectInputDevice);
HOOKRIID2(DirectInputDevice2A, MyDirectInputDevice);
HOOKRIID2(DirectInputDevice2W, MyDirectInputDevice);
HOOKRIID2(DirectInputDevice7A, MyDirectInputDevice);
HOOKRIID2(DirectInputDevice7W, MyDirectInputDevice);
HOOKRIID2(DirectInputDevice8A, MyDirectInputDevice);
HOOKRIID2(DirectInputDevice8W, MyDirectInputDevice);
default: return false;
}
return true;
}
bool HookCOMInterfaceInputEx(REFIID riid, LPVOID* ppvOut, REFGUID parameter, bool uncheckedFastNew)
{
switch (riid.Data1)
{
HOOKRIID(DirectInput, A);
HOOKRIID(DirectInput, W);
HOOKRIID(DirectInput, 2A);
HOOKRIID(DirectInput, 2W);
HOOKRIID(DirectInput, 7A);
HOOKRIID(DirectInput, 7W);
HOOKRIID(DirectInput, 8A);
HOOKRIID(DirectInput, 8W);
HOOKRIID2EX(DirectInputDeviceA, MyDirectInputDevice, parameter);
HOOKRIID2EX(DirectInputDeviceW, MyDirectInputDevice, parameter);
HOOKRIID2EX(DirectInputDevice2A, MyDirectInputDevice, parameter);
HOOKRIID2EX(DirectInputDevice2W, MyDirectInputDevice, parameter);
HOOKRIID2EX(DirectInputDevice7A, MyDirectInputDevice, parameter);
HOOKRIID2EX(DirectInputDevice7W, MyDirectInputDevice, parameter);
HOOKRIID2EX(DirectInputDevice8A, MyDirectInputDevice, parameter);
HOOKRIID2EX(DirectInputDevice8W, MyDirectInputDevice, parameter);
default: return false;
}
return true;
}
}
namespace DirectInput
{
void ApplyDirectInputIntercepts()
{
static const InterceptDescriptor intercepts[] =
{
MAKE_INTERCEPT(1, DINPUT, DirectInputCreateA),
MAKE_INTERCEPT(1, DINPUT, DirectInputCreateW),
MAKE_INTERCEPT(1, DINPUT, DirectInputCreateEx),
MAKE_INTERCEPT(1, DINPUT8, DirectInput8Create),
};
ApplyInterceptTable(intercepts, ARRAYSIZE(intercepts));
}
}
namespace WinInput
{
void ApplyWinInputIntercepts()
{
static const InterceptDescriptor intercepts[] =
{
MAKE_INTERCEPT(1, USER32, GetAsyncKeyState),
MAKE_INTERCEPT(1, USER32, GetKeyState),
MAKE_INTERCEPT(1, USER32, GetKeyboardState),
MAKE_INTERCEPT(1, USER32, GetLastInputInfo),
MAKE_INTERCEPT(1, WINMM, joyReleaseCapture),
MAKE_INTERCEPT(1, WINMM, joySetCapture),
MAKE_INTERCEPT(1, WINMM, joyGetPosEx),
MAKE_INTERCEPT(1, WINMM, joyGetPos),
MAKE_INTERCEPT(1, WINMM, joyGetNumDevs),
MAKE_INTERCEPT(1, WINMM, joyGetDevCapsA),
MAKE_INTERCEPT(1, WINMM, joyGetDevCapsW),
MAKE_INTERCEPT(1, USER32, GetCursorPos),
MAKE_INTERCEPT(1, USER32, GetCursorInfo),
};
ApplyInterceptTable(intercepts, ARRAYSIZE(intercepts));
}
}
}
| gpl-2.0 |
t-zuehlsdorff/wesnoth | src/whiteboard/mapbuilder.cpp | 5573 | /*
Copyright (C) 2010 - 2016 by Gabriel Morin <gabrielmorin (at) gmail (dot) com>
Part of the Battle for Wesnoth Project http://www.wesnoth.org
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
*/
#include "mapbuilder.hpp"
#include "action.hpp"
#include "move.hpp"
#include "side_actions.hpp"
#include "utility.hpp"
#include "game_board.hpp"
#include "play_controller.hpp"
#include "resources.hpp"
#include "unit.hpp"
#include "unit_map.hpp"
#include <boost/foreach.hpp>
namespace wb
{
mapbuilder::mapbuilder(unit_map& unit_map)
: unit_map_(unit_map)
, applied_actions_()
, applied_actions_this_turn_()
, resetters_()
, removers_()
, acted_this_turn_()
, has_invalid_actions_()
, invalid_actions_()
{
}
mapbuilder::~mapbuilder()
{
try {
restore_normal_map();
//Remember that the member variable resetters_ is destructed here
} catch (...) {}
}
void mapbuilder::pre_build()
{
BOOST_FOREACH(team& t, *resources::teams) {
//Reset spent gold to zero, it'll be recalculated during the map building
t.get_side_actions()->reset_gold_spent();
}
int current_side = resources::controller->current_side();
BOOST_FOREACH(unit& u, *resources::units) {
bool on_current_side = (u.side() == current_side);
//Remove any unit the current side cannot see to avoid their detection by planning
//Units will be restored to the unit map by destruction of removers_
if(!on_current_side && !u.is_visible_to_team((*resources::teams)[viewer_team()], resources::gameboard->map(), false)) {
removers_.push_back(new temporary_unit_remover(*resources::units, u.get_location()));
//Don't do anything else to the removed unit!
continue;
}
//Reset movement points, to be restored by destruction of resetters_
//restore movement points only to units not on the current side
resetters_.push_back(new unit_movement_resetter(u,!on_current_side));
//make sure current side's units are not reset to full moves on first turn
if(on_current_side) {
acted_this_turn_.insert(&u);
}
}
}
void mapbuilder::build_map()
{
pre_build();
if(!wb::has_actions()) {
return;
}
bool end = false;
for(size_t turn=0; !end; ++turn) {
end = true;
BOOST_FOREACH(team &side, *resources::teams) {
side_actions &actions = *side.get_side_actions();
if(turn < actions.num_turns() && team_has_visible_plan(side)) {
end = false;
side_actions::iterator it = actions.turn_begin(turn), next = it, end = actions.turn_end(turn);
while(it != end) {
std::advance(next, 1);
process(actions, it);
it = next;
}
post_visit_team(turn);
}
}
}
}
void mapbuilder::process(side_actions &sa, side_actions::iterator action_it)
{
action_ptr action = *action_it;
bool acted=false;
unit_ptr unit = action->get_unit();
if(!unit) {
return;
}
if(acted_this_turn_.find(unit.get()) == acted_this_turn_.end()) {
//reset MP
unit->set_movement(unit->total_movement());
acted=true;
}
// Validity check
action::error erval = action->check_validity();
action->redraw();
if(erval != action::OK) {
// We do not delete obstructed moves, nor invalid actions caused by obstructed moves.
if(has_invalid_actions_.find(unit.get()) == has_invalid_actions_.end()) {
if(erval == action::TOO_FAR || (erval == action::LOCATION_OCCUPIED && boost::dynamic_pointer_cast<move>(action))) {
has_invalid_actions_.insert(unit.get());
invalid_actions_.push_back(action_it);
} else {
sa.remove_action(action_it, false);
return;
}
} else {
invalid_actions_.push_back(action_it);
}
return;
}
// We do not keep invalid actions replaced by a valid one.
std::set<class unit const*>::iterator invalid_it = has_invalid_actions_.find(unit.get());
if(invalid_it != has_invalid_actions_.end()) {
for(std::list<side_actions::iterator>::iterator it = invalid_actions_.begin(); it != invalid_actions_.end();) {
if((**it)->get_unit().get() == unit.get()) {
sa.remove_action(*it, false);
it = invalid_actions_.erase(it);
} else {
++it;
}
}
has_invalid_actions_.erase(invalid_it);
}
if(acted) {
acted_this_turn_.insert(unit.get());
}
action->apply_temp_modifier(unit_map_);
applied_actions_.push_back(action);
applied_actions_this_turn_.push_back(action);
}
void mapbuilder::post_visit_team(size_t turn)
{
std::set<unit const*> seen;
// Go backwards through the actions of this turn to identify
// which ones are moves that end a turn.
BOOST_REVERSE_FOREACH(action_ptr action, applied_actions_this_turn_) {
move_ptr move = boost::dynamic_pointer_cast<class move>(action);
if(move) {
move->set_turn_number(0);
if(move->get_route().steps.size() > 1 && seen.count(move->get_unit().get()) == 0) {
seen.insert(move->get_unit().get());
move->set_turn_number(turn + 1);
}
}
}
// Clear list of planned actions applied this turn
applied_actions_this_turn_.clear();
// Clear the list of units of this team that have acted this turn
acted_this_turn_.clear();
}
void mapbuilder::restore_normal_map()
{
//applied_actions_ contain only the actions that we applied to the unit map
BOOST_REVERSE_FOREACH(action_ptr act, applied_actions_) {
act->remove_temp_modifier(unit_map_);
}
}
} // end namespace wb
| gpl-2.0 |
ranrolls/ras-full-portal | administrator/components/com_acymailing/classes/acyhistory.php | 1311 | <?php
/**
* @package AcyMailing for Joomla!
* @version 4.8.0
* @author acyba.com
* @copyright (C) 2009-2014 ACYBA S.A.R.L. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><?php
class acyhistoryClass extends acymailingClass{
function insert($subid,$action,$data = array(),$mailid = 0){
$user = JFactory::getUser();
if(!empty($user->id)){
$data[] = 'EXECUTED_BY::'.$user->id.' ( '.$user->username.' )';
}
$history = new stdClass();
$history->subid = intval($subid);
$history->action = strip_tags($action);
$history->data = implode("\n",$data);
if(strlen($history->data) > 100000) $history->data = substr($history->data,0,10000);
$history->date = time();
$history->mailid = $mailid;
$userHelper = acymailing_get('helper.user');
$history->ip = $userHelper->getIP();
if(!empty($_SERVER)){
$source = array();
$vars = array('HTTP_REFERER','HTTP_USER_AGENT','HTTP_HOST','SERVER_ADDR','REMOTE_ADDR','REQUEST_URI','QUERY_STRING');
foreach($vars as $oneVar){
if(!empty($_SERVER[$oneVar])) $source[] = $oneVar.'::'.strip_tags($_SERVER[$oneVar]);
}
$history->source = implode("\n",$source);
}
return $this->database->insertObject(acymailing_table('history'),$history);
}
}
| gpl-2.0 |
xstory61/server | scripts/quest/3454.js | 1771 | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc>
Matthias Butz <matze@odinms.de>
Jan Christian Meyer <vimes@odinms.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
Author : Ronan
NPC Name: Dr. Kim
Map(s): Omega Sector
Description: Quest - Wave Translator
Quest ID: 3454
*/
function end(mode, type, selection) {
if(qm.getPlayer().getInventory(Packages.client.inventory.MapleInventoryType.ETC).getNumFreeSlot() < 1) {
qm.sendOk("Make room on your ETC inventory first.");
qm.dispose();
return;
}
qm.gainItem(4000125, -1);
qm.gainItem(4031926, -10);
qm.gainItem(4000119, -30);
qm.gainItem(4000118, -30);
rnd = Math.random();
if(rnd < 1.0) {
qm.gainItem(4031928, 1);
}
else {
qm.gainItem(4031927, 1);
}
qm.sendOk("Now, go meet Alien Gray and use this undercover to read through their plans. If this fails, we will need to gather some materials once again.");
qm.forceCompleteQuest();
qm.dispose();
}
| gpl-2.0 |
bbeckman/NDL-VuFind2 | module/VuFindSearch/src/VuFindSearch/Backend/WorldCat/Backend.php | 5041 | <?php
/**
* WorldCat backend.
*
* PHP version 5
*
* Copyright (C) Villanova University 2010.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Search
* @author David Maus <maus@hab.de>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org
*/
namespace VuFindSearch\Backend\WorldCat;
use VuFindSearch\Backend\AbstractBackend;
use VuFindSearch\ParamBag;
use VuFindSearch\Query\AbstractQuery;
use VuFindSearch\Response\RecordCollectionFactoryInterface;
use VuFindSearch\Response\RecordCollectionInterface;
/**
* WorldCat backend.
*
* @category VuFind
* @package Search
* @author David Maus <maus@hab.de>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org
*/
class Backend extends AbstractBackend
{
/**
* Connector.
*
* @var Connector
*/
protected $connector;
/**
* Query builder.
*
* @var QueryBuilder
*/
protected $queryBuilder = null;
/**
* Constructor.
*
* @param Connector $connector WorldCat connector
* @param RecordCollectionFactoryInterface $factory Record collection factory
* (null for default)
*
* @return void
*/
public function __construct(Connector $connector,
RecordCollectionFactoryInterface $factory = null
) {
if (null !== $factory) {
$this->setRecordCollectionFactory($factory);
}
$this->connector = $connector;
$this->identifier = null;
}
/**
* Perform a search and return record collection.
*
* @param AbstractQuery $query Search query
* @param int $offset Search offset
* @param int $limit Search limit
* @param ParamBag $params Search backend parameters
*
* @return RecordCollectionInterface
*/
public function search(AbstractQuery $query, $offset, $limit,
ParamBag $params = null
) {
if (null === $params) {
$params = new ParamBag();
}
$params->mergeWith($this->getQueryBuilder()->build($query));
$response = $this->connector->search($params, $offset, $limit);
$collection = $this->createRecordCollection($response);
$this->injectSourceIdentifier($collection);
return $collection;
}
/**
* Retrieve a single document.
*
* @param string $id Document identifier
* @param ParamBag $params Search backend parameters
*
* @return RecordCollectionInterface
*/
public function retrieve($id, ParamBag $params = null)
{
$response = $this->connector->getRecord($id, $params);
$collection = $this->createRecordCollection($response);
$this->injectSourceIdentifier($collection);
return $collection;
}
/**
* Set the query builder.
*
* @param QueryBuilder $queryBuilder Query builder
*
* @return void
*/
public function setQueryBuilder(QueryBuilder $queryBuilder)
{
$this->queryBuilder = $queryBuilder;
}
/**
* Return query builder.
*
* Lazy loads an empty QueryBuilder if none was set.
*
* @return QueryBuilder
*/
public function getQueryBuilder()
{
if (!$this->queryBuilder) {
$this->queryBuilder = new QueryBuilder();
}
return $this->queryBuilder;
}
/**
* Return the record collection factory.
*
* Lazy loads a generic collection factory.
*
* @return RecordCollectionFactoryInterface
*/
public function getRecordCollectionFactory()
{
if ($this->collectionFactory === null) {
$this->collectionFactory = new Response\XML\RecordCollectionFactory();
}
return $this->collectionFactory;
}
/**
* Return the WorldCat connector.
*
* @return Connector
*/
public function getConnector()
{
return $this->connector;
}
/// Internal API
/**
* Create record collection.
*
* @param array $records Records to process
*
* @return RecordCollectionInterface
*/
protected function createRecordCollection($records)
{
return $this->getRecordCollectionFactory()->factory($records);
}
}
| gpl-2.0 |
otservme/global1053 | data/movements/scripts/the ape city/Mission9TheDeepestCatacombsteleport2.lua | 1265 | local config = {
AmphorasPositions = {
[1] = Position({x = 32792, y = 32527, z = 10}),
[2] = Position({x = 32823, y = 32525, z = 10}),
[3] = Position({x = 32876, y = 32584, z = 10}),
[4] = Position({x = 32744, y = 32586, z = 10})
},
brokenAmphoraId = 4997
}
function onStepIn(cid, item, position, lastPosition)
local player = Player(cid)
if not player then
return true
end
if item.uid == 12130 then
for i = 1, #config["AmphorasPositions"] do
local tile = config["AmphorasPositions"][i]:getTile()
if tile then
local thing = tile:getItemById(config["brokenAmphoraId"])
if thing and thing:isItem() then
Amphorasbroken = 1
else
Amphorasbroken = 0
break
end
end
end
if Amphorasbroken == 1 then
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
player:teleportTo({x = 32885, y = 32632, z = 11})
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
else
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
player:teleportTo({x = 32852, y = 32544, z = 10})
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
player:sendTextMessage(MESSAGE_STATUS_SMALL, "There are 4 Large Amphoras that must be broken in order to open the teleporter.")
end
end
return true
end
| gpl-2.0 |
drazenzadravec/nequeo | Source/Components/Wpf/Nequeo.Wpf.Controls/Nequeo.Wpf.Controls/UI/MediaPlayer.xaml.cs | 2391 | /* Company : Nequeo Pty Ltd, http://www.nequeo.com.au/
* Copyright : Copyright © Nequeo Pty Ltd 2012 http://www.nequeo.com.au/
*
* File :
* Purpose :
*
*/
#region Nequeo Pty Ltd License
/*
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace Nequeo.Wpf.UI
{
/// <summary>
/// Media player.
/// </summary>
public partial class MediaPlayer : Window
{
/// <summary>
/// Media player.
/// </summary>
public MediaPlayer()
{
InitializeComponent();
}
/// <summary>
/// On unload.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Window_Unloaded(object sender, RoutedEventArgs e)
{
try
{
// Close the media player on exit.
mediaPlayer.CloseMedia();
}
catch { }
}
}
}
| gpl-2.0 |
htw-pk15/vufind | module/LinkedSwissbib/src/LinkedSwissbib/Backend/Elasticsearch/DSLBuilder/Query/Nested.php | 1037 | <?php
/**
*
* @category linked-swissbib
* @package Backend_Eleasticsearch
* @author Guenter Hipler <guenter.hipler@unibas.ch>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link http://linked.swissbib.ch Main Page
*/
namespace LinkedSwissbib\Backend\Elasticsearch\DSLBuilder\Query;
class Nested extends CompoundQueryClause
{
/**
* @return array
* @throws \Exception
*/
public function build()
{
if (!array_key_exists('query',$this->spec))
{
//todo: or do we use some kind of default fields?
throw new \Exception('missing fields definition in multi_match clause');
}
//$queryClause = ['nested'];
$queryClause['nested']['path'] = $this->spec['path'];
/** @var Query $queryClass */
$queryClass = new $this->registeredQueryClasses['query']($this->query, $this->spec);
$queryClause['nested']['query'] = $queryClass->build();
return $queryClause;
}
} | gpl-2.0 |
MobileRobots/ArAndroidApp | jni/pthread_android_additions.cpp | 3484 | /*
Copyright 2011 Adept Technology, Inc.
*/
#include "pthread_android_additions.h"
/*
Additions to pthread.cpp needed by Aria. These functions are supposed to be a
part of libc.so, but it appears they were left out. As a first pass I have
commented out all code to get them to compile, and it actually appears that
the arnetworking library still works fine. At some some point this code should
be added back in.
*/
int pthread_condattr_init(pthread_condattr_t *attr)
{
return 0;
}
int pthread_condattr_destroy(pthread_condattr_t *attr)
{
return 0;
}
int pthread_setcancelstate(int state, int * oldstate)
{
/*
pthread_descr self = thread_self();
if (state < PTHREAD_CANCEL_ENABLE || state > PTHREAD_CANCEL_DISABLE)
return EINVAL;
if (oldstate != NULL) *oldstate = THREAD_GETMEM(self, p_cancelstate);
THREAD_SETMEM(self, p_cancelstate, state);
if (THREAD_GETMEM(self, p_canceled) &&
THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE &&
THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
__pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
*/
return 0;
}
int pthread_setcanceltype(int type, int * oldtype)
{
/*
pthread_descr self = thread_self();
if (type < PTHREAD_CANCEL_DEFERRED || type > PTHREAD_CANCEL_ASYNCHRONOUS)
return EINVAL;
if (oldtype != NULL) *oldtype = THREAD_GETMEM(self, p_canceltype);
THREAD_SETMEM(self, p_canceltype, type);
if (THREAD_GETMEM(self, p_canceled) &&
THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE &&
THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
__pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
*/
return 0;
}
int pthread_cancel(pthread_t thread)
{
/*
pthread_handle handle = thread_handle(thread);
int pid;
int dorestart = 0;
pthread_descr th;
pthread_extricate_if *pextricate;
int already_canceled;
__pthread_lock(&handle->h_lock, NULL);
if (invalid_handle(handle, thread)) {
__pthread_unlock(&handle->h_lock);
return ESRCH;
}
th = handle->h_descr;
already_canceled = th->p_canceled;
th->p_canceled = 1;
if (th->p_cancelstate == PTHREAD_CANCEL_DISABLE || already_canceled) {
__pthread_unlock(&handle->h_lock);
return 0;
}
pextricate = th->p_extricate;
pid = th->p_pid;
*/
/* If the thread has registered an extrication interface, then
invoke the interface. If it returns 1, then we succeeded in
dequeuing the thread from whatever waiting object it was enqueued
with. In that case, it is our responsibility to wake it up.
And also to set the p_woken_by_cancel flag so the woken thread
can tell that it was woken by cancellation. */
/*
if (pextricate != NULL) {
dorestart = pextricate->pu_extricate_func(pextricate->pu_object, th);
th->p_woken_by_cancel = dorestart;
}
__pthread_unlock(&handle->h_lock);
*/
/* If the thread has suspended or is about to, then we unblock it by
issuing a restart, instead of a cancel signal. Otherwise we send
the cancel signal to unblock the thread from a cancellation point,
or to initiate asynchronous cancellation. The restart is needed so
we have proper accounting of restarts; suspend decrements the thread's
resume count, and restart() increments it. This also means that suspend's
handling of the cancel signal is obsolete. */
/*
if (dorestart)
restart(th);
else
kill(pid, __pthread_sig_cancel);
*/
return 0;
}
| gpl-2.0 |
eyetrackingDB/GazeTrackingOfflineProcessing | EyeTabTracker/src_eyetab/gaze_geometry.cpp | 8529 | #include "stdafx.h"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <math.h>
#include "../lib_eigen/Geometry"
#include "../lib_eigen/StdVector"
#include "utils.h"
#include "ConicSection.h"
#include "../GazeSettingsEyeTab.h"
using namespace Eigen;
using namespace std;
using namespace cv;
const float LIMBUS_R_MM = 6;
vector<Vector3d> ellipse_to_limbus_approx(cv::RotatedRect ellipse, bool limbus_switch=true){
vector<Vector3d> limbus_to_return;
double maj_axis_px = ellipse.size.width, min_axis_px = ellipse.size.height;
// Using iris_r_px / focal_len_px = iris_r_mm / distance_to_iris_mm
double iris_z_mm = (LIMBUS_R_MM * 2 * FOCAL_LEN_Z_PX) / maj_axis_px;
// Using (x_screen_px - prin_point) / focal_len_px = x_world / z_world
double iris_x_mm = -iris_z_mm * (ellipse.center.x - PRIN_POINT.x) / FOCAL_LEN_X_PX;
double iris_y_mm = iris_z_mm * (ellipse.center.y - PRIN_POINT.y) / FOCAL_LEN_Y_PX;
Vector3d limbus_center(iris_x_mm, iris_y_mm, iris_z_mm);
double psi = CV_PI / 180.0 * (ellipse.angle+90); // z-axis rotation (radians)
double tht = acos(min_axis_px / maj_axis_px); // y-axis rotation (radians)
if (limbus_switch) tht = -tht; // ambiguous acos, so sometimes switch limbus
// Get limbus normal for chosen theta
Vector3d limb_normal(sin(tht) * cos(psi), -sin(tht) * sin(psi), -cos(tht));
// Now correct for weak perspective by modifying angle by offset between camera axis and limbus
double x_correction = -atan2(iris_y_mm, iris_z_mm);
double y_correction = -atan2(iris_x_mm, iris_z_mm);
AngleAxisd rot1(y_correction, Vector3d(0,-1,0));
AngleAxisd rot2(x_correction, Vector3d(1,0,0));
limb_normal = rot1 * limb_normal;
limb_normal = rot2 * limb_normal;
limbus_to_return.push_back(limbus_center);
limbus_to_return.push_back(limb_normal);
return limbus_to_return;
}
vector<Vector3d> ellipse_to_limbus_geo(cv::RotatedRect ellipse) {
vector<Vector3d> limbus_to_return;
double maj_axis_px = ellipse.size.width;
// Using iris_r_px / focal_len_px = iris_r_mm / distance_to_iris_mm
double iris_z_mm = (LIMBUS_R_MM * 2 * FOCAL_LEN_Z_PX) / maj_axis_px;
// Using (x_screen_px - prin_point) / focal_len_px = x_world / z_world
double iris_x_mm = -iris_z_mm * (ellipse.center.x - PRIN_POINT.x)
/ FOCAL_LEN_X_PX;
double iris_y_mm = iris_z_mm * (ellipse.center.y - PRIN_POINT.y)
/ FOCAL_LEN_Y_PX;
Vector3d limbus_center(iris_x_mm, iris_y_mm, iris_z_mm);
//Create the new rotated rectangle
float rotRecX0 = ellipse.center.x - PRIN_POINT.x;
float rotRecY0 = ellipse.center.y - PRIN_POINT.y;
RotatedRect rotRect(Point2f(rotRecX0, rotRecY0), ellipse.size,
ellipse.angle);
//Create the conic section object and a matrix of it
ConicSection ell(rotRect);
Matx33f mati(ell.A, ell.B / 2.0f, ell.D / (2.0f * FOCAL_LEN_Z_PX),
ell.B / 2.0f, ell.C, ell.E / (2.0f * FOCAL_LEN_Z_PX),
ell.D / (2.0f * FOCAL_LEN_Z_PX), ell.E / (2.0f * FOCAL_LEN_Z_PX), ell.F / (FOCAL_LEN_Z_PX * FOCAL_LEN_Z_PX));
Matx31f eigenValues;
Matx33f eigenVectors;
eigen(mati, true, eigenValues, eigenVectors);
//Get the indexes for sorting
vector<float> eigValVec(3);
for(int i=0; i<eigValVec.size(); i++){
eigValVec[i] = eigenValues.val[i];
}
vector<size_t> indexes = sort_indexes(eigValVec);
//Rearange the matrix
Matx31f sortedEigenValues;
Matx33f sortedEigenVectors;
int counter = 0;
for(size_t i : indexes){
sortedEigenValues.val[i] = eigenValues.val[counter];
sortedEigenVectors.val[i*3] = eigenVectors.val[counter*3];
sortedEigenVectors.val[(i*3)+1] = eigenVectors.val[(counter*3) + 1];
sortedEigenVectors.val[(i*3)+2] = eigenVectors.val[(counter*3) + 2];
counter++;
}
float L1 = sortedEigenValues.val[0];
float L2 = sortedEigenValues.val[1];
float L3 = sortedEigenValues.val[2];
// Calculate the parameters for determining the normals
float g = sqrt((L2-L3) / (L1-L3));
float h = sqrt((L1-L2) / (L1-L3));
//Calculate the normals
float norm1_x = sortedEigenVectors.val[0] * h + sortedEigenVectors.val[1] * 0 + sortedEigenVectors.val[2] * -g;
float norm1_y = sortedEigenVectors.val[3] * h + sortedEigenVectors.val[4] * 0 + sortedEigenVectors.val[5] * -g;
float norm1_z = sortedEigenVectors.val[6] * h + sortedEigenVectors.val[7] * 0 + sortedEigenVectors.val[8] * -g;
float norm2_x = sortedEigenVectors.val[0] * h + sortedEigenVectors.val[1] * 0 + sortedEigenVectors.val[2] * g;
float norm2_y = sortedEigenVectors.val[3] * h + sortedEigenVectors.val[4] * 0 + sortedEigenVectors.val[5] * g;
float norm2_z = sortedEigenVectors.val[6] * h + sortedEigenVectors.val[7] * 0 + sortedEigenVectors.val[8] * g;
float norm3_x = sortedEigenVectors.val[0] * -h + sortedEigenVectors.val[1] * 0 + sortedEigenVectors.val[2] * -g;
float norm3_y = sortedEigenVectors.val[3] * -h + sortedEigenVectors.val[4] * 0 + sortedEigenVectors.val[5] * -g;
float norm3_z = sortedEigenVectors.val[6] * -h + sortedEigenVectors.val[7] * 0 + sortedEigenVectors.val[8] * -g;
float norm4_x = sortedEigenVectors.val[0] * -h + sortedEigenVectors.val[1] * 0 + sortedEigenVectors.val[2] * g;
float norm4_y = sortedEigenVectors.val[3] * -h + sortedEigenVectors.val[4] * 0 + sortedEigenVectors.val[5] * g;
float norm4_z = sortedEigenVectors.val[6] * -h + sortedEigenVectors.val[7] * 0 + sortedEigenVectors.val[8] * g;
// Consider the constraints (some are specific for reverse portrait!!)
float nx, ny, nz;
if(iris_x_mm > 0){
nx = norm1_x;
ny = norm1_y;
nz = norm1_z;
} else {
nx = norm2_x;
ny = norm2_y;
nz = norm2_z;
}
if(nz > 0){
nx = -nx;
ny = -ny;
nz = -nz;
}
if((ny * nz) < 0){
ny *= -1;
}
if(iris_x_mm > 0){
if(nx > 0){
nx *= -1;
}
} else if (nx < 0){
nx *= -1;
}
//Finally, the normal
Vector3d limb_normal(nx,ny,nz);
limbus_to_return.push_back(limbus_center);
limbus_to_return.push_back(limb_normal);
return limbus_to_return;
}
bool isOutliner(Vector3d& limbusCenterEye0, Vector3d& limbusCenterEye1){
//no need to remove gaze points that are out of the screen, as we want them to exist
//only remove gaze points where the eye center distance is higher than 80mm
double diffX = limbusCenterEye1.x() - limbusCenterEye0.x();
double diffY = limbusCenterEye1.y() - limbusCenterEye0.y();
double diffZ = limbusCenterEye1.z() - limbusCenterEye0.z();
double distance = sqrt(pow(diffX, 2.0) + pow(diffY, 2.0) + pow(diffZ, 2.0));
if(distance > 80.0){ //check if we distance is bigger than 80.0mm
return true;
}
return false;
}
// returns intersection with z-plane of optical axis vector (mm)
Point2d get_gaze_point_mm(Vector3d limb_center, Vector3d limb_normal){
// ray/plane intersection
double t = -limb_center.z() / limb_normal.z();
return Point2d(limb_center.x() + limb_normal.x() * t, limb_center.y() + limb_normal.y() * t);
}
void get_gaze_pt_mm(RotatedRect& ellipse, Vector3d& limbusCenter, Point2d& gp_mm){
if(GAZE_TRACKING_ALGO == "GAZE_TRACKING_ALGO_APPROX"){
// get two possible limbus centres and normals because of ambiguous trig
vector<Vector3d> limbus_a = ellipse_to_limbus_approx(ellipse, true);
vector<Vector3d> limbus_b = ellipse_to_limbus_approx(ellipse, false);
Vector3d limb_center_a = limbus_a[0];
Vector3d limb_normal_a = limbus_a[1];
Vector3d limb_center_b = limbus_b[0];
Vector3d limb_normal_b = limbus_b[1];
// calculate gaze points for each possible limbus
Point2d gp_mm_a = get_gaze_point_mm(limbus_a[0], limbus_a[1]);
Point2d gp_mm_b = get_gaze_point_mm(limbus_b[0], limbus_b[1]);
// calculate distance from centre of screen for each possible gaze point
int dist_a = std::abs(gp_mm_a.x) + std::abs(gp_mm_a.y);
int dist_b = std::abs(gp_mm_b.x) + std::abs(gp_mm_b.y);
if(dist_a < dist_b){
gp_mm = gp_mm_a;
limbusCenter = limb_center_a;
} else {
gp_mm = gp_mm_b;
limbusCenter = limb_center_b;
}
} else if (GAZE_TRACKING_ALGO == "GAZE_TRACKING_ALGO_GEO"){
vector<Vector3d> limbus = ellipse_to_limbus_geo(ellipse);
Vector3d limb_center = limbus[0];
Vector3d limb_normal = limbus[1];
gp_mm = get_gaze_point_mm(limbus[0], limbus[1]);
}
}
Point2i convert_gaze_pt_mm_to_px(Point2d gaze_pt_mm){
int gp_px_x = (gaze_pt_mm.x + CAMERA_OFFSET_MM.x) / SCREEN_SIZE_MM.width * SCREEN_SIZE_PX.width;
//###### Changed to fit python code (gaze_pt_mm.y - CAMERA_OFFSET_MM.y) Before it was a +
int gp_px_y = (gaze_pt_mm.y - CAMERA_OFFSET_MM.y) / SCREEN_SIZE_MM.height * SCREEN_SIZE_PX.height;
return Point2i(gp_px_x, gp_px_y);
}
| gpl-2.0 |
pollux1er/SajoscolApp | orm/propel-build/classes/gepi/UtilisateurProfessionnelPeer.php | 1324 | <?php
/**
* Skeleton subclass for performing query and update operations on the 'utilisateurs' table.
*
* Utilisateur de gepi
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package propel.generator.gepi
*/
class UtilisateurProfessionnelPeer extends BaseUtilisateurProfessionnelPeer {
/**
*
* Renvoi l'utilisateur de la session en crous
* Manually added for N:M relationship
*
* @return UtilisateurProfessionnel utilisateur
*/
public static function getUtilisateursSessionEnCours() {
if (isset($_SESSION['objets_propel']['utilisateurProfessionnel'])
&& $_SESSION['objets_propel']['utilisateurProfessionnel'] != null
&& $_SESSION['objets_propel']['utilisateurProfessionnel'] instanceof UtilisateurProfessionnel) {
//echo 'utilisateur recupere dans la session';
return $_SESSION['objets_propel']['utilisateurProfessionnel'];
} else {
$utilisateur = UtilisateurProfessionnelQuery::create()->filterByLogin($_SESSION['login'])->findOne();
if ($utilisateur != null) {
$_SESSION['objets_propel']['utilisateurProfessionnel'] = $utilisateur;
}
return $utilisateur;
}
}
} // UtilisateurProfessionnelPeer
| gpl-2.0 |
Exiv2/exiv2 | src/samsungmn_int.hpp | 2063 | // ***************************************************************** -*- C++ -*-
/*
* Copyright (C) 2004-2021 Exiv2 authors
* This program is part of the Exiv2 distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA.
*/
#ifndef SAMSUNGMN_INT_HPP_
#define SAMSUNGMN_INT_HPP_
// *****************************************************************************
// included header files
#include "tags.hpp"
#include "types.hpp"
// + standard includes
#include <string>
#include <iosfwd>
#include <memory>
// *****************************************************************************
// namespace extensions
namespace Exiv2 {
namespace Internal {
// *****************************************************************************
// class definitions
//! MakerNote for Samsung cameras
class Samsung2MakerNote {
public:
//! Return read-only list of built-in Samsung tags
static const TagInfo* tagList();
//! Return read-only list of built-in PictureWizard tags
static const TagInfo* tagListPw();
private:
//! Tag information
static const TagInfo tagInfo_[];
//! PictureWizard tag information
static const TagInfo tagInfoPw_[];
}; // class Samsung2MakerNote
}} // namespace Internal, Exiv2
#endif // #ifndef SAMSUNGMN_INT_HPP_
| gpl-2.0 |
fighterCui/L4ReFiascoOC | l4/pkg/l4re_c/lib/src/goos.cc | 2420 | /*
* (c) 2008-2009 Adam Lackorzynski <adam@os.inf.tu-dresden.de>
* economic rights: Technische Universität Dresden (Germany)
*
* This file is part of TUD:OS and distributed under the terms of the
* GNU General Public License 2.
* Please see the COPYING-GPL-2 file for details.
*
* As a special exception, you may use this file as part of a free software
* library without restriction. Specifically, if other files instantiate
* templates or use macros or inline functions from this file, or you compile
* this file and link it with other files to produce an executable, this
* file does not by itself cause the resulting executable to be covered by
* the GNU General Public License. This exception does not however
* invalidate any other reasons why the executable file might be covered by
* the GNU General Public License.
*/
#include <l4/re/c/video/goos.h>
#include <l4/re/video/goos>
using namespace L4Re::Video;
L4_CV int
l4re_video_goos_create_buffer(l4re_video_goos_t goos, unsigned long size,
l4_cap_idx_t buffer) L4_NOTHROW
{
L4::Cap<Goos> g(goos);
return g->create_buffer(size, L4::Cap<L4Re::Dataspace>(buffer));
}
L4_CV int
l4re_video_goos_refresh(l4re_video_goos_t goos, int x, int y, int w,
int h) L4_NOTHROW
{
L4::Cap<Goos> g(goos);
return g->refresh(x, y, w, h);
}
L4_CV int
l4re_video_goos_delete_buffer(l4re_video_goos_t goos, unsigned idx) L4_NOTHROW
{
L4::Cap<Goos> g(goos);
return g->delete_buffer(idx);
}
L4_CV int
l4re_video_goos_get_static_buffer(l4re_video_goos_t goos, unsigned idx,
l4_cap_idx_t buffer) L4_NOTHROW
{
L4::Cap<Goos> g(goos);
return g->get_static_buffer(idx, L4::Cap<L4Re::Dataspace>(buffer));
}
L4_CV int
l4re_video_goos_create_view(l4re_video_goos_t goos,
l4re_video_view_t *view) L4_NOTHROW
{
L4::Cap<Goos> g(goos);
return g->create_view(reinterpret_cast<View*>(view));
}
L4_CV int
l4re_video_goos_delete_view(l4re_video_goos_t goos,
l4re_video_view_t *view) L4_NOTHROW
{
L4::Cap<Goos> g(goos);
return g->delete_view(*reinterpret_cast<View*>(view));
}
L4_CV int
l4re_video_goos_get_view(l4re_video_goos_t goos, unsigned idx,
l4re_video_view_t *view) L4_NOTHROW
{
L4::Cap<Goos> g(goos);
*reinterpret_cast<View*>(view) = g->view(idx);
return 0;
}
| gpl-2.0 |
NateJacobs/Brickset-API | admin/class-users-profile.php | 2719 | <?php
/**
* Display necessary fields on the user profile page to allow a user to authenticate themselves with Brickset.
* Take the user hash and save it in the usermeta table.
*
* @author Nate Jacobs
* @date 2/2/13
* @since 1.0
*/
class BricksetAPIUserProfile extends BricksetAPIUtilities
{
/**
* Start things off
*
* @author Nate Jacobs
* @date 2/2/13
* @since 1.0
*/
public function __construct()
{
add_action( 'show_user_profile', array( $this, 'add_user_profile_fields' ) );
add_action( 'edit_user_profile', array( $this, 'add_user_profile_fields' ) );
add_action( 'personal_options_update', array( $this, 'set_brickset_user_hash' ) );
add_action( 'edit_user_profile_update', array( $this, 'set_brickset_user_hash' ) );
}
/**
* Add Brickset username, password, and userHash fields to the profile page.
*
* @author Nate Jacobs
* @date 2/3/13
* @since 1.0
*
* @param object WP_User
*/
public function add_user_profile_fields( $user)
{
$user_hash = $this->get_user_hash( $user->ID );
?>
<h3><?php _e( 'Brickset Login Information', 'bs_api' ); ?></h3>
<span><?php _e( 'If the Brickset Identifier is filled you do not need to add your username and password unless you have changed your password on Brickset.', 'bs_api' ); ?></span>
<table class="form-table">
<tr>
<th><label for="bs_user_name"><?php _e( 'Brickset Username', 'bs_api' ); ?></label></th>
<td><input type="text" name="bs_user_name" id="bs_user_name" value="" class="regular-text" /></td>
</tr>
<tr>
<th><label for="bs_password"><?php _e( 'Brickset Password', 'bs_api' ); ?></label></th>
<td><input type="password" name="bs_password" id="bs_password" value="" class="regular-text" /></td>
</tr>
<tr>
<th><label for="bs_user_hash"><?php _e( 'Brickset Identifier', 'bs_api' ); ?></label></th>
<td><input type="text" readonly name="bs_user_hash" id="bs_user_hash" value="<?php echo $user_hash; ?>" class="regular-text" /></td>
</tr>
</table>
<?php
}
/**
* Takes the entered Brickset username and password and gets the userHash.
*
* @author Nate Jacobs
* @date 2/6/13
* @since 1.0
*
* @param int
*/
public function set_brickset_user_hash( $user_id )
{
if ( !current_user_can( 'edit_user' ) )
return false;
if( !empty( $_POST['bs_user_name'] ) && !empty( $_POST['bs_password'] ) )
{
$response = $this->brickset_login( $user_id, sanitize_text_field( $_POST['bs_user_name'] ), $_POST['bs_password'] );
if( is_wp_error( $response ) )
{
wp_die( $response->get_error_message(), 'brickset-login-error', array( 'back_link' => true ) );
}
}
}
}
$brickset_user_profile = new BricksetAPIUserProfile; | gpl-2.0 |
tedbow/scheduled-updates-demo | modules/contrib/workbench_moderation/src/Entity/Handler/NodeModerationHandler.php | 1632 | <?php
/**
* @file
* Contains Drupal\workbench_moderation\Entity\Handler\NodeCustomizations.
*/
namespace Drupal\workbench_moderation\Entity\Handler;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
/**
* Customizations for node entities.
*/
class NodeModerationHandler extends ModerationHandler {
/**
* {@inheritdoc}
*/
public function onPresave(ContentEntityInterface $entity, $default_revision, $published_state) {
parent::onPresave($entity, $default_revision, $published_state);
// Only nodes have a concept of published.
/** @var $entity Node */
$entity->setPublished($published_state);
}
/**
* {@inheritdoc}
*/
public function enforceRevisionsEntityFormAlter(array &$form, FormStateInterface $form_state, $form_id) {
$form['revision']['#disabled'] = TRUE;
$form['revision']['#default_value'] = TRUE;
$form['revision']['#description'] = $this->t('Revisions are required.');
}
/**
* {@inheritdoc}
*/
public function enforceRevisionsBundleFormAlter(array &$form, FormStateInterface $form_state, $form_id) {
/* @var \Drupal\node\Entity\NodeType $entity */
$entity = $form_state->getFormObject()->getEntity();
if ($entity->getThirdPartySetting('workbench_moderation', 'enabled', FALSE)) {
// Force the revision checkbox on.
$form['workflow']['options']['#default_value']['revision'] = 'revision';
$form['workflow']['options']['revision']['#disabled'] = TRUE;
}
}
}
| gpl-2.0 |
wshearn/openshift-quickstart-modx | php/core/model/modx/sqlsrv/modplugin.class.php | 212 | <?php
/**
* @package modx
* @subpackage sqlsrv
*/
require_once (dirname(dirname(__FILE__)) . '/modplugin.class.php');
/**
* @package modx
* @subpackage sqlsrv
*/
class modPlugin_sqlsrv extends modPlugin {
} | gpl-2.0 |
shannah/cn1 | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/auth/src/test/java/common/org/apache/harmony/auth/tests/javax/security/sasl/serialization/RealmChoiceCallbackTest.java | 3805 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Vera Y. Petrashkova
*/
package org.apache.harmony.auth.tests.javax.security.sasl.serialization;
import java.io.Serializable;
import javax.security.sasl.RealmChoiceCallback;
import org.apache.harmony.testframework.serialization.SerializationTest;
/**
* Test for RealmChoiceCallback serialization
*
*/
public class RealmChoiceCallbackTest extends SerializationTest implements
SerializationTest.SerializableAssert {
public static String[] msgs = {
"New String",
"Another string",
"Long string. Long string. Long string. Long string. Long string. Long string. Long string. Long string. Long string. Long string. Long string. Long string. Long string. Long string. Long string. Long string. Long string.",
"t"};
public static final int [] idx = {2, 3};
@Override
protected Object[] getData() {
Object [] oo = {
new RealmChoiceCallback(msgs[0], msgs, 0, true),
new RealmChoiceCallback(msgs[1], msgs, 1, true),
new RealmChoiceCallback(msgs[1], msgs, 0, false),
new RealmChoiceCallback(msgs[2], msgs, 0, false)
};
for (Object element : oo) {
RealmChoiceCallback rc = (RealmChoiceCallback)element;
if (rc.allowMultipleSelections()) {
rc.setSelectedIndexes(idx);
} else {
rc.setSelectedIndex(msgs.length - 1);
}
}
return oo;
}
public void assertDeserialized(Serializable oref, Serializable otest) {
RealmChoiceCallback ref = (RealmChoiceCallback) oref;
RealmChoiceCallback test = (RealmChoiceCallback) otest;
boolean all = ref.allowMultipleSelections();
assertEquals(all, test.allowMultipleSelections());
String prompt = ref.getPrompt();
assertEquals(prompt, test.getPrompt());
String [] ch = ref.getChoices();
String [] tCh = test.getChoices();
assertEquals(ch.length, tCh.length);
for (int i = 0; i < ch.length; i++) {
assertEquals(ch[i], tCh[i]);
}
assertEquals(ref.getDefaultChoice(), test.getDefaultChoice());
int [] in = ref.getSelectedIndexes();
int [] tIn = test.getSelectedIndexes();
// assertNull("in is not null", in);
// assertNull("tIn is not null", tIn);
if (!all) {
assertEquals("Incorrect length in ", in.length, 1);
assertEquals("Incorrect length tIn ", tIn.length, 1);
assertEquals("Incorrect index", in[0], tIn[0]);
} else {
assertEquals("Incorrect length", in.length, tIn.length);
for (int i = 0; i < in.length; i++) {
assertEquals(in[i], tIn[i]);
}
}
}
} | gpl-2.0 |
cuongnd/banhangonline88_joomla | libraries/fsj_core/html/field/fsjrating.php | 3985 | <?php
/**
* @package Freestyle Joomla
* @author Freestyle Joomla
* @copyright (C) 2013 Freestyle Joomla
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
**/
defined('_JEXEC') or die;
JFormHelper::loadFieldClass('text');
jimport('fsj_core.lib.fields.rating');
class JFormFieldFSJRating extends JFormFieldText
{
protected $type = 'FSJRating';
protected function getInput()
{
$document = JFactory::getDocument();
//print_p($this);
$rating = $this->form->getValue('rating');
$rating_votes = $this->form->getValue('rating_votes');
$rating_score = $this->form->getValue('rating_score');
FSJ_Page::Script("libraries/fsj_core/assets/js/jquery/jquery.slider.js");
FSJ_Page::Style("libraries/fsj_core/assets/css/jquery/jquery.slider.less");
$rating_obj = new FSJ_Rating();
$output = array();
$output[] = "<div>";
$output[] = " <div>";
$output[] = " " . $rating_obj->AdminDisplay("fsj_rating", $rating, 24, 'float: left;');
$output[] = " <span id='fsj_rating_value' style='font-weight: bold'>" . $rating / 100 . "</span> from <span id='fsj_rating_votes' style='font-weight: bold'>" . $rating_votes . "</span> votes";
$output[] = " <a class='btn' href='#' onclick='jQuery(\"#fsj_rating_edit\").toggle();'>";
$output[] = " Edit";
$output[] = " </a>";
$output[] = " </div>";
// Edit form:
$output[] = " <div id='fsj_rating_edit' class='form-horizontal form-condensed' style='display:none;margin-top:8px;'>";
$output[] = ' <div class="control-group">';
$output[] = ' <label class="control-label">';
$output[] = " Vote Count:";
$output[] = ' </label>';
$output[] = ' <div class="controls" style="width:350px">';
$output[] = ' <input type="text" name="jform[rating_votes]" id="jform_rating_votes" value="' . htmlspecialchars($rating_votes, ENT_COMPAT, 'UTF-8') . '"/>';
$output[] = " </div>";
$output[] = " </div>";
$output[] = ' <div class="control-group">';
$output[] = ' <label class="control-label">';
$output[] = " Rating:";
$output[] = ' </label>';
$output[] = ' <div class="controls">';
$output[] = ' <input type="text" name="' . $this->name . '" id="' . $this->id . '" value="' . htmlspecialchars($rating, ENT_COMPAT, 'UTF-8') . '" data-slider="true" data-slider-range="0,500" data-slider-step="1"/>';
$output[] = " </div>";
$output[] = " </div>";
$output[] = " </div>";
$output[] = ' <input type="hidden" name="jform[rating_score]" id="jform_rating_score" value="' . htmlspecialchars($rating_score, ENT_COMPAT, 'UTF-8') . '"/>';
$output[] = "</div>";
$js = "
jQuery(document).ready(function () {
jQuery('[data-slider]').bind('slider:ready slider:changed', function (event, data) {
var size = 24;
var width = size * 5;
var votes = jQuery('#jform_rating_votes').val();
if (votes == 0)
{
jQuery('#jform_rating_votes').val(1);
votes = 1;
}
var score = Math.round(data.value / 100 * votes);
var rating = Math.round(score / votes * 100);
var disprating = score / votes;
jQuery('#fsj_rating_value').html(disprating.toFixed(2));
jQuery('#fsj_rating_votes').html(votes);
jQuery('#jform_rating').val(rating);
jQuery('#jform_rating_score').val(score);
var ratingpct = rating / 500;
var ratwid = parseInt(width * ratingpct);
var graywid = width - ratwid;
jQuery('#fsj_rating_active').css('width', ratwid + 'px');
jQuery('#fsj_rating_inactive').css('left', ratwid + 'px');
jQuery('#fsj_rating_inactive').css('width', graywid + 'px');
});
});";
$document->addScriptDeclaration($js);
return implode($output);
}
function AdminDisplay($value, $name, $item)
{
$rating_obj = new FSJ_Rating();
return $rating_obj->AdminDisplay("fsj_rating", $value, 16) . "<div style='white-space: nowrap;'>".round($value / 100, 2) . " (" . $item->rating_votes . " votes)</div>";
}
}
| gpl-2.0 |
d4span/freemindfx | src/main/java/plugins/script/ScriptEditor.java | 7942 | /*FreeMind - A Program for creating and viewing Mindmaps
*Copyright (C) 2000-2007 Joerg Mueller, Daniel Polansky, Dimitri Polivaev, Christian Foltin and others.
*
*See COPYING for Details
*
*This program is free software; you can redistribute it and/or
*modify it under the terms of the GNU General Public License
*as published by the Free Software Foundation; either version 2
*of the License, or (at your option) any later version.
*
*This program is distributed in the hope that it will be useful,
*but WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*GNU General Public License for more details.
*
*You should have received a copy of the GNU General Public License
*along with this program; if not, write to the Free Software
*Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Created on 10.01.2007
*/
/*$Id: ScriptEditor.java,v 1.1.2.11 2008/05/21 19:15:23 christianfoltin Exp $*/
package plugins.script;
import freemind.controller.actions.generated.instance.ScriptEditorWindowConfigurationStorage;
import freemind.main.Tools.BooleanHolder;
import freemind.modes.MindMapNode;
import freemind.modes.attributes.Attribute;
import freemind.modes.mindmapmode.MindMapController;
import freemind.modes.mindmapmode.hooks.MindMapHookAdapter;
import plugins.script.ScriptEditorPanel.ScriptHolder;
import plugins.script.ScriptEditorPanel.ScriptModel;
import plugins.script.ScriptingEngine.ErrorHandler;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Vector;
/**
* @author foltin
*/
public class ScriptEditor extends MindMapHookAdapter {
private final class AttributeHolder {
Attribute mAttribute;
int mPosition;
public AttributeHolder(Attribute pAttribute, int pPosition) {
super();
mAttribute = pAttribute;
mPosition = pPosition;
}
}
private final class NodeScriptModel implements ScriptModel {
/**
* Of AttributeHolder
*/
private final Vector mScripts;
private final MindMapNode mNode;
private final MindMapController mMindMapController;
private boolean isDirty = false;
private NodeScriptModel(Vector pScripts, MindMapNode node,
MindMapController pMindMapController) {
mScripts = pScripts;
mNode = node;
mMindMapController = pMindMapController;
}
public ScriptEditorWindowConfigurationStorage decorateDialog(
ScriptEditorPanel pPanel,
String pWindow_preference_storage_property) {
return (ScriptEditorWindowConfigurationStorage) getMindMapController()
.decorateDialog(pPanel, pWindow_preference_storage_property);
}
public boolean executeScript(int pIndex, PrintStream pOutStream,
ErrorHandler pErrorHandler) {
String script = getScript(pIndex).getScript();
// get cookies from base plugin:
ScriptingRegistration reg = (ScriptingRegistration) getPluginBaseClass();
return ScriptingEngine.executeScript(
mMindMapController.getSelected(), new BooleanHolder(true),
script, mMindMapController, pErrorHandler, pOutStream,
reg.getScriptCookies());
}
public int getAmountOfScripts() {
return mScripts.size();
}
public ScriptHolder getScript(int pIndex) {
Attribute attribute = ((AttributeHolder) mScripts.get(pIndex)).mAttribute;
return new ScriptHolder(attribute.getName(), attribute.getValue());
}
public void setScript(int pIndex, ScriptHolder pScript) {
AttributeHolder oldHolder = (AttributeHolder) mScripts.get(pIndex);
if (!pScript.mScriptName.equals(oldHolder.mAttribute.getName())) {
isDirty = true;
}
if (!pScript.mScript.equals(oldHolder.mAttribute.getValue())) {
isDirty = true;
}
oldHolder.mAttribute.setName(pScript.mScriptName);
oldHolder.mAttribute.setValue(pScript.mScript);
}
public void storeDialogPositions(ScriptEditorPanel pPanel,
ScriptEditorWindowConfigurationStorage pStorage,
String pWindow_preference_storage_property) {
getMindMapController().storeDialogPositions(pPanel, pStorage,
pWindow_preference_storage_property);
}
public void endDialog(boolean pIsCanceled) {
if (!pIsCanceled) {
// read length only once, as new attributes get this number as
// position.
int attributeTableLength = mNode.getAttributeTableLength();
// store node attributes back
for (Iterator iter = mScripts.iterator(); iter.hasNext(); ) {
AttributeHolder holder = (AttributeHolder) iter.next();
Attribute attribute = holder.mAttribute;
int position = holder.mPosition;
if (attributeTableLength <= position) {
// add new attribute
mMindMapController.addAttribute(mNode, attribute);
} else if (mNode.getAttribute(position).getValue() != attribute
.getValue()) {
// logger.info("Setting attribute " + position + " to "
// + attribute);
mMindMapController.setAttribute(mNode, position,
attribute);
}
}
}
}
public boolean isDirty() {
return isDirty;
}
public int addNewScript() {
int index = mScripts.size();
/**
* is in general different from index, as not all attributes need to
* be scripts.
*/
int attributeIndex = mNode.getAttributeTableLength();
String scriptName = ScriptingEngine.SCRIPT_PREFIX;
int scriptNameSuffix = 1;
boolean found;
do {
found = false;
for (Iterator iterator = mScripts.iterator(); iterator
.hasNext(); ) {
AttributeHolder holder = (AttributeHolder) iterator.next();
if ((scriptName + scriptNameSuffix)
.equals(holder.mAttribute.getName())) {
found = true;
scriptNameSuffix++;
break;
}
}
} while (found);
mScripts.add(new AttributeHolder(new Attribute(scriptName
+ scriptNameSuffix, ""), attributeIndex));
isDirty = true;
return index;
}
}
public void startupMapHook() {
super.startupMapHook();
final MindMapNode node = getMindMapController().getSelected();
final Vector scripts = new Vector();
for (int position = 0; position < node.getAttributeTableLength(); position++) {
Attribute attribute = node.getAttribute(position);
if (attribute.getName().startsWith(ScriptingEngine.SCRIPT_PREFIX)) {
scripts.add(new AttributeHolder(attribute, position));
}
}
NodeScriptModel nodeScriptModel = new NodeScriptModel(scripts, node,
getMindMapController());
ScriptEditorPanel scriptEditorPanel = new ScriptEditorPanel(
nodeScriptModel, getController().getFrame(), true);
scriptEditorPanel.setVisible(true);
}
}
| gpl-2.0 |
yakuzmenko/bereg | administrator/components/com_sh404sef/plugins/system/shlib/shl_packages/ZendFramework-1.11.7-minimal/library/Zendshl/Amf/Response/Http.php | 1746 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zendshl_Amf
* @subpackage Response
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: Http.php 23775 2011-03-01 17:25:24Z ralph $
*/
defined('_JEXEC') or die;
/** Zendshl_Amf_Response */
require_once SHLIB_PATH_TO_ZEND . 'Zendshl/Amf/Response.php';
/**
* Creates the proper http headers and send the serialized AMF stream to standard out.
*
* @package Zendshl_Amf
* @subpackage Response
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zendshl_Amf_Response_Http extends Zendshl_Amf_Response
{
/**
* Create the application response header for AMF and sends the serialized AMF string
*
* @return string
*/
public function getResponse()
{
if (!headers_sent()) {
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Thu, 19 Nov 1981 08:52:00 GMT');
header('Pragma: no-cache');
header('Content-Type: application/x-amf');
}
return parent::getResponse();
}
}
| gpl-2.0 |
AdmireTheDistance/android_libcore | jsr166-tests/src/test/java/jsr166/FutureTaskTest.java | 29263 | /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
* Other contributors include Andrew Wright, Jeffrey Hayes,
* Pat Fisher, Mike Judd.
*/
package jsr166;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import junit.framework.Test;
import junit.framework.TestSuite;
public class FutureTaskTest extends JSR166TestCase {
// android-note: Removed because the CTS runner does a bad job of
// retrying tests that have suite() declarations.
//
// public static void main(String[] args) {
// main(suite(), args);
// }
// public static Test suite() {
// return new TestSuite(...);
// }
void checkIsDone(Future<?> f) {
assertTrue(f.isDone());
assertFalse(f.cancel(false));
assertFalse(f.cancel(true));
if (f instanceof PublicFutureTask) {
PublicFutureTask pf = (PublicFutureTask) f;
assertEquals(1, pf.doneCount());
assertFalse(pf.runAndReset());
assertEquals(1, pf.doneCount());
Object r = null; Object exInfo = null;
try {
r = f.get();
} catch (CancellationException t) {
exInfo = CancellationException.class;
} catch (ExecutionException t) {
exInfo = t.getCause();
} catch (Throwable t) {
threadUnexpectedException(t);
}
// Check that run and runAndReset have no effect.
int savedRunCount = pf.runCount();
pf.run();
pf.runAndReset();
assertEquals(savedRunCount, pf.runCount());
try {
assertSame(r, f.get());
} catch (CancellationException t) {
assertSame(exInfo, CancellationException.class);
} catch (ExecutionException t) {
assertSame(exInfo, t.getCause());
} catch (Throwable t) {
threadUnexpectedException(t);
}
assertTrue(f.isDone());
}
}
void checkNotDone(Future<?> f) {
assertFalse(f.isDone());
assertFalse(f.isCancelled());
if (f instanceof PublicFutureTask) {
PublicFutureTask pf = (PublicFutureTask) f;
assertEquals(0, pf.doneCount());
assertEquals(0, pf.setCount());
assertEquals(0, pf.setExceptionCount());
}
}
void checkIsRunning(Future<?> f) {
checkNotDone(f);
if (f instanceof FutureTask) {
FutureTask ft = (FutureTask<?>) f;
// Check that run methods do nothing
ft.run();
if (f instanceof PublicFutureTask) {
PublicFutureTask pf = (PublicFutureTask) f;
int savedRunCount = pf.runCount();
pf.run();
assertFalse(pf.runAndReset());
assertEquals(savedRunCount, pf.runCount());
}
checkNotDone(f);
}
}
<T> void checkCompletedNormally(Future<T> f, T expected) {
checkIsDone(f);
assertFalse(f.isCancelled());
try {
assertSame(expected, f.get());
} catch (Throwable fail) { threadUnexpectedException(fail); }
try {
assertSame(expected, f.get(5L, SECONDS));
} catch (Throwable fail) { threadUnexpectedException(fail); }
}
void checkCancelled(Future<?> f) {
checkIsDone(f);
assertTrue(f.isCancelled());
try {
f.get();
shouldThrow();
} catch (CancellationException success) {
} catch (Throwable fail) { threadUnexpectedException(fail); }
try {
f.get(5L, SECONDS);
shouldThrow();
} catch (CancellationException success) {
} catch (Throwable fail) { threadUnexpectedException(fail); }
}
void tryToConfuseDoneTask(PublicFutureTask pf) {
pf.set(new Object());
pf.setException(new Error());
for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
pf.cancel(mayInterruptIfRunning);
}
}
void checkCompletedAbnormally(Future<?> f, Throwable t) {
checkIsDone(f);
assertFalse(f.isCancelled());
try {
f.get();
shouldThrow();
} catch (ExecutionException success) {
assertSame(t, success.getCause());
} catch (Throwable fail) { threadUnexpectedException(fail); }
try {
f.get(5L, SECONDS);
shouldThrow();
} catch (ExecutionException success) {
assertSame(t, success.getCause());
} catch (Throwable fail) { threadUnexpectedException(fail); }
}
/**
* Subclass to expose protected methods
*/
static class PublicFutureTask extends FutureTask {
private final AtomicInteger runCount;
private final AtomicInteger doneCount = new AtomicInteger(0);
private final AtomicInteger runAndResetCount = new AtomicInteger(0);
private final AtomicInteger setCount = new AtomicInteger(0);
private final AtomicInteger setExceptionCount = new AtomicInteger(0);
public int runCount() { return runCount.get(); }
public int doneCount() { return doneCount.get(); }
public int runAndResetCount() { return runAndResetCount.get(); }
public int setCount() { return setCount.get(); }
public int setExceptionCount() { return setExceptionCount.get(); }
PublicFutureTask(Runnable runnable) {
this(runnable, seven);
}
PublicFutureTask(Runnable runnable, Object result) {
this(runnable, result, new AtomicInteger(0));
}
private PublicFutureTask(final Runnable runnable, Object result,
final AtomicInteger runCount) {
super(new Runnable() {
public void run() {
runCount.getAndIncrement();
runnable.run();
}}, result);
this.runCount = runCount;
}
PublicFutureTask(Callable callable) {
this(callable, new AtomicInteger(0));
}
private PublicFutureTask(final Callable callable,
final AtomicInteger runCount) {
super(new Callable() {
public Object call() throws Exception {
runCount.getAndIncrement();
return callable.call();
}});
this.runCount = runCount;
}
@Override public void done() {
assertTrue(isDone());
doneCount.incrementAndGet();
super.done();
}
@Override public boolean runAndReset() {
runAndResetCount.incrementAndGet();
return super.runAndReset();
}
@Override public void set(Object x) {
setCount.incrementAndGet();
super.set(x);
}
@Override public void setException(Throwable t) {
setExceptionCount.incrementAndGet();
super.setException(t);
}
}
class Counter extends CheckedRunnable {
final AtomicInteger count = new AtomicInteger(0);
public int get() { return count.get(); }
public void realRun() {
count.getAndIncrement();
}
}
/**
* creating a future with a null callable throws NullPointerException
*/
public void testConstructor() {
try {
new FutureTask(null);
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* creating a future with null runnable throws NullPointerException
*/
public void testConstructor2() {
try {
new FutureTask(null, Boolean.TRUE);
shouldThrow();
} catch (NullPointerException success) {}
}
/**
* isDone is true when a task completes
*/
public void testIsDone() {
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
assertFalse(task.isDone());
task.run();
assertTrue(task.isDone());
checkCompletedNormally(task, Boolean.TRUE);
assertEquals(1, task.runCount());
}
/**
* runAndReset of a non-cancelled task succeeds
*/
public void testRunAndReset() {
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
for (int i = 0; i < 3; i++) {
assertTrue(task.runAndReset());
checkNotDone(task);
assertEquals(i+1, task.runCount());
assertEquals(i+1, task.runAndResetCount());
assertEquals(0, task.setCount());
assertEquals(0, task.setExceptionCount());
}
}
/**
* runAndReset after cancellation fails
*/
public void testRunAndResetAfterCancel() {
for (boolean mayInterruptIfRunning : new boolean[] { true, false }) {
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
assertTrue(task.cancel(mayInterruptIfRunning));
for (int i = 0; i < 3; i++) {
assertFalse(task.runAndReset());
assertEquals(0, task.runCount());
assertEquals(i+1, task.runAndResetCount());
assertEquals(0, task.setCount());
assertEquals(0, task.setExceptionCount());
}
tryToConfuseDoneTask(task);
checkCancelled(task);
}
}
/**
* setting value causes get to return it
*/
public void testSet() throws Exception {
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
task.set(one);
for (int i = 0; i < 3; i++) {
assertSame(one, task.get());
assertSame(one, task.get(LONG_DELAY_MS, MILLISECONDS));
assertEquals(1, task.setCount());
}
tryToConfuseDoneTask(task);
checkCompletedNormally(task, one);
assertEquals(0, task.runCount());
}
/**
* setException causes get to throw ExecutionException
*/
public void testSetException_get() throws Exception {
Exception nse = new NoSuchElementException();
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
task.setException(nse);
try {
task.get();
shouldThrow();
} catch (ExecutionException success) {
assertSame(nse, success.getCause());
checkCompletedAbnormally(task, nse);
}
try {
task.get(LONG_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (ExecutionException success) {
assertSame(nse, success.getCause());
checkCompletedAbnormally(task, nse);
}
assertEquals(1, task.setExceptionCount());
assertEquals(0, task.setCount());
tryToConfuseDoneTask(task);
checkCompletedAbnormally(task, nse);
assertEquals(0, task.runCount());
}
/**
* cancel(false) before run succeeds
*/
public void testCancelBeforeRun() {
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
assertTrue(task.cancel(false));
task.run();
assertEquals(0, task.runCount());
assertEquals(0, task.setCount());
assertEquals(0, task.setExceptionCount());
assertTrue(task.isCancelled());
assertTrue(task.isDone());
tryToConfuseDoneTask(task);
assertEquals(0, task.runCount());
checkCancelled(task);
}
/**
* cancel(true) before run succeeds
*/
public void testCancelBeforeRun2() {
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
assertTrue(task.cancel(true));
task.run();
assertEquals(0, task.runCount());
assertEquals(0, task.setCount());
assertEquals(0, task.setExceptionCount());
assertTrue(task.isCancelled());
assertTrue(task.isDone());
tryToConfuseDoneTask(task);
assertEquals(0, task.runCount());
checkCancelled(task);
}
/**
* cancel(false) of a completed task fails
*/
public void testCancelAfterRun() {
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
task.run();
assertFalse(task.cancel(false));
assertEquals(1, task.runCount());
assertEquals(1, task.setCount());
assertEquals(0, task.setExceptionCount());
tryToConfuseDoneTask(task);
checkCompletedNormally(task, Boolean.TRUE);
assertEquals(1, task.runCount());
}
/**
* cancel(true) of a completed task fails
*/
public void testCancelAfterRun2() {
PublicFutureTask task = new PublicFutureTask(new NoOpCallable());
task.run();
assertFalse(task.cancel(true));
assertEquals(1, task.runCount());
assertEquals(1, task.setCount());
assertEquals(0, task.setExceptionCount());
tryToConfuseDoneTask(task);
checkCompletedNormally(task, Boolean.TRUE);
assertEquals(1, task.runCount());
}
/**
* cancel(true) interrupts a running task that subsequently succeeds
*/
public void testCancelInterrupt() {
final CountDownLatch pleaseCancel = new CountDownLatch(1);
final PublicFutureTask task =
new PublicFutureTask(new CheckedRunnable() {
public void realRun() {
pleaseCancel.countDown();
try {
delay(LONG_DELAY_MS);
shouldThrow();
} catch (InterruptedException success) {}
}});
Thread t = newStartedThread(task);
await(pleaseCancel);
assertTrue(task.cancel(true));
assertTrue(task.isCancelled());
assertTrue(task.isDone());
awaitTermination(t);
assertEquals(1, task.runCount());
assertEquals(1, task.setCount());
assertEquals(0, task.setExceptionCount());
tryToConfuseDoneTask(task);
checkCancelled(task);
}
/**
* cancel(true) tries to interrupt a running task, but
* Thread.interrupt throws (simulating a restrictive security
* manager)
*/
public void testCancelInterrupt_ThrowsSecurityException() {
final CountDownLatch pleaseCancel = new CountDownLatch(1);
final CountDownLatch cancelled = new CountDownLatch(1);
final PublicFutureTask task =
new PublicFutureTask(new CheckedRunnable() {
public void realRun() {
pleaseCancel.countDown();
await(cancelled);
assertFalse(Thread.interrupted());
}});
final Thread t = new Thread(task) {
// Simulate a restrictive security manager.
@Override public void interrupt() {
throw new SecurityException();
}};
t.setDaemon(true);
t.start();
await(pleaseCancel);
try {
task.cancel(true);
shouldThrow();
} catch (SecurityException expected) {}
// We failed to deliver the interrupt, but the world retains
// its sanity, as if we had done task.cancel(false)
assertTrue(task.isCancelled());
assertTrue(task.isDone());
assertEquals(1, task.runCount());
assertEquals(1, task.doneCount());
assertEquals(0, task.setCount());
assertEquals(0, task.setExceptionCount());
cancelled.countDown();
awaitTermination(t);
assertEquals(1, task.setCount());
assertEquals(0, task.setExceptionCount());
tryToConfuseDoneTask(task);
checkCancelled(task);
}
/**
* cancel(true) interrupts a running task that subsequently throws
*/
public void testCancelInterrupt_taskFails() {
final CountDownLatch pleaseCancel = new CountDownLatch(1);
final PublicFutureTask task =
new PublicFutureTask(new Runnable() {
public void run() {
pleaseCancel.countDown();
try {
delay(LONG_DELAY_MS);
threadShouldThrow();
} catch (InterruptedException success) {
} catch (Throwable t) { threadUnexpectedException(t); }
throw new RuntimeException();
}});
Thread t = newStartedThread(task);
await(pleaseCancel);
assertTrue(task.cancel(true));
assertTrue(task.isCancelled());
awaitTermination(t);
assertEquals(1, task.runCount());
assertEquals(0, task.setCount());
assertEquals(1, task.setExceptionCount());
tryToConfuseDoneTask(task);
checkCancelled(task);
}
/**
* cancel(false) does not interrupt a running task
*/
public void testCancelNoInterrupt() {
final CountDownLatch pleaseCancel = new CountDownLatch(1);
final CountDownLatch cancelled = new CountDownLatch(1);
final PublicFutureTask task =
new PublicFutureTask(new CheckedCallable<Boolean>() {
public Boolean realCall() {
pleaseCancel.countDown();
await(cancelled);
assertFalse(Thread.interrupted());
return Boolean.TRUE;
}});
Thread t = newStartedThread(task);
await(pleaseCancel);
assertTrue(task.cancel(false));
assertTrue(task.isCancelled());
cancelled.countDown();
awaitTermination(t);
assertEquals(1, task.runCount());
assertEquals(1, task.setCount());
assertEquals(0, task.setExceptionCount());
tryToConfuseDoneTask(task);
checkCancelled(task);
}
/**
* run in one thread causes get in another thread to retrieve value
*/
public void testGetRun() {
final CountDownLatch pleaseRun = new CountDownLatch(2);
final PublicFutureTask task =
new PublicFutureTask(new CheckedCallable<Object>() {
public Object realCall() {
return two;
}});
Thread t1 = newStartedThread(new CheckedRunnable() {
public void realRun() throws Exception {
pleaseRun.countDown();
assertSame(two, task.get());
}});
Thread t2 = newStartedThread(new CheckedRunnable() {
public void realRun() throws Exception {
pleaseRun.countDown();
assertSame(two, task.get(2*LONG_DELAY_MS, MILLISECONDS));
}});
await(pleaseRun);
checkNotDone(task);
assertTrue(t1.isAlive());
assertTrue(t2.isAlive());
task.run();
checkCompletedNormally(task, two);
assertEquals(1, task.runCount());
assertEquals(1, task.setCount());
assertEquals(0, task.setExceptionCount());
awaitTermination(t1);
awaitTermination(t2);
tryToConfuseDoneTask(task);
checkCompletedNormally(task, two);
}
/**
* set in one thread causes get in another thread to retrieve value
*/
public void testGetSet() {
final CountDownLatch pleaseSet = new CountDownLatch(2);
final PublicFutureTask task =
new PublicFutureTask(new CheckedCallable<Object>() {
public Object realCall() throws InterruptedException {
return two;
}});
Thread t1 = newStartedThread(new CheckedRunnable() {
public void realRun() throws Exception {
pleaseSet.countDown();
assertSame(two, task.get());
}});
Thread t2 = newStartedThread(new CheckedRunnable() {
public void realRun() throws Exception {
pleaseSet.countDown();
assertSame(two, task.get(2*LONG_DELAY_MS, MILLISECONDS));
}});
await(pleaseSet);
checkNotDone(task);
assertTrue(t1.isAlive());
assertTrue(t2.isAlive());
task.set(two);
assertEquals(0, task.runCount());
assertEquals(1, task.setCount());
assertEquals(0, task.setExceptionCount());
tryToConfuseDoneTask(task);
checkCompletedNormally(task, two);
awaitTermination(t1);
awaitTermination(t2);
}
/**
* Cancelling a task causes timed get in another thread to throw
* CancellationException
*/
public void testTimedGet_Cancellation() {
testTimedGet_Cancellation(false);
}
public void testTimedGet_Cancellation_interrupt() {
testTimedGet_Cancellation(true);
}
public void testTimedGet_Cancellation(final boolean mayInterruptIfRunning) {
final CountDownLatch pleaseCancel = new CountDownLatch(3);
final CountDownLatch cancelled = new CountDownLatch(1);
final Callable<Object> callable =
new CheckedCallable<Object>() {
public Object realCall() throws InterruptedException {
pleaseCancel.countDown();
if (mayInterruptIfRunning) {
try {
delay(2*LONG_DELAY_MS);
} catch (InterruptedException success) {}
} else {
await(cancelled);
}
return two;
}};
final PublicFutureTask task = new PublicFutureTask(callable);
Thread t1 = new ThreadShouldThrow(CancellationException.class) {
public void realRun() throws Exception {
pleaseCancel.countDown();
task.get();
}};
Thread t2 = new ThreadShouldThrow(CancellationException.class) {
public void realRun() throws Exception {
pleaseCancel.countDown();
task.get(2*LONG_DELAY_MS, MILLISECONDS);
}};
t1.start();
t2.start();
Thread t3 = newStartedThread(task);
await(pleaseCancel);
checkIsRunning(task);
task.cancel(mayInterruptIfRunning);
checkCancelled(task);
awaitTermination(t1);
awaitTermination(t2);
cancelled.countDown();
awaitTermination(t3);
assertEquals(1, task.runCount());
assertEquals(1, task.setCount());
assertEquals(0, task.setExceptionCount());
tryToConfuseDoneTask(task);
checkCancelled(task);
}
/**
* A runtime exception in task causes get to throw ExecutionException
*/
public void testGet_ExecutionException() throws InterruptedException {
final ArithmeticException e = new ArithmeticException();
final PublicFutureTask task = new PublicFutureTask(new Callable() {
public Object call() {
throw e;
}});
task.run();
assertEquals(1, task.runCount());
assertEquals(0, task.setCount());
assertEquals(1, task.setExceptionCount());
try {
task.get();
shouldThrow();
} catch (ExecutionException success) {
assertSame(e, success.getCause());
tryToConfuseDoneTask(task);
checkCompletedAbnormally(task, success.getCause());
}
}
/**
* A runtime exception in task causes timed get to throw ExecutionException
*/
public void testTimedGet_ExecutionException2() throws Exception {
final ArithmeticException e = new ArithmeticException();
final PublicFutureTask task = new PublicFutureTask(new Callable() {
public Object call() {
throw e;
}});
task.run();
try {
task.get(LONG_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (ExecutionException success) {
assertSame(e, success.getCause());
tryToConfuseDoneTask(task);
checkCompletedAbnormally(task, success.getCause());
}
}
/**
* get is interruptible
*/
public void testGet_interruptible() {
final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
final FutureTask task = new FutureTask(new NoOpCallable());
Thread t = newStartedThread(new CheckedRunnable() {
public void realRun() throws Exception {
Thread.currentThread().interrupt();
try {
task.get();
shouldThrow();
} catch (InterruptedException success) {}
assertFalse(Thread.interrupted());
pleaseInterrupt.countDown();
try {
task.get();
shouldThrow();
} catch (InterruptedException success) {}
assertFalse(Thread.interrupted());
}});
await(pleaseInterrupt);
t.interrupt();
awaitTermination(t);
checkNotDone(task);
}
/**
* timed get is interruptible
*/
public void testTimedGet_interruptible() {
final CountDownLatch pleaseInterrupt = new CountDownLatch(1);
final FutureTask task = new FutureTask(new NoOpCallable());
Thread t = newStartedThread(new CheckedRunnable() {
public void realRun() throws Exception {
Thread.currentThread().interrupt();
try {
task.get(2*LONG_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (InterruptedException success) {}
assertFalse(Thread.interrupted());
pleaseInterrupt.countDown();
try {
task.get(2*LONG_DELAY_MS, MILLISECONDS);
shouldThrow();
} catch (InterruptedException success) {}
assertFalse(Thread.interrupted());
}});
await(pleaseInterrupt);
t.interrupt();
awaitTermination(t);
checkNotDone(task);
}
/**
* A timed out timed get throws TimeoutException
*/
public void testGet_TimeoutException() throws Exception {
FutureTask task = new FutureTask(new NoOpCallable());
long startTime = System.nanoTime();
try {
task.get(timeoutMillis(), MILLISECONDS);
shouldThrow();
} catch (TimeoutException success) {
assertTrue(millisElapsedSince(startTime) >= timeoutMillis());
}
}
/**
* timed get with null TimeUnit throws NullPointerException
*/
public void testGet_NullTimeUnit() throws Exception {
FutureTask task = new FutureTask(new NoOpCallable());
long[] timeouts = { Long.MIN_VALUE, 0L, Long.MAX_VALUE };
for (long timeout : timeouts) {
try {
task.get(timeout, null);
shouldThrow();
} catch (NullPointerException success) {}
}
task.run();
for (long timeout : timeouts) {
try {
task.get(timeout, null);
shouldThrow();
} catch (NullPointerException success) {}
}
}
/**
* timed get with most negative timeout works correctly (i.e. no
* underflow bug)
*/
public void testGet_NegativeInfinityTimeout() throws Exception {
final ExecutorService pool = Executors.newFixedThreadPool(10);
final Runnable nop = new Runnable() { public void run() {}};
final FutureTask<Void> task = new FutureTask<>(nop, null);
final List<Future<?>> futures = new ArrayList<>();
Runnable r = new Runnable() { public void run() {
for (long timeout : new long[] { 0L, -1L, Long.MIN_VALUE }) {
try {
task.get(timeout, NANOSECONDS);
shouldThrow();
} catch (TimeoutException success) {
} catch (Throwable fail) {threadUnexpectedException(fail);}}}};
for (int i = 0; i < 10; i++)
futures.add(pool.submit(r));
try {
joinPool(pool);
for (Future<?> future : futures)
checkCompletedNormally(future, null);
} finally {
task.run(); // last resort to help terminate
}
}
}
| gpl-2.0 |
DevDean/jissaticket | administrator/components/com_hikashop/views/product/tmpl/waitlist.php | 499 | <?php
/**
* @package HikaShop for Joomla!
* @version 2.6.0
* @author hikashop.com
* @copyright (C) 2010-2015 HIKARI SOFTWARE. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?> <span id="result" >
<?php echo @$this->rows[0]->product_id.' '.@$this->rows[0]->product_name; ?>
<input type="hidden" name="data[waitlist][product_id]" value="<?php echo @$this->rows[0]->product_id; ?>" />
</span>
| gpl-2.0 |
maitak/testing | modules/search_api/tests/src/Unit/Plugin/Processor/AggregatedFieldsTest.php | 11759 | <?php
namespace Drupal\Tests\search_api\Unit\Plugin\Processor;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\search_api\Entity\Index;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Plugin\search_api\processor\AggregatedFields;
use Drupal\search_api\Processor\ProcessorInterface;
use Drupal\search_api\Processor\ProcessorProperty;
use Drupal\search_api\Utility;
use Drupal\Tests\UnitTestCase;
/**
* Tests the "Aggregated fields" processor.
*
* @group search_api
*
* @see \Drupal\search_api\Plugin\search_api\processor\AggregatedField
*/
class AggregatedFieldsTest extends UnitTestCase {
use TestItemsTrait;
/**
* The processor to be tested.
*
* @var \Drupal\search_api\Plugin\search_api\processor\AggregatedFields
*/
protected $processor;
/**
* A search index mock for the tests.
*
* @var \Drupal\search_api\IndexInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $index;
/**
* The field ID used in this test.
*
* @var string
*/
protected $fieldId = 'aggregated_field';
/**
* Creates a new processor object for use in the tests.
*/
protected function setUp() {
parent::setUp();
$this->index = new Index(array(
'datasourceInstances' => array(
'entity:test1' => (object) array(),
),
'processorInstances' => array(),
'field_settings' => array(
'foo' => array(
'type' => 'string',
'datasource_id' => 'entity:test1',
'property_path' => 'foo',
),
'bar' => array(
'type' => 'string',
'datasource_id' => 'entity:test1',
'property_path' => 'foo:bar',
),
'bla' => array(
'type' => 'string',
'datasource_id' => 'entity:test2',
'property_path' => 'foobaz:bla',
),
'aggregated_field' => array(
'type' => 'string',
'property_path' => 'aggregated_field',
),
),
'properties' => array(
NULL => array(),
'entity:test1' => array(),
'entity:test2' => array(),
),
), 'search_api_index');
$this->processor = new AggregatedFields(array('index' => $this->index), 'aggregated_field', array());
$this->index->addProcessor($this->processor);
$this->setUpDataTypePlugin();
}
/**
* Tests aggregated fields of the given type.
*
* @param string $type
* The aggregation type to test.
* @param array $expected
* The expected values for the two items.
* @param bool $integer
* (optional) TRUE if the items' normal fields should contain integers,
* FALSE otherwise.
*
* @dataProvider aggregationTestsDataProvider
*/
public function testAggregation($type, $expected, $integer = FALSE) {
// Add the field configuration.
$configuration = array(
'type' => $type,
'fields' => array(
'entity:test1/foo',
'entity:test1/foo:bar',
'entity:test2/foobaz:bla',
),
);
$this->index->getField($this->fieldId)->setConfiguration($configuration);
if ($integer) {
$field_values = array(
'foo' => array(2, 4),
'bar' => array(16),
'bla' => array(7),
);
}
else {
$field_values = array(
'foo' => array('foo', 'bar'),
'bar' => array('baz'),
'bla' => array('foobar'),
);
}
$items = array();
$i = 0;
foreach (array('entity:test1', 'entity:test2') as $datasource_id) {
$this->itemIds[$i++] = $item_id = Utility::createCombinedId($datasource_id, '1:en');
$item = Utility::createItem($this->index, $item_id);
foreach ($this->index->getFields() as $field_id => $field) {
$field = clone $field;
if (!empty($field_values[$field_id])) {
$field->setValues($field_values[$field_id]);
}
$item->setField($field_id, $field);
}
$item->setFieldsExtracted(TRUE);
$items[$item_id] = $item;
}
// Add the processor's field values to the items.
foreach ($items as $item) {
$this->processor->addFieldValues($item);
}
$this->assertEquals($expected[0], $items[$this->itemIds[0]]->getField($this->fieldId)->getValues(), 'Correct aggregation for item 1.');
$this->assertEquals($expected[1], $items[$this->itemIds[1]]->getField($this->fieldId)->getValues(), 'Correct aggregation for item 2.');
}
/**
* Provides test data for aggregation tests.
*
* @return array
* An array containing test data sets, with each being an array of
* arguments to pass to the test method.
*
* @see static::testAggregation()
*/
public function aggregationTestsDataProvider() {
return array(
'"Union" aggregation' => array(
'union',
array(
array('foo', 'bar', 'baz'),
array('foobar'),
),
),
'"Concatenation" aggregation' => array(
'concat',
array(
array("foo\n\nbar\n\nbaz"),
array('foobar'),
),
),
'"Sum" aggregation' => array(
'sum',
array(
array(22),
array(7),
),
TRUE,
),
'"Count" aggregation' => array(
'count',
array(
array(3),
array(1),
),
),
'"Maximum" aggregation' => array(
'max',
array(
array(16),
array(7),
),
TRUE,
),
'"Minimum" aggregation' => array(
'min',
array(
array(2),
array(7),
),
TRUE,
),
'"First" aggregation' => array(
'first',
array(
array('foo'),
array('foobar'),
),
),
);
}
/**
* Tests whether the properties are correctly altered.
*
* @see \Drupal\search_api\Plugin\search_api\processor\AggregatedField::alterPropertyDefinitions()
*/
public function testAlterPropertyDefinitions() {
/** @var \Drupal\Core\StringTranslation\TranslationInterface $translation */
$translation = $this->getStringTranslationStub();
$this->processor->setStringTranslation($translation);
// Check for added properties when no datasource is given.
/** @var \Drupal\search_api\Processor\ProcessorPropertyInterface[] $properties */
$properties = $this->processor->getPropertyDefinitions(NULL);
$this->assertArrayHasKey('aggregated_field', $properties, 'The "aggregated_field" property was added to the properties.');
$this->assertInstanceOf('Drupal\search_api\Plugin\search_api\processor\Property\AggregatedFieldProperty', $properties['aggregated_field'], 'The "aggregated_field" property has the correct class.');
$this->assertEquals('string', $properties['aggregated_field']->getDataType(), 'Correct data type set in the data definition.');
$this->assertEquals($translation->translate('Aggregated field'), $properties['aggregated_field']->getLabel(), 'Correct label set in the data definition.');
$expected_description = $translation->translate('An aggregation of multiple other fields.');
$this->assertEquals($expected_description, $properties['aggregated_field']->getDescription(), 'Correct description set in the data definition.');
// Verify that there are no properties if a datasource is given.
$datasource = $this->getMock('Drupal\search_api\Datasource\DatasourceInterface');
$properties = $this->processor->getPropertyDefinitions($datasource);
$this->assertEmpty($properties, 'Datasource-specific properties did not get changed.');
}
/**
* Tests that field extraction in the processor works correctly.
*/
public function testFieldExtraction() {
/** @var \Drupal\Tests\search_api\TestComplexDataInterface|\PHPUnit_Framework_MockObject_MockObject $object */
$object = $this->getMock('Drupal\Tests\search_api\TestComplexDataInterface');
$bar_foo_property = $this->getMock('Drupal\Core\TypedData\TypedDataInterface');
$bar_foo_property->method('getValue')
->willReturn('value3');
$bar_foo_property->method('getDataDefinition')
->willReturn(new DataDefinition());
$bar_property = $this->getMock('Drupal\Tests\search_api\TestComplexDataInterface');
$bar_property->method('get')
->willReturnMap(array(
array('foo', $bar_foo_property),
));
$foobar_property = $this->getMock('Drupal\Core\TypedData\TypedDataInterface');
$foobar_property->method('getValue')
->willReturn('wrong_value2');
$foobar_property->method('getDataDefinition')
->willReturn(new DataDefinition());
$object->method('get')
->willReturnMap(array(
array('bar', $bar_property),
array('foobar', $foobar_property),
));
/** @var \Drupal\search_api\IndexInterface|\PHPUnit_Framework_MockObject_MockObject $index */
$index = $this->getMock('Drupal\search_api\IndexInterface');
$field = Utility::createField($index, 'aggregated_field', array(
'property_path' => 'aggregated_field',
'configuration' => array(
'type' => 'union',
'fields' => array(
'aggregated_field',
'foo',
'entity:test1/bar:foo',
'entity:test1/baz',
'entity:test2/foobar',
),
),
));
$index->method('getFieldsByDatasource')
->willReturnMap(array(
array(NULL, array('aggregated_field' => $field)),
));
$index->method('getPropertyDefinitions')
->willReturnMap(array(
array(
NULL,
array(
'foo' => new ProcessorProperty(array(
'processor_id' => 'processor1',
)),
),
),
array(
'entity:test1',
array(
'bar' => new DataDefinition(),
'foobar' => new DataDefinition(),
),
),
));
$processor_mock = $this->getMock('Drupal\search_api\Processor\ProcessorInterface');
$processor_mock->method('addFieldValues')
->willReturnCallback(function (ItemInterface $item) {
foreach ($item->getFields(FALSE) as $field) {
if ($field->getCombinedPropertyPath() == 'foo') {
$field->setValues(array('value4', 'value5'));
}
}
});
$index->method('getProcessorsByStage')
->willReturnMap(array(
array(
ProcessorInterface::STAGE_ADD_PROPERTIES,
array(
'aggregated_field' => $this->processor,
'processor1' => $processor_mock,
),
),
));
$this->processor->setIndex($index);
/** @var \Drupal\search_api\Datasource\DatasourceInterface|\PHPUnit_Framework_MockObject_MockObject $datasource */
$datasource = $this->getMock('Drupal\search_api\Datasource\DatasourceInterface');
$datasource->method('getPluginId')
->willReturn('entity:test1');
$item = Utility::createItem($index, 'id', $datasource);
$item->setOriginalObject($object);
$item->setField('aggregated_field', clone $field);
$item->setField('test1', Utility::createField($index, 'test1', array(
'property_path' => 'baz',
'values' => array(
'wrong_value1',
),
)));
$item->setField('test2', Utility::createField($index, 'test2', array(
'datasource_id' => 'entity:test1',
'property_path' => 'baz',
'values' => array(
'value1',
'value2',
),
)));
$item->setFieldsExtracted(TRUE);
$this->processor->addFieldValues($item);
$expected = array(
'value1',
'value2',
'value3',
'value4',
'value5',
);
$actual = $item->getField('aggregated_field')->getValues();
sort($actual);
$this->assertEquals($expected, $actual);
}
}
| gpl-2.0 |
chinhtx91/khoaquocte | modules/users/language/admin_en.php | 26215 | <?php
/**
* @Project NUKEVIET 4.x
* @Author VINADES.,JSC (contact@vinades.vn)
* @Copyright (C) 2015 VINADES.,JSC. All rights reserved
* @Language English
* @License CC BY-SA (http://creativecommons.org/licenses/by-sa/4.0/)
* @Createdate May 30, 2010, 05:07:00 PM
*/
if( ! defined( 'NV_ADMIN' ) or ! defined( 'NV_MAINFILE' ) ) die( 'Stop!!!' );
$lang_translator['author'] = 'VINADES.,JSC (contact@vinades.vn)';
$lang_translator['createdate'] = '31/05/2010, 00:07';
$lang_translator['copyright'] = 'Copyright (C) 2010 VINADES.,JSC. All rights reserved';
$lang_translator['info'] = '';
$lang_translator['langtype'] = 'lang_module';
$lang_module['avatar_size'] = 'Avatar size';
$lang_module['dir_forum'] = 'Dir forum';
$lang_module['modforum'] = 'Members management by forum %1$s.';
$lang_module['list_module_title'] = 'Members list';
$lang_module['member_add'] = 'Add member';
$lang_module['member_wating'] = 'Member wating';
$lang_module['list_question'] = 'Question list';
$lang_module['search_type'] = 'Search by';
$lang_module['search_id'] = 'Member\'s ID';
$lang_module['search_account'] = 'Member\'s account';
$lang_module['search_name'] = 'Member\'s name';
$lang_module['search_mail'] = 'Member\'s email';
$lang_module['search_key'] = 'Keyword search';
$lang_module['search_note'] = 'Keyword maximum length is 64 characters, html isn\'t allowed';
$lang_module['submit'] = 'Searcg';
$lang_module['members_list'] = 'Member list';
$lang_module['main_title'] = 'Manage member';
$lang_module['userid'] = 'ID';
$lang_module['account'] = 'Account';
$lang_module['name'] = 'Name';
$lang_module['first_name'] = 'First Name';
$lang_module['last_name'] = 'Last Name';
$lang_module['email'] = 'Email';
$lang_module['register_date'] = 'Register date';
$lang_module['status'] = 'Status';
$lang_module['funcs'] = 'Features';
$lang_module['user_add'] = 'Add member';
$lang_module['password'] = 'Password';
$lang_module['repassword'] = 'Repeat password';
$lang_module['answer'] = 'Answer';
$lang_module['gender'] = 'Gender';
$lang_module['male'] = 'Male';
$lang_module['female'] = 'Female';
$lang_module['NA'] = 'N/A';
$lang_module['name_show'] = 'Type display name';
$lang_module['firstname_lastname'] = 'Firstname and Lastname';
$lang_module['lastname_firstname'] = 'Lastname and Firstname';
$lang_module['error_language'] = 'Error: You do not select the type of display Name';
$lang_module['avata'] = 'Avatar';
$lang_module['avata_chosen'] = 'Chosen avatar';
$lang_module['birthday'] = 'Birthday';
$lang_module['date'] = 'Day';
$lang_module['month'] = 'Month';
$lang_module['year'] = 'Year';
$lang_module['show_email'] = 'Display email';
$lang_module['sig'] = 'Signature';
$lang_module['in_group'] = 'Member of group';
$lang_module['question'] = 'Secret question';
$lang_module['addquestion'] = 'Add secret question';
$lang_module['savequestion'] = 'Save secret question';
$lang_module['deletequestion'] = 'Delete security question';
$lang_module['errornotitle'] = 'Error: Empty secret question';
$lang_module['errorsave'] = 'Error: Can\'t update data, please check topic title';
$lang_module['weight'] = 'position';
$lang_module['save'] = 'Save';
$lang_module['siteterms'] = 'Site rules';
$lang_module['error_content'] = 'Error: Empty site rules';
$lang_module['saveok'] = 'Update successful';
$lang_module['config'] = 'Configuration';
$lang_module['allow_reg'] = 'Allow register';
$lang_module['allow_login'] = 'Allow login';
$lang_module['allow_change_email'] = 'Allow change email';
$lang_module['type_reg'] = 'Register type';
$lang_module['active_not_allow'] = 'Not grant to register';
$lang_module['allow_public'] = 'Allow members register in public groups';
$lang_module['allow_question'] = 'Answer secret question for Lost Password';
$lang_module['active_admin_check'] = 'Admin active';
$lang_module['active_all'] = 'No need to active';
$lang_module['active_email'] = 'Email activation';
$lang_module['deny_email'] = 'Deny words on member\'s email';
$lang_module['deny_name'] = 'Deny words on member\'s account';
$lang_module['password_simple'] = 'Simple passwords';
$lang_module['memberlist_active'] = 'Active';
$lang_module['memberlist_unactive'] = 'Active';
$lang_module['memberlist_error_method'] = 'Please select search method!';
$lang_module['memberlist_error_value'] = 'Search value must be at least 1 and doesn\'t exceed 64 characters!';
$lang_module['memberlist_nousers'] = 'No result match!';
$lang_module['memberlist_selectusers'] = 'Select at least 1 user to delete!';
$lang_module['checkall'] = 'Select all';
$lang_module['uncheckall'] = 'Unselect all';
$lang_module['delete'] = 'Delete';
$lang_module['delete_success'] = 'Success!';
$lang_module['delete_group_system'] = 'Error: not delete the account because this account is the administrator of the site';
$lang_module['active_success'] = 'Success!';
$lang_module['memberlist_edit'] = 'Edit';
$lang_module['memberlist_deleteconfirm'] = 'Do you realy want to delete?';
$lang_module['edit_title'] = 'Edit';
$lang_module['edit_password_note'] = 'Change password (leave blank if you don\'t want to change password)';
$lang_module['edit_avatar_note'] = 'Leave blank if you don\'t want to change avatar mới';
$lang_module['edit_save'] = 'Accept';
$lang_module['edit_error_username_exist'] = 'User name used by another member. Please choose another name';
$lang_module['edit_error_photo'] = 'File type doesn\'t allowed';
$lang_module['edit_error_email'] = 'Incorrect email';
$lang_module['edit_error_email_exist'] = 'Your email used in another account. Please choose another account.';
$lang_module['edit_error_permission'] = 'You can not change the account information.';
$lang_module['edit_error_password'] = 'Password doesn\'t match';
$lang_module['edit_error_nopassword'] = 'Empty password';
$lang_module['edit_add_error'] = 'Can\'t update member information!';
$lang_module['edit_error_question'] = 'Empty secret question';
$lang_module['edit_error_answer'] = 'Empty answer';
$lang_module['edit_error_group'] = 'Please select group for member';
$lang_module['account_deny_name'] = 'Sorry, Account %s banned.';
$lang_module['awaiting_active'] = 'Activate';
$lang_module['delconfirm_message'] = 'Do you realy want to delete selected member?';
$lang_module['delconfirm_email'] = 'Send notification email:';
$lang_module['delconfirm_email_yes'] = 'Yes';
$lang_module['delconfirm_ok'] = 'Ok!';
$lang_module['delconfirm_email_title'] = 'Email notification to delete account';
$lang_module['delconfirm_email_content'] = 'Hi %1$s,<br />We are so sorry to delete your account at website %2$s.';
$lang_module['adduser_email'] = 'Send notification email:';
$lang_module['adduser_email_yes'] = 'Yes';
$lang_module['adduser_register'] = 'Your account was created';
$lang_module['adduser_register_info'] = 'Hi %1$s,<br />Your account at website %2$s activated. Your login information:<br />URL: <a href="%3$s">%3$s</a><br />Account: %4$s<br />Password: %5$s<br />This is email automatic sending from website %2$s.<br />Site administrator';
$lang_module['openid_servers'] = 'Oauth, OpenID accepted list';
$lang_module['openid_processing'] = 'The default processing mode after OpenID login';
$lang_module['openid_processing_0'] = 'Users can choose the mode of processing';
$lang_module['openid_processing_3'] = 'Register a new account and link this OpenID';
$lang_module['openid_processing_4'] = 'Login with account create automatic by system';
$lang_module['allow_change_login'] = 'Allow change login name';
$lang_module['is_user_forum'] = 'Use forum\'s users';
$lang_module['search_page_title'] = 'Result';
$lang_module['click_to_view'] = 'Click to view';
$lang_module['level0'] = 'User';
$lang_module['admin_add'] = 'Set to admin';
$lang_module['nv_admin_add'] = 'Add group';
$lang_module['nv_admin_edit'] = 'Edit group';
$lang_module['title_empty'] = 'You do not declare group title';
$lang_module['nv_admin_add_caption'] = 'To create a new group, you need to declare fully in the box below';
$lang_module['nv_admin_edit_caption'] = 'To change content of the group “%s”, you need to declare fully in the box below';
$lang_module['title'] = 'Group name';
$lang_module['content'] = 'Content';
$lang_module['add_time'] = 'Start date';
$lang_module['exp_time'] = 'Expire date';
$lang_module['public'] = 'Public';
$lang_module['siteus'] = 'Allow subsite add members to the group';
$lang_module['users'] = 'User';
$lang_module['error_title_exists'] = 'Group name "%s" already exist';
$lang_module['users_in_group_caption'] = 'Member list in group "%s" (%d group)';
$lang_module['error_group_not_found'] = 'Error: Can\'t find group';
$lang_module['error_users_not_found'] = 'Group has not member';
$lang_module['error_group_in_site'] = 'Error: You just added and deleted from the group account, the account management of your site.';
$lang_module['error_not_groups'] = 'There are no groups to be established. Click here <a href="%s">vào đây</a> to create a group';
$lang_module['add_users'] = 'Add user';
$lang_module['form_search_label0'] = 'Search members by';
$lang_module['form_search_label1'] = 'Keyword (Null = all member)';
$lang_module['form_search_select0'] = 'Name';
$lang_module['form_search_select1'] = 'Email';
$lang_module['form_search_select2'] = 'ID';
$lang_module['search_not_result'] = 'Not found any results';
$lang_module['search_result_caption'] = 'Result';
$lang_module['group_pgtitle'] = 'Detail';
$lang_module['group_info'] = 'Group information “%s”';
$lang_module['add_user'] = 'Member %1$s group %2$s';
$lang_module['exclude_user'] = 'Delete member %1$s in group %2$s';
$lang_module['siteinfo_user'] = 'Members';
$lang_module['siteinfo_waiting'] = 'Unactive members';
$lang_module['pagetitle'] = 'Get Member ID';
$lang_module['pagetitle1'] = 'Search Member ID';
$lang_module['search'] = 'Find Member';
$lang_module['reset'] = 'Repeat';
$lang_module['waiting'] = 'Enter the information and then press the search member button to perform';
$lang_module['from'] = 'From';
$lang_module['to'] = 'to';
$lang_module['select'] = 'Select';
$lang_module['noresult'] = 'No results match your request';
$lang_module['enter_key'] = 'Please enter information to find a member';
$lang_module['username'] = 'Username';
$lang_module['full_name'] = 'Full Name';
$lang_module['regdate'] = 'Registration Date';
$lang_module['last_login'] = 'Last session';
$lang_module['last_idlogin'] = 'IP of the last session';
$lang_module['select_gender'] = 'Select your gender';
$lang_module['select_gender_male'] = 'Male';
$lang_module['select_gender_female'] = 'Female';
$lang_module['changeGroupWeight'] = 'Change the weight of groups';
$lang_module['ChangeGroupAct'] = 'Change status of groups';
$lang_module['delGroup'] = 'Delete group';
$lang_module['ChangeGroupPublic'] = 'Change the type of group';
$lang_module['emptyIsUnlimited'] = 'Empty same with the infinite';
$lang_module['dateError'] = 'Error! Your date is error';
$lang_module['delConfirm'] = 'Are you sure to delete';
$lang_module['errorChangeWeight'] = 'Error! Can not change the position';
$lang_module['choiceUserID'] = 'Please enter the user ID';
$lang_module['UserInGroup'] = 'This user has on the list of group users';
$lang_module['UserNotInGroup'] = 'User of your choice is not in the list of group members';
$lang_module['addMemberToGroup'] = 'Add users to group';
$lang_module['detail'] = 'Detail';
$lang_module['exclude_user2'] = 'Remove from group';
$lang_module['ChangeConfigModule'] = 'Change module configuration';
$lang_module['active_users'] = 'Activate members';
$lang_module['unactive_users'] = 'Inactivates members';
$lang_module['whoviewlistuser'] = 'Who can view a list of members';
$lang_module['whoview_all'] = 'All';
$lang_module['whoview_user'] = 'User';
$lang_module['whoview_admin'] = 'Administrator';
$lang_module['random_password'] = 'Random Password';
$lang_module['show_password'] = 'Show password';
$lang_module['usactive'] = 'Account status';
$lang_module['usactive_0'] = 'Account locked';
$lang_module['usactive_1'] = 'Account active';
$lang_module['usactive_2'] = 'Account admin blocked';
$lang_module['usactive_3'] = 'Account admin active';
$lang_module['access_register'] = 'Configure register';
$lang_module['nv_unick'] = 'Number characters account';
$lang_module['nv_unick_type'] = 'Characters allow when create account';
$lang_module['nv_upass'] = 'Number characters of password';
$lang_module['unick_type_0'] = 'Use any character';
$lang_module['nv_upass_type'] = 'Complexity of the password';
$lang_module['upass_type_0'] = 'Unlimit';
$lang_module['access_other'] = 'Other configure';
$lang_module['access_caption'] = 'Configure using module';
$lang_module['access_admin'] = 'Group manage';
$lang_module['access_addus'] = 'Create member';
$lang_module['access_waiting'] = 'Active member';
$lang_module['access_editus'] = 'Edit member';
$lang_module['access_delus'] = 'Delete member';
$lang_module['access_passus'] = 'Change password';
$lang_module['access_groups'] = 'Group manage';
$lang_module['fields'] = 'Custom User Fields';
$lang_module['captionform_add'] = 'Add User Fields';
$lang_module['captionform_edit'] = 'Edit User Fields';
$lang_module['field_edit'] = 'Edit';
$lang_module['field_choices_empty'] = 'Empty Choice Fields';
$lang_module['field_id'] = 'Field ID';
$lang_module['field_id_note'] = 'This is the unique identifier for this field. It cannot be changed once set ';
$lang_module['field_title'] = 'Title';
$lang_module['field_description'] = 'Description';
$lang_module['field_required'] = 'Field is required';
$lang_module['field_required_note'] = 'Required fields will always be shown during register';
$lang_module['field_show_register'] = 'Show during register';
$lang_module['field_user_editable'] = 'User editable';
$lang_module['field_show_profile'] = 'Show on profile pages';
$lang_module['field_type'] = 'Field Type';
$lang_module['field_type_number'] = 'Number';
$lang_module['field_type_date'] = 'Date';
$lang_module['field_type_textbox'] = 'Single-line text box';
$lang_module['field_type_textarea'] = 'Multi-line text box';
$lang_module['field_type_editor'] = 'Editor';
$lang_module['field_type_select'] = 'Drop down selection';
$lang_module['field_type_radio'] = 'Radio Buttons';
$lang_module['field_type_checkbox'] = 'Check Boxes';
$lang_module['field_type_multiselect'] = 'Multiple-choice drop down selection';
$lang_module['field_type_note'] = 'It cannot be changed once set ';
$lang_module['field_class'] = 'Html class form';
$lang_module['field_size'] = 'Size textarea';
$lang_module['field_options_text'] = 'Options for Text Fields';
$lang_module['field_match_type'] = 'Value Match Requirements:<br>Empty values are always allowed.';
$lang_module['field_match_type_none'] = 'none';
$lang_module['field_match_type_alphanumeric'] = 'A-Z, 0-9, and _ only';
$lang_module['field_match_type_url'] = 'Url';
$lang_module['field_match_type_regex'] = 'Regular expression';
$lang_module['field_match_type_callback'] = 'Func callback';
$lang_module['field_default_value'] = 'Default Value';
$lang_module['field_min_length'] = 'Min Length';
$lang_module['field_max_length'] = 'Max Length';
$lang_module['field_min_value'] = 'Min value';
$lang_module['field_max_value'] = 'Max value';
$lang_module['field_options_number'] = 'Options for Number Fields';
$lang_module['field_number_type'] = 'Number Type';
$lang_module['field_integer'] = 'Integer';
$lang_module['field_real'] = 'Real';
$lang_module['field_options_date'] = 'Options for Date Fields';
$lang_module['field_current_date'] = 'Use the current date';
$lang_module['field_default_date'] = 'Default Date';
$lang_module['field_min_date'] = 'Min Date';
$lang_module['field_max_date'] = 'Max Date';
$lang_module['field_options_choice'] = 'Options for Choice Fields';
$lang_module['field_number'] = 'STT';
$lang_module['field_value'] = 'Value';
$lang_module['field_text'] = 'Text';
$lang_module['field_add_choice'] = 'More choices';
$lang_module['field_date_error'] = 'Min date must smaller max day';
$lang_module['field_number_error'] = 'Min value must smaller max value';
$lang_module['field_error_empty'] = 'Field do not empty';
$lang_module['field_error_not_allow'] = 'Field do not allow';
$lang_module['field_error'] = 'Field already exists';
$lang_module['field_match_type_error'] = '%s do not rule';
$lang_module['field_match_type_required'] = '%s require enter';
$lang_module['field_min_max_error'] = '%1$s enter from %2$s to %3$s letter';
$lang_module['field_min_max_value'] = '%1$s enter from %2$s to %3$s';
$lang_module['field_choicetypes_title'] = 'Choose the type of data';
$lang_module['field_choicetypes_sql'] = 'Retrieve data from database';
$lang_module['field_choicetypes_text'] = 'Get data from input';
$lang_module['field_options_choicesql'] = 'Module selection, data tables and data fields';
$lang_module['field_options_choicesql_module'] = 'Select the module';
$lang_module['field_options_choicesql_table'] = 'Select the data table';
$lang_module['field_options_choicesql_column'] = 'Select the column data';
$lang_module['field_options_choicesql_key'] = 'Select columns as key';
$lang_module['field_options_choicesql_val'] = 'Select column as value';
$lang_module['field_sql_choices_empty'] = 'Error: Selection retrieve data from the database is not full';
$lang_module['oauth_config'] = 'Configure login, register width %s';
$lang_module['oauth_client_id'] = 'App ID/API Key';
$lang_module['oauth_client_secret'] = 'Secret code';
$lang_module['import'] = 'Import from excel';
$lang_module['import_note'] = 'To import data from Excel files, you need <a title="Download sample file" href="%1$s" /> download sample file , then fill full data file not exceeding 2,000 per account and upload to folder <b />%2$s';
$lang_module['export'] = 'Export data to excel';
$lang_module['export_example'] = 'Sample file data module users';
$lang_module['required_phpexcel'] = 'To use this function you need to install the PHPExcel library, you can download in <a title="Download PHPExcel" href="http://nukeviet.vn/vi/store/other/phpexcel/">NukeViet Store</a>';
$lang_module['export_comment_userid'] = 'This data should be blank, if you enter this value system will replace the account with corresponding userid';
$lang_module['export_comment_password'] = 'If you do not enter data system will set the default password is the current date';
$lang_module['export_comment_gender'] = 'Accep values: M = Male, F = Female';
$lang_module['export_comment_date'] = 'Enter by: Month / Day / Year or empty';
$lang_module['export_complete'] = 'Export data successfully, you just download and unzip the file to retrieve data';
$lang_module['export_note'] = 'The process of data can occur within a few minutes, please wait until the completion notice';
$lang_module['read_note'] = 'To continue the process of reading the data file, select the file you need then click on the execute button, the data read process can take place within a few minutes, please wait until further notice';
$lang_module['read_submit'] = 'Perform';
$lang_module['read_filename'] = 'File name';
$lang_module['read_filesite'] = 'Size';
$lang_module['read_complete'] = 'Reading data successfully, you want to move to site members list';
$lang_module['read_error'] = 'Error reading file %1$s, the system does not update account: %2$s Name: %3$s. So the system is stopped!';
$lang_module['read_error_field'] = 'Error reading file %1$s, you need to check column: %2$s column should be: %3$s. So the system is stopped!';
$lang_module['read_error_memory_limit'] = 'Error: The system can not read the data, please check your data files only to about 2,000 lines per file or you must configure the php.ini file memory_limit value (128MB read about 2,000 lines)';
$lang_module['read_ignore'] = 'Read the incorrect data standards';
$lang_module['update_field'] = 'Upgrade site';
$lang_module['update_field_oncreate'] = 'Once created';
$lang_module['update_field_onlogin'] = 'Site Update Newsletter';
$lang_module['cas_config'] = 'Set the CAS server';
$lang_module['cas_config_hostname'] = 'Hostname';
$lang_module['cas_config_hostname_info'] = 'Hostname of the CAS server <br />eg: cas.nukeviet.vn';
$lang_module['cas_config_baseUri'] = 'Base URI';
$lang_module['cas_config_baseUri_info'] = 'URI of the server (nothing if no baseUri)<br />For example, if the CAS server responds to cas.nukeviet.vn/cas/ then<br />cas_baseuri = cas/';
$lang_module['cas_config_port'] = 'Port';
$lang_module['cas_config_port_info'] = 'Port of the CAS server';
$lang_module['cas_config_version'] = 'CAS protocol version';
$lang_module['cas_config_version_info'] = 'CAS protocol version to use';
$lang_module['cas_config_language'] = 'Language';
$lang_module['cas_config_language_info'] = 'Select language for authentication pages';
$lang_module['cas_config_proxyMode'] = 'Proxy mode';
$lang_module['cas_config_proxyMode_info'] = 'Select \'yes\' if you use CAS in proxy-mode';
$lang_module['cas_config_multiAuthentication'] = 'Multi-authentication';
$lang_module['cas_config_multiAuthentication_info'] = 'Select \'yes\' if you want to have multi-authentication (CAS + other authentication)';
$lang_module['cas_config_serverValidation'] = 'Server validation';
$lang_module['cas_config_serverValidation_info'] = 'Select \'yes\' if you want to validate the server certificate';
$lang_module['cas_config_certificatePath'] = 'Certificate path';
$lang_module['cas_config_certificatePath_info'] = 'Path of the CA chain file (PEM Format) to validate the server certificate';
$lang_module['ldap_config'] = 'The LDAP server settings';
$lang_module['ldap_config_hostURL'] = 'Host URL';
$lang_module['ldap_config_hostURL_info'] = 'Only the LDAP server in the form URL like \'ldap: //ldap.nukeviet.vn/\' or \'ldaps: //ldap.nukeviet.vn/\'.';
$lang_module['ldap_config_version'] = 'Version';
$lang_module['ldap_config_version_info'] = 'The version of the LDAP protocol your server is being used.';
$lang_module['ldap_config_useTLS'] = 'Use TLS';
$lang_module['ldap_config_useTLS_info'] = 'Use regular LDAP service (port 389) with TLS encryption';
$lang_module['ldap_config_LDAPencoding'] = 'LDAP encoding';
$lang_module['ldap_config_LDAPencoding_info'] = 'Specify encoding used by LDAP server. Most probably utf-8, MS AD v2 uses default platform encoding such as cp1252, cp1250, etc.';
$lang_module['ldap_config_PageSize'] = 'Page Size';
$lang_module['ldap_config_PageSize_info'] = 'Make sure this value is smaller than your LDAP server result set size limit (the maximum number of entries that can be returned in a single query)';
$lang_module['rb_config'] = 'The set binding';
$lang_module['rb_config_dn'] = 'Distinguished name';
$lang_module['rb_config_dn_info'] = 'If you want to use binding the user to identify the user, indicating it here. Sometimes it\'s like \'cn = Manager, dc = NukeViet, dc = VN\'';
$lang_module['rb_config_pw'] = 'Password';
$lang_module['rb_config_pw_info'] = 'Password for the user constraints.';
$lang_module['user_config'] = 'The setup user lookup';
$lang_module['user_config_userType'] = 'User type';
$lang_module['user_config_userType_info'] = 'Choose how users are stored in LDAP. These settings also indicate disable login how to create a user and the activity log will look like.';
$lang_module['user_config_context'] = 'Contexts';
$lang_module['user_config_context_info'] = 'List of the context in which the user is identified. Separating the different contexts by a \';\'. Example : \'ou=people,dc=nukeviet,dc=vn\'';
$lang_module['user_config_searchSubcontexts'] = 'Search subcontexts';
$lang_module['user_config_searchSubcontexts_info'] = 'Put another value 0. If you want to search from context secondary users.';
$lang_module['user_config_dereferenceAliases'] = 'Dereference aliases';
$lang_module['user_config_dereferenceAliases_info'] = 'Decide how many aliases used in the search process. Choose one of the following values: \'No\' (LDAP_DEREF_NEVER) or \'Yes\' (LDAP_DEREF_ALWAYS)';
$lang_module['user_config_userAttribute'] = 'User attribute';
$lang_module['user_config_userAttribute_info'] = 'Options: Override attributes used to indicate / search users. Normally \'cn\'.';
$lang_module['user_config_memberAttribute'] = 'Member attribute';
$lang_module['user_config_memberAttribute_info'] = 'Optional: Override attributes about the user, when the user is related to a group. Usually the \'members\'';
$lang_module['user_config_memberAttributeUsesDn'] = 'Member attribute uses dn';
$lang_module['user_config_memberAttributeUsesDn_info'] = 'Optional: Overrides handling of member attribute values, either 0 or 1';
$lang_module['user_config_objectClass'] = 'Object class';
$lang_module['user_config_objectClass_info'] = 'Optional: Override object class used to specify / search users on the type of user ldap_user_type. Normally you do not need to change this.';
$lang_module['update_LDAP_config'] = 'Updated data from LDAP to website';
$lang_module['update_LDAP_config_name'] = 'First Name';
$lang_module['update_LDAP_config_lname'] = 'Last Name';
$lang_module['default'] = 'Default';
$lang_module['info'] = 'Updated data from LDAP to the website is optional. You can choose to pre-fill some NukeViet user information with information from the <b /> LDAP fields is shown here. <p> <br /> If you leave these fields blank, then no What have been converted from LDAP and the default value of NukeViet will be used to replace <p> <br /> In other cases, users will be able to prepare all This after school starts. <p> <b /> Update site: If enabled, the entry will be updated (from external authentication) each time the user logged in or have synced users. </p> <hr /> <p> <br /> <b /> Note: to update the data you require an external LDAP settings and bindpw binddn to bind a user has the right to edit all User log. Currently it does not preserve multi-valued attributes, and will remove the added value when updating. </p>';
$lang_module['allowuserloginmulti'] = 'Allow user login multi';
$lang_module['user_check_pass_time'] = 'Check pass time';
$lang_module['safe_mode'] = 'Safe mode';
$lang_module['safe_active_info'] = 'Your account is in safe mode, all the features to edit your account information is protected.';
$lang_module['safe_deactivate'] = 'Safe mode turn off'; | gpl-2.0 |
Moergil/MultiBox | MultiBoxClientJavaCore/src/sk/hackcraft/multibox/TestThread.java | 522 | package sk.hackcraft.multibox;
public class TestThread
{
public static void main(String[] args)
{
Runnable testCode = new Runnable()
{
@Override
public void run()
{
for (int i = 0; i < 10000; i++)
{
System.out.println(".");
}
Thread.currentThread().interrupt();
try
{
synchronized (this)
{
wait();
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
};
Thread t = new Thread(testCode);
t.start();
}
}
| gpl-2.0 |
WMFO/rivendell | ripcd/livewire_lwrpaudio.cpp | 7239 | // livewire_lwrpaudio.cpp
//
// A Rivendell LWRP audio switcher driver for LiveWire networks.
//
// (C) Copyright 2002-2013,2016 Fred Gleason <fredg@paravelsystems.com>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
#include <stdlib.h>
#include <rddb.h>
#include <globals.h>
#include <livewire_lwrpaudio.h>
LiveWireLwrpAudio::LiveWireLwrpAudio(RDMatrix *matrix,QObject *parent)
: Switcher(matrix,parent)
{
QString sql;
RDSqlQuery *q;
//
// Get Matrix Parameters
//
livewire_stationname=rdstation->name();
livewire_matrix=matrix->matrix();
//
// Load The Node List
//
sql=QString().sprintf("select HOSTNAME,TCP_PORT,PASSWORD,BASE_OUTPUT \
from SWITCHER_NODES where (STATION_NAME=\"%s\")&&\
(MATRIX=%d)",(const char *)livewire_stationname,
livewire_matrix);
q=new RDSqlQuery(sql);
while(q->next()) {
livewire_nodes.push_back(new RDLiveWire(livewire_nodes.size(),this));
connect(livewire_nodes.back(),SIGNAL(connected(unsigned)),
this,SLOT(nodeConnectedData(unsigned)));
connect(livewire_nodes.back(),
SIGNAL(sourceChanged(unsigned,RDLiveWireSource *)),
this,
SLOT(sourceChangedData(unsigned,RDLiveWireSource *)));
connect(livewire_nodes.back(),
SIGNAL(destinationChanged(unsigned,RDLiveWireDestination *)),
this,
SLOT(destinationChangedData(unsigned,RDLiveWireDestination *)));
/*
connect(livewire_nodes.back(),
SIGNAL(gpoConfigChanged(unsigned,unsigned,unsigned)),
this,
SLOT(gpoConfigChangedData(unsigned,unsigned,unsigned)));
connect(livewire_nodes.back(),
SIGNAL(gpiChanged(unsigned,unsigned,unsigned,bool)),
this,
SLOT(gpiChangedData(unsigned,unsigned,unsigned,bool)));
connect(livewire_nodes.back(),
SIGNAL(gpoChanged(unsigned,unsigned,unsigned,bool)),
this,
SLOT(gpoChangedData(unsigned,unsigned,unsigned,bool)));
*/
connect(livewire_nodes.back(),
SIGNAL(watchdogStateChanged(unsigned,const QString &)),
this,SLOT(watchdogStateChangedData(unsigned,const QString &)));
livewire_nodes.back()->connectToHost(q->value(0).toString(),
q->value(1).toInt(),
q->value(2).toString(),
q->value(3).toUInt());
}
delete q;
}
LiveWireLwrpAudio::~LiveWireLwrpAudio()
{
for(unsigned i=0;i<livewire_nodes.size();i++) {
delete livewire_nodes[i];
}
livewire_nodes.clear();
}
RDMatrix::Type LiveWireLwrpAudio::type()
{
return RDMatrix::LiveWireLwrpAudio;
}
unsigned LiveWireLwrpAudio::gpiQuantity()
{
return 0;
}
unsigned LiveWireLwrpAudio::gpoQuantity()
{
return 0;
}
bool LiveWireLwrpAudio::primaryTtyActive()
{
return false;
}
bool LiveWireLwrpAudio::secondaryTtyActive()
{
return false;
}
void LiveWireLwrpAudio::processCommand(RDMacro *cmd)
{
QString label;
unsigned input;
unsigned output;
RDLiveWire *node=NULL;
RDLiveWire *dest_node=NULL;
switch(cmd->command()) {
case RDMacro::ST:
input=cmd->arg(1).toUInt();
if(input>RD_LIVEWIRE_MAX_SOURCE) {
cmd->acknowledge(false);
emit rmlEcho(cmd);
return;
}
output=cmd->arg(2).toUInt();
if(output>RD_LIVEWIRE_MAX_SOURCE) {
cmd->acknowledge(false);
emit rmlEcho(cmd);
return;
}
//
// Find the destination node
//
for(unsigned i=0;i<livewire_nodes.size();i++) {
node=livewire_nodes[i];
if((output>=node->baseOutput())&&
(output<(node->baseOutput()+node->destinations()))) {
dest_node=node;
}
}
if(dest_node==NULL) { // No such output!
cmd->acknowledge(false);
emit rmlEcho(cmd);
return;
}
dest_node->setRoute(input,output-dest_node->baseOutput());
cmd->acknowledge(true);
emit rmlEcho(cmd);
break;
default:
cmd->acknowledge(false);
emit rmlEcho(cmd);
break;
}
}
void LiveWireLwrpAudio::nodeConnectedData(unsigned id)
{
LogLine(RDConfig::LogInfo,QString().
sprintf("connection established to LiveWire node at \"%s\"",
(const char *)livewire_nodes[id]->hostname()));
}
void LiveWireLwrpAudio::sourceChangedData(unsigned id,RDLiveWireSource *src)
{
QString sql;
RDSqlQuery *q;
sql=QString().sprintf("delete from INPUTS where \
(STATION_NAME=\"%s\")&&\
(MATRIX=%d)&&\
(NODE_HOSTNAME=\"%s\")&&\
(NODE_TCP_PORT=%d)&&\
(NODE_SLOT=%d)",
(const char *)livewire_stationname,
livewire_matrix,
(const char *)livewire_nodes[id]->hostname(),
livewire_nodes[id]->tcpPort(),
src->slotNumber());
q=new RDSqlQuery(sql);
delete q;
if(src->rtpEnabled()) {
sql=QString().sprintf("insert into INPUTS set \
STATION_NAME=\"%s\",\
MATRIX=%d,\
NODE_HOSTNAME=\"%s\",\
NODE_TCP_PORT=%d,\
NODE_SLOT=%d,\
NAME=\"%s\",\
NUMBER=%d",
(const char *)livewire_stationname,
livewire_matrix,
(const char *)livewire_nodes[id]->hostname(),
livewire_nodes[id]->tcpPort(),
src->slotNumber(),
(const char *)src->primaryName(),
src->channelNumber());
q=new RDSqlQuery(sql);
delete q;
}
}
void LiveWireLwrpAudio::destinationChangedData(unsigned id,RDLiveWireDestination *dst)
{
QString sql;
RDSqlQuery *q;
sql=QString().sprintf("delete from OUTPUTS where \
(STATION_NAME=\"%s\")&&\
(MATRIX=%d)&&\
(NODE_HOSTNAME=\"%s\")&&\
(NODE_TCP_PORT=%d)&&\
(NODE_SLOT=%d)",
(const char *)livewire_stationname,
livewire_matrix,
(const char *)livewire_nodes[id]->hostname(),
livewire_nodes[id]->tcpPort(),
dst->slotNumber());
q=new RDSqlQuery(sql);
delete q;
sql=QString().sprintf("insert into OUTPUTS set \
STATION_NAME=\"%s\",\
MATRIX=%d,\
NODE_HOSTNAME=\"%s\",\
NODE_TCP_PORT=%d,\
NODE_SLOT=%d,\
NAME=\"%s\",\
NUMBER=%d",
(const char *)livewire_stationname,
livewire_matrix,
(const char *)livewire_nodes[id]->hostname(),
livewire_nodes[id]->tcpPort(),
dst->slotNumber(),
(const char *)dst->primaryName(),
livewire_nodes[id]->baseOutput()+dst->slotNumber()-1);
q=new RDSqlQuery(sql);
delete q;
}
void LiveWireLwrpAudio::watchdogStateChangedData(unsigned id,const QString &msg)
{
LogLine(RDConfig::LogNotice,msg);
}
| gpl-2.0 |
thebruce/d8-test-junk | drupal-8.x-dev/core/modules/user/lib/Drupal/user/UserInterface.php | 3895 | <?php
/**
* @file
* Contains \Drupal\user\UserInterface.
*/
namespace Drupal\user;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Provides an interface defining a user entity.
*/
interface UserInterface extends EntityInterface, AccountInterface {
/**
* Returns a list of roles.
*
* @return array
* List of role IDs.
*/
public function getRoles();
/**
* Whether a user has a certain role.
*
* @param string $rid
* The role ID to check.
*
* @return bool
* Returns TRUE if the user has the role, otherwise FALSE.
*/
public function hasRole($rid);
/**
* Add a role to a user.
*
* @param string $rid
* The role ID to add.
*/
public function addRole($rid);
/**
* Remove a role from a user.
*
* @param string $rid
* The role ID to remove.
*/
public function removeRole($rid);
/**
* Returns the hashed password.
*
* @return string
* The hashed password.
*/
public function getPassword();
/**
* Sets the user password.
*
* @param string $password
* The new unhashed password.
*/
public function setPassword($password);
/**
* Returns the e-mail address of the user.
*
* @return string
* The e-mail address.
*/
public function getEmail();
/**
* Sets the e-mail address of the user.
*
* @param string $mail
* The new e-mail address of the user.
*/
public function setEmail($mail);
/**
* Returns the default theme of the user.
*
* @return string
* Name of the theme.
*/
public function getDefaultTheme();
/**
* Returns the user signature.
*
* @todo: Convert this to a configurable field.
*
* @return string
* The signature text.
*/
public function getSignature();
/**
* Returns the signature format.
*
* @return string
* Name of the filter format.
*/
public function getSignatureFormat();
/**
* Returns the creation time of the user as a UNIX timestamp.
*
* @return int
* Timestamp of the creation date.
*/
public function getCreatedTime();
/**
* The timestamp when the user last accessed the site.
*
* A value of 0 means the user has never accessed the site.
*
* @return int
* Timestamp of the last access.
*/
public function getLastAccessedTime();
/**
* Sets the UNIX timestamp when the user last accessed the site..
*
* @param int $timestamp
* Timestamp of the last access.
*/
public function setLastAccessTime($timestamp);
/**
* Returns the UNIX timestamp when the user last logged in.
*
* @return int
* Timestamp of the last login time.
*/
public function getLastLoginTime();
/**
* Sets the UNIX timestamp when the user last logged in.
*
* @param int $timestamp
* Timestamp of the last login time.
*/
public function setLastLoginTime($timestamp);
/**
* Returns TRUE if the user is active.
*
* @return bool
* TRUE if the user is active, false otherwise.
*/
public function isActive();
/**
* Returns TRUE if the user is blocked.
*
* @return bool
* TRUE if the user is blocked, false otherwise.
*/
public function isBlocked();
/**
* Activates the user.
*
* @return \Drupal\user\UserInterface
* The called user entity.
*/
public function activate();
/**
* Blocks the user.
*
* @return \Drupal\user\UserInterface
* The called user entity.
*/
public function block();
/**
* Returns the timezone of the user.
*
* @return string
* Name of the timezone.
*/
public function getTimeZone();
/**
* Returns the e-mail that was used when the user was registered.
*
* @return string
* Initial e-mail address of the user.
*/
public function getInitialEmail();
}
| gpl-2.0 |
xkun147/qcvn | wp-content/themes/goodnews5/framework/helpers/js/cats.js | 1124 | //Set up the color pickers to work with our text input field
jQuery( document ).ready(function($){
"use strict";
//jQuery( '.mom_color_picker' ).wpColorPicker();
//upload image
var custom_uploader;
$('#upload_image_button').click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
var attachment = custom_uploader.state().get('selection').first().toJSON();
$('#category_image').val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
}); | gpl-2.0 |
njmube/mixerp | src/Libraries/DAL/Core/GetShippingAddressByShippingAddressIdProcedure.cs | 4031 | // ReSharper disable All
/********************************************************************************
Copyright (C) MixERP Inc. (http://mixof.org).
This file is part of MixERP.
MixERP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2 of the License.
MixERP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MixERP. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
using MixERP.Net.DbFactory;
using MixERP.Net.Framework;
using PetaPoco;
using MixERP.Net.Entities.Core;
using Npgsql;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
namespace MixERP.Net.Schemas.Core.Data
{
/// <summary>
/// Prepares, validates, and executes the function "core.get_shipping_address_by_shipping_address_id(pg_arg0 bigint)" on the database.
/// </summary>
public class GetShippingAddressByShippingAddressIdProcedure : DbAccess
{
/// <summary>
/// The schema of this PostgreSQL function.
/// </summary>
public override string _ObjectNamespace => "core";
/// <summary>
/// The schema unqualified name of this PostgreSQL function.
/// </summary>
public override string _ObjectName => "get_shipping_address_by_shipping_address_id";
/// <summary>
/// Login id of application user accessing this PostgreSQL function.
/// </summary>
public long _LoginId { get; set; }
/// <summary>
/// User id of application user accessing this table.
/// </summary>
public int _UserId { get; set; }
/// <summary>
/// The name of the database on which queries are being executed to.
/// </summary>
public string _Catalog { get; set; }
/// <summary>
/// Maps to "pg_arg0" argument of the function "core.get_shipping_address_by_shipping_address_id".
/// </summary>
public long PgArg0 { get; set; }
/// <summary>
/// Prepares, validates, and executes the function "core.get_shipping_address_by_shipping_address_id(pg_arg0 bigint)" on the database.
/// </summary>
public GetShippingAddressByShippingAddressIdProcedure()
{
}
/// <summary>
/// Prepares, validates, and executes the function "core.get_shipping_address_by_shipping_address_id(pg_arg0 bigint)" on the database.
/// </summary>
/// <param name="pgArg0">Enter argument value for "pg_arg0" parameter of the function "core.get_shipping_address_by_shipping_address_id".</param>
public GetShippingAddressByShippingAddressIdProcedure(long pgArg0)
{
this.PgArg0 = pgArg0;
}
/// <summary>
/// Prepares and executes the function "core.get_shipping_address_by_shipping_address_id".
/// </summary>
public string Execute()
{
if (!this.SkipValidation)
{
if (!this.Validated)
{
this.Validate(AccessTypeEnum.Execute, this._LoginId, false);
}
if (!this.HasAccess)
{
Log.Information("Access to the function \"GetShippingAddressByShippingAddressIdProcedure\" was denied to the user with Login ID {LoginId}.", this._LoginId);
throw new UnauthorizedException("Access is denied.");
}
}
const string query = "SELECT * FROM core.get_shipping_address_by_shipping_address_id(@0::bigint);";
return Factory.Scalar<string>(this._Catalog, query, this.PgArg0);
}
}
} | gpl-2.0 |
alioso/museumfire | modules/contrib/audiofield/js/jplayer.builder.es6.js | 5140 | /**
* @file
* Audiofield build jPlayer audio players of various types.
*/
(($, Drupal) => {
'use strict';
Drupal.AudiofieldJplayer = {};
/**
* Generate a jplayer player for the default single file layout.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {jQuery} settings
* The Drupal settings for this player.
*/
Drupal.AudiofieldJplayer.generate = (context, settings) => {
// Create the media player.
$(`#jquery_jplayer_${settings.unique_id}`, context).once('generate-jplayer').jPlayer(
{
cssSelectorAncestor: `#jp_container_${settings.unique_id}`,
},
{
ready: () => {
const mediaArray = {
title: settings.description,
};
mediaArray[settings.filetype] = settings.file;
$(`#jquery_jplayer_${settings.unique_id}`, context).jPlayer('setMedia', mediaArray);
},
canplay: () => {
// Handle autoplay.
if (!!settings.autoplay) {
$(`#jquery_jplayer_${settings.unique_id}`, context).jPlayer('play');
}
},
swfPath: '/libraries/jplayer/dist/jplayer',
supplied: settings.filetype,
wmode: 'window',
useStateClassSkin: true,
autoBlur: false,
smoothPlayBar: true,
keyEnabled: true,
remainingDuration: false,
toggleDuration: false,
volume: settings.volume,
},
);
};
/**
* Generate a jplayer formatter for a player.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {jQuery} settings
* The Drupal settings for this player.
*/
Drupal.AudiofieldJplayer.generatePlaylist = (context, settings) => {
$.each($(context).find(`#jquery_jplayer_${settings.unique_id}`).once('generate-jplayer'), (index, item) => {
// Initialize the container audio player.
const thisPlaylist = new jPlayerPlaylist({
jPlayer: $(item),
cssSelectorAncestor: `#jp_container_${settings.unique_id}`,
}, [], {
canplay: () => {
// Handle autoplay.
if (!!settings.autoplay) {
$(item).jPlayer('play');
}
},
playlistOptions: {
enableRemoveControls: false,
},
swfPath: '/libraries/jplayer/dist/jplayer',
wmode: 'window',
useStateClassSkin: true,
autoBlur: false,
smoothPlayBar: true,
keyEnabled: true,
volume: settings.volume,
});
// Loop over each file.
$.each(settings.files, (key, fileEntry) => {
// Build the media array.
const mediaArray = {
title: fileEntry.description,
};
mediaArray[fileEntry.filetype] = fileEntry.file;
// Add the file to the playlist.
thisPlaylist.add(mediaArray);
});
});
};
/**
* Generate a jplayer circle player.
*
* @param {jQuery} context
* The Drupal context for which we are finding and generating this player.
* @param {array} file
* The audio file for which we are generating a player.
*/
Drupal.AudiofieldJplayer.generateCircle = (context, file) => {
// Create the media player.
$.each($(context).find(`#jquery_jplayer_${file.fid}`).once('generate-jplayer'), (index, item) => {
// Build the media array for this player.
const mediaArray = {};
mediaArray[file.filetype] = file.file;
// Initialize the player.
new CirclePlayer(
$(item),
mediaArray,
{
cssSelectorAncestor: `#cp_container_${file.fid}`,
canplay: () => {
// Handle autoplay.
if (!!file.autoplay) {
$(item).jPlayer('play');
}
},
swfPath: '/libraries/jplayer/dist/jplayer',
wmode: 'window',
keyEnabled: true,
supplied: file.filetype,
},
);
});
};
/**
* Attach the behaviors to generate the audio player.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches generation of Jplayer audio players.
*/
Drupal.behaviors.audiofieldjplayer = {
attach: (context, settings) => {
$.each(settings.audiofieldjplayer, (key, settingEntry) => {
// Default audio player.
if (settingEntry.playertype === 'default') {
// We can just initialize the audio player direcly.
Drupal.AudiofieldJplayer.generate(context, settingEntry);
}
// Playlist audio player.
else if (settingEntry.playertype === 'playlist') {
Drupal.AudiofieldJplayer.generatePlaylist(context, settingEntry);
}
// Circle audio player.
else if (settingEntry.playertype === 'circle') {
// Loop over the files.
$.each(settingEntry.files, (key2, fileEntry) => {
// Create the player.
Drupal.AudiofieldJplayer.generateCircle(context, fileEntry);
});
}
});
},
};
})(jQuery, Drupal);
| gpl-2.0 |
tharindum/opennms_dashboard | integrations/opennms-link-provisioning-adapter/src/main/java/org/opennms/netmgt/provision/adapters/link/endpoint/EndPointTypeValidator.java | 4010 | /*******************************************************************************
* This file is part of OpenNMS(R).
*
* Copyright (C) 2009-2011 The OpenNMS Group, Inc.
* OpenNMS(R) is Copyright (C) 1999-2011 The OpenNMS Group, Inc.
*
* OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
*
* OpenNMS(R) is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* OpenNMS(R) is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenNMS(R). If not, see:
* http://www.gnu.org/licenses/
*
* For more information contact:
* OpenNMS(R) Licensing <license@opennms.org>
* http://www.opennms.org/
* http://www.opennms.com/
*******************************************************************************/
/**
* <p>EndPointTypeValidator class.</p>
*
* @author ranger
* @version $Id: $
*/
package org.opennms.netmgt.provision.adapters.link.endpoint;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.opennms.netmgt.provision.adapters.link.EndPoint;
import org.opennms.netmgt.provision.adapters.link.EndPointStatusException;
@XmlRootElement(name="endpoint-types")
public class EndPointTypeValidator {
@XmlAttribute(name="endpoint-service-name")
String m_endPointServiceName = "EndPoint";
@XmlElement(name="endpoint-type")
List<EndPointType> m_endPointConfigs = Collections.synchronizedList(new ArrayList<EndPointType>());
/**
* <p>Constructor for EndPointTypeValidator.</p>
*/
public EndPointTypeValidator() {
}
/**
* <p>getServiceName</p>
*
* @return a {@link java.lang.String} object.
*/
public String getServiceName() {
return m_endPointServiceName;
}
/**
* <p>setServiceName</p>
*
* @param serviceName a {@link java.lang.String} object.
*/
public void setServiceName(String serviceName) {
m_endPointServiceName = serviceName;
}
/**
* <p>getConfigs</p>
*
* @return a {@link java.util.List} object.
*/
public List<EndPointType> getConfigs() {
return m_endPointConfigs;
}
/**
* <p>setConfigs</p>
*
* @param configs a {@link java.util.List} object.
*/
public void setConfigs(List<EndPointType> configs) {
synchronized(m_endPointConfigs) {
m_endPointConfigs.clear();
m_endPointConfigs.addAll(configs);
}
}
/**
* <p>hasMatch</p>
*
* @param ep a {@link org.opennms.netmgt.provision.adapters.link.EndPoint} object.
* @return a boolean.
*/
public boolean hasMatch(EndPoint ep) {
for (EndPointType config : m_endPointConfigs) {
if (config.matches(ep)) {
return true;
}
}
return false;
}
/**
* <p>validate</p>
*
* @param ep a {@link org.opennms.netmgt.provision.adapters.link.EndPoint} object.
* @throws org.opennms.netmgt.provision.adapters.link.EndPointStatusException if any.
*/
public void validate(EndPoint ep) throws EndPointStatusException {
for (EndPointType config : m_endPointConfigs) {
if (config.matches(ep)) {
config.validate(ep);
return;
}
}
throw new EndPointStatusException(String.format("unable to find matching endpoint type config for endpoint %s", ep));
}
}
| gpl-2.0 |
ldoktor/virt-test | kvm/tests/timedrift_with_migration.py | 3935 | import logging
from autotest.client.shared import error
from virttest import utils_test
def run_timedrift_with_migration(test, params, env):
"""
Time drift test with migration:
1) Log into a guest.
2) Take a time reading from the guest and host.
3) Migrate the guest.
4) Take a second time reading.
5) If the drift (in seconds) is higher than a user specified value, fail.
@param test: KVM test object.
@param params: Dictionary with test parameters.
@param env: Dictionary with the test environment.
"""
vm = env.get_vm(params["main_vm"])
vm.verify_alive()
timeout = int(params.get("login_timeout", 360))
session = vm.wait_for_login(timeout=timeout)
# Collect test parameters:
# Command to run to get the current time
time_command = params.get("time_command")
# Filter which should match a string to be passed to time.strptime()
time_filter_re = params.get("time_filter_re")
# Time format for time.strptime()
time_format = params.get("time_format")
drift_threshold = float(params.get("drift_threshold", "10"))
drift_threshold_single = float(params.get("drift_threshold_single", "3"))
migration_iterations = int(params.get("migration_iterations", 1))
try:
# Get initial time
# (ht stands for host time, gt stands for guest time)
(ht0, gt0) = utils_test.get_time(session, time_command,
time_filter_re, time_format)
# Migrate
for i in range(migration_iterations):
# Get time before current iteration
(ht0_, gt0_) = utils_test.get_time(session, time_command,
time_filter_re, time_format)
session.close()
# Run current iteration
logging.info("Migrating: iteration %d of %d...",
(i + 1), migration_iterations)
vm.migrate()
# Log in
logging.info("Logging in after migration...")
session = vm.wait_for_login(timeout=30)
logging.info("Logged in after migration")
# Get time after current iteration
(ht1_, gt1_) = utils_test.get_time(session, time_command,
time_filter_re, time_format)
# Report iteration results
host_delta = ht1_ - ht0_
guest_delta = gt1_ - gt0_
drift = abs(host_delta - guest_delta)
logging.info("Host duration (iteration %d): %.2f",
(i + 1), host_delta)
logging.info("Guest duration (iteration %d): %.2f",
(i + 1), guest_delta)
logging.info("Drift at iteration %d: %.2f seconds",
(i + 1), drift)
# Fail if necessary
if drift > drift_threshold_single:
raise error.TestFail("Time drift too large at iteration %d: "
"%.2f seconds" % (i + 1, drift))
# Get final time
(ht1, gt1) = utils_test.get_time(session, time_command,
time_filter_re, time_format)
finally:
if session:
session.close()
# Report results
host_delta = ht1 - ht0
guest_delta = gt1 - gt0
drift = abs(host_delta - guest_delta)
logging.info("Host duration (%d migrations): %.2f",
migration_iterations, host_delta)
logging.info("Guest duration (%d migrations): %.2f",
migration_iterations, guest_delta)
logging.info("Drift after %d migrations: %.2f seconds",
migration_iterations, drift)
# Fail if necessary
if drift > drift_threshold:
raise error.TestFail("Time drift too large after %d migrations: "
"%.2f seconds" % (migration_iterations, drift))
| gpl-2.0 |
ghodder/pdnsmgr | vendor/autoload.php | 183 | <?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer' . '/autoload_real.php';
return ComposerAutoloaderInit0df268a22953d0c7bfb76d6d1b5a826d::getLoader();
| gpl-2.0 |
prasadtalasila/MMTP | Main/Database/cleaningdata/updated/label.py | 401 | #Sort data according to departure time
from operator import itemgetter
L = []
line = []
for _ in xrange(47377):
line = raw_input().split(" ")
L.append([(line[0]),int(line[1]),int(line[2]),int(line[3]),int(line[4])])
temp = []
for item in L:
if len(item[0])==5:
print item[0],item[1],item[2],item[3],item[4],"train"
elif len(item[0])>5:
print item[0],item[1],item[2],item[3],item[4],"flight"
| gpl-2.0 |
IE-LN/HMCOM | wp-content/themes/holly/widgets/templates/gallery-cgo.sidebar.php | 1958 | <?php
$func = function_exists('ice_get_attachment_image') ? 'ice_get_attachment_image' : 'wp_get_attachment_image';
?>
<?php $before_widget ?>
<div class="bmsbw-container bmsbw-gallery-sidebar <?php $instance['css_container_class'] ?>">
<div class="bmsbw-photoHead">
<?php wp_nav_menu(array('theme_location' => 'hot-photos-widget-filters')); ?>
<?php $before_title ?><span class="bmsbw-title"><?php $instance['widget_title']?></span><?php $after_title ?>
<div class="clear"></div>
<?php /*
<ul class="bmsbw-sub-nav-links menu right">
<li><a href="/photos/hot-bodies/">HOT BODIES</a></li>
<li><a href="/photos/sightings/">SIGHTINGS</a></li>
<li><a href="/photos/">RECENT</a></li>
</ul>
<div class="clear"></div>
*/ ?>
</div>
<div class="bmsbw-inside blackmaroon">
<div class="bmsbw-inside-inner">
<table>
<tbody>
<?php
$per_row = 3;
global $post;
foreach ($posts as $ind => $post):
setup_postdata($post);
if ($ind != 0 && $ind % $per_row == 0):
?></tr><?php
endif;
if ($ind != count($posts) - 1 && $ind % $per_row == 0):
?><tr class="bmsbw-post-list"><?php
endif;
$img = $func($post->_thumb_id, array(94, 94));
$perma = get_permalink();
?>
<td class="bmsbw-gallery-image-block">
<?php if ($img): ?>
<div class="bmsbw-valign-fix-image bmsbw-94x94-keyhole"><a href="<?php $perma ?>" title="Read More"
class="bmsbw-image-keyhole"><?php $img ?></a></div>
<?php endif; ?>
<div class="bmsbw-title-fix"><h2><a href="<?php $perma ?>" title="Read More"><?php the_title() ?></a></h2></div>
</td>
<?php
endforeach;
?>
</tr>
</tbody>
</table>
</div>
</div>
<div class="bmsbw-bottom blue">
<a class="see-more" href="<?php home_url()?>/photos/">See All Photos »</a>
<div class="clear"></div>
</div>
</div>
<?php $after_widget ?>
| gpl-2.0 |
cidesa/roraima | apps/nomina/modules/asignarcategoriasconceptosxempleado/templates/editSuccess.php | 1083 | <?php
/**
* Funciones de la vista.
*
* @package Roraima
* @subpackage vistas
* @author $Author$ <desarrollo@cidesa.com.ve>
* @version SVN: $Id$
*/
// date: 2007/12/28 10:23:00
?>
<?php use_helper('Object', 'Validation', 'ObjectAdmin', 'I18N', 'Date') ?>
<?php use_stylesheet('/sf/sf_admin/css/main') ?>
<div id="sf_admin_container">
<h1><?php echo __('Asignación de Categorias por Empleados',
array()) ?></h1>
<div id="sf_admin_header">
<?php include_partial('asignarcategoriasconceptosxempleado/edit_header', array('npasicatconemp' => $npasicatconemp)) ?>
</div>
<div id="sf_admin_content">
<?php include_partial('asignarcategoriasconceptosxempleado/edit_messages', array('npasicatconemp' => $npasicatconemp, 'labels' => $labels)) ?>
<?php include_partial('asignarcategoriasconceptosxempleado/edit_form', array('npasicatconemp' => $npasicatconemp, 'labels' => $labels, 'obj' => $obj)) ?>
</div>
<div id="sf_admin_footer">
<?php include_partial('asignarcategoriasconceptosxempleado/edit_footer', array('npasicatconemp' => $npasicatconemp)) ?>
</div>
</div>
| gpl-2.0 |
bugcy013/opennms-tmp-tools | features/instrumentationLogReader/src/main/java/org/opennms/util/ilr/Filter.java | 8150 | package org.opennms.util.ilr;
import java.util.ArrayList;
import java.util.Collection;
public class Filter {
private static String m_searchString = null;
public static interface PropertyGetter<T> {
T get(ServiceCollector c);
}
static PropertyGetter<String> serviceID() {
return new PropertyGetter<String>() {
public String get(ServiceCollector c) {
return c.getServiceID();
}
};
}
static PropertyGetter<Integer> collectionCount() {
return new PropertyGetter<Integer>() {
public Integer get(ServiceCollector c) {
return c.getCollectionCount();
}
};
}
static Predicate<ServiceCollector> and(final Predicate<ServiceCollector> a, final Predicate<ServiceCollector> b) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return a.apply(svcCollector) && b.apply(svcCollector);
}
};
}
static Predicate<ServiceCollector> or(final Predicate<ServiceCollector> a, final Predicate<ServiceCollector> b) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return a.apply(svcCollector) || b.apply(svcCollector);
}
};
}
static <T> Predicate<ServiceCollector> eq(final PropertyGetter<T> getter, final T val) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return getter.get(svcCollector).equals(val);
}
};
}
static Predicate<ServiceCollector> greaterThan(final PropertyGetter<Integer> getter, final Integer val) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return getter.get(svcCollector) > val;
}
};
}
static Predicate<ServiceCollector> lessThan(final PropertyGetter<Integer> getter, final Integer val) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return getter.get(svcCollector) < val;
}
};
}
static Predicate<ServiceCollector> byServiceID(final String serviceID) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getServiceID().equals(serviceID);
}
};
}
static Predicate<ServiceCollector> byPartialServiceID(final String searchString) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector){
return svcCollector.getServiceID().contains(searchString);
}
};
}
static Predicate<ServiceCollector> byTotalCollections(final long totalCollections) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getCollectionCount() == totalCollections;
}
};
}
static Predicate<ServiceCollector> byTotalCollectionTime(final long totalCollectionTime) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getCollectionCount() == totalCollectionTime;
}
};
}
static Predicate<ServiceCollector> byAverageCollectionTime(final long averageCollectionTime) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getCollectionCount() == averageCollectionTime;
}
};
}
static Predicate<ServiceCollector> byAverageTimeBetweenCollections(final long averageTimeBetweenCollections) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getCollectionCount() == averageTimeBetweenCollections;
}
};
}
static Predicate<ServiceCollector> byTotalSuccessfulCollections(final long totalSuccessfulCollections) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getCollectionCount() == totalSuccessfulCollections;
}
};
}
static Predicate<ServiceCollector> bySuccessfulPercentage(final double successfulPercentage) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getCollectionCount() == successfulPercentage;
}
};
}
static Predicate<ServiceCollector> byAverageSuccessfulCollectionTime(final long averageSuccessfulCollectionTime) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getCollectionCount() == averageSuccessfulCollectionTime;
}
};
}
static Predicate<ServiceCollector> byTotalUnsuccessfulCollections(final long totalUnsuccessfulCollections) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getCollectionCount() == totalUnsuccessfulCollections;
}
};
}
static Predicate<ServiceCollector> byUnsuccessfulPercentage(final double unsuccessfulPercentage) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getCollectionCount() == unsuccessfulPercentage;
}
};
}
static Predicate<ServiceCollector> byAverageUnsuccessfulCollectionTime(final long averageUnsuccessfulCollectionTime) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getCollectionCount() == averageUnsuccessfulCollectionTime;
}
};
}
static Predicate<ServiceCollector> byTotalPersistTime(final long totalPersistTime) {
return new Predicate<ServiceCollector>() {
public boolean apply(ServiceCollector svcCollector) {
return svcCollector.getCollectionCount() == totalPersistTime;
}
};
}
public Predicate<Integer> createIntegerBasedPredicate(final int j) {
Predicate<Integer> predicate = new Predicate<Integer>() {
public boolean apply(Integer i) {
if(i == j){
return true;
}else{
return false;
}
}
};
return predicate;
}
public Predicate<String> createStringBasedPredicate(final String filterString) {
Predicate<String> predicate = new Predicate<String>() {
public boolean apply(String s) {
if(s.equals(filterString)){
return true;
}else {
return false;
}
}
};
return predicate;
}
static public <T> Collection<T> filter(Collection<T> target, Predicate<T> predicate) {
Collection<T> filteredCollection = new ArrayList<T>();
for (T t : target) {
if (predicate.apply(t)) {
filteredCollection.add(t);
}
}
return filteredCollection;
}
public interface Predicate<T> {
public boolean apply(T type);
}
public static void setSearchString(String searchString) {
m_searchString = searchString;
}
public static String getSearchString() {
return m_searchString;
}
}
| gpl-2.0 |
tectronics/scummvm-for-sally | engines/sword1/control.cpp | 47578 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* $URL: https://scummvm.svn.sourceforge.net/svnroot/scummvm/scummvm/tags/release-1-1-1/engines/sword1/control.cpp $
* $Id: control.cpp 45616 2009-11-02 21:54:57Z fingolfin $
*
*/
#include "common/file.h"
#include "common/util.h"
#include "common/savefile.h"
#include "common/events.h"
#include "common/system.h"
#include "common/config-manager.h"
#include "graphics/thumbnail.h"
#include "gui/message.h"
#include "sword1/control.h"
#include "sword1/logic.h"
#include "sword1/mouse.h"
#include "sword1/music.h"
#include "sword1/objectman.h"
#include "sword1/resman.h"
#include "sword1/sound.h"
#include "sword1/sword1.h"
#include "sword1/sworddefs.h"
#include "sword1/swordres.h"
#include "sword1/screen.h"
namespace Sword1 {
enum LangStrings {
STR_PAUSED = 0,
STR_INSERT_CD_A,
STR_INSERT_CD_B,
STR_INCORRECT_CD,
STR_SAVE,
STR_RESTORE,
STR_RESTART,
STR_START,
STR_QUIT,
STR_SPEED,
STR_VOLUME,
STR_TEXT,
STR_DONE,
STR_OK,
STR_CANCEL,
STR_MUSIC,
STR_SPEECH,
STR_FX,
STR_THE_END,
STR_DRIVE_FULL
};
enum ButtonIds {
BUTTON_DONE = 1,
BUTTON_MAIN_PANEL,
BUTTON_SAVE_PANEL,
BUTTON_RESTORE_PANEL,
BUTTON_RESTART,
BUTTON_QUIT,
BUTTON_SPEED,
BUTTON_VOLUME_PANEL,
BUTTON_TEXT,
BUTTON_CONFIRM,
//-
BUTTON_SCROLL_UP_FAST,
BUTTON_SCROLL_UP_SLOW,
BUTTON_SCROLL_DOWN_SLOW,
BUTTON_SCROLL_DOWN_FAST,
BUTTON_SAVE_SELECT1,
BUTTON_SAVE_SELECT2,
BUTTON_SAVE_SELECT3,
BUTTON_SAVE_SELECT4,
BUTTON_SAVE_SELECT5,
BUTTON_SAVE_SELECT6,
BUTTON_SAVE_SELECT7,
BUTTON_SAVE_SELECT8,
BUTTON_SAVE_RESTORE_OKAY,
BUTTON_SAVE_CANCEL,
//-
CONFIRM_OKAY,
CONFIRM_CANCEL
};
enum TextModes {
TEXT_LEFT_ALIGN = 0,
TEXT_CENTER,
TEXT_RIGHT_ALIGN,
TEXT_RED_FONT = 128
};
ControlButton::ControlButton(uint16 x, uint16 y, uint32 resId, uint8 id, uint8 flag, ResMan *pResMan, uint8 *screenBuf, OSystem *system) {
_x = x;
_y = y;
_id = id;
_flag = flag;
_resId = resId;
_resMan = pResMan;
_frameIdx = 0;
_resMan->resOpen(_resId);
FrameHeader *tmp = _resMan->fetchFrame(_resMan->fetchRes(_resId), 0);
_width = _resMan->getUint16(tmp->width);
_width = (_width > SCREEN_WIDTH) ? SCREEN_WIDTH : _width;
_height = _resMan->getUint16(tmp->height);
if ((x == 0) && (y == 0)) { // center the frame (used for panels);
_x = (((640 - _width) / 2) < 0)? 0 : ((640 - _width) / 2) ;
_y = (((480 - _height) / 2) < 0)? 0 : ((480 - _height) / 2);
}
_dstBuf = screenBuf + _y * SCREEN_WIDTH + _x;
_system = system;
}
ControlButton::~ControlButton() {
_resMan->resClose(_resId);
}
bool ControlButton::isSaveslot() {
return ((_resId >= SR_SLAB1) && (_resId <= SR_SLAB4));
}
void ControlButton::draw() {
FrameHeader *fHead = _resMan->fetchFrame(_resMan->fetchRes(_resId), _frameIdx);
uint8 *src = (uint8*)fHead + sizeof(FrameHeader);
uint8 *dst = _dstBuf;
if (SwordEngine::isPsx() && _resId) {
uint8 *HIFbuf = (uint8*)malloc(_resMan->readUint16(&fHead->height) * _resMan->readUint16(&fHead->width));
memset(HIFbuf, 0, _resMan->readUint16(&fHead->height) * _resMan->readUint16(&fHead->width));
Screen::decompressHIF(src, HIFbuf);
src = HIFbuf;
if (_resMan->readUint16(&fHead->width) < 300)
for (uint16 cnt = 0; cnt < _resMan->readUint16(&fHead->height); cnt++) {
for (uint16 cntx = 0; cntx < _resMan->readUint16(&fHead->width); cntx++)
if (src[cntx])
dst[cntx] = src[cntx];
dst += SCREEN_WIDTH;
for (uint16 cntx = 0; cntx < _resMan->readUint16(&fHead->width); cntx++)
if (src[cntx])
dst[cntx] = src[cntx];
dst += SCREEN_WIDTH;
src += _resMan->readUint16(&fHead->width);
}
else if (_resId == SR_DEATHPANEL) { // Check for death panel psx version (which is 1/3 of original width)
for (uint16 cnt = 0; cnt < _resMan->readUint16(&fHead->height)/2; cnt++) {
//Stretched panel is bigger than 640px, check we don't draw outside screen
for (uint16 cntx = 0; (cntx < (_resMan->readUint16(&fHead->width))/3) && (cntx < (SCREEN_WIDTH-3) ); cntx++)
if (src[cntx]) {
dst[cntx * 3] = src[cntx];
dst[cntx * 3 + 1] = src[cntx];
dst[cntx * 3 + 2] = src[cntx];
}
dst+= SCREEN_WIDTH;
for (uint16 cntx = 0; cntx < (_resMan->readUint16(&fHead->width))/3; cntx++)
if (src[cntx]) {
dst[cntx * 3] = src[cntx];
dst[cntx * 3 + 1] = src[cntx];
dst[cntx * 3 + 2] = src[cntx];
}
dst += SCREEN_WIDTH;
src += _resMan->readUint16(&fHead->width)/3;
}
} else { //save slots needs to be multiplied by 2 in height
for (uint16 cnt = 0; cnt < _resMan->readUint16(&fHead->height); cnt++) {
for (uint16 cntx = 0; cntx < _resMan->readUint16(&fHead->width) / 2; cntx++)
if (src[cntx]) {
dst[cntx * 2] = src[cntx];
dst[cntx * 2 + 1] = src[cntx];
}
dst += SCREEN_WIDTH;
for (uint16 cntx = 0; cntx < _resMan->readUint16(&fHead->width) / 2; cntx++)
if (src[cntx]) {
dst[cntx * 2] = src[cntx];
dst[cntx * 2 + 1] = src[cntx];
}
dst += SCREEN_WIDTH;
src += _resMan->readUint16(&fHead->width)/2;
}
}
free(HIFbuf);
} else
for (uint16 cnt = 0; cnt < _resMan->readUint16(&fHead->height); cnt++) {
for (uint16 cntx = 0; cntx < _resMan->readUint16(&fHead->width); cntx++)
if (src[cntx])
dst[cntx] = src[cntx];
dst += SCREEN_WIDTH;
src += _resMan->readUint16(&fHead->width);
}
_system->copyRectToScreen(_dstBuf, SCREEN_WIDTH, _x, _y, _width, _height);
}
bool ControlButton::wasClicked(uint16 mouseX, uint16 mouseY) {
if ((_x <= mouseX) && (_y <= mouseY) && (_x + _width >= mouseX) && (_y + _height >= mouseY))
return true;
else
return false;
}
void ControlButton::setSelected(uint8 selected) {
_frameIdx = selected;
draw();
}
Control::Control(Common::SaveFileManager *saveFileMan, ResMan *pResMan, ObjectMan *pObjMan, OSystem *system, Mouse *pMouse, Sound *pSound, Music *pMusic) {
_saveFileMan = saveFileMan;
_resMan = pResMan;
_objMan = pObjMan;
_system = system;
_mouse = pMouse;
_music = pMusic;
_sound = pSound;
_lStrings = _languageStrings + SwordEngine::_systemVars.language * 20;
_selectedButton = 255;
_panelShown = false;
}
void Control::askForCd() {
_screenBuf = (uint8*)malloc(640 * 480);
uint32 fontId = SR_FONT;
if (SwordEngine::_systemVars.language == BS1_CZECH)
fontId = CZECH_SR_FONT;
_font = (uint8*)_resMan->openFetchRes(fontId);
uint8 *pal = (uint8*)_resMan->openFetchRes(SR_PALETTE);
uint8 *palOut = (uint8*)malloc(256 * 4);
for (uint16 cnt = 1; cnt < 256; cnt++) {
palOut[cnt * 4 + 0] = pal[cnt * 3 + 0] << 2;
palOut[cnt * 4 + 1] = pal[cnt * 3 + 1] << 2;
palOut[cnt * 4 + 2] = pal[cnt * 3 + 2] << 2;
}
palOut[0] = palOut[1] = palOut[2] = palOut[3] = 0;
_resMan->resClose(SR_PALETTE);
_system->setPalette(palOut, 0, 256);
free(palOut);
char fName[10];
uint8 textA[50];
sprintf(fName, "cd%d.id", SwordEngine::_systemVars.currentCD);
sprintf((char*)textA, "%s%d", _lStrings[STR_INSERT_CD_A], SwordEngine::_systemVars.currentCD);
bool notAccepted = true;
bool refreshText = true;
do {
if (refreshText) {
memset(_screenBuf, 0, 640 * 480);
renderText(textA, 320, 220, TEXT_CENTER);
renderText(_lStrings[STR_INSERT_CD_B], 320, 240, TEXT_CENTER);
_system->copyRectToScreen(_screenBuf, 640, 0, 0, 640, 480);
}
delay(300);
if (_keyPressed.keycode) {
if (!Common::File::exists(fName)) {
memset(_screenBuf, 0, 640 * 480);
renderText(_lStrings[STR_INCORRECT_CD], 320, 230, TEXT_CENTER);
_system->copyRectToScreen(_screenBuf, 640, 0, 0, 640, 480);
delay(2000);
refreshText = true;
} else {
notAccepted = false;
}
}
} while (notAccepted && (!Engine::shouldQuit()));
_resMan->resClose(fontId);
free(_screenBuf);
}
static int volToBalance(int volL, int volR) {
if (volL + volR == 0) {
return 50;
} else {
return (100 * volL / (volL + volR));
}
}
uint8 Control::runPanel() {
_panelShown = true;
_mouseDown = false;
_restoreBuf = NULL;
_keyPressed.reset();
_numButtons = 0;
_screenBuf = (uint8*)malloc(640 * 480);
memset(_screenBuf, 0, 640 * 480);
_system->copyRectToScreen(_screenBuf, 640, 0, 0, 640, 480);
_sound->quitScreen();
uint32 fontId = SR_FONT, redFontId = SR_REDFONT;
if (SwordEngine::_systemVars.language == BS1_CZECH) {
fontId = CZECH_SR_FONT;
redFontId = CZECH_SR_REDFONT;
}
_font = (uint8*)_resMan->openFetchRes(fontId);
_redFont = (uint8*)_resMan->openFetchRes(redFontId);
uint8 *pal = (uint8*)_resMan->openFetchRes(SR_PALETTE);
uint8 *palOut = (uint8*)malloc(256 * 4);
for (uint16 cnt = 1; cnt < 256; cnt++) {
palOut[cnt * 4 + 0] = pal[cnt * 3 + 0] << 2;
palOut[cnt * 4 + 1] = pal[cnt * 3 + 1] << 2;
palOut[cnt * 4 + 2] = pal[cnt * 3 + 2] << 2;
}
palOut[0] = palOut[1] = palOut[2] = palOut[3] = 0;
_resMan->resClose(SR_PALETTE);
_system->setPalette(palOut, 0, 256);
free(palOut);
uint8 mode = 0, newMode = BUTTON_MAIN_PANEL;
bool fullRefresh = false;
_mouse->controlPanel(true);
uint8 retVal = CONTROL_NOTHING_DONE;
_music->startMusic(61, 1);
do {
if (newMode) {
mode = newMode;
fullRefresh = true;
destroyButtons();
memset(_screenBuf, 0, 640 * 480);
if (mode != BUTTON_SAVE_PANEL)
_cursorVisible = false;
}
switch (mode) {
case BUTTON_MAIN_PANEL:
if (fullRefresh)
setupMainPanel();
break;
case BUTTON_SAVE_PANEL:
if (fullRefresh) {
setupSaveRestorePanel(true);
}
if (_selectedSavegame < 255) {
_system->setFeatureState(OSystem::kFeatureVirtualKeyboard, true);
bool visible = _cursorVisible;
_cursorTick++;
if (_cursorTick == 7)
_cursorVisible = true;
else if (_cursorTick == 14) {
_cursorVisible = false;
_cursorTick = 0;
}
if (_keyPressed.keycode)
handleSaveKey(_keyPressed);
else if (_cursorVisible != visible)
showSavegameNames();
} else {
_system->setFeatureState(OSystem::kFeatureVirtualKeyboard, false);
}
break;
case BUTTON_RESTORE_PANEL:
if (fullRefresh)
setupSaveRestorePanel(false);
break;
case BUTTON_VOLUME_PANEL:
if (fullRefresh)
setupVolumePanel();
break;
default:
break;
}
if (fullRefresh) {
fullRefresh = false;
_system->copyRectToScreen(_screenBuf, SCREEN_WIDTH, 0, 0, SCREEN_WIDTH, 480);
}
delay(1000 / 12);
newMode = getClicks(mode, &retVal);
} while ((newMode != BUTTON_DONE) && (retVal == 0) && (!Engine::shouldQuit()));
if (SwordEngine::_systemVars.controlPanelMode == CP_NORMAL) {
uint8 volL, volR;
_music->giveVolume(&volL, &volR);
ConfMan.setInt("music_volume", (int)((volR + volL) / 2));
ConfMan.setInt("music_balance", volToBalance(volL, volR));
_sound->giveSpeechVol(&volL, &volR);
ConfMan.setInt("speech_volume", (int)((volR + volL) / 2));
ConfMan.setInt("speech_balance", volToBalance(volL, volR));
_sound->giveSfxVol(&volL, &volR);
ConfMan.setInt("sfx_volume", (int)((volR + volL) / 2));
ConfMan.setInt("sfx_balance", volToBalance(volL, volR));
ConfMan.setBool("subtitles", SwordEngine::_systemVars.showText == 1);
ConfMan.flushToDisk();
}
destroyButtons();
_resMan->resClose(fontId);
_resMan->resClose(redFontId);
memset(_screenBuf, 0, 640 * 480);
_system->copyRectToScreen(_screenBuf, 640, 0, 0, 640, 480);
free(_screenBuf);
_mouse->controlPanel(false);
// Can also be used to end the control panel music.
_music->startMusic(Logic::_scriptVars[CURRENT_MUSIC], 1);
_sound->newScreen(Logic::_scriptVars[SCREEN]);
_panelShown = false;
return retVal;
}
uint8 Control::getClicks(uint8 mode, uint8 *retVal) {
uint8 checkButtons = _numButtons;
if (mode == BUTTON_VOLUME_PANEL) {
handleVolumeClicks();
checkButtons = 1;
}
uint8 flag = 0;
if (_keyPressed.keycode == Common::KEYCODE_ESCAPE)
flag = kButtonCancel;
else if (_keyPressed.keycode == Common::KEYCODE_RETURN || _keyPressed.keycode == Common::KEYCODE_KP_ENTER)
flag = kButtonOk;
if (flag) {
for (uint8 cnt = 0; cnt < checkButtons; cnt++)
if (_buttons[cnt]->_flag == flag)
return handleButtonClick(_buttons[cnt]->_id, mode, retVal);
}
if (!_mouseState)
return 0;
if (_mouseState & BS1L_BUTTON_DOWN)
for (uint8 cnt = 0; cnt < checkButtons; cnt++)
if (_buttons[cnt]->wasClicked(_mouseCoord.x, _mouseCoord.y)) {
_selectedButton = cnt;
_buttons[cnt]->setSelected(1);
if (_buttons[cnt]->isSaveslot())
showSavegameNames();
}
if (_mouseState & BS1L_BUTTON_UP) {
for (uint8 cnt = 0; cnt < checkButtons; cnt++)
if (_buttons[cnt]->wasClicked(_mouseCoord.x, _mouseCoord.y))
if (_selectedButton == cnt) {
// saveslots stay selected after clicking
if (!_buttons[cnt]->isSaveslot())
_buttons[cnt]->setSelected(0);
_selectedButton = 255;
return handleButtonClick(_buttons[cnt]->_id, mode, retVal);
}
if (_selectedButton < checkButtons) {
_buttons[_selectedButton]->setSelected(0);
if (_buttons[_selectedButton]->isSaveslot())
showSavegameNames();
}
_selectedButton = 255;
}
if (_mouseState & BS1_WHEEL_UP) {
for (uint8 cnt = 0; cnt < checkButtons; cnt++)
if (_buttons[cnt]->_id == BUTTON_SCROLL_UP_SLOW)
return handleButtonClick(_buttons[cnt]->_id, mode, retVal);
}
if (_mouseState & BS1_WHEEL_DOWN) {
for (uint8 cnt = 0; cnt < checkButtons; cnt++)
if (_buttons[cnt]->_id == BUTTON_SCROLL_DOWN_SLOW)
return handleButtonClick(_buttons[cnt]->_id, mode, retVal);
}
return 0;
}
uint8 Control::handleButtonClick(uint8 id, uint8 mode, uint8 *retVal) {
switch (mode) {
case BUTTON_MAIN_PANEL:
if (id == BUTTON_RESTART) {
if (SwordEngine::_systemVars.controlPanelMode) // if player is dead or has just started, don't ask for confirmation
*retVal |= CONTROL_RESTART_GAME;
else if (getConfirm(_lStrings[STR_RESTART]))
*retVal |= CONTROL_RESTART_GAME;
else
return mode;
} else if ((id == BUTTON_RESTORE_PANEL) || (id == BUTTON_SAVE_PANEL) ||
(id == BUTTON_DONE) || (id == BUTTON_VOLUME_PANEL))
return id;
else if (id == BUTTON_TEXT) {
SwordEngine::_systemVars.showText ^= 1;
_buttons[5]->setSelected(SwordEngine::_systemVars.showText);
} else if (id == BUTTON_QUIT) {
if (getConfirm(_lStrings[STR_QUIT]))
Engine::quitGame();
return mode;
}
break;
case BUTTON_SAVE_PANEL:
case BUTTON_RESTORE_PANEL:
if ((id >= BUTTON_SCROLL_UP_FAST) && (id <= BUTTON_SCROLL_DOWN_FAST))
saveNameScroll(id, mode == BUTTON_SAVE_PANEL);
else if ((id >= BUTTON_SAVE_SELECT1) && (id <= BUTTON_SAVE_SELECT8))
saveNameSelect(id, mode == BUTTON_SAVE_PANEL);
else if (id == BUTTON_SAVE_RESTORE_OKAY) {
if (mode == BUTTON_SAVE_PANEL) {
_system->setFeatureState(OSystem::kFeatureVirtualKeyboard, false);
if (saveToFile()) // don't go back to main panel if save fails.
return BUTTON_DONE;
} else {
if (restoreFromFile()) { // don't go back to main panel if restore fails.
*retVal |= CONTROL_GAME_RESTORED;
return BUTTON_MAIN_PANEL;
}
}
} else if (id == BUTTON_SAVE_CANCEL) {
_system->setFeatureState(OSystem::kFeatureVirtualKeyboard, false);
return BUTTON_MAIN_PANEL; // mode down to main panel
}
break;
case BUTTON_VOLUME_PANEL:
return id;
}
return 0;
}
void Control::deselectSaveslots() {
for (uint8 cnt = 0; cnt < 8; cnt++)
_buttons[cnt]->setSelected(0);
}
void Control::setupMainPanel() {
uint32 panelId;
if (SwordEngine::_systemVars.controlPanelMode == CP_DEATHSCREEN)
panelId = SR_DEATHPANEL;
else {
if (SwordEngine::_systemVars.language <= BS1_SPANISH)
panelId = SR_PANEL_ENGLISH + SwordEngine::_systemVars.language;
else
panelId = SR_PANEL_ENGLISH;
}
ControlButton *panel = new ControlButton(0, 0, panelId, 0, 0, _resMan, _screenBuf, _system);
panel->draw();
delete panel;
if (SwordEngine::_systemVars.controlPanelMode != CP_NORMAL)
createButtons(_deathButtons, 3);
else {
createButtons(_panelButtons, 7);
_buttons[5]->setSelected(SwordEngine::_systemVars.showText);
}
if (SwordEngine::_systemVars.controlPanelMode == CP_THEEND) // end of game
renderText(_lStrings[STR_THE_END], 480, 188 + 40, TEXT_RIGHT_ALIGN);
if (SwordEngine::_systemVars.controlPanelMode == CP_NORMAL) { // normal panel
renderText(_lStrings[STR_SAVE], 180, 188 + 40, TEXT_LEFT_ALIGN);
renderText(_lStrings[STR_DONE], 460, 332 + 40, TEXT_RIGHT_ALIGN);
renderText(_lStrings[STR_RESTORE], 180, 224 + 40, TEXT_LEFT_ALIGN);
renderText(_lStrings[STR_RESTART], 180, 260 + 40, TEXT_LEFT_ALIGN);
renderText(_lStrings[STR_QUIT], 180, 296 + 40, TEXT_LEFT_ALIGN);
renderText(_lStrings[STR_VOLUME], 460, 188 + 40, TEXT_RIGHT_ALIGN);
renderText(_lStrings[STR_TEXT], 460, 224 + 40, TEXT_RIGHT_ALIGN);
} else {
renderText(_lStrings[STR_RESTORE], 285, 224 + 40, TEXT_LEFT_ALIGN);
if (SwordEngine::_systemVars.controlPanelMode == CP_NEWGAME) // just started game
renderText(_lStrings[STR_START], 285, 260 + 40, TEXT_LEFT_ALIGN);
else
renderText(_lStrings[STR_RESTART], 285, 260 + 40, TEXT_LEFT_ALIGN);
renderText(_lStrings[STR_QUIT], 285, 296 + 40, TEXT_LEFT_ALIGN);
}
}
void Control::setupSaveRestorePanel(bool saving) {
readSavegameDescriptions();
FrameHeader *savePanel = _resMan->fetchFrame(_resMan->openFetchRes(SR_WINDOW), 0);
uint16 panelX = (640 - _resMan->getUint16(savePanel->width)) / 2;
uint16 panelY = (480 - _resMan->getUint16(savePanel->height)) / 2;
ControlButton *panel = new ControlButton(panelX, panelY, SR_WINDOW, 0, 0, _resMan, _screenBuf, _system);
panel->draw();
delete panel;
_resMan->resClose(SR_WINDOW);
createButtons(_saveButtons, 14);
renderText(_lStrings[STR_CANCEL], _saveButtons[13].x - 10, _saveButtons[13].y, TEXT_RIGHT_ALIGN);
if (saving) {
renderText(_lStrings[STR_SAVE], _saveButtons[12].x + 30, _saveButtons[13].y, TEXT_LEFT_ALIGN);
} else {
renderText(_lStrings[STR_RESTORE], _saveButtons[12].x + 30, _saveButtons[13].y, TEXT_LEFT_ALIGN);
}
readSavegameDescriptions();
_selectedSavegame = 255;
showSavegameNames();
}
void Control::setupVolumePanel() {
ControlButton *panel = new ControlButton(0, 0, SR_VOLUME, 0, 0, _resMan, _screenBuf, _system);
panel->draw();
delete panel;
renderText(_lStrings[STR_MUSIC], 149, 39 + 40, TEXT_LEFT_ALIGN);
renderText(_lStrings[STR_SPEECH], 320, 39 + 40, TEXT_CENTER);
renderText(_lStrings[STR_FX], 438, 39 + 40, TEXT_LEFT_ALIGN);
createButtons(_volumeButtons, 4);
renderText(_lStrings[STR_DONE], _volumeButtons[0].x - 10, _volumeButtons[0].y, TEXT_RIGHT_ALIGN);
uint8 volL, volR;
_music->giveVolume(&volL, &volR);
renderVolumeBar(1, volL, volR);
_sound->giveSpeechVol(&volL, &volR);
renderVolumeBar(2, volL, volR);
_sound->giveSfxVol(&volL, &volR);
renderVolumeBar(3, volL, volR);
}
void Control::handleVolumeClicks() {
if (_mouseDown) {
uint8 clickedId = 0;
for (uint8 cnt = 1; cnt < 4; cnt++)
if (_buttons[cnt]->wasClicked(_mouseCoord.x, _mouseCoord.y))
clickedId = cnt;
if (clickedId) { // these are circle shaped, so check again if it was clicked.
uint8 clickDest = 0;
int16 mouseDiffX = _mouseCoord.x - (_volumeButtons[clickedId].x + 48);
int16 mouseDiffY = _mouseCoord.y - (_volumeButtons[clickedId].y + 48);
int16 mouseOffs = (int16)sqrt((double)(mouseDiffX * mouseDiffX + mouseDiffY * mouseDiffY));
// check if the player really hit the button (but not the center).
if ((mouseOffs <= 42) && (mouseOffs >= 8)) {
if (mouseDiffX > 8) { // right part
if (mouseDiffY < -8) // upper right
clickDest = 2;
else if (ABS(mouseDiffY) <= 8) // right
clickDest = 3;
else // lower right
clickDest = 4;
} else if (mouseDiffX < -8) { // left part
if (mouseDiffY < -8) // upper left
clickDest = 8;
else if (ABS(mouseDiffY) <= 8) // left
clickDest = 7;
else // lower left
clickDest = 6;
} else { // middle
if (mouseDiffY < -8)
clickDest = 1; // upper
else if (mouseDiffY > 8)
clickDest = 5; // lower
}
}
_buttons[clickedId]->setSelected(clickDest);
changeVolume(clickedId, clickDest);
}
} else if (_mouseState & BS1L_BUTTON_UP) {
_buttons[1]->setSelected(0);
_buttons[2]->setSelected(0);
_buttons[3]->setSelected(0);
}
}
void Control::changeVolume(uint8 id, uint8 action) {
// ids: 1 = music, 2 = speech, 3 = sfx
uint8 volL = 0, volR = 0;
if (id == 1)
_music->giveVolume(&volL, &volR);
else if (id == 2)
_sound->giveSpeechVol(&volL, &volR);
else if (id == 3)
_sound->giveSfxVol(&volL, &volR);
int8 direction = 0;
if ((action >= 4) && (action <= 6)) // lower part of the button => decrease volume
direction = -1;
else if ((action == 8) || (action == 1) || (action == 2)) // upper part => increase volume
direction = 1;
else if ((action == 3) || (action == 7)) // middle part => pan volume
direction = 1;
int8 factorL = 8, factorR = 8;
if ((action >= 6) && (action <= 8)) { // left part => left pan
factorL = 8;
factorR = (action == 7) ? -8 : 0;
} else if ((action >= 2) && (action <= 4)) { // right part
factorR = 8;
factorL = (action == 3) ? -8 : 0;
}
int16 resVolL = volL + direction * factorL;
int16 resVolR = volR + direction * factorR;
volL = (uint8)MAX((int16)0, MIN(resVolL, (int16)255));
volR = (uint8)MAX((int16)0, MIN(resVolR, (int16)255));
if (id == 1)
_music->setVolume(volL, volR);
else if (id == 2)
_sound->setSpeechVol(volL, volR);
else if (id == 3)
_sound->setSfxVol(volL, volR);
renderVolumeBar(id, volL, volR);
}
bool Control::getConfirm(const uint8 *title) {
ControlButton *panel = new ControlButton(0, 0, SR_CONFIRM, 0, 0, _resMan, _screenBuf, _system);
panel->draw();
delete panel;
renderText(title, 320, 160, TEXT_CENTER);
ControlButton *buttons[2];
buttons[0] = new ControlButton(260, 192 + 40, SR_BUTTON, 0, 0, _resMan, _screenBuf, _system);
renderText(_lStrings[STR_OK], 640 - 260, 192 + 40, TEXT_RIGHT_ALIGN);
buttons[1] = new ControlButton(260, 256 + 40, SR_BUTTON, 0, 0, _resMan, _screenBuf, _system);
renderText(_lStrings[STR_CANCEL], 640 - 260, 256 + 40, TEXT_RIGHT_ALIGN);
uint8 retVal = 0;
uint8 clickVal = 0;
do {
buttons[0]->draw();
buttons[1]->draw();
delay(1000 / 12);
if (_keyPressed.keycode == Common::KEYCODE_ESCAPE)
retVal = 2;
else if (_keyPressed.keycode == Common::KEYCODE_RETURN || _keyPressed.keycode == Common::KEYCODE_KP_ENTER)
retVal = 1;
if (_mouseState & BS1L_BUTTON_DOWN) {
if (buttons[0]->wasClicked(_mouseCoord.x, _mouseCoord.y))
clickVal = 1;
else if (buttons[1]->wasClicked(_mouseCoord.x, _mouseCoord.y))
clickVal = 2;
else
clickVal = 0;
if (clickVal)
buttons[clickVal - 1]->setSelected(1);
}
if ((_mouseState & BS1L_BUTTON_UP) && (clickVal)) {
if (buttons[clickVal - 1]->wasClicked(_mouseCoord.x, _mouseCoord.y))
retVal = clickVal;
else
buttons[clickVal - 1]->setSelected(0);
clickVal = 0;
}
} while (!retVal);
delete buttons[0];
delete buttons[1];
return retVal == 1;
}
bool Control::keyAccepted(uint16 ascii) {
static const char allowedSpecials[] = ",.:-()?! \"\'";
if (((ascii >= 'A') && (ascii <= 'Z')) ||
((ascii >= 'a') && (ascii <= 'z')) ||
((ascii >= '0') && (ascii <= '9')) ||
strchr(allowedSpecials, ascii))
return true;
else
return false;
}
void Control::handleSaveKey(Common::KeyState kbd) {
if (_selectedSavegame < 255) {
uint8 len = _saveNames[_selectedSavegame].size();
if ((kbd.keycode == Common::KEYCODE_BACKSPACE) && len) // backspace
_saveNames[_selectedSavegame].deleteLastChar();
else if (kbd.ascii && keyAccepted(kbd.ascii) && (len < 31)) {
_saveNames[_selectedSavegame].insertChar(kbd.ascii, len);
}
showSavegameNames();
}
}
bool Control::saveToFile() {
if ((_selectedSavegame == 255) || _saveNames[_selectedSavegame].size() == 0)
return false; // no saveslot selected or no name entered
saveGameToFile(_selectedSavegame);
return true;
}
bool Control::restoreFromFile() {
if (_selectedSavegame < 255) {
return restoreGameFromFile(_selectedSavegame);
} else
return false;
}
void Control::readSavegameDescriptions() {
char saveName[40];
Common::String pattern = "sword1.???";
Common::StringList filenames = _saveFileMan->listSavefiles(pattern);
sort(filenames.begin(), filenames.end()); // Sort (hopefully ensuring we are sorted numerically..)
_saveNames.clear();
int num = 0;
int slotNum = 0;
for (Common::StringList::const_iterator file = filenames.begin(); file != filenames.end(); ++file) {
// Obtain the last 3 digits of the filename, since they correspond to the save slot
slotNum = atoi(file->c_str() + file->size() - 3);
while (num < slotNum) {
_saveNames.push_back("");
num++;
}
if (slotNum >= 0 && slotNum <= 999) {
num++;
Common::InSaveFile *in = _saveFileMan->openForLoading(*file);
if (in) {
in->readUint32LE(); // header
in->read(saveName, 40);
_saveNames.push_back(saveName);
delete in;
}
}
}
for (int i = _saveNames.size(); i < 1000; i++)
_saveNames.push_back("");
_saveScrollPos = 0;
_selectedSavegame = 255;
_saveFiles = _numSaves = _saveNames.size();
}
bool Control::isPanelShown() {
return _panelShown;
}
int Control::displayMessage(const char *altButton, const char *message, ...) {
char buf[STRINGBUFLEN];
va_list va;
va_start(va, message);
vsnprintf(buf, STRINGBUFLEN, message, va);
va_end(va);
GUI::MessageDialog dialog(buf, "OK", altButton);
int result = dialog.runModal();
_mouse->setPointer(MSE_POINTER, 0);
return result;
}
bool Control::savegamesExist() {
Common::String pattern = "sword1.???";
Common::StringList saveNames = _saveFileMan->listSavefiles(pattern);
return saveNames.size() > 0;
}
void Control::checkForOldSaveGames() {
Common::InSaveFile *inf = _saveFileMan->openForLoading("SAVEGAME.INF");
if (!inf) {
delete inf;
return;
}
GUI::MessageDialog dialog0(
"ScummVM found that you have old savefiles for Broken Sword 1 that should be converted.\n"
"The old save game format is no longer supported, so you will not be able to load your games if you don't convert them.\n\n"
"Press OK to convert them now, otherwise you will be asked again the next time you start the game.\n", "OK", "Cancel");
int choice = dialog0.runModal();
if (choice == GUI::kMessageCancel) {
// user pressed cancel
return;
}
// Convert every save slot we find in the index file to the new format
uint8 saveName[32];
uint8 slot = 0;
uint8 ch;
memset(saveName, 0, sizeof(saveName));
do {
uint8 pos = 0;
do {
ch = inf->readByte();
if (pos < sizeof(saveName) - 1) {
if ((ch == 10) || (ch == 255) || (inf->eos()))
saveName[pos++] = '\0';
else if (ch >= 32)
saveName[pos++] = ch;
}
} while ((ch != 10) && (ch != 255) && (!inf->eos()));
if (pos > 1) // if the slot has a description
convertSaveGame(slot, (char*)saveName);
slot++;
} while ((ch != 255) && (!inf->eos()));
delete inf;
// Delete index file
_saveFileMan->removeSavefile("SAVEGAME.INF");
}
void Control::showSavegameNames() {
for (uint8 cnt = 0; cnt < 8; cnt++) {
_buttons[cnt]->draw();
uint8 textMode = TEXT_LEFT_ALIGN;
uint16 ycoord = _saveButtons[cnt].y + 2;
uint8 str[40];
sprintf((char*)str, "%d. %s", cnt + _saveScrollPos + 1, _saveNames[cnt + _saveScrollPos].c_str());
if (cnt + _saveScrollPos == _selectedSavegame) {
textMode |= TEXT_RED_FONT;
ycoord += 2;
if (_cursorVisible)
strcat((char*)str, "_");
}
renderText(str, _saveButtons[cnt].x + 6, ycoord, textMode);
}
}
void Control::saveNameSelect(uint8 id, bool saving) {
deselectSaveslots();
_buttons[id - BUTTON_SAVE_SELECT1]->setSelected(1);
uint8 num = (id - BUTTON_SAVE_SELECT1) + _saveScrollPos;
if (saving && (_selectedSavegame != 255)) // the player may have entered something, clear it again
_saveNames[_selectedSavegame] = _oldName;
if (num < _saveFiles) {
_selectedSavegame = num;
_oldName = _saveNames[num]; // save for later
} else {
if (!saving)
_buttons[id - BUTTON_SAVE_SELECT1]->setSelected(0); // no save in slot, deselect it
else {
if (_saveFiles <= num)
_saveFiles = num + 1;
_selectedSavegame = num;
_oldName.clear();
}
}
if (_selectedSavegame < 255)
_cursorTick = 0;
showSavegameNames();
}
void Control::saveNameScroll(uint8 scroll, bool saving) {
uint16 maxScroll;
if (saving)
maxScroll = 64;
else
maxScroll = _saveFiles; // for loading, we can only scroll as far as there are savegames
if (scroll == BUTTON_SCROLL_UP_FAST) {
if (_saveScrollPos >= 8)
_saveScrollPos -= 8;
else
_saveScrollPos = 0;
} else if (scroll == BUTTON_SCROLL_UP_SLOW) {
if (_saveScrollPos >= 1)
_saveScrollPos--;
} else if (scroll == BUTTON_SCROLL_DOWN_SLOW) {
if (_saveScrollPos + 8 < maxScroll)
_saveScrollPos++;
} else if (scroll == BUTTON_SCROLL_DOWN_FAST) {
if (_saveScrollPos + 16 < maxScroll)
_saveScrollPos += 8;
else {
if (maxScroll >= 8)
_saveScrollPos = maxScroll - 8;
else
_saveScrollPos = 0;
}
}
_selectedSavegame = 255; // deselect savegame
deselectSaveslots();
showSavegameNames();
}
void Control::createButtons(const ButtonInfo *buttons, uint8 num) {
for (uint8 cnt = 0; cnt < num; cnt++) {
_buttons[cnt] = new ControlButton(buttons[cnt].x, buttons[cnt].y, buttons[cnt].resId, buttons[cnt].id, buttons[cnt].flag, _resMan, _screenBuf, _system);
_buttons[cnt]->draw();
}
_numButtons = num;
}
void Control::destroyButtons() {
for (uint8 cnt = 0; cnt < _numButtons; cnt++)
delete _buttons[cnt];
_numButtons = 0;
}
uint16 Control::getTextWidth(const uint8 *str) {
uint16 width = 0;
while (*str) {
width += _resMan->getUint16(_resMan->fetchFrame(_font, *str - 32)->width) - 3;
str++;
}
return width;
}
void Control::renderText(const uint8 *str, uint16 x, uint16 y, uint8 mode) {
uint8 *font = _font;
if (mode & TEXT_RED_FONT) {
mode &= ~TEXT_RED_FONT;
font = _redFont;
}
if (mode == TEXT_RIGHT_ALIGN) // negative x coordinate means right-aligned.
x -= getTextWidth(str);
else if (mode == TEXT_CENTER)
x -= getTextWidth(str) / 2;
uint16 destX = x;
while (*str) {
uint8 *dst = _screenBuf + y * SCREEN_WIDTH + destX;
FrameHeader *chSpr = _resMan->fetchFrame(font, *str - 32);
uint8 *sprData = (uint8*)chSpr + sizeof(FrameHeader);
uint8 *HIFbuf = NULL;
if (SwordEngine::isPsx()) { //Text fonts are compressed in psx version
HIFbuf = (uint8 *)malloc(_resMan->getUint16(chSpr->height) * _resMan->getUint16(chSpr->width));
memset(HIFbuf, 0, _resMan->getUint16(chSpr->height) * _resMan->getUint16(chSpr->width));
Screen::decompressHIF(sprData, HIFbuf);
sprData = HIFbuf;
}
for (uint16 cnty = 0; cnty < _resMan->getUint16(chSpr->height); cnty++) {
for (uint16 cntx = 0; cntx < _resMan->getUint16(chSpr->width); cntx++) {
if (sprData[cntx])
dst[cntx] = sprData[cntx];
}
if (SwordEngine::isPsx()) { //On PSX version we need to double horizontal lines
dst += SCREEN_WIDTH;
for (uint16 cntx = 0; cntx < _resMan->getUint16(chSpr->width); cntx++)
if (sprData[cntx])
dst[cntx] = sprData[cntx];
}
sprData += _resMan->getUint16(chSpr->width);
dst += SCREEN_WIDTH;
}
destX += _resMan->getUint16(chSpr->width) - 3;
str++;
free(HIFbuf);
}
_system->copyRectToScreen(_screenBuf + y * SCREEN_WIDTH + x, SCREEN_WIDTH, x, y, (destX - x) + 3, 28);
}
void Control::renderVolumeBar(uint8 id, uint8 volL, uint8 volR) {
uint16 destX = _volumeButtons[id].x + 20;
uint16 destY = _volumeButtons[id].y + 116;
for (uint8 chCnt = 0; chCnt < 2; chCnt++) {
uint8 vol = (chCnt == 0) ? volL : volR;
FrameHeader *frHead = _resMan->fetchFrame(_resMan->openFetchRes(SR_VLIGHT), (vol + 15) >> 4);
uint8 *destMem = _screenBuf + destY * SCREEN_WIDTH + destX;
uint8 *srcMem = (uint8*)frHead + sizeof(FrameHeader);
uint16 barHeight = _resMan->getUint16(frHead->height);
uint8 *psxVolBuf = NULL;
if (SwordEngine::isPsx()) {
psxVolBuf = (uint8 *)malloc(_resMan->getUint16(frHead->height) / 2 * _resMan->getUint16(frHead->width));
memset(psxVolBuf, 0, _resMan->getUint16(frHead->height) / 2 * _resMan->getUint16(frHead->width));
Screen::decompressHIF(srcMem, psxVolBuf);
srcMem = psxVolBuf;
barHeight /= 2;
}
for (uint16 cnty = 0; cnty < barHeight; cnty++) {
memcpy(destMem, srcMem, _resMan->getUint16(frHead->width));
if (SwordEngine::isPsx()) { //linedoubling
destMem += SCREEN_WIDTH;
memcpy(destMem, srcMem, _resMan->getUint16(frHead->width));
}
srcMem += _resMan->getUint16(frHead->width);
destMem += SCREEN_WIDTH;
}
_system->copyRectToScreen(_screenBuf + destY * SCREEN_WIDTH + destX, SCREEN_WIDTH, destX, destY, _resMan->getUint16(frHead->width), _resMan->getUint16(frHead->height));
_resMan->resClose(SR_VLIGHT);
destX += 32;
free(psxVolBuf);
}
}
void Control::saveGameToFile(uint8 slot) {
char fName[15];
uint16 cnt;
sprintf(fName, "sword1.%03d", slot);
uint16 liveBuf[TOTAL_SECTIONS];
Common::OutSaveFile *outf;
outf = _saveFileMan->openForSaving(fName);
if (!outf) {
// Display an error message and do nothing
displayMessage(0, "Unable to create file '%s'. (%s)", fName, _saveFileMan->popErrorDesc().c_str());
return;
}
outf->writeUint32LE(SAVEGAME_HEADER);
outf->write(_saveNames[slot].c_str(), 40);
outf->writeByte(SAVEGAME_VERSION);
if (!isPanelShown()) // Generate a thumbnail only if we are outside of game menu
Graphics::saveThumbnail(*outf);
// Date / time
TimeDate curTime;
_system->getTimeAndDate(curTime);
uint32 saveDate = (curTime.tm_mday & 0xFF) << 24 | ((curTime.tm_mon + 1) & 0xFF) << 16 | ((curTime.tm_year + 1900) & 0xFFFF);
uint16 saveTime = (curTime.tm_hour & 0xFF) << 8 | ((curTime.tm_min) & 0xFF);
outf->writeUint32BE(saveDate);
outf->writeUint16BE(saveTime);
uint32 currentTime = _system->getMillis() / 1000;
outf->writeUint32BE(currentTime - SwordEngine::_systemVars.engineStartTime);
_objMan->saveLiveList(liveBuf);
for (cnt = 0; cnt < TOTAL_SECTIONS; cnt++)
outf->writeUint16LE(liveBuf[cnt]);
Object *cpt = _objMan->fetchObject(PLAYER);
Logic::_scriptVars[CHANGE_DIR] = cpt->o_dir;
Logic::_scriptVars[CHANGE_X] = cpt->o_xcoord;
Logic::_scriptVars[CHANGE_Y] = cpt->o_ycoord;
Logic::_scriptVars[CHANGE_STANCE] = STAND;
Logic::_scriptVars[CHANGE_PLACE] = cpt->o_place;
for (cnt = 0; cnt < NUM_SCRIPT_VARS; cnt++)
outf->writeUint32LE(Logic::_scriptVars[cnt]);
uint32 playerSize = (sizeof(Object) - 12000) / 4;
uint32 *playerRaw = (uint32*)cpt;
for (uint32 cnt2 = 0; cnt2 < playerSize; cnt2++)
outf->writeUint32LE(playerRaw[cnt2]);
outf->finalize();
if (outf->err())
displayMessage(0, "Couldn't write to file '%s'. Device full? (%s)", fName, _saveFileMan->popErrorDesc().c_str());
delete outf;
}
bool Control::restoreGameFromFile(uint8 slot) {
char fName[15];
uint16 cnt;
sprintf(fName, "sword1.%03d", slot);
Common::InSaveFile *inf;
inf = _saveFileMan->openForLoading(fName);
if (!inf) {
// Display an error message, and do nothing
displayMessage(0, "Can't open file '%s'. (%s)", fName, _saveFileMan->popErrorDesc().c_str());
return false;
}
uint saveHeader = inf->readUint32LE();
if (saveHeader != SAVEGAME_HEADER) {
// Display an error message, and do nothing
displayMessage(0, "Save game '%s' is corrupt", fName);
return false;
}
inf->skip(40); // skip description
uint8 saveVersion = inf->readByte();
if (saveVersion > SAVEGAME_VERSION) {
warning("Different save game version");
return false;
}
if (saveVersion < 2) // These older version of the savegames used a flag to signal presence of thumbnail
inf->skip(1);
if (Graphics::checkThumbnailHeader(*inf))
Graphics::skipThumbnailHeader(*inf);
inf->readUint32BE(); // save date
inf->readUint16BE(); // save time
if (saveVersion < 2) { // Before version 2 we didn't had play time feature
SwordEngine::_systemVars.engineStartTime = _system->getMillis() / 1000; // Start counting
} else {
uint32 currentTime = _system->getMillis() / 1000;
SwordEngine::_systemVars.engineStartTime = currentTime - inf->readUint32BE(); // Engine start time
}
_restoreBuf = (uint8*)malloc(
TOTAL_SECTIONS * 2 +
NUM_SCRIPT_VARS * 4 +
(sizeof(Object) - 12000));
uint16 *liveBuf = (uint16*)_restoreBuf;
uint32 *scriptBuf = (uint32*)(_restoreBuf + 2 * TOTAL_SECTIONS);
uint32 *playerBuf = (uint32*)(_restoreBuf + 2 * TOTAL_SECTIONS + 4 * NUM_SCRIPT_VARS);
for (cnt = 0; cnt < TOTAL_SECTIONS; cnt++)
liveBuf[cnt] = inf->readUint16LE();
for (cnt = 0; cnt < NUM_SCRIPT_VARS; cnt++)
scriptBuf[cnt] = inf->readUint32LE();
uint32 playerSize = (sizeof(Object) - 12000) / 4;
for (uint32 cnt2 = 0; cnt2 < playerSize; cnt2++)
playerBuf[cnt2] = inf->readUint32LE();
if (inf->err() || inf->eos()) {
displayMessage(0, "Can't read from file '%s'. (%s)", fName, _saveFileMan->popErrorDesc().c_str());
delete inf;
free(_restoreBuf);
_restoreBuf = NULL;
return false;
}
delete inf;
return true;
}
bool Control::convertSaveGame(uint8 slot, char* desc) {
char oldFileName[15];
char newFileName[40];
sprintf(oldFileName, "SAVEGAME.%03d", slot);
sprintf(newFileName, "sword1.%03d", slot);
uint8 *saveData;
int dataSize;
// Check if the new file already exists
Common::InSaveFile *testSave = _saveFileMan->openForLoading(newFileName);
if (testSave) {
delete testSave;
char msg[200];
sprintf(msg, "Target new save game already exists!\n"
"Would you like to keep the old save game (%s) or the new one (%s)?\n",
oldFileName, newFileName);
GUI::MessageDialog dialog0(msg, "Keep the old one", "Keep the new one");
int choice = dialog0.runModal();
if (choice == GUI::kMessageCancel) {
// User chose to keep the new game, so delete the old one
_saveFileMan->removeSavefile(oldFileName);
return true;
}
}
Common::InSaveFile *oldSave = _saveFileMan->openForLoading(oldFileName);
if (!oldSave) {
// Display a warning message and do nothing
warning("Can't open file '%s'", oldFileName);
return false;
}
// Read data from old type of save game
dataSize = oldSave->size();
saveData = new uint8[dataSize];
oldSave->read(saveData, dataSize);
delete oldSave;
// Now write the save data to a new type of save game
Common::OutSaveFile *newSave;
newSave = _saveFileMan->openForSaving(newFileName);
if (!newSave) {
// Display a warning message and do nothing
warning("Unable to create file '%s'. (%s)", newFileName, _saveFileMan->popErrorDesc().c_str());
delete[] saveData;
saveData = NULL;
return false;
}
newSave->writeUint32LE(SAVEGAME_HEADER);
newSave->write(desc, 40);
newSave->writeByte(SAVEGAME_VERSION);
// Date / time
TimeDate curTime;
_system->getTimeAndDate(curTime);
uint32 saveDate = (curTime.tm_mday & 0xFF) << 24 | ((curTime.tm_mon + 1) & 0xFF) << 16 | ((curTime.tm_year + 1900) & 0xFFFF);
uint16 saveTime = (curTime.tm_hour & 0xFF) << 8 | ((curTime.tm_min) & 0xFF);
newSave->writeUint32BE(saveDate);
newSave->writeUint16BE(saveTime);
newSave->writeUint32BE(0); // We don't have playtime info when converting, so we start from 0.
newSave->write(saveData, dataSize);
newSave->finalize();
if (newSave->err())
warning("Couldn't write to file '%s'. Device full?", newFileName);
delete newSave;
// Delete old save
_saveFileMan->removeSavefile(oldFileName);
// Cleanup
delete[] saveData;
saveData = NULL;
return true;
}
void Control::doRestore() {
uint8 *bufPos = _restoreBuf;
_objMan->loadLiveList((uint16*)bufPos);
bufPos += TOTAL_SECTIONS * 2;
for (uint16 cnt = 0; cnt < NUM_SCRIPT_VARS; cnt++) {
Logic::_scriptVars[cnt] = *(uint32*)bufPos;
bufPos += 4;
}
uint32 playerSize = (sizeof(Object) - 12000) / 4;
uint32 *playerRaw = (uint32*)_objMan->fetchObject(PLAYER);
Object *cpt = _objMan->fetchObject(PLAYER);
for (uint32 cnt2 = 0; cnt2 < playerSize; cnt2++) {
*playerRaw = *(uint32*)bufPos;
playerRaw++;
bufPos += 4;
}
free(_restoreBuf);
Logic::_scriptVars[CHANGE_DIR] = cpt->o_dir;
Logic::_scriptVars[CHANGE_X] = cpt->o_xcoord;
Logic::_scriptVars[CHANGE_Y] = cpt->o_ycoord;
Logic::_scriptVars[CHANGE_STANCE] = STAND;
Logic::_scriptVars[CHANGE_PLACE] = cpt->o_place;
SwordEngine::_systemVars.justRestoredGame = 1;
if (SwordEngine::_systemVars.isDemo)
Logic::_scriptVars[PLAYINGDEMO] = 1;
}
void Control::delay(uint32 msecs) {
Common::Event event;
uint32 now = _system->getMillis();
uint32 endTime = now + msecs;
_keyPressed.reset();
_mouseState = 0;
do {
Common::EventManager *eventMan = _system->getEventManager();
while (eventMan->pollEvent(event)) {
switch (event.type) {
case Common::EVENT_KEYDOWN:
_keyPressed = event.kbd;
// we skip the rest of the delay and return immediately
// to handle keyboard input
return;
case Common::EVENT_MOUSEMOVE:
_mouseCoord = event.mouse;
break;
case Common::EVENT_LBUTTONDOWN:
_mouseDown = true;
_mouseState |= BS1L_BUTTON_DOWN;
_mouseCoord = event.mouse;
break;
case Common::EVENT_LBUTTONUP:
_mouseDown = false;
_mouseState |= BS1L_BUTTON_UP;
_mouseCoord = event.mouse;
break;
case Common::EVENT_WHEELUP:
_mouseDown = false;
_mouseState |= BS1_WHEEL_UP;
_mouseCoord = event.mouse;
break;
case Common::EVENT_WHEELDOWN:
_mouseDown = false;
_mouseState |= BS1_WHEEL_DOWN;
break;
default:
break;
}
}
_system->updateScreen();
_system->delayMillis(10);
} while (_system->getMillis() < endTime);
}
const ButtonInfo Control::_deathButtons[3] = {
{250, 224 + 40, SR_BUTTON, BUTTON_RESTORE_PANEL, 0 },
{250, 260 + 40, SR_BUTTON, BUTTON_RESTART, kButtonOk },
{250, 296 + 40, SR_BUTTON, BUTTON_QUIT, kButtonCancel }
};
const ButtonInfo Control::_panelButtons[7] = {
{145, 188 + 40, SR_BUTTON, BUTTON_SAVE_PANEL, 0 },
{145, 224 + 40, SR_BUTTON, BUTTON_RESTORE_PANEL, 0 },
{145, 260 + 40, SR_BUTTON, BUTTON_RESTART, 0 },
{145, 296 + 40, SR_BUTTON, BUTTON_QUIT, kButtonCancel },
{475, 188 + 40, SR_BUTTON, BUTTON_VOLUME_PANEL, 0 },
{475, 224 + 40, SR_TEXT_BUTTON, BUTTON_TEXT, 0 },
{475, 332 + 40, SR_BUTTON, BUTTON_DONE, kButtonOk }
};
const ButtonInfo Control::_saveButtons[16] = {
{114, 32 + 40, SR_SLAB1, BUTTON_SAVE_SELECT1, 0 },
{114, 68 + 40, SR_SLAB2, BUTTON_SAVE_SELECT2, 0 },
{114, 104 + 40, SR_SLAB3, BUTTON_SAVE_SELECT3, 0 },
{114, 140 + 40, SR_SLAB4, BUTTON_SAVE_SELECT4, 0 },
{114, 176 + 40, SR_SLAB1, BUTTON_SAVE_SELECT5, 0 },
{114, 212 + 40, SR_SLAB2, BUTTON_SAVE_SELECT6, 0 },
{114, 248 + 40, SR_SLAB3, BUTTON_SAVE_SELECT7, 0 },
{114, 284 + 40, SR_SLAB4, BUTTON_SAVE_SELECT8, 0 },
{516, 25 + 40, SR_BUTUF, BUTTON_SCROLL_UP_FAST, 0 },
{516, 45 + 40, SR_BUTUS, BUTTON_SCROLL_UP_SLOW, 0 },
{516, 289 + 40, SR_BUTDS, BUTTON_SCROLL_DOWN_SLOW, 0 },
{516, 310 + 40, SR_BUTDF, BUTTON_SCROLL_DOWN_FAST, 0 },
{125, 338 + 40, SR_BUTTON, BUTTON_SAVE_RESTORE_OKAY, kButtonOk},
{462, 338 + 40, SR_BUTTON, BUTTON_SAVE_CANCEL, kButtonCancel }
};
const ButtonInfo Control::_volumeButtons[4] = {
{ 478, 338 + 40, SR_BUTTON, BUTTON_MAIN_PANEL, kButtonOk },
{ 138, 135, SR_VKNOB, 0, 0 },
{ 273, 135, SR_VKNOB, 0, 0 },
{ 404, 135, SR_VKNOB, 0, 0 },
};
const uint8 Control::_languageStrings[8 * 20][43] = {
// BS1_ENGLISH:
"PAUSED",
"PLEASE INSERT CD-",
"THEN PRESS A KEY",
"INCORRECT CD",
"Save",
"Restore",
"Restart",
"Start",
"Quit",
"Speed",
"Volume",
"Text",
"Done",
"OK",
"Cancel",
"Music",
"Speech",
"Fx",
"The End",
"DRIVE FULL!",
// BS1_FRENCH:
"PAUSE",
"INS\xC9REZ LE CD-",
"ET APPUYES SUR UNE TOUCHE",
"CD INCORRECT",
"Sauvegarder",
"Recharger",
"Recommencer",
"Commencer",
"Quitter",
"Vitesse",
"Volume",
"Texte",
"Termin\xE9",
"OK",
"Annuler",
"Musique",
"Voix",
"Fx",
"Fin",
"DISQUE PLEIN!",
//BS1_GERMAN:
"PAUSE",
"BITTE LEGEN SIE CD-",
"EIN UND DR\xDC""CKEN SIE EINE BELIEBIGE TASTE",
"FALSCHE CD",
"Speichern",
"Laden",
"Neues Spiel",
"Start",
"Beenden",
"Geschwindigkeit",
"Lautst\xE4rke",
"Text",
"Fertig",
"OK",
"Abbrechen",
"Musik",
"Sprache",
"Fx",
"Ende",
"DRIVE FULL!",
//BS1_ITALIAN:
"PAUSA",
"INSERITE IL CD-",
"E PREMETE UN TASTO",
"CD ERRATO",
"Salva",
"Ripristina",
"Ricomincia",
"Inizio",
"Esci",
"Velocit\xE0",
"Volume",
"Testo",
"Fatto",
"OK",
"Annulla",
"Musica",
"Parlato",
"Fx",
"Fine",
"DISCO PIENO!",
//BS1_SPANISH:
"PAUSA",
"POR FAVOR INTRODUCE EL CD-",
"Y PULSA UNA TECLA",
"CD INCORRECTO",
"Guardar",
"Recuperar",
"Reiniciar",
"Empezar",
"Abandonar",
"Velocidad",
"Volumen",
"Texto",
"Hecho",
"OK",
"Cancelar",
"M\xFAsica",
"Di\xE1logo",
"Fx",
"Fin",
"DISCO LLENO",
// BS1_CZECH:
"\xAC\x41S SE ZASTAVIL",
"VLO\xA6TE DO MECHANIKY CD DISK",
"PAK STISKN\xB7TE LIBOVOLNOU KL\xB5VESU",
"TO NEBUDE TO SPR\xB5VN\x90 CD",
"Ulo\xA7it pozici",
"Nahr\xA0t pozici",
"Za\x9F\xA1t znovu",
"Start",
"Ukon\x9Fit hru",
"Rychlost",
"Hlasitost",
"Titulky",
"Souhlas\xA1m",
"Ano",
"Ne",
"Hudba",
"Mluven, slovo",
"Zvuky",
"Konec",
"Disk pln\xEC",
//BS1_PORTUGESE:
"PAUSA",
"FAVOR INSERIR CD",
"E DIGITAR UMA TECLA",
"CD INCORRETO",
"Salvar",
"Restaurar",
"Reiniciar",
"Iniciar",
"Sair",
"Velocidade",
"Volume",
"Texto",
"Feito",
"OK",
"Cancelar",
"M\xFAsica",
"Voz",
"Efeitos",
"Fim",
"UNIDADE CHEIA!",
};
} // End of namespace Sword1
| gpl-2.0 |
sanjay-jagdish/barkerby | webmin/pages/shift_other_employees.php | 2292 | <?php
session_start();
include_once('redirect.php');
include '../config/config.php';
$employee_sql = "SELECT type_id
FROM account WHERE id=".$_POST['account_id'];
$employee_qry = mysql_query($employee_sql);
$employee_res = mysql_fetch_assoc($employee_qry);
//determine the time using the passed schedule_id
$sched_id = $_POST['sched_id'];
$time_sql = "SELECT start_time, end_time FROM schedule WHERE id=".$sched_id;
$time_qry = mysql_query($time_sql);
$time_res = mysql_fetch_assoc($time_qry);
$date_dropped = $_POST['date'];
$day_dropped = date('D',strtotime($_POST['date']));
$employees_sql = "SELECT a.id, CONCAT(fname, ' ', lname) AS name, email
FROM account a, type t
WHERE a.id<>".$_POST['account_id']."
AND a.type_id=".$employee_res['type_id']."
AND a.id NOT IN
(
SELECT account_id AS id FROM schedule WHERE deleted=0
AND ( '".$date_dropped."' BETWEEN STR_TO_DATE(valid_from, '%m/%d/%Y') AND STR_TO_DATE(valid_until, '%m/%d/%Y') )
AND ( '".$time_res['start_time']."' BETWEEN STR_TO_DATE(start_time, '%H:%i') AND STR_TO_DATE(end_time, '%H:%i') )
AND days NOT LIKE '%".$day_dropped."%'
)
GROUP BY a.id
ORDER BY CONCAT(fname, ' ', lname) ASC
";
$employees_qry = mysql_query($employees_sql);
$employees_num = mysql_num_rows($employees_qry);
//<option value='".$employees_res['id']."'>".$employees_res['name']." <".$employees_res['email']."></option>
if($employees_num>0){
?>
<br />
List of off-duty employees whom you may offer the scheduled shift.<br /><br />
<i>To select/desselect multiple names, pres and hold the <strong>Ctrl</strong> key (Windows) or <strong>Cmd</strong> key (Macintosh) while clicking the names.</i><br /><br />
<select multiple="multiple" id="other_emp_selected">
<?php
//foreach($other_employees as $id => $data){
while($employees_res = mysql_fetch_assoc($employees_qry)){
//$emp_data = explode('^',$data);
//echo "<option value='".$id."'>".$emp_data[0]." <".$emp_data[1]."></option>\n";
echo "<option value='".$employees_res['id']."'>".$employees_res['name']." <".$employees_res['email']."></option>\n";
}
?>
</select>
<?php
}else{
?>
<br />
<div style="color:#F00;">Ingen personal tillgänglig.</div>
<?php
}
?> | gpl-2.0 |
Ideo-lt/l2.skilas.lt | aCis_gameserver/java/net/sf/l2j/gameserver/network/serverpackets/SendTradeRequest.java | 958 | /*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.l2j.gameserver.network.serverpackets;
public class SendTradeRequest extends L2GameServerPacket
{
private final int _senderID;
public SendTradeRequest(int senderID)
{
_senderID = senderID;
}
@Override
protected final void writeImpl()
{
writeC(0x5e);
writeD(_senderID);
}
} | gpl-2.0 |
jug-berlin/joomla.berlin | administrator/components/com_rsform/controller.php | 8243 | <?php
/**
* @package RSForm! Pro
* @copyright (C) 2007-2014 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
class RSFormController extends JControllerLegacy
{
protected $_db;
public function __construct()
{
parent::__construct();
JHtml::_('behavior.framework');
$this->_db = JFactory::getDBO();
$version = new RSFormProVersion();
$v = $version->revision;
$doc = JFactory::getDocument();
if (RSFormProHelper::isJ('3.0')) {
JHtml::_('jquery.framework');
} else {
$doc->addScript(JURI::root(true).'/administrator/components/com_rsform/assets/js/jquery.js?v='.$v);
}
$doc->addScript(JURI::root(true).'/administrator/components/com_rsform/assets/js/script.js?v='.$v);
$doc->addScript(JURI::root(true).'/administrator/components/com_rsform/assets/js/tablednd.js?v='.$v);
$doc->addScript(JURI::root(true).'/administrator/components/com_rsform/assets/js/jquery.scrollto.js?v='.$v);
$doc->addStyleSheet(JURI::root(true).'/administrator/components/com_rsform/assets/css/style.css?v='.$v);
if (RSFormProHelper::isJ('3.0')) {
$doc->addStyleSheet(JURI::root(true).'/administrator/components/com_rsform/assets/css/style30.css?v='.$v);
} else {
$doc->addStyleSheet(JURI::root(true).'/administrator/components/com_rsform/assets/css/style25.css?v='.$v);
}
$doc->addStyleSheet(JURI::root(true).'/administrator/components/com_rsform/assets/css/rsdesign.css?v='.$v);
}
function mappings()
{
JRequest::setVar('view', 'forms');
JRequest::setVar('layout', 'edit_mappings');
JRequest::setVar('tmpl', 'component');
parent::display();
}
function changeLanguage()
{
$formId = JRequest::getInt('formId');
$tabposition = JRequest::getInt('tabposition');
$tab = JRequest::getInt('tab',0);
$tab = $tabposition ? '&tab='.$tab : '';
$session = JFactory::getSession();
$session->set('com_rsform.form.'.$formId.'.lang', JRequest::getVar('Language'));
$this->setRedirect('index.php?option=com_rsform&task=forms.edit&formId='.$formId.'&tabposition='.$tabposition.$tab);
}
function changeEmailLanguage()
{
$formId = JRequest::getInt('formId');
$cid = JRequest::getInt('id');
$session = JFactory::getSession();
$session->set('com_rsform.emails.'.$cid.'.lang', JRequest::getVar('ELanguage'));
$this->setRedirect('index.php?option=com_rsform&task=forms.emails&tmpl=component&formId='.$formId.'&cid='.$cid);
}
function layoutsGenerate()
{
$model = $this->getModel('forms');
$model->getForm();
$model->_form->FormLayoutName = JRequest::getCmd('layoutName');
$model->autoGenerateLayout();
echo $model->_form->FormLayout;
exit();
}
function layoutsSaveName()
{
$formId = JRequest::getInt('formId');
$name = JRequest::getVar('formLayoutName');
$db = JFactory::getDBO();
$db->setQuery("UPDATE #__rsform_forms SET FormLayoutName='".$db->escape($name)."' WHERE FormId='".$formId."'");
$db->execute();
exit();
}
function submissionExportPDF()
{
$cid = JRequest::getInt('cid');
$this->setRedirect('index.php?option=com_rsform&view=submissions&layout=edit&cid='.$cid.'&format=pdf');
}
/**
* Backup / Restore Screen
*/
function backupRestore()
{
JRequest::setVar('view', 'backuprestore');
JRequest::setVar('layout', 'default');
parent::display();
}
/**
* Backup Generate Process
*
* @param str $option
*/
function backupDownload()
{
require_once JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/backup.php';
jimport('joomla.filesystem.archive');
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.file');
// Get the selected items
$cid = JRequest::getVar('cid', array(0), 'post', 'array');
// Force array elements to be integers
JArrayHelper::toInteger($cid, array(0));
$tmpdir = uniqid('rsformbkp');
$path = JPATH_SITE.'/media/'.$tmpdir;
if (!JFolder::create($path, 0777))
{
JError::raiseWarning(500, JText::_('Could not create directory ').$path);
return $this->setRedirect('index.php?option=com_rsform&task=backup.restore');
}
$export_submissions = JRequest::getInt('submissions');
if (!RSFormProBackup::create($cid, $export_submissions, $path.'/install.xml'))
{
JError::raiseWarning(500, JText::_('Could not write to ').$path);
return $this->setRedirect('index.php?option=com_rsform&task=backup.restore');
}
$name = 'rsform_backup_'.date('Y-m-d_His').'.zip';
$files = array(array('data' => JFile::read($path.'/install.xml'), 'name' => 'install.xml'));
$adapter = JArchive::getAdapter('zip');
if (!$adapter->create($path.'/'.$name, $files))
{
JError::raiseWarning(500, JText::_('Could not create archive ').$path.'/'.$name);
return $this->setRedirect('index.php?option=com_rsform&task=backup.restore');
}
$this->setRedirect(JURI::root().'media/'.$tmpdir.'/'.$name);
}
function restoreProcess()
{
require_once JPATH_ADMINISTRATOR.'/components/com_rsform/helpers/restore.php';
jimport('joomla.filesystem.archive');
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.file');
$lang = JFactory::getLanguage();
$lang->load('com_installer');
$link = 'index.php?option=com_rsform&task=backup.restore';
if(!extension_loaded('zlib'))
{
JError::raiseWarning(500, JText::_('WARNINSTALLZLIB'));
return $this->setRedirect($link);
}
$userfile = JRequest::getVar('userfile', null, 'files');
if ($userfile['error'])
{
JError::raiseWarning(500, JText::_($userfile['error'] == 4 ? 'ERRORNOFILE' : 'WARNINSTALLUPLOADERROR'));
return $this->setRedirect($link);
}
$baseDir = JPATH_SITE.'/media';
$moved = JFile::upload($userfile['tmp_name'], $baseDir.'/'.$userfile['name']);
if (!$moved)
{
JError::raiseWarning(500, JText::_('FAILED TO MOVE UPLOADED FILE TO'));
return $this->setRedirect($link);
}
$options = array();
$options['filename'] = $baseDir.'/'.$userfile['name'];
$options['overwrite'] = JRequest::getInt('overwrite');
$restore = new RSFormProRestore($options);
if (!$restore->process())
{
JError::raiseWarning(500, JText::_('Unable to extract archive'));
return $this->setRedirect($link);
}
if (!$restore->restore())
return $this->setRedirect($link);
$this->setRedirect($link, JText::_('RSFP_RESTORE_OK'));
}
function updatesManage()
{
JRequest::setVar('view', 'updates');
JRequest::setVar('layout', 'default');
parent::display();
}
function goToPlugins()
{
$mainframe = JFactory::getApplication();
$mainframe->redirect('http://www.rsjoomla.com/support/documentation/view-knowledgebase/26-plugins-and-modules.html');
}
function goToSupport()
{
$mainframe = JFactory::getApplication();
$mainframe->redirect('http://www.rsjoomla.com/support/documentation/view-knowledgebase/21-rsform-pro-user-guide.html');
}
function plugin()
{
$mainframe = JFactory::getApplication();
$mainframe->triggerEvent('rsfp_bk_onSwitchTasks');
}
function setMenu()
{
$app = JFactory::getApplication();
$type = json_decode('{"id":0,"title":"COM_RSFORM_MENU_FORM","request":{"option":"com_rsform","view":"rsform"}}');
$title = 'component';
$app->setUserState('com_menus.edit.item.type', $title);
$component = JComponentHelper::getComponent($type->request->option);
$data['component_id'] = $component->id;
$params['option'] = 'com_rsform';
$params['view'] = 'rsform';
$params['formId'] = JRequest::getInt('formId');
$app->setUserState('com_menus.edit.item.link', 'index.php?'.JURI::buildQuery($params));
$data['type'] = $title;
$data['formId'] = JRequest::getInt('formId');
$app->setUserState('com_menus.edit.item.data', $data);
$this->setRedirect(JRoute::_('index.php?option=com_menus&view=item&layout=edit', false));
}
function captcha()
{
require_once JPATH_SITE.'/components/com_rsform/helpers/captcha.php';
$componentId = JRequest::getInt('componentId');
$captcha = new RSFormProCaptcha($componentId);
$session = JFactory::getSession();
$session->set('com_rsform.captcha.'.$componentId, $captcha->getCaptcha());
exit();
}
} | gpl-2.0 |
kamildanak/ForgeEconomy | src/main/java/com/kamildanak/minecraft/enderpay/network/server/MessageIssueBanknote.java | 2885 | package com.kamildanak.minecraft.enderpay.network.server;
import com.kamildanak.minecraft.enderpay.EnderPay;
import com.kamildanak.minecraft.enderpay.Utils;
import com.kamildanak.minecraft.enderpay.economy.Account;
import com.kamildanak.minecraft.enderpay.item.ItemFilledBanknote;
import com.kamildanak.minecraft.enderpay.network.AbstractMessage;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.text.Style;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.fml.relauncher.Side;
import java.io.IOException;
public class MessageIssueBanknote extends AbstractMessage.AbstractServerMessage<MessageIssueBanknote> {
private long amount;
private boolean expires;
@SuppressWarnings("unused")
public MessageIssueBanknote() {
}
public MessageIssueBanknote(long amount, boolean expires) {
this.amount = amount;
this.expires = expires;
}
@Override
protected void read(PacketBuffer buffer) throws IOException {
amount = buffer.readLong();
expires = buffer.readBoolean();
}
@Override
protected void write(PacketBuffer buffer) throws IOException {
buffer.writeLong(amount);
buffer.writeBoolean(expires);
}
@Override
public void process(EntityPlayer player, Side side) {
if (!Utils.isOP(player)) expires = true;
int currentItemIndex = player.inventory.currentItem;
ItemStack currentItem = player.inventory.getStackInSlot(currentItemIndex);
if (!currentItem.isEmpty() && currentItem.isItemEqual(new ItemStack(EnderPay.itemBlankBanknote))) {
Account account = Account.get(player);
if (amount <= 0) {
//noinspection RedundantArrayCreation
player.sendStatusMessage((new TextComponentTranslation("exception.enderpay.number_must_be_positive", new Object[0]))
.setStyle((new Style()).setColor(TextFormatting.RED)), true);
return;
}
if (account.getBalance() < amount) {
//noinspection RedundantArrayCreation
player.sendStatusMessage((new TextComponentTranslation("exception.enderpay.insufficient_credit", new Object[0]))
.setStyle((new Style()).setColor(TextFormatting.RED)), true);
return;
}
account.addBalance(-amount);
ItemStack newBanknote = ItemFilledBanknote.getItemStack(amount, expires);
if (!player.isCreative() || EnderPay.settings.isConsumeBanknotesInCreativeMode())
player.inventory.decrStackSize(currentItemIndex, 1);
player.inventory.addItemStackToInventory(newBanknote);
}
}
}
| gpl-2.0 |
BestWebTech/creativefreelanceprofessionals | wp-content/themes/freelanceengine/plugins/yuzo-related-post/assets/ilenframework/assets/lib/utils.php | 22021 | <?php
/**
* Pack Functions and Utils
* iLenFramework
* @package ilentheme
*/
if ( !class_exists('IF_utils') ) {
class IF_utils{
/* FUNCTION GET IMAGE POST */
/*
// Thumbnail (default 150px x 150px max)
// Medium resolution (default 300px x 300px max)
// Large resolution (default 640px x 640px max)
// Full resolution (original size uploaded)
*/
function get_ALTImage($ID){
return get_post_meta( $ID , '_wp_attachment_image_alt', true);
}
/* get image for src image in post // get original size */
function IF_catch_that_image( $post_id=null ) {
global $post;
$_post = null;
if( is_object( $post ) && !is_admin() ){
$post_id = $post;
}elseif( is_admin() ) {
$post_id = get_post($post_id);
}
if( $post_id ){
$first_img = array();
$matches = array();
$output = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_id->post_content, $matches);
if( isset($matches[1][0]) ){
$first_img['src'] = $matches[1][0];
}
$first_img['alt'] = '';
return $first_img;
}else{
return null;
}
}
/* get featured image */
function IF_get_featured_image( $size = "medium", $post_id=null ){
global $post;
/*if( is_object( $post ) && !is_admin() ){
$post_id = $post->ID;
}elseif( is_admin() ) {
$post_id = $post_id;
}*/
$url = array();
if ( has_post_thumbnail($post_id) ) { // check if the post has a Post Thumbnail assigned to it.
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), $size );
$url['alt'] = $this->get_ALTImage( $post_id );
$url['src'] = $thumb['0'];
}
return $url;
}
/* get attachment image */
function IF_get_image_post_attachment( $size = "medium", $post_id=null, $order = 'DESC' ){
$image = array();
$args = array(
'post_type' => 'attachment',
'numberposts' => 5,
'post_parent' => $post_id,
'order' => $order,
);
$args = apply_filters( 'yuzo_attachment_query' , $args );
$image['alt'] = $this->get_ALTImage($post_id);
$attachments = get_posts( $args );
//wp_reset_postdata();
//var_dump( count($attachments) );exit;
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$_array_img = wp_get_attachment_image_src( $attachment->ID , $size );
$image['src']=$_array_img[0];
return $image;
}
}
return $image;
}
/* get default imagen */
function IF_get_image_default2( $default_src="" ){
$image = array();
$image['alt']='';
$image['src']= $default_src;
return $image;
}
function IF_get_image( $size = 'medium' , $default = '', $post_id=null, $order = 'DESC' ) {
$img = array();
$img = $this->IF_get_featured_image($size,$post_id);
if( isset($img['src']) ){
return $img;
}
$img = $this->IF_get_image_post_attachment($size, $post_id, $order);
if( isset($img['src']) ){
return $img;
}
$img = $this->IF_catch_that_image( $post_id );
if( isset($img['src']) ){
return $img;
}else{
return $this->IF_get_image_default2( $default );
}
}
/* END FUNCTION GET IMAGE POST */
/**
* Return post
* See the post via ajaxat
* @return $data
*
*/
function IF_get_result_post_via_ajax(){
/*$array_value[] = array('id'=>'01','text'=>'blabla1');
$array_value[] = array('id'=>'02','text'=>'blabla2');
header( "Content-Type: application/json" );
echo json_encode($array_value);
die();
exit();*/
$term = (string) urldecode(stripslashes(strip_tags($_REQUEST['term'])));
$image_default = $_REQUEST['image_default'];
if (empty($term))
die();
$args = array(
//'post_type' => $post_types,
'post_status' => 'publish',
'posts_per_page' => 15,
's' => $term,
//'fields' => 'ids'
);
$size = "thumbnail";
$get_posts = get_posts($args);
$found_posts = array();
//$counter = 0;
if ($get_posts) {
foreach ($get_posts as $post) {
$url = array();
if( !isset( $url['src'] ) ){
if ( has_post_thumbnail( $post->ID ) ) { // check if the post has a Post Thumbnail assigned to it.
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size);
$url['src'] = $thumb['0'];
}
}
if( !isset( $url['src'] ) ){
$url = array();
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$url['alt'] = $this->get_ALTImage($post->ID);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$_array_img = wp_get_attachment_image_src( $attachment->ID , $size );
$url['src']=$_array_img[0];
break;
}
}
}
if( ! isset($url['src']) ) {
$url = array();
$matches = array();
$output = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
if( isset($matches[1][0]) ){
$url['src'] = $matches[1][0];
}
$url['alt'] = '';
}
if( ! isset($url['src']) ){
$url['src'] = $image_default;
}
$found_posts[] = array( 'id' => $post->ID,
'text' => $this->IF_cut_text(get_the_title($post->ID),75),
'image'=> $url['src'] );
//$counter++;
}
}
wp_reset_postdata();
//$response_found_posts['total'] = 10;
//$response_found_posts['posts'] = $found_posts;
// response output
header( "Content-Type: application/json" );
wp_send_json($found_posts); // http://codex.wordpress.org/Function_Reference/wp_send_json
wp_die(); // IMPORTANT: don't forget to "exit"
}
// Class paginate [experimental]
function IF_paginate( $total_rows,
$pagego,
$pagina,
$Nrecords=10,
$pagevar="pag",
$lang = ''){
$targetpage = "$pagego";
$limit = $Nrecords; // TOTAL REGISTRATION PER PAGE
$stages = 3;
// Initial pagina num setup
if ($pagina == 0 || !$pagina){$pagina = 1;}
$prev = $pagina - 1;
$next = $pagina + 1;
$lastpagina = ceil($total_rows/$limit);
$Lastpaginam1 = $lastpagina - 1;
$paginate = '';
if($lastpagina > 1)
{
$paginate .= "<div class='paginate'>";
// Previous
if ($pagina > 1){
$paginate.= "<a class='' href='$targetpage&$pagevar=$prev'>".__('Previous',$lang)."</a>";
}else{
$paginate.= "<span class=' disabled'>".__('Previous',$lang)."</span>"; }
// paginas
if ($lastpagina < 7 + ($stages * 2)) // Not enough paginas to breaking it up
{
for ($counter = 1; $counter <= $lastpagina; $counter++)
{
if ($counter == $pagina){
$paginate.= "<span class='current'>$counter</span>";
}else{
$paginate.= "<a class='' href='$targetpage&$pagevar=$counter'>$counter</a>";}
}
}
elseif($lastpagina > 5 + ($stages * 2)) // Enough paginas to hide a few?
{
// Beginning only hide later paginas
if($pagina < 1 + ($stages * 2))
{
for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
{
if ($counter == $pagina){
$paginate.= "<span class='current'>$counter</span>";
}else{
$paginate.= "<a class='' href='$targetpage&$pagevar=$counter'>$counter</a>";}
}
$paginate.= "<a href='#'>....</a>";
$paginate.= "<a class='' href='$targetpage&$pagevar=$Lastpaginam1'>$Lastpaginam1</a>";
$paginate.= "<a class='' href='$targetpage&$pagevar=$lastpagina'>$lastpagina</a>";
}
// Middle hide some front and some back
elseif($lastpagina - ($stages * 2) > $pagina && $pagina > ($stages * 2))
{
$paginate.= "<a class='' href='$targetpage&$pagevar=1'>1</a>";
$paginate.= "<a class='' href='$targetpage&$pagevar=2'>2</a>";
$paginate.= "<a href='#'>....</a>";
for ($counter = $pagina - $stages; $counter <= $pagina + $stages; $counter++)
{
if ($counter == $pagina){
$paginate.= "<span class='current'>$counter</span>";
}else{
$paginate.= "<a class='' href='$targetpage&$pagevar=$counter'>$counter</a>";
}
}
$paginate.= "<a href='#'>....</a>";
$paginate.= "<a class='' href='$targetpage&$pagevar=$Lastpaginam1'>$Lastpaginam1</a>";
$paginate.= "<a class='' href='$targetpage&$pagevar=$lastpagina'>$lastpagina</a>";
}
// End only hide early paginas
else
{
$paginate.= "<a class='' href='$targetpage&$pagevar=1'>1</a>";
$paginate.= "<a class='' href='$targetpage&$pagevar=2'>2</a>";
$paginate.= "<a href='#'>....</a>";
for ($counter = $lastpagina - (2 + ($stages * 2)); $counter <= $lastpagina; $counter++)
{
if ($counter == $pagina){
$paginate.= "<span class='' class='current'>$counter</span>";
}else{
$paginate.= "<a class='' href='$targetpage&$pagevar=$counter'>$counter</a>";}
}
}
}
// Next
if ($pagina < $counter - 1){
$paginate.= "<a class='' href='$targetpage&$pagevar=$next'>".__('Next',$lang)."</a>";
}else{
$paginate.= "<span class=' disabled' >".__('Next',$lang)."</span>";
}
// calculo
$desc_text_end = $pagina * $Nrecords;
$desc_text_begin = $desc_text_end - $Nrecords;
$desc_text_begin = ($desc_text_begin==0)?1:$desc_text_begin;
$paginate .="</div>";
}
// pagination
return $paginate;
//FIN PAGINACION // PAGINACION *******************************************************************************************************
}
function IF_get_option( $subject ){
require_once(ABSPATH . 'wp-includes/pluggable.php');
$transient_name = "cache_".$subject;
$cacheTime = 10; // Time in minutes between updates.
if( function_exists('bbp_is_user_keymaster') ){ // fix problem bbpress
//if( false === ($data = get_transient($transient_name) ) || ( bbp_is_user_keymaster() && !isset($_GET['P3_NOCACHE']) ) ){
$new_array = array();
$new_data = get_option( $subject."_options" );
if( is_array( $new_data ) ){
foreach ($new_data as $key => $value) {
$new_array[ str_replace($subject.'_', '', $key) ] = $value;
}
}
$data = json_decode (json_encode ($new_array), FALSE);
//set_transient( $transient_name , $data, MINUTE_IN_SECONDS * $cacheTime);
return $data;
/*} else {
return $data;
}*/
}else{
//if( false === ($data = get_transient($transient_name) ) || ( current_user_can( 'manage_options' ) && !isset($_GET['P3_NOCACHE']) ) ){
$new_array = array();
$new_data = get_option( $subject."_options" );
if( is_array( $new_data ) ){
foreach ($new_data as $key => $value) {
$new_array[ str_replace($subject.'_', '', $key) ] = $value;
}
}
$data = json_decode (json_encode ($new_array), FALSE);
//set_transient( $transient_name , $data, MINUTE_IN_SECONDS * $cacheTime);
return $data;
/*} else {
return $data;
}*/
}
}
function IF_getyoutubeID( $url ){
$matches = null;
preg_match("/^(?:http(?:s)?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:(?:watch)?\?(?:.*&)?v(?:i)?=|(?:embed|v|vi|user)\/))([^\?&\"'>]+)/", $url, $matches);
if( isset($matches[1]) && $matches[1] )
return (string)$matches[1];
}
/*
* @see http://stackoverflow.com/posts/2068371/revisions
*/
function IF_getyoutubeThumbnail( $id_youtube ){
return "https://img.youtube.com/vi/$id_youtube/hqdefault.jpg";
}
/**
* set string in html characteres, UTF-8
*/
function IF_setHtml( $s ){
return html_entity_decode( stripslashes($s), ENT_QUOTES, 'UTF-8' );
}
/**
* Convert Hex Color to RGB
* @link http://bavotasan.com/2011/convert-hex-color-to-rgb-using-php/
*/
function IF_hex2rgb($hex) {
$hex = str_replace("#", "", $hex);
if(strlen($hex) == 3) {
$r = hexdec(substr($hex,0,1).substr($hex,0,1));
$g = hexdec(substr($hex,1,1).substr($hex,1,1));
$b = hexdec(substr($hex,2,1).substr($hex,2,1));
} else {
$r = hexdec(substr($hex,0,2));
$g = hexdec(substr($hex,2,2));
$b = hexdec(substr($hex,4,2));
}
$rgb = array($r, $g, $b);
return implode(",", $rgb); // returns the rgb values separated by commas
//return $rgb; // returns an array with the rgb values
}
/**
* Convert hexdec color string to rgb(a) string
* @link http://mekshq.com/how-to-convert-hexadecimal-color-code-to-rgb-or-rgba-using-php/
*/
function IF_hex2rgba($color, $opacity = false, $to_array = false) {
$default = 'rgb(0,0,0)';
//Return default if no color provided
if(empty($color))
return $default;
//Sanitize $color if "#" is provided
if ($color[0] == '#' ) {
$color = substr( $color, 1 );
}
//Check if color has 6 or 3 characters and get values
if (strlen($color) == 6) {
$hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] );
} elseif ( strlen( $color ) == 3 ) {
$hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] );
} else {
return $default;
}
//Convert hexadec to rgb
$rgb = array_map('hexdec', $hex);
//Check if opacity is set(rgba or rgb)
if($opacity){
if(abs($opacity) > 1)
$opacity = 1.0;
$output = 'rgba('.implode(",",$rgb).','.$opacity.')';
}elseif( $to_array == true ){
$output = $rgb;
}else {
$output = 'rgb('.implode(",",$rgb).')';
}
//Return rgb(a) color string
return $output;
}
/**
* MIX COLORS
* @link https://gist.github.com/andrewrcollins/4570993
* @since 2.7.5 It was commented that causes problems with versions of PHP.
* @since 2.7.7 reactivate.
*/
/*function IF_mix_colors($color_1 = array(0, 0, 0), $color_2 = array(0, 0, 0), $weight = 0.5){
$f = @function($x) use ($weight) { return $weight * $x; };
$g = @function($x) use ($weight) { return (1 - $weight) * $x; };
$h = @function($x, $y) { return round($x + $y); };
return @array_map($h, array_map($f, $color_1), array_map($g, $color_2));
}
function IF_rgb2hex($rgb = array(0, 0, 0)){
$f = @function($x) { return str_pad(dechex($x), 2, "0", STR_PAD_LEFT); };
return "#" . implode("", array_map($f, $rgb));
}
function IF_tint($color, $weight = 0.5){
$t = $color;
if(is_string($color)) $t = $this->IF_hex2rgba($color,false,true);
$u = $this->IF_mix_colors($t, array(255, 255, 255), $weight);
if(is_string($color)) return $this->IF_rgb2hex($u);
return $u;
}*/
/**
* Correctly determine if date string is a valid date in that format
* @link http://stackoverflow.com/questions/19271381/correctly-determine-if-date-string-is-a-valid-date-in-that-format#comment37720734_19271434
*/
function IF_isDateFormat( $date ){
$d = DateTime::createFromFormat('Y-m-d', $date);
return $d && $d->format('Y-m-d') == $date;
}
/**
* Date Diff
* @link http://php.net/manual/es/function.date-diff.php
*/
function IF_dateDifference( $date_1 , $date_2 , $differenceFormat = '%r%a' ){
$datetime1 = date_create($date_1);
$datetime2 = date_create($date_2);
$interval = date_diff($datetime1, $datetime2);
return $interval->format($differenceFormat);
}
/**
* Return without shortcode text
* @param String $text (text to replace)
* @return $new_text
*
* @since 2.0
* @since 2.7.4 modified preg_replace
* @since 2.7.9 modified preg_replace
*/
function IF_removeShortCode( $text ){
//$new_text = preg_replace( '|\[(.+?)\](.+?\[/\\1\])?|s', '', $text );
//$new_text = preg_replace( "~(?:\[/?)[^/\]]+/?\]~s", '', $text );
/**
*
* @link http://endlessgeek.com/2014/02/wordpress-strip-shortcodes-excerpts/
*/
$new_text = preg_replace( '/\[[^\]]+\]/', '', $text );
return $new_text;
}
/**
* Return text cut
* Use strip_tags for text with and without HTML format
* @return $new_txt
*
*/
function IF_cut_text( $text = "", $length = 30, $strip_tags = false ){
$new_txt = $this->IF_removeShortCode( $text );
//$new_txt = strip_shortcodes( $new_txt );
$new_txt = trim( $new_txt );
if( $strip_tags == true ){
$new_txt = strip_tags($new_txt);
}else{
$new_txt = $new_txt;
}
if( strlen( $new_txt ) > (int)$length ){
$new_txt = mb_substr( $new_txt , 0 , (int)$length )."...";
}else{
$new_txt = mb_substr( $new_txt , 0 , (int)$length );
}
// @link https://wordpress.org/support/topic/stripping-shortcodes-keeping-the-content?replies=16
//$exclude_codes = 'shortcode_to_keep_1|keep_this_shortcode|another_shortcode_to_keep';
//$the_content = get_the_content();
//$the_content= preg_replace("~(?:\[/?)(?!(?:$exclude_codes))[^/\]]+/?\]~s", '', $the_content); # strip shortcodes, keep shortcode content
return $new_txt;
}
/**
* Return true/false
* Detect if document index is localhost
* @return boolean
*
*/
function IF_if_localhost(){
if (substr($_SERVER['REMOTE_ADDR'], 0, 4) == '127.'
|| $_SERVER['REMOTE_ADDR'] == '::1') {
return true;
}else{
return;
}
}
/**
* Return String modify
* Insert string at specified position (for string)
* Example: $oldstring = $args['before_widget'];
* $okok = insert_text_middel($oldstring, "<aside ", "style='background:black;'");
* @return String
*
*/
function IF_insert_text_middel($string, $keyword, $body) {
return substr_replace($string, PHP_EOL . $body, strpos($string, $keyword) + strlen($keyword), 0);
}
/**
* Function for retrieving and saving fonts from Google
*
*
* @uses get_transient()
* @uses set_transient()
* @uses wp_remote_get()
* @uses wp_remote_retrieve_body()
* @uses json_decode()
* @return JSON object with font data
*
*/
function IF_get_google_fonts() {
if( $this->IF_if_localhost() ){
$api_google_fonts_url = get_template_directory_uri()."/framework/ilenframework/assets/lib/webfonts.json";
}else{
$api_google_fonts_url = "https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyCjae0lAeI-4JLvCgxJExjurC4whgoOigA";
}
$fonts_url = "//fonts.googleapis.com/css?family=";
$fonts = get_transient("ilen_google_typography_fonts");
if (false === $fonts) {
//$request = wp_remote_get( $api_google_fonts_url );
$request = wp_remote_get( $api_google_fonts_url );
if(is_wp_error($request)) {
$error_message = $request->get_error_message();
echo "Something went wrong: $error_message";
} else {
$json = wp_remote_retrieve_body($request);
$data = json_decode($json, TRUE);
$items = $data["items"];
$i = 0;
foreach ($items as $item) {
$i++;
$variants = array();
foreach ($item['variants'] as $variant) {
if(!stripos($variant, "italic") && $variant != "italic") {
if($variant == "regular") {
$variants[] = "normal";
} else {
$variants[] = $variant;
}
}
}
$fonts[] = array("uid" => $i, "family" => $item["family"], "variants" => $variants);
}
set_transient("ilen_google_typography_fonts", $fonts, 60 * 60 * 24);
}
}
return $fonts;
}
/**
* Function for searching array of fonts
*
*
* @return JSON object with font data
*
*/
function multidimensional_search($parents, $searched) {
if(empty($searched) || empty($parents)) {
return false;
}
foreach($parents as $key => $value) {
$exists = true;
foreach ($searched as $skey => $svalue) {
$exists = ($exists && IsSet($parents[$key][$skey]) && $parents[$key][$skey] == $svalue);
}
if($exists){ return $parents[$key]; }
}
return false;
}
/**
* Build the frontend CSS to apply to wp_head()
*
*
*/
function build_frontend_fonts( $selector, $font, $size = null, $variant = null, $color = null, $add_style_tag = false ) {
$font_styles = "";
$frontend = "";
if( isset($selector) && $selector != "") {
$font_styles .= $selector . '{ ';
$font_styles .= 'font-family: "' . $font . '"!important; ';
if( $variant ){
$font_styles .= 'font-weight: ' . $variant . '!important; ';
}
if($size!=null) {
$font_styles .= 'font-size: ' . $size . '!important; ';
}
if($color!=null) {
$font_styles .= 'color: ' . $color . '!important; ';
}
$font_styles .= " }"; // \n
if( $add_style_tag ) { $frontend = "\n<style type=\"text/css\">\n"; }
$frontend .= $font_styles;
if( $add_style_tag ) { $frontend .= "</style>\n"; }
return $frontend;
}
}
/**
* Build the frontend CSS manual
*/
function build_frontend_css($selector, $property, $put_tag = false){
$build_css = null;
$build_css = $selector."{ $property }";
if( $put_tag == true ){
$build_css = "<style>$build_css</style>";
}
return $build_css;
}
/**
* Replace all accents for their equivalents without them
*
* @param $string
* string chain to clean
*
* @return $string
* string chain
*/
function clean_string($string){
//Esta parte se encarga de eliminar cualquier caracter extraño
$string = str_replace(
array("\\", "¨", "º", "-", "~",
"#", "@", "|", "!", "\"",
"·", "$", "%", "&", "/",
"(", ")", "?", "'", "¡",
"¿", "[", "^", "`", "]",
"+", "}", "{", "¨", "´",
">", "<", ";", ",", ":",
".", " "),
'',
$string
);
$string = str_replace(
array('á', 'à', 'ä', 'â', 'ª', 'Á', 'À', 'Â', 'Ä'),
array('a', 'a', 'a', 'a', 'a', 'A', 'A', 'A', 'A'),
$string
);
$string = str_replace(
array('é', 'è', 'ë', 'ê', 'É', 'È', 'Ê', 'Ë'),
array('e', 'e', 'e', 'e', 'E', 'E', 'E', 'E'),
$string
);
$string = str_replace(
array('í', 'ì', 'ï', 'î', 'Í', 'Ì', 'Ï', 'Î'),
array('i', 'i', 'i', 'i', 'I', 'I', 'I', 'I'),
$string
);
$string = str_replace(
array('ó', 'ò', 'ö', 'ô', 'Ó', 'Ò', 'Ö', 'Ô'),
array('o', 'o', 'o', 'o', 'O', 'O', 'O', 'O'),
$string
);
$string = str_replace(
array('ú', 'ù', 'ü', 'û', 'Ú', 'Ù', 'Û', 'Ü'),
array('u', 'u', 'u', 'u', 'U', 'U', 'U', 'U'),
$string
);
$string = str_replace(
array('ñ', 'Ñ', 'ç', 'Ç'),
array('n', 'N', 'c', 'C'),
$string
);
$string = trim($string);
return $string;
}
} // end class
global $if_utils;
$if_utils = new IF_utils;
} // end if
?> | gpl-2.0 |
iegor/kdegraphics | ksvg/dom/SVGRadialGradientElement.cc | 2479 | /*
Copyright (C) 2001-2003 KSVG Team
This file is part of the KDE project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "SVGRadialGradientElement.h"
#include "SVGRadialGradientElementImpl.h"
#include "SVGAnimatedLength.h"
using namespace KSVG;
SVGRadialGradientElement::SVGRadialGradientElement() : SVGGradientElement()
{
impl = 0;
}
SVGRadialGradientElement::SVGRadialGradientElement(const SVGRadialGradientElement &other) : SVGGradientElement(other), impl(0)
{
(*this) = other;
}
SVGRadialGradientElement &SVGRadialGradientElement::operator =(const SVGRadialGradientElement &other)
{
SVGGradientElement::operator=(other);
if(impl == other.impl)
return *this;
if(impl)
impl->deref();
impl = other.impl;
if(impl)
impl->ref();
return *this;
}
SVGRadialGradientElement::SVGRadialGradientElement(SVGRadialGradientElementImpl *other) : SVGGradientElement(other)
{
impl = other;
if(impl)
impl->ref();
}
SVGRadialGradientElement::~SVGRadialGradientElement()
{
if(impl)
impl->deref();
}
SVGAnimatedLength SVGRadialGradientElement::cx() const
{
if(!impl) return SVGAnimatedLength(0);
return SVGAnimatedLength(impl->cx());
}
SVGAnimatedLength SVGRadialGradientElement::cy() const
{
if(!impl) return SVGAnimatedLength(0);
return SVGAnimatedLength(impl->cy());
}
SVGAnimatedLength SVGRadialGradientElement::r() const
{
if(!impl) return SVGAnimatedLength(0);
return SVGAnimatedLength(impl->r());
}
SVGAnimatedLength SVGRadialGradientElement::fx() const
{
if(!impl) return SVGAnimatedLength(0);
return SVGAnimatedLength(impl->fx());
}
SVGAnimatedLength SVGRadialGradientElement::fy() const
{
if(!impl) return SVGAnimatedLength(0);
return SVGAnimatedLength(impl->fy());
}
// vim:ts=4:noet
| gpl-2.0 |
cvicentiu/mariadb-10.0 | client/mysqltest.cc | 297320 | /* Copyright (c) 2000, 2013, Oracle and/or its affiliates.
Copyright (c) 2009, 2016, Monty Program Ab.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/*
mysqltest
Tool used for executing a .test file
See the "MySQL Test framework manual" for more information
http://dev.mysql.com/doc/mysqltest/en/index.html
Please keep the test framework tools identical in all versions!
Written by:
Sasha Pachev <sasha@mysql.com>
Matt Wagner <matt@mysql.com>
Monty
Jani
Holyfoot
And many others
*/
#define MTEST_VERSION "3.4"
#include "client_priv.h"
#include <mysql_version.h>
#include <mysqld_error.h>
#include <sql_common.h>
#include <m_ctype.h>
#include <my_dir.h>
#include <hash.h>
#include <stdarg.h>
#include <violite.h>
#define PCRE_STATIC 1 /* Important on Windows */
#include "pcreposix.h" /* pcreposix regex library */
#ifdef HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#ifdef __WIN__
#include <direct.h>
#endif
#include <signal.h>
#include <my_stacktrace.h>
#include <welcome_copyright_notice.h> // ORACLE_WELCOME_COPYRIGHT_NOTICE
#ifdef __WIN__
#include <crtdbg.h>
#define SIGNAL_FMT "exception 0x%x"
#else
#define SIGNAL_FMT "signal %d"
#endif
#include <my_context.h>
static my_bool non_blocking_api_enabled= 0;
#if !defined(EMBEDDED_LIBRARY) && !defined(MY_CONTEXT_DISABLE)
#define WRAP_NONBLOCK_ENABLED non_blocking_api_enabled
#include "../tests/nonblock-wrappers.h"
#endif
/* Use cygwin for --exec and --system before 5.0 */
#if MYSQL_VERSION_ID < 50000
#define USE_CYGWIN
#endif
#define MAX_VAR_NAME_LENGTH 256
#define MAX_COLUMNS 256
#define MAX_EMBEDDED_SERVER_ARGS 64
#define MAX_DELIMITER_LENGTH 16
#define DEFAULT_MAX_CONN 64
#define DIE_BUFF_SIZE 8192
/* Flags controlling send and reap */
#define QUERY_SEND_FLAG 1
#define QUERY_REAP_FLAG 2
#define QUERY_PRINT_ORIGINAL_FLAG 4
#ifndef HAVE_SETENV
static int setenv(const char *name, const char *value, int overwrite);
#endif
C_MODE_START
static sig_handler signal_handler(int sig);
static my_bool get_one_option(int optid, const struct my_option *,
char *argument);
C_MODE_END
enum {
OPT_LOG_DIR=OPT_MAX_CLIENT_OPTION, OPT_RESULT_FORMAT_VERSION
};
static int record= 0, opt_sleep= -1;
static char *opt_db= 0, *opt_pass= 0;
const char *opt_user= 0, *opt_host= 0, *unix_sock= 0, *opt_basedir= "./";
static char *shared_memory_base_name=0;
const char *opt_logdir= "";
const char *opt_prologue= 0, *opt_charsets_dir;
static int opt_port= 0;
static int opt_max_connect_retries;
static int opt_result_format_version;
static int opt_max_connections= DEFAULT_MAX_CONN;
static int error_count= 0;
static my_bool opt_compress= 0, silent= 0, verbose= 0;
static my_bool debug_info_flag= 0, debug_check_flag= 0;
static my_bool tty_password= 0;
static my_bool opt_mark_progress= 0;
static my_bool ps_protocol= 0, ps_protocol_enabled= 0;
static my_bool sp_protocol= 0, sp_protocol_enabled= 0;
static my_bool view_protocol= 0, view_protocol_enabled= 0;
static my_bool cursor_protocol= 0, cursor_protocol_enabled= 0;
static my_bool parsing_disabled= 0;
static my_bool display_result_vertically= FALSE, display_result_lower= FALSE,
display_metadata= FALSE, display_result_sorted= FALSE;
static my_bool disable_query_log= 0, disable_result_log= 0;
static my_bool disable_connect_log= 1;
static my_bool disable_warnings= 0, disable_column_names= 0;
static my_bool prepare_warnings_enabled= 0;
static my_bool disable_info= 1;
static my_bool abort_on_error= 1, opt_continue_on_error= 0;
static my_bool server_initialized= 0;
static my_bool is_windows= 0;
static char **default_argv;
static const char *load_default_groups[]=
{ "mysqltest", "client", "client-server", "client-mariadb", 0 };
static char line_buffer[MAX_DELIMITER_LENGTH], *line_buffer_pos= line_buffer;
/* Info on properties that can be set with --enable_X and --disable_X */
struct property {
my_bool *var; /* Actual variable */
my_bool set; /* Has been set for ONE command */
my_bool old; /* If set, thus is the old value */
my_bool reverse; /* Varible is true if disabled */
const char *env_name; /* Env. variable name */
};
static struct property prop_list[] = {
{ &abort_on_error, 0, 1, 0, "$ENABLED_ABORT_ON_ERROR" },
{ &disable_connect_log, 0, 1, 1, "$ENABLED_CONNECT_LOG" },
{ &disable_info, 0, 1, 1, "$ENABLED_INFO" },
{ &display_metadata, 0, 0, 0, "$ENABLED_METADATA" },
{ &ps_protocol_enabled, 0, 0, 0, "$ENABLED_PS_PROTOCOL" },
{ &disable_query_log, 0, 0, 1, "$ENABLED_QUERY_LOG" },
{ &disable_result_log, 0, 0, 1, "$ENABLED_RESULT_LOG" },
{ &disable_warnings, 0, 0, 1, "$ENABLED_WARNINGS" }
};
static my_bool once_property= FALSE;
enum enum_prop {
P_ABORT= 0,
P_CONNECT,
P_INFO,
P_META,
P_PS,
P_QUERY,
P_RESULT,
P_WARN,
P_MAX
};
static uint start_lineno= 0; /* Start line of current command */
static uint my_end_arg= 0;
/* Number of lines of the result to include in failure report */
static uint opt_tail_lines= 0;
static uint opt_connect_timeout= 0;
static uint opt_wait_for_pos_timeout= 0;
static char delimiter[MAX_DELIMITER_LENGTH]= ";";
static uint delimiter_length= 1;
static char TMPDIR[FN_REFLEN];
static char global_subst_from[200];
static char global_subst_to[200];
static char *global_subst= NULL;
static MEM_ROOT require_file_root;
/* Block stack */
enum block_cmd {
cmd_none,
cmd_if,
cmd_while
};
struct st_block
{
int line; /* Start line of block */
my_bool ok; /* Should block be executed */
enum block_cmd cmd; /* Command owning the block */
char delim[MAX_DELIMITER_LENGTH]; /* Delimiter before block */
};
static struct st_block block_stack[32];
static struct st_block *cur_block, *block_stack_end;
/* Open file stack */
struct st_test_file
{
FILE* file;
char *file_name;
uint lineno; /* Current line in file */
};
static struct st_test_file file_stack[16];
static struct st_test_file* cur_file;
static struct st_test_file* file_stack_end;
static CHARSET_INFO *charset_info= &my_charset_latin1; /* Default charset */
static const char *embedded_server_groups[]=
{
"server",
"embedded",
"mysqltest_SERVER",
NullS
};
static int embedded_server_arg_count=0;
static char *embedded_server_args[MAX_EMBEDDED_SERVER_ARGS];
/*
Timer related variables
See the timer_output() definition for details
*/
static char *timer_file = NULL;
static ulonglong timer_start;
static void timer_output(void);
static ulonglong timer_now(void);
static ulong connection_retry_sleep= 100000; /* Microseconds */
static const char *opt_plugin_dir;
static const char *opt_suite_dir, *opt_overlay_dir;
static size_t suite_dir_len, overlay_dir_len;
/* Precompiled re's */
static regex_t ps_re; /* the query can be run using PS protocol */
static regex_t sp_re; /* the query can be run as a SP */
static regex_t view_re; /* the query can be run as a view*/
static void init_re(void);
static int match_re(regex_t *, char *);
static void free_re(void);
static char *get_string(char **to_ptr, char **from_ptr,
struct st_command *command);
static int replace(DYNAMIC_STRING *ds_str,
const char *search_str, ulong search_len,
const char *replace_str, ulong replace_len);
static uint opt_protocol=0;
DYNAMIC_ARRAY q_lines;
#include "sslopt-vars.h"
struct Parser
{
int read_lines,current_line;
} parser;
struct MasterPos
{
char file[FN_REFLEN];
ulong pos;
} master_pos;
/* if set, all results are concated and compared against this file */
const char *result_file_name= 0;
typedef struct
{
char *name;
int name_len;
char *str_val;
int str_val_len;
int int_val;
int alloced_len;
bool int_dirty; /* do not update string if int is updated until first read */
bool is_int;
bool alloced;
} VAR;
/*Perl/shell-like variable registers */
VAR var_reg[10];
HASH var_hash;
struct st_connection
{
MYSQL *mysql;
/* Used when creating views and sp, to avoid implicit commit */
MYSQL* util_mysql;
char *name;
size_t name_len;
MYSQL_STMT* stmt;
/* Set after send to disallow other queries before reap */
my_bool pending;
#ifdef EMBEDDED_LIBRARY
pthread_t tid;
const char *cur_query;
int cur_query_len;
int command, result;
pthread_mutex_t query_mutex;
pthread_cond_t query_cond;
pthread_mutex_t result_mutex;
pthread_cond_t result_cond;
int query_done;
my_bool has_thread;
#endif /*EMBEDDED_LIBRARY*/
};
struct st_connection *connections= NULL;
struct st_connection* cur_con= NULL, *next_con, *connections_end;
/*
List of commands in mysqltest
Must match the "command_names" array
Add new commands before Q_UNKNOWN!
*/
enum enum_commands {
Q_CONNECTION=1, Q_QUERY,
Q_CONNECT, Q_SLEEP, Q_REAL_SLEEP,
Q_INC, Q_DEC,
Q_SOURCE, Q_DISCONNECT,
Q_LET, Q_ECHO,
Q_WHILE, Q_END_BLOCK,
Q_SYSTEM, Q_RESULT,
Q_REQUIRE, Q_SAVE_MASTER_POS,
Q_SYNC_WITH_MASTER,
Q_SYNC_SLAVE_WITH_MASTER,
Q_ERROR,
Q_SEND, Q_REAP,
Q_DIRTY_CLOSE, Q_REPLACE, Q_REPLACE_COLUMN,
Q_PING, Q_EVAL,
Q_EVALP,
Q_EVAL_RESULT,
Q_ENABLE_QUERY_LOG, Q_DISABLE_QUERY_LOG,
Q_ENABLE_RESULT_LOG, Q_DISABLE_RESULT_LOG,
Q_ENABLE_CONNECT_LOG, Q_DISABLE_CONNECT_LOG,
Q_WAIT_FOR_SLAVE_TO_STOP,
Q_ENABLE_WARNINGS, Q_DISABLE_WARNINGS,
Q_ENABLE_INFO, Q_DISABLE_INFO,
Q_ENABLE_METADATA, Q_DISABLE_METADATA,
Q_ENABLE_COLUMN_NAMES, Q_DISABLE_COLUMN_NAMES,
Q_EXEC, Q_DELIMITER,
Q_DISABLE_ABORT_ON_ERROR, Q_ENABLE_ABORT_ON_ERROR,
Q_DISPLAY_VERTICAL_RESULTS, Q_DISPLAY_HORIZONTAL_RESULTS,
Q_QUERY_VERTICAL, Q_QUERY_HORIZONTAL, Q_SORTED_RESULT,
Q_LOWERCASE,
Q_START_TIMER, Q_END_TIMER,
Q_CHARACTER_SET, Q_DISABLE_PS_PROTOCOL, Q_ENABLE_PS_PROTOCOL,
Q_ENABLE_NON_BLOCKING_API, Q_DISABLE_NON_BLOCKING_API,
Q_DISABLE_RECONNECT, Q_ENABLE_RECONNECT,
Q_IF,
Q_DISABLE_PARSING, Q_ENABLE_PARSING,
Q_REPLACE_REGEX, Q_REMOVE_FILE, Q_FILE_EXIST,
Q_WRITE_FILE, Q_COPY_FILE, Q_PERL, Q_DIE, Q_EXIT, Q_SKIP,
Q_CHMOD_FILE, Q_APPEND_FILE, Q_CAT_FILE, Q_DIFF_FILES,
Q_SEND_QUIT, Q_CHANGE_USER, Q_MKDIR, Q_RMDIR,
Q_LIST_FILES, Q_LIST_FILES_WRITE_FILE, Q_LIST_FILES_APPEND_FILE,
Q_SEND_SHUTDOWN, Q_SHUTDOWN_SERVER,
Q_RESULT_FORMAT_VERSION,
Q_MOVE_FILE, Q_REMOVE_FILES_WILDCARD, Q_SEND_EVAL,
Q_ENABLE_PREPARE_WARNINGS, Q_DISABLE_PREPARE_WARNINGS,
Q_UNKNOWN, /* Unknown command. */
Q_COMMENT, /* Comments, ignored. */
Q_COMMENT_WITH_COMMAND,
Q_EMPTY_LINE
};
const char *command_names[]=
{
"connection",
"query",
"connect",
"sleep",
"real_sleep",
"inc",
"dec",
"source",
"disconnect",
"let",
"echo",
"while",
"end",
"system",
"result",
"require",
"save_master_pos",
"sync_with_master",
"sync_slave_with_master",
"error",
"send",
"reap",
"dirty_close",
"replace_result",
"replace_column",
"ping",
"eval",
"evalp",
"eval_result",
/* Enable/disable that the _query_ is logged to result file */
"enable_query_log",
"disable_query_log",
/* Enable/disable that the _result_ from a query is logged to result file */
"enable_result_log",
"disable_result_log",
"enable_connect_log",
"disable_connect_log",
"wait_for_slave_to_stop",
"enable_warnings",
"disable_warnings",
"enable_info",
"disable_info",
"enable_metadata",
"disable_metadata",
"enable_column_names",
"disable_column_names",
"exec",
"delimiter",
"disable_abort_on_error",
"enable_abort_on_error",
"vertical_results",
"horizontal_results",
"query_vertical",
"query_horizontal",
"sorted_result",
"lowercase_result",
"start_timer",
"end_timer",
"character_set",
"disable_ps_protocol",
"enable_ps_protocol",
"enable_non_blocking_api",
"disable_non_blocking_api",
"disable_reconnect",
"enable_reconnect",
"if",
"disable_parsing",
"enable_parsing",
"replace_regex",
"remove_file",
"file_exists",
"write_file",
"copy_file",
"perl",
"die",
/* Don't execute any more commands, compare result */
"exit",
"skip",
"chmod",
"append_file",
"cat_file",
"diff_files",
"send_quit",
"change_user",
"mkdir",
"rmdir",
"list_files",
"list_files_write_file",
"list_files_append_file",
"send_shutdown",
"shutdown_server",
"result_format",
"move_file",
"remove_files_wildcard",
"send_eval",
"enable_prepare_warnings",
"disable_prepare_warnings",
0
};
/*
The list of error codes to --error are stored in an internal array of
structs. This struct can hold numeric SQL error codes, error names or
SQLSTATE codes as strings. The element next to the last active element
in the list is set to type ERR_EMPTY. When an SQL statement returns an
error, we use this list to check if this is an expected error.
*/
enum match_err_type
{
ERR_EMPTY= 0,
ERR_ERRNO,
ERR_SQLSTATE
};
struct st_match_err
{
enum match_err_type type;
union
{
uint errnum;
char sqlstate[SQLSTATE_LENGTH+1]; /* \0 terminated string */
} code;
};
struct st_expected_errors
{
struct st_match_err err[10];
uint count;
};
static struct st_expected_errors saved_expected_errors;
struct st_command
{
char *query, *query_buf,*first_argument,*last_argument,*end;
DYNAMIC_STRING content;
DYNAMIC_STRING eval_query;
int first_word_len, query_len;
my_bool abort_on_error, used_replace;
struct st_expected_errors expected_errors;
char *require_file;
enum enum_commands type;
};
TYPELIB command_typelib= {array_elements(command_names),"",
command_names, 0};
DYNAMIC_STRING ds_res;
/* Points to ds_warning in run_query, so it can be freed */
DYNAMIC_STRING *ds_warn= 0;
struct st_command *curr_command= 0;
char builtin_echo[FN_REFLEN];
struct st_replace_regex
{
DYNAMIC_ARRAY regex_arr; /* stores a list of st_regex subsitutions */
/*
Temporary storage areas for substitutions. To reduce unnessary copying
and memory freeing/allocation, we pre-allocate two buffers, and alternate
their use, one for input/one for output, the roles changing on the next
st_regex substition. At the end of substitutions buf points to the
one containing the final result.
*/
char* buf;
char* even_buf;
char* odd_buf;
int even_buf_len;
int odd_buf_len;
};
struct st_replace_regex *glob_replace_regex= 0;
struct st_replace;
struct st_replace *glob_replace= 0;
void replace_strings_append(struct st_replace *rep, DYNAMIC_STRING* ds,
const char *from, int len);
static void cleanup_and_exit(int exit_code) __attribute__((noreturn));
void really_die(const char *msg) __attribute__((noreturn));
void report_or_die(const char *fmt, ...) ATTRIBUTE_FORMAT(printf, 1, 2);
void die(const char *fmt, ...) ATTRIBUTE_FORMAT(printf, 1, 2)
__attribute__((noreturn));
static void make_error_message(char *buf, size_t len, const char *fmt, va_list args);
void abort_not_supported_test(const char *fmt, ...) ATTRIBUTE_FORMAT(printf, 1, 2)
__attribute__((noreturn));
void verbose_msg(const char *fmt, ...) ATTRIBUTE_FORMAT(printf, 1, 2);
void log_msg(const char *fmt, ...) ATTRIBUTE_FORMAT(printf, 1, 2);
VAR* var_from_env(const char *, const char *);
VAR* var_init(VAR* v, const char *name, int name_len, const char *val,
int val_len);
VAR* var_get(const char *var_name, const char** var_name_end,
my_bool raw, my_bool ignore_not_existing);
void eval_expr(VAR* v, const char *p, const char** p_end,
bool open_end=false, bool do_eval=true);
my_bool match_delimiter(int c, const char *delim, uint length);
void dump_result_to_reject_file(char *buf, int size);
void dump_warning_messages();
void do_eval(DYNAMIC_STRING *query_eval, const char *query,
const char *query_end, my_bool pass_through_escape_chars);
void str_to_file(const char *fname, char *str, int size);
void str_to_file2(const char *fname, char *str, int size, my_bool append);
void fix_win_paths(const char *val, int len);
const char *get_errname_from_code (uint error_code);
int multi_reg_replace(struct st_replace_regex* r,char* val);
#ifdef __WIN__
void free_tmp_sh_file();
void free_win_path_patterns();
#endif
/* For replace_column */
static char *replace_column[MAX_COLUMNS];
static uint max_replace_column= 0;
void do_get_replace_column(struct st_command*);
void free_replace_column();
/* For replace */
void do_get_replace(struct st_command *command);
void free_replace();
/* For replace_regex */
void do_get_replace_regex(struct st_command *command);
void free_replace_regex();
/* Used by sleep */
void check_eol_junk_line(const char *eol);
void free_all_replace(){
free_replace();
free_replace_regex();
free_replace_column();
}
void var_set_int(const char* name, int value);
class LogFile {
FILE* m_file;
char m_file_name[FN_REFLEN];
size_t m_bytes_written;
public:
LogFile() : m_file(NULL), m_bytes_written(0) {
bzero(m_file_name, sizeof(m_file_name));
}
~LogFile() {
close();
}
const char* file_name() const { return m_file_name; }
size_t bytes_written() const { return m_bytes_written; }
void open(const char* dir, const char* name, const char* ext)
{
DBUG_ENTER("LogFile::open");
DBUG_PRINT("enter", ("dir: '%s', name: '%s'", dir, name));
if (!name)
{
m_file= stdout;
DBUG_VOID_RETURN;
}
fn_format(m_file_name, name, dir, ext,
*dir ? MY_REPLACE_DIR | MY_REPLACE_EXT :
MY_REPLACE_EXT);
DBUG_PRINT("info", ("file_name: %s", m_file_name));
if ((m_file= fopen(m_file_name, "wb+")) == NULL)
die("Failed to open log file %s, errno: %d", m_file_name, errno);
DBUG_VOID_RETURN;
}
void close()
{
if (m_file) {
if (m_file != stdout)
fclose(m_file);
else
fflush(m_file);
}
m_file= NULL;
}
void flush()
{
if (m_file && m_file != stdout)
{
if (fflush(m_file))
die("Failed to flush '%s', errno: %d", m_file_name, errno);
}
}
void write(DYNAMIC_STRING* ds)
{
DBUG_ENTER("LogFile::write");
DBUG_ASSERT(m_file);
if (ds->length == 0)
DBUG_VOID_RETURN;
DBUG_ASSERT(ds->str);
#ifdef EXTRA_DEBUG
DBUG_PRINT("QQ", ("str: %*s", (int) ds->length, ds->str));
#endif
if (fwrite(ds->str, 1, ds->length, m_file) != ds->length)
die("Failed to write %lu bytes to '%s', errno: %d",
(unsigned long)ds->length, m_file_name, errno);
m_bytes_written+= ds->length;
DBUG_VOID_RETURN;
}
void show_tail(uint lines) {
DBUG_ENTER("LogFile::show_tail");
if (!m_file || m_file == stdout)
DBUG_VOID_RETURN;
if (lines == 0)
DBUG_VOID_RETURN;
lines++;
int show_offset= 0;
char buf[256+1]; /* + zero termination for DBUG_PRINT */
size_t bytes;
bool found_bof= false;
/* Search backward in file until "lines" newline has been found */
while (lines && !found_bof)
{
show_offset-= sizeof(buf)-1;
while(fseek(m_file, show_offset, SEEK_END) != 0 && show_offset < 0)
{
found_bof= true;
// Seeking before start of file
show_offset++;
}
if ((bytes= fread(buf, 1, sizeof(buf)-1, m_file)) <= 0)
{
// ferror=0 will happen here if no queries executed yet
if (ferror(m_file))
fprintf(stderr,
"Failed to read from '%s', errno: %d, feof:%d, ferror:%d\n",
m_file_name, errno, feof(m_file), ferror(m_file));
DBUG_VOID_RETURN;
}
DBUG_PRINT("info", ("Read %zu bytes from file, buf: %.*s",
bytes, (int)bytes, buf));
char* show_from= buf + bytes;
while(show_from > buf && lines > 0 )
{
show_from--;
if (*show_from == '\n')
lines--;
}
if (show_from != buf)
{
// The last new line was found in this buf, adjust offset
show_offset+= (show_from - buf) + 1;
DBUG_PRINT("info", ("adjusted offset to %d", show_offset));
}
DBUG_PRINT("info", ("show_offset: %d", show_offset));
}
fprintf(stderr, "\nThe result from queries just before the failure was:\n");
DBUG_PRINT("info", ("show_offset: %d", show_offset));
if (!lines)
{
fprintf(stderr, "< snip >\n");
if (fseek(m_file, show_offset, SEEK_END) != 0)
{
fprintf(stderr, "Failed to seek to position %d in '%s', errno: %d",
show_offset, m_file_name, errno);
DBUG_VOID_RETURN;
}
}
else {
DBUG_PRINT("info", ("Showing the whole file"));
if (fseek(m_file, 0L, SEEK_SET) != 0)
{
fprintf(stderr, "Failed to seek to pos 0 in '%s', errno: %d",
m_file_name, errno);
DBUG_VOID_RETURN;
}
}
while ((bytes= fread(buf, 1, sizeof(buf)-1, m_file)) > 0)
if (bytes != fwrite(buf, 1, bytes, stderr))
die("Failed to write to '%s', errno: %d",
m_file_name, errno);
if (!lines)
{
fprintf(stderr,
"\nMore results from queries before failure can be found in %s\n",
m_file_name);
}
fflush(stderr);
DBUG_VOID_RETURN;
}
};
LogFile log_file;
LogFile progress_file;
void replace_dynstr_append_mem(DYNAMIC_STRING *ds, const char *val,
int len);
void replace_dynstr_append(DYNAMIC_STRING *ds, const char *val);
void replace_dynstr_append_uint(DYNAMIC_STRING *ds, uint val);
void dynstr_append_sorted(DYNAMIC_STRING* ds, DYNAMIC_STRING* ds_input,
bool keep_header);
static int match_expected_error(struct st_command *command,
unsigned int err_errno,
const char *err_sqlstate);
void handle_error(struct st_command*,
unsigned int err_errno, const char *err_error,
const char *err_sqlstate, DYNAMIC_STRING *ds);
void handle_no_error(struct st_command*);
void revert_properties();
static void handle_no_active_connection(struct st_command* command,
struct st_connection *cn, DYNAMIC_STRING *ds);
#ifdef EMBEDDED_LIBRARY
#define EMB_SEND_QUERY 1
#define EMB_READ_QUERY_RESULT 2
#define EMB_END_CONNECTION 3
#define EMB_PREPARE_STMT 4
#define EMB_EXECUTE_STMT 5
#define EMB_CLOSE_STMT 6
/* workaround for MySQL BUG#57491 */
#undef MY_WME
#define MY_WME 0
/* attributes of the query thread */
pthread_attr_t cn_thd_attrib;
/*
This procedure represents the connection and actually
runs queries when in the EMBEDDED-SERVER mode.
The run_query_normal() just sends request for running
mysql_send_query and mysql_read_query_result() here.
*/
pthread_handler_t connection_thread(void *arg)
{
struct st_connection *cn= (struct st_connection*)arg;
mysql_thread_init();
while (cn->command != EMB_END_CONNECTION)
{
if (!cn->command)
{
pthread_mutex_lock(&cn->query_mutex);
while (!cn->command)
pthread_cond_wait(&cn->query_cond, &cn->query_mutex);
pthread_mutex_unlock(&cn->query_mutex);
}
switch (cn->command)
{
case EMB_END_CONNECTION:
goto end_thread;
case EMB_SEND_QUERY:
cn->result= mysql_send_query(cn->mysql,
cn->cur_query, cn->cur_query_len);
break;
case EMB_READ_QUERY_RESULT:
cn->result= mysql_read_query_result(cn->mysql);
break;
case EMB_PREPARE_STMT:
cn->result= mysql_stmt_prepare(cn->stmt,
cn->cur_query, cn->cur_query_len);
break;
case EMB_EXECUTE_STMT:
cn->result= mysql_stmt_execute(cn->stmt);
break;
case EMB_CLOSE_STMT:
cn->result= mysql_stmt_close(cn->stmt);
break;
default:
DBUG_ASSERT(0);
}
cn->command= 0;
pthread_mutex_lock(&cn->result_mutex);
cn->query_done= 1;
pthread_cond_signal(&cn->result_cond);
pthread_mutex_unlock(&cn->result_mutex);
}
end_thread:
cn->query_done= 1;
mysql_thread_end();
pthread_exit(0);
return 0;
}
static void wait_query_thread_done(struct st_connection *con)
{
DBUG_ASSERT(con->has_thread);
if (!con->query_done)
{
pthread_mutex_lock(&con->result_mutex);
while (!con->query_done)
pthread_cond_wait(&con->result_cond, &con->result_mutex);
pthread_mutex_unlock(&con->result_mutex);
}
}
static void signal_connection_thd(struct st_connection *cn, int command)
{
DBUG_ASSERT(cn->has_thread);
cn->query_done= 0;
cn->command= command;
pthread_mutex_lock(&cn->query_mutex);
pthread_cond_signal(&cn->query_cond);
pthread_mutex_unlock(&cn->query_mutex);
}
/*
Sometimes we try to execute queries when the connection is closed.
It's done to make sure it was closed completely.
So that if our connection is closed (cn->has_thread == 0), we just return
the mysql_send_query() result which is an error in this case.
*/
static int do_send_query(struct st_connection *cn, const char *q, int q_len)
{
if (!cn->has_thread)
return mysql_send_query(cn->mysql, q, q_len);
cn->cur_query= q;
cn->cur_query_len= q_len;
signal_connection_thd(cn, EMB_SEND_QUERY);
return 0;
}
static int do_read_query_result(struct st_connection *cn)
{
DBUG_ASSERT(cn->has_thread);
wait_query_thread_done(cn);
if (cn->result)
goto exit_func;
signal_connection_thd(cn, EMB_READ_QUERY_RESULT);
wait_query_thread_done(cn);
exit_func:
return cn->result;
}
static int do_stmt_prepare(struct st_connection *cn, const char *q, int q_len)
{
/* The cn->stmt is already set. */
if (!cn->has_thread)
return mysql_stmt_prepare(cn->stmt, q, q_len);
cn->cur_query= q;
cn->cur_query_len= q_len;
signal_connection_thd(cn, EMB_PREPARE_STMT);
wait_query_thread_done(cn);
return cn->result;
}
static int do_stmt_execute(struct st_connection *cn)
{
/* The cn->stmt is already set. */
if (!cn->has_thread)
return mysql_stmt_execute(cn->stmt);
signal_connection_thd(cn, EMB_EXECUTE_STMT);
wait_query_thread_done(cn);
return cn->result;
}
static int do_stmt_close(struct st_connection *cn)
{
/* The cn->stmt is already set. */
if (!cn->has_thread)
return mysql_stmt_close(cn->stmt);
signal_connection_thd(cn, EMB_CLOSE_STMT);
wait_query_thread_done(cn);
return cn->result;
}
static void emb_close_connection(struct st_connection *cn)
{
if (!cn->has_thread)
return;
wait_query_thread_done(cn);
signal_connection_thd(cn, EMB_END_CONNECTION);
pthread_join(cn->tid, NULL);
cn->has_thread= FALSE;
pthread_mutex_destroy(&cn->query_mutex);
pthread_cond_destroy(&cn->query_cond);
pthread_mutex_destroy(&cn->result_mutex);
pthread_cond_destroy(&cn->result_cond);
}
static void init_connection_thd(struct st_connection *cn)
{
cn->query_done= 1;
cn->command= 0;
if (pthread_mutex_init(&cn->query_mutex, NULL) ||
pthread_cond_init(&cn->query_cond, NULL) ||
pthread_mutex_init(&cn->result_mutex, NULL) ||
pthread_cond_init(&cn->result_cond, NULL) ||
pthread_create(&cn->tid, &cn_thd_attrib, connection_thread, (void*)cn))
die("Error in the thread library");
cn->has_thread=TRUE;
}
#else /*EMBEDDED_LIBRARY*/
#define init_connection_thd(X) do { } while(0)
#define do_send_query(cn,q,q_len) mysql_send_query(cn->mysql, q, q_len)
#define do_read_query_result(cn) mysql_read_query_result(cn->mysql)
#define do_stmt_prepare(cn, q, q_len) mysql_stmt_prepare(cn->stmt, q, q_len)
#define do_stmt_execute(cn) mysql_stmt_execute(cn->stmt)
#define do_stmt_close(cn) mysql_stmt_close(cn->stmt)
#endif /*EMBEDDED_LIBRARY*/
void do_eval(DYNAMIC_STRING *query_eval, const char *query,
const char *query_end, my_bool pass_through_escape_chars)
{
const char *p;
register char c, next_c;
register int escaped = 0;
VAR *v;
DBUG_ENTER("do_eval");
for (p= query; (c= *p) && p < query_end; ++p)
{
switch(c) {
case '$':
if (escaped)
{
escaped= 0;
dynstr_append_mem(query_eval, p, 1);
}
else
{
if (!(v= var_get(p, &p, 0, 0)))
{
report_or_die( "Bad variable in eval");
return;
}
dynstr_append_mem(query_eval, v->str_val, v->str_val_len);
}
break;
case '\\':
next_c= *(p+1);
if (escaped)
{
escaped= 0;
dynstr_append_mem(query_eval, p, 1);
}
else if (next_c == '\\' || next_c == '$' || next_c == '"')
{
/* Set escaped only if next char is \, " or $ */
escaped= 1;
if (pass_through_escape_chars)
{
/* The escape char should be added to the output string. */
dynstr_append_mem(query_eval, p, 1);
}
}
else
dynstr_append_mem(query_eval, p, 1);
break;
default:
escaped= 0;
dynstr_append_mem(query_eval, p, 1);
break;
}
}
#ifdef __WIN__
fix_win_paths(query_eval->str, query_eval->length);
#endif
DBUG_VOID_RETURN;
}
/*
Run query and dump the result to stderr in vertical format
NOTE! This function should be safe to call when an error
has occurred and thus any further errors will be ignored (although logged)
SYNOPSIS
show_query
mysql - connection to use
query - query to run
*/
static void show_query(MYSQL* mysql, const char* query)
{
MYSQL_RES* res;
DBUG_ENTER("show_query");
if (!mysql)
DBUG_VOID_RETURN;
if (mysql_query(mysql, query))
{
log_msg("Error running query '%s': %d %s",
query, mysql_errno(mysql), mysql_error(mysql));
DBUG_VOID_RETURN;
}
if ((res= mysql_store_result(mysql)) == NULL)
{
/* No result set returned */
DBUG_VOID_RETURN;
}
{
MYSQL_ROW row;
unsigned int i;
unsigned int row_num= 0;
unsigned int num_fields= mysql_num_fields(res);
MYSQL_FIELD *fields= mysql_fetch_fields(res);
fprintf(stderr, "=== %s ===\n", query);
while ((row= mysql_fetch_row(res)))
{
unsigned long *lengths= mysql_fetch_lengths(res);
row_num++;
fprintf(stderr, "---- %d. ----\n", row_num);
for(i= 0; i < num_fields; i++)
{
fprintf(stderr, "%s\t%.*s\n",
fields[i].name,
(int)lengths[i], row[i] ? row[i] : "NULL");
}
}
for (i= 0; i < strlen(query)+8; i++)
fprintf(stderr, "=");
fprintf(stderr, "\n\n");
}
mysql_free_result(res);
DBUG_VOID_RETURN;
}
/*
Show any warnings just before the error. Since the last error
is added to the warning stack, only print @@warning_count-1 warnings.
NOTE! This function should be safe to call when an error
has occurred and this any further errors will be ignored(although logged)
SYNOPSIS
show_warnings_before_error
mysql - connection to use
*/
static void show_warnings_before_error(MYSQL* mysql)
{
MYSQL_RES* res;
const char* query= "SHOW WARNINGS";
DBUG_ENTER("show_warnings_before_error");
if (!mysql)
DBUG_VOID_RETURN;
if (mysql_query(mysql, query))
{
log_msg("Error running query '%s': %d %s",
query, mysql_errno(mysql), mysql_error(mysql));
DBUG_VOID_RETURN;
}
if ((res= mysql_store_result(mysql)) == NULL)
{
/* No result set returned */
DBUG_VOID_RETURN;
}
if (mysql_num_rows(res) <= 1)
{
/* Don't display the last row, it's "last error" */
}
else
{
MYSQL_ROW row;
unsigned int row_num= 0;
unsigned int num_fields= mysql_num_fields(res);
fprintf(stderr, "\nWarnings from just before the error:\n");
while ((row= mysql_fetch_row(res)))
{
unsigned int i;
unsigned long *lengths= mysql_fetch_lengths(res);
if (++row_num >= mysql_num_rows(res))
{
/* Don't display the last row, it's "last error" */
break;
}
for(i= 0; i < num_fields; i++)
{
fprintf(stderr, "%.*s ", (int)lengths[i],
row[i] ? row[i] : "NULL");
}
fprintf(stderr, "\n");
}
}
mysql_free_result(res);
DBUG_VOID_RETURN;
}
enum arg_type
{
ARG_STRING,
ARG_REST
};
struct command_arg {
const char *argname; /* Name of argument */
enum arg_type type; /* Type of argument */
my_bool required; /* Argument required */
DYNAMIC_STRING *ds; /* Storage for argument */
const char *description; /* Description of the argument */
};
void check_command_args(struct st_command *command,
const char *arguments,
const struct command_arg *args,
int num_args, const char delimiter_arg)
{
int i;
const char *ptr= arguments;
const char *start;
DBUG_ENTER("check_command_args");
DBUG_PRINT("enter", ("num_args: %d", num_args));
for (i= 0; i < num_args; i++)
{
const struct command_arg *arg= &args[i];
char delimiter;
switch (arg->type) {
/* A string */
case ARG_STRING:
/* Skip leading spaces */
while (*ptr && *ptr == ' ')
ptr++;
start= ptr;
delimiter = delimiter_arg;
/* If start of arg is ' ` or " search to matching quote end instead */
if (*ptr && strchr ("'`\"", *ptr))
{
delimiter= *ptr;
start= ++ptr;
}
/* Find end of arg, terminated by "delimiter" */
while (*ptr && *ptr != delimiter)
ptr++;
if (ptr > start)
{
init_dynamic_string(arg->ds, 0, ptr-start, 32);
do_eval(arg->ds, start, ptr, FALSE);
}
else
{
/* Empty string */
init_dynamic_string(arg->ds, "", 0, 0);
}
/* Find real end of arg, terminated by "delimiter_arg" */
/* This will do nothing if arg was not closed by quotes */
while (*ptr && *ptr != delimiter_arg)
ptr++;
command->last_argument= (char*)ptr;
/* Step past the delimiter */
if (*ptr && *ptr == delimiter_arg)
ptr++;
DBUG_PRINT("info", ("val: %s", arg->ds->str));
break;
/* Rest of line */
case ARG_REST:
start= ptr;
init_dynamic_string(arg->ds, 0, command->query_len, 256);
do_eval(arg->ds, start, command->end, FALSE);
command->last_argument= command->end;
DBUG_PRINT("info", ("val: %s", arg->ds->str));
break;
default:
DBUG_ASSERT("Unknown argument type");
break;
}
/* Check required arg */
if (arg->ds->length == 0 && arg->required)
die("Missing required argument '%s' to command '%.*s'", arg->argname,
command->first_word_len, command->query);
}
/* Check for too many arguments passed */
ptr= command->last_argument;
while(ptr <= command->end && *ptr != '#')
{
if (*ptr && *ptr != ' ')
die("Extra argument '%s' passed to '%.*s'",
ptr, command->first_word_len, command->query);
ptr++;
}
DBUG_VOID_RETURN;
}
void handle_command_error(struct st_command *command, uint error,
int sys_errno)
{
DBUG_ENTER("handle_command_error");
DBUG_PRINT("enter", ("error: %d", error));
var_set_int("$sys_errno",sys_errno);
var_set_int("$errno",error);
if (error != 0)
{
int i;
if (command->abort_on_error)
{
report_or_die("command \"%.*s\" failed with error: %u my_errno: %d "
"errno: %d",
command->first_word_len, command->query, error, my_errno,
sys_errno);
DBUG_VOID_RETURN;
}
i= match_expected_error(command, error, NULL);
if (i >= 0)
{
DBUG_PRINT("info", ("command \"%.*s\" failed with expected error: %u, errno: %d",
command->first_word_len, command->query, error,
sys_errno));
revert_properties();
DBUG_VOID_RETURN;
}
if (command->expected_errors.count > 0)
report_or_die("command \"%.*s\" failed with wrong error: %u "
"my_errno: %d errno: %d",
command->first_word_len, command->query, error, my_errno,
sys_errno);
}
else if (command->expected_errors.err[0].type == ERR_ERRNO &&
command->expected_errors.err[0].code.errnum != 0)
{
/* Error code we wanted was != 0, i.e. not an expected success */
report_or_die("command \"%.*s\" succeeded - should have failed with "
"errno %d...",
command->first_word_len, command->query,
command->expected_errors.err[0].code.errnum);
}
revert_properties();
DBUG_VOID_RETURN;
}
void close_connections()
{
DBUG_ENTER("close_connections");
for (--next_con; next_con >= connections; --next_con)
{
if (next_con->stmt)
do_stmt_close(next_con);
#ifdef EMBEDDED_LIBRARY
emb_close_connection(next_con);
#endif
next_con->stmt= 0;
mysql_close(next_con->mysql);
next_con->mysql= 0;
if (next_con->util_mysql)
mysql_close(next_con->util_mysql);
my_free(next_con->name);
}
my_free(connections);
DBUG_VOID_RETURN;
}
void close_statements()
{
struct st_connection *con;
DBUG_ENTER("close_statements");
for (con= connections; con < next_con; con++)
{
if (con->stmt)
mysql_stmt_close(con->stmt);
con->stmt= 0;
}
DBUG_VOID_RETURN;
}
void close_files()
{
DBUG_ENTER("close_files");
for (; cur_file >= file_stack; cur_file--)
{
if (cur_file->file && cur_file->file != stdin)
{
DBUG_PRINT("info", ("closing file: %s", cur_file->file_name));
fclose(cur_file->file);
}
my_free(cur_file->file_name);
cur_file->file_name= 0;
}
DBUG_VOID_RETURN;
}
void free_used_memory()
{
uint i;
DBUG_ENTER("free_used_memory");
if (connections)
close_connections();
close_files();
my_hash_free(&var_hash);
for (i= 0 ; i < q_lines.elements ; i++)
{
struct st_command **q= dynamic_element(&q_lines, i, struct st_command**);
my_free((*q)->query_buf);
if ((*q)->eval_query.str)
dynstr_free(&(*q)->eval_query);
if ((*q)->content.str)
dynstr_free(&(*q)->content);
my_free((*q));
}
for (i= 0; i < 10; i++)
{
if (var_reg[i].alloced_len)
my_free(var_reg[i].str_val);
}
while (embedded_server_arg_count > 1)
my_free(embedded_server_args[--embedded_server_arg_count]);
delete_dynamic(&q_lines);
dynstr_free(&ds_res);
if (ds_warn)
dynstr_free(ds_warn);
free_all_replace();
my_free(opt_pass);
free_defaults(default_argv);
free_root(&require_file_root, MYF(0));
free_re();
#ifdef __WIN__
free_tmp_sh_file();
free_win_path_patterns();
#endif
DBUG_VOID_RETURN;
}
static void cleanup_and_exit(int exit_code)
{
free_used_memory();
/* Only call mysql_server_end if mysql_server_init has been called */
if (server_initialized)
mysql_server_end();
/*
mysqltest is fundamentally written in a way that makes impossible
to free all memory before exit (consider memory allocated
for frame local DYNAMIC_STRING's and die() invoked down the stack.
We close stderr here to stop unavoidable safemalloc reports
from polluting the output.
*/
fclose(stderr);
my_end(my_end_arg);
if (!silent) {
switch (exit_code) {
case 1:
printf("not ok\n");
break;
case 0:
printf("ok\n");
break;
case 62:
printf("skipped\n");
break;
default:
printf("unknown exit code: %d\n", exit_code);
DBUG_ASSERT(0);
}
}
sf_leaking_memory= 0; /* all memory should be freed by now */
exit(exit_code);
}
size_t print_file_stack(char *s, const char *end)
{
char *start= s;
struct st_test_file* err_file= cur_file;
if (err_file == file_stack)
return 0;
for (;;)
{
err_file--;
s+= my_snprintf(s, end - s, "included from %s at line %d:\n",
err_file->file_name, err_file->lineno);
if (err_file == file_stack)
break;
}
return s - start;
}
static void make_error_message(char *buf, size_t len, const char *fmt, va_list args)
{
char *s= buf, *end= buf + len;
s+= my_snprintf(s, end - s, "mysqltest: ");
if (cur_file && cur_file != file_stack)
{
s+= my_snprintf(s, end - s, "In included file \"%s\": \n",
cur_file->file_name);
s+= print_file_stack(s, end);
}
if (start_lineno > 0)
s+= my_snprintf(s, end -s, "At line %u: ", start_lineno);
if (!fmt)
fmt= "unknown error";
s+= my_vsnprintf(s, end - s, fmt, args);
s+= my_snprintf(s, end -s, "\n", start_lineno);
}
void die(const char *fmt, ...)
{
char buff[DIE_BUFF_SIZE];
va_list args;
va_start(args, fmt);
make_error_message(buff, sizeof(buff), fmt, args);
really_die(buff);
}
void really_die(const char *msg)
{
static int dying= 0;
fflush(stdout);
fprintf(stderr, "%s", msg);
fflush(stderr);
/*
Protect against dying twice
first time 'die' is called, try to write log files
second time, just exit
*/
if (dying)
cleanup_and_exit(1);
dying= 1;
log_file.show_tail(opt_tail_lines);
/*
Help debugging by displaying any warnings that might have
been produced prior to the error
*/
if (cur_con && !cur_con->pending)
show_warnings_before_error(cur_con->mysql);
cleanup_and_exit(1);
}
void report_or_die(const char *fmt, ...)
{
va_list args;
DBUG_ENTER("report_or_die");
char buff[DIE_BUFF_SIZE];
va_start(args, fmt);
make_error_message(buff, sizeof(buff), fmt, args);
va_end(args);
if (opt_continue_on_error)
{
/* Just log the error and continue */
replace_dynstr_append(&ds_res, buff);
error_count++;
DBUG_VOID_RETURN;
}
really_die(buff);
}
void abort_not_supported_test(const char *fmt, ...)
{
va_list args;
DBUG_ENTER("abort_not_supported_test");
/* Print include filestack */
fflush(stdout);
fprintf(stderr, "The test '%s' is not supported by this installation\n",
file_stack->file_name);
fprintf(stderr, "Detected in file %s at line %d\n",
cur_file->file_name, cur_file->lineno);
char buff[DIE_BUFF_SIZE];
print_file_stack(buff, buff + sizeof(buff));
fprintf(stderr, "%s", buff);
/* Print error message */
va_start(args, fmt);
if (fmt)
{
fprintf(stderr, "reason: ");
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
fflush(stderr);
}
va_end(args);
cleanup_and_exit(62);
}
void abort_not_in_this_version()
{
die("Not available in this version of mysqltest");
}
void verbose_msg(const char *fmt, ...)
{
va_list args;
DBUG_ENTER("verbose_msg");
DBUG_PRINT("enter", ("format: %s", fmt));
if (!verbose)
DBUG_VOID_RETURN;
fflush(stdout);
va_start(args, fmt);
fprintf(stderr, "mysqltest: ");
if (cur_file && cur_file != file_stack)
fprintf(stderr, "In included file \"%s\": ",
cur_file->file_name);
if (start_lineno != 0)
fprintf(stderr, "At line %u: ", start_lineno);
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
fflush(stderr);
DBUG_VOID_RETURN;
}
void log_msg(const char *fmt, ...)
{
va_list args;
char buff[1024];
size_t len;
DBUG_ENTER("log_msg");
va_start(args, fmt);
len= my_vsnprintf(buff, sizeof(buff)-1, fmt, args);
va_end(args);
dynstr_append_mem(&ds_res, buff, len);
dynstr_append(&ds_res, "\n");
DBUG_VOID_RETURN;
}
/*
Read a file and append it to ds
SYNOPSIS
cat_file
ds - pointer to dynamic string where to add the files content
filename - name of the file to read
*/
int cat_file(DYNAMIC_STRING* ds, const char* filename)
{
int fd;
size_t len;
char buff[16384];
if ((fd= my_open(filename, O_RDONLY, MYF(0))) < 0)
return 1;
while((len= my_read(fd, (uchar*)&buff,
sizeof(buff)-1, MYF(0))) > 0)
{
char *p= buff, *start= buff;
while (p < buff+len)
{
/* Convert cr/lf to lf */
if (*p == '\r' && *(p+1) && *(p+1)== '\n')
{
/* Add fake newline instead of cr and output the line */
*p= '\n';
p++; /* Step past the "fake" newline */
*p= 0;
replace_dynstr_append_mem(ds, start, p-start);
p++; /* Step past the "fake" newline */
start= p;
}
else
p++;
}
/* Output any chars that migh be left */
*p= 0;
replace_dynstr_append_mem(ds, start, p-start);
}
my_close(fd, MYF(0));
return 0;
}
/*
Run the specified command with popen
SYNOPSIS
run_command
cmd - command to execute(should be properly quoted
ds_res- pointer to dynamic string where to store the result
*/
static int run_command(char* cmd,
DYNAMIC_STRING *ds_res)
{
char buf[512]= {0};
FILE *res_file;
int error;
DBUG_ENTER("run_command");
DBUG_PRINT("enter", ("cmd: %s", cmd));
if (!(res_file= popen(cmd, "r")))
{
report_or_die("popen(\"%s\", \"r\") failed", cmd);
return -1;
}
while (fgets(buf, sizeof(buf), res_file))
{
DBUG_PRINT("info", ("buf: %s", buf));
if(ds_res)
{
/* Save the output of this command in the supplied string */
dynstr_append(ds_res, buf);
}
else
{
/* Print it directly on screen */
fprintf(stdout, "%s", buf);
}
}
error= pclose(res_file);
DBUG_RETURN(WEXITSTATUS(error));
}
/*
Run the specified tool with variable number of arguments
SYNOPSIS
run_tool
tool_path - the name of the tool to run
ds_res - pointer to dynamic string where to store the result
... - variable number of arguments that will be properly
quoted and appended after the tool's name
*/
static int run_tool(const char *tool_path, DYNAMIC_STRING *ds_res, ...)
{
int ret;
const char* arg;
va_list args;
DYNAMIC_STRING ds_cmdline;
DBUG_ENTER("run_tool");
DBUG_PRINT("enter", ("tool_path: %s", tool_path));
if (init_dynamic_string(&ds_cmdline, IF_WIN("\"", ""), FN_REFLEN, FN_REFLEN))
die("Out of memory");
dynstr_append_os_quoted(&ds_cmdline, tool_path, NullS);
dynstr_append(&ds_cmdline, " ");
va_start(args, ds_res);
while ((arg= va_arg(args, char *)))
{
/* Options should be os quoted */
if (strncmp(arg, "--", 2) == 0)
dynstr_append_os_quoted(&ds_cmdline, arg, NullS);
else
dynstr_append(&ds_cmdline, arg);
dynstr_append(&ds_cmdline, " ");
}
va_end(args);
#ifdef __WIN__
dynstr_append(&ds_cmdline, "\"");
#endif
DBUG_PRINT("info", ("Running: %s", ds_cmdline.str));
ret= run_command(ds_cmdline.str, ds_res);
DBUG_PRINT("exit", ("ret: %d", ret));
dynstr_free(&ds_cmdline);
DBUG_RETURN(ret);
}
/*
Test if diff is present. This is needed on Windows systems
as the OS returns 1 whether diff is successful or if it is
not present.
We run diff -v and look for output in stdout.
We don't redirect stderr to stdout to make for a simplified check
Windows will output '"diff"' is not recognized... to stderr if it is
not present.
*/
#ifdef __WIN__
static int diff_check(const char *diff_name)
{
FILE *res_file;
char buf[128];
int have_diff= 0;
my_snprintf(buf, sizeof(buf), "%s -v", diff_name);
if (!(res_file= popen(buf, "r")))
die("popen(\"%s\", \"r\") failed", buf);
/*
if diff is not present, nothing will be in stdout to increment
have_diff
*/
if (fgets(buf, sizeof(buf), res_file))
have_diff= 1;
pclose(res_file);
return have_diff;
}
#endif
/*
Show the diff of two files using the systems builtin diff
command. If no such diff command exist, just dump the content
of the two files and inform about how to get "diff"
SYNOPSIS
show_diff
ds - pointer to dynamic string where to add the diff(may be NULL)
filename1 - name of first file
filename2 - name of second file
*/
void show_diff(DYNAMIC_STRING* ds,
const char* filename1, const char* filename2)
{
DYNAMIC_STRING ds_tmp;
const char *diff_name = 0;
if (init_dynamic_string(&ds_tmp, "", 256, 256))
die("Out of memory");
/* determine if we have diff on Windows
needs special processing due to return values
on that OS
This test is only done on Windows since it's only needed there
in order to correctly detect non-availibility of 'diff', and
the way it's implemented does not work with default 'diff' on Solaris.
*/
#ifdef __WIN__
if (diff_check("diff"))
diff_name = "diff";
else if (diff_check("mtrdiff"))
diff_name = "mtrdiff";
else
diff_name = 0;
#else
diff_name = "diff"; /* Otherwise always assume it's called diff */
#endif
if (diff_name)
{
/* First try with unified diff */
if (run_tool(diff_name,
&ds_tmp, /* Get output from diff in ds_tmp */
"-u",
filename1,
filename2,
"2>&1",
NULL) > 1) /* Most "diff" tools return >1 if error */
{
dynstr_set(&ds_tmp, "");
/* Fallback to context diff with "diff -c" */
if (run_tool(diff_name,
&ds_tmp, /* Get output from diff in ds_tmp */
"-c",
filename1,
filename2,
"2>&1",
NULL) > 1) /* Most "diff" tools return >1 if error */
{
dynstr_set(&ds_tmp, "");
/* Fallback to simple diff with "diff" */
if (run_tool(diff_name,
&ds_tmp, /* Get output from diff in ds_tmp */
filename1,
filename2,
"2>&1",
NULL) > 1) /* Most "diff" tools return >1 if error */
{
diff_name= 0;
}
}
}
}
if (! diff_name)
{
/*
Fallback to dump both files to result file and inform
about installing "diff"
*/
dynstr_append(&ds_tmp, "\n");
dynstr_append(&ds_tmp,
"\n"
"The two files differ but it was not possible to execute 'diff' in\n"
"order to show only the difference. Instead the whole content of the\n"
"two files was shown for you to diff manually.\n\n"
"To get a better report you should install 'diff' on your system, which you\n"
"for example can get from http://www.gnu.org/software/diffutils/diffutils.html\n"
#ifdef __WIN__
"or http://gnuwin32.sourceforge.net/packages/diffutils.htm\n"
#endif
"\n");
dynstr_append(&ds_tmp, " --- ");
dynstr_append(&ds_tmp, filename1);
dynstr_append(&ds_tmp, " >>>\n");
cat_file(&ds_tmp, filename1);
dynstr_append(&ds_tmp, "<<<\n --- ");
dynstr_append(&ds_tmp, filename1);
dynstr_append(&ds_tmp, " >>>\n");
cat_file(&ds_tmp, filename2);
dynstr_append(&ds_tmp, "<<<<\n");
}
if (ds)
{
/* Add the diff to output */
dynstr_append_mem(ds, ds_tmp.str, ds_tmp.length);
}
else
{
/* Print diff directly to stdout */
fprintf(stderr, "%s\n", ds_tmp.str);
}
dynstr_free(&ds_tmp);
}
enum compare_files_result_enum {
RESULT_OK= 0,
RESULT_CONTENT_MISMATCH= 1,
RESULT_LENGTH_MISMATCH= 2
};
/*
Compare two files, given a fd to the first file and
name of the second file
SYNOPSIS
compare_files2
fd - Open file descriptor of the first file
filename2 - Name of second file
RETURN VALUES
According to the values in "compare_files_result_enum"
*/
int compare_files2(File fd1, const char* filename2)
{
int error= RESULT_OK;
File fd2;
size_t fd1_length, fd2_length;
DYNAMIC_STRING fd1_result, fd2_result;
if ((fd2= my_open(filename2, O_RDONLY, MYF(0))) < 0)
{
my_close(fd1, MYF(0));
die("Failed to open second file: '%s'", filename2);
}
fd1_length= (size_t) my_seek(fd1, 0, SEEK_END, MYF(0));
fd2_length= (size_t) my_seek(fd2, 0, SEEK_END, MYF(0));
if (init_dynamic_string(&fd1_result, 0, fd1_length, 0) ||
init_dynamic_string(&fd2_result, 0, fd2_length, 0))
die("Out of memory when allocating data for result");
fd1_result.length= fd1_length;
fd2_result.length= fd2_length;
(void) my_seek(fd1, 0, SEEK_SET, MYF(0));
(void) my_seek(fd2, 0, SEEK_SET, MYF(0));
if (my_read(fd1, (uchar*) fd1_result.str, fd1_length, MYF(MY_WME | MY_NABP)))
die("Error when reading data from result file");
if (my_read(fd2, (uchar*) fd2_result.str, fd2_length, MYF(MY_WME | MY_NABP)))
die("Error when reading data from result file");
if (global_subst &&
(fd1_length != fd2_length ||
memcmp(fd1_result.str, fd2_result.str, fd1_length)))
{
/**
@todo MARIA_HACK
This serves for when a test is run with --default-storage-engine=X
where X is not MyISAM: tests using SHOW CREATE TABLE will always fail
because SHOW CREATE TABLE prints X instead of MyISAM. With
--global-subst=X,MyISAM , such trivial differences are eliminated and
test may be reported as passing.
--global-subst is only a quick way to run a lot of existing tests
with Maria and find bugs; it is not good enough for reaching the main
trees when Maria is merged into them.
--global-subst should be removed.
*/
uint global_subst_from_len= strlen(global_subst_from);
uint global_subst_to_len= strlen(global_subst_to);
while (replace(&fd1_result,
global_subst_from, global_subst_from_len,
global_subst_to, global_subst_to_len) == 0)
/* do nothing */ ;
/* let's compare again to see if it is ok now */
}
if (fd1_result.length != fd2_result.length)
error= RESULT_LENGTH_MISMATCH;
else if ((memcmp(fd1_result.str, fd2_result.str, fd1_result.length)))
error= RESULT_CONTENT_MISMATCH;
my_close(fd2, MYF(0));
dynstr_free(&fd1_result);
dynstr_free(&fd2_result);
return error;
}
/*
Compare two files, given their filenames
SYNOPSIS
compare_files
filename1 - Name of first file
filename2 - Name of second file
RETURN VALUES
See 'compare_files2'
*/
int compare_files(const char* filename1, const char* filename2)
{
File fd;
int error;
if ((fd= my_open(filename1, O_RDONLY, MYF(0))) < 0)
die("Failed to open first file: '%s'", filename1);
error= compare_files2(fd, filename2);
my_close(fd, MYF(0));
return error;
}
/*
Compare content of the string in ds to content of file fname
SYNOPSIS
dyn_string_cmp
ds - Dynamic string containing the string o be compared
fname - Name of file to compare with
RETURN VALUES
See 'compare_files2'
*/
int dyn_string_cmp(DYNAMIC_STRING* ds, const char *fname)
{
int error;
File fd;
char temp_file_path[FN_REFLEN];
DBUG_ENTER("dyn_string_cmp");
DBUG_PRINT("enter", ("fname: %s", fname));
if ((fd= create_temp_file(temp_file_path, TMPDIR,
"tmp", O_CREAT | O_SHARE | O_RDWR,
MYF(MY_WME))) < 0)
die("Failed to create temporary file for ds");
/* Write ds to temporary file and set file pos to beginning*/
if (my_write(fd, (uchar *) ds->str, ds->length,
MYF(MY_FNABP | MY_WME)) ||
my_seek(fd, 0, SEEK_SET, MYF(0)) == MY_FILEPOS_ERROR)
{
my_close(fd, MYF(0));
/* Remove the temporary file */
my_delete(temp_file_path, MYF(MY_WME));
die("Failed to write file '%s'", temp_file_path);
}
error= compare_files2(fd, fname);
my_close(fd, MYF(0));
/* Remove the temporary file */
my_delete(temp_file_path, MYF(MY_WME));
DBUG_RETURN(error);
}
/*
Check the content of log against result file
SYNOPSIS
check_result
RETURN VALUES
error - the function will not return
*/
void check_result()
{
const char *mess= 0;
DBUG_ENTER("check_result");
DBUG_ASSERT(result_file_name);
DBUG_PRINT("enter", ("result_file_name: %s", result_file_name));
switch (compare_files(log_file.file_name(), result_file_name)) {
case RESULT_OK:
if (!error_count)
break; /* ok */
mess= "Got errors while running test";
/* Fallthrough */
case RESULT_LENGTH_MISMATCH:
if (!mess)
mess= "Result length mismatch\n";
/* Fallthrough */
case RESULT_CONTENT_MISMATCH:
{
/*
Result mismatched, dump results to .reject file
and then show the diff
*/
char reject_file[FN_REFLEN];
size_t reject_length;
if (!mess)
mess= "Result content mismatch\n";
dirname_part(reject_file, result_file_name, &reject_length);
if (access(reject_file, W_OK) == 0)
{
/* Result file directory is writable, save reject file there */
fn_format(reject_file, result_file_name, "",
".reject", MY_REPLACE_EXT);
}
else
{
/* Put reject file in opt_logdir */
fn_format(reject_file, result_file_name, opt_logdir,
".reject", MY_REPLACE_DIR | MY_REPLACE_EXT);
}
if (my_copy(log_file.file_name(), reject_file, MYF(0)) != 0)
die("Failed to copy '%s' to '%s', errno: %d",
log_file.file_name(), reject_file, errno);
show_diff(NULL, result_file_name, reject_file);
die("%s", mess);
break;
}
default: /* impossible */
die("Unknown error code from dyn_string_cmp()");
}
DBUG_VOID_RETURN;
}
/*
Check the content of ds against a require file
If match fails, abort the test with special error code
indicating that test is not supported
SYNOPSIS
check_require
ds - content to be checked
fname - name of file to check against
RETURN VALUES
error - the function will not return
*/
void check_require(DYNAMIC_STRING* ds, const char *fname)
{
DBUG_ENTER("check_require");
if (dyn_string_cmp(ds, fname))
{
char reason[FN_REFLEN];
fn_format(reason, fname, "", "", MY_REPLACE_EXT | MY_REPLACE_DIR);
abort_not_supported_test("Test requires: '%s'", reason);
}
DBUG_VOID_RETURN;
}
/*
Remove surrounding chars from string
Return 1 if first character is found but not last
*/
static int strip_surrounding(char* str, char c1, char c2)
{
char* ptr= str;
/* Check if the first non space character is c1 */
while(*ptr && my_isspace(charset_info, *ptr))
ptr++;
if (*ptr == c1)
{
/* Replace it with a space */
*ptr= ' ';
/* Last non space charecter should be c2 */
ptr= strend(str)-1;
while(*ptr && my_isspace(charset_info, *ptr))
ptr--;
if (*ptr == c2)
{
/* Replace it with \0 */
*ptr= 0;
}
else
{
/* Mismatch detected */
return 1;
}
}
return 0;
}
static void strip_parentheses(struct st_command *command)
{
if (strip_surrounding(command->first_argument, '(', ')'))
die("%.*s - argument list started with '%c' must be ended with '%c'",
command->first_word_len, command->query, '(', ')');
}
C_MODE_START
static uchar *get_var_key(const uchar* var, size_t *len,
my_bool __attribute__((unused)) t)
{
register char* key;
key = ((VAR*)var)->name;
*len = ((VAR*)var)->name_len;
return (uchar*)key;
}
static void var_free(void *v)
{
VAR *var= (VAR*) v;
my_free(var->str_val);
if (var->alloced)
my_free(var);
}
C_MODE_END
void var_check_int(VAR *v)
{
char *endptr;
char *str= v->str_val;
/* Initially assume not a number */
v->int_val= 0;
v->is_int= false;
v->int_dirty= false;
if (!str) return;
v->int_val = (int) strtol(str, &endptr, 10);
/* It is an int if strtol consumed something up to end/space/tab */
if (endptr > str && (!*endptr || *endptr == ' ' || *endptr == '\t'))
v->is_int= true;
}
VAR *var_init(VAR *v, const char *name, int name_len, const char *val,
int val_len)
{
int val_alloc_len;
VAR *tmp_var;
if (!name_len && name)
name_len = strlen(name);
if (!val_len && val)
val_len = strlen(val) ;
if (!val)
val_len= 0;
val_alloc_len = val_len + 16; /* room to grow */
if (!(tmp_var=v) && !(tmp_var = (VAR*)my_malloc(sizeof(*tmp_var)
+ name_len+2, MYF(MY_WME))))
die("Out of memory");
if (name != NULL)
{
tmp_var->name= reinterpret_cast<char*>(tmp_var) + sizeof(*tmp_var);
memcpy(tmp_var->name, name, name_len);
tmp_var->name[name_len]= 0;
}
else
tmp_var->name= NULL;
tmp_var->alloced = (v == 0);
if (!(tmp_var->str_val = (char*)my_malloc(val_alloc_len+1, MYF(MY_WME))))
die("Out of memory");
if (val)
memcpy(tmp_var->str_val, val, val_len);
tmp_var->str_val[val_len]= 0;
var_check_int(tmp_var);
tmp_var->name_len = name_len;
tmp_var->str_val_len = val_len;
tmp_var->alloced_len = val_alloc_len;
return tmp_var;
}
VAR* var_from_env(const char *name, const char *def_val)
{
const char *tmp;
VAR *v;
if (!(tmp = getenv(name)))
tmp = def_val;
v = var_init(0, name, strlen(name), tmp, strlen(tmp));
my_hash_insert(&var_hash, (uchar*)v);
return v;
}
VAR* var_get(const char *var_name, const char **var_name_end, my_bool raw,
my_bool ignore_not_existing)
{
int digit;
VAR *v;
DBUG_ENTER("var_get");
DBUG_PRINT("enter", ("var_name: %s",var_name));
if (*var_name != '$')
goto err;
digit = *++var_name - '0';
if (digit < 0 || digit >= 10)
{
const char *save_var_name = var_name, *end;
uint length;
end = (var_name_end) ? *var_name_end : 0;
while (my_isvar(charset_info,*var_name) && var_name != end)
var_name++;
if (var_name == save_var_name)
{
if (ignore_not_existing)
DBUG_RETURN(0);
die("Empty variable");
}
length= (uint) (var_name - save_var_name);
if (length >= MAX_VAR_NAME_LENGTH)
die("Too long variable name: %s", save_var_name);
if (!(v = (VAR*) my_hash_search(&var_hash, (const uchar*) save_var_name,
length)))
{
char buff[MAX_VAR_NAME_LENGTH+1];
strmake(buff, save_var_name, length);
v= var_from_env(buff, "");
}
var_name--; /* Point at last character */
}
else
v = var_reg + digit;
if (!raw && v->int_dirty)
{
sprintf(v->str_val, "%d", v->int_val);
v->int_dirty= false;
v->str_val_len = strlen(v->str_val);
}
if (var_name_end)
*var_name_end = var_name ;
DBUG_RETURN(v);
err:
if (var_name_end)
*var_name_end = 0;
die("Unsupported variable name: %s", var_name);
DBUG_RETURN(0);
}
VAR *var_obtain(const char *name, int len)
{
VAR* v;
if ((v = (VAR*)my_hash_search(&var_hash, (const uchar *) name, len)))
return v;
v = var_init(0, name, len, "", 0);
my_hash_insert(&var_hash, (uchar*)v);
return v;
}
/*
- if variable starts with a $ it is regarded as a local test varable
- if not it is treated as a environment variable, and the corresponding
environment variable will be updated
*/
void var_set(const char *var_name, const char *var_name_end,
const char *var_val, const char *var_val_end)
{
int digit, env_var= 0;
VAR *v;
DBUG_ENTER("var_set");
DBUG_PRINT("enter", ("var_name: '%.*s' = '%.*s' (length: %d)",
(int) (var_name_end - var_name), var_name,
(int) (var_val_end - var_val), var_val,
(int) (var_val_end - var_val)));
if (*var_name != '$')
env_var= 1;
else
var_name++;
digit= *var_name - '0';
if (!(digit < 10 && digit >= 0))
{
v= var_obtain(var_name, (uint) (var_name_end - var_name));
}
else
v= var_reg + digit;
eval_expr(v, var_val, (const char**) &var_val_end);
if (env_var)
{
if (v->int_dirty)
{
sprintf(v->str_val, "%d", v->int_val);
v->int_dirty=false;
v->str_val_len= strlen(v->str_val);
}
/* setenv() expects \0-terminated strings */
DBUG_ASSERT(v->name[v->name_len] == 0);
setenv(v->name, v->str_val, 1);
}
DBUG_VOID_RETURN;
}
void var_set_string(const char* name, const char* value)
{
var_set(name, name + strlen(name), value, value + strlen(value));
}
void var_set_int(const char* name, int value)
{
char buf[21];
my_snprintf(buf, sizeof(buf), "%d", value);
var_set_string(name, buf);
}
/*
Store an integer (typically the returncode of the last SQL)
statement in the mysqltest builtin variable $mysql_errno
*/
void var_set_errno(int sql_errno)
{
var_set_int("$mysql_errno", sql_errno);
var_set_string("$mysql_errname", get_errname_from_code(sql_errno));
}
/* Functions to handle --disable and --enable properties */
void set_once_property(enum_prop prop, my_bool val)
{
property &pr= prop_list[prop];
pr.set= 1;
pr.old= *pr.var;
*pr.var= val;
var_set_int(pr.env_name, (val != pr.reverse));
once_property= TRUE;
}
void set_property(st_command *command, enum_prop prop, my_bool val)
{
char* p= command->first_argument;
if (p && !strcmp (p, "ONCE"))
{
command->last_argument= p + 4;
set_once_property(prop, val);
return;
}
property &pr= prop_list[prop];
*pr.var= val;
pr.set= 0;
var_set_int(pr.env_name, (val != pr.reverse));
}
void revert_properties()
{
if (! once_property)
return;
for (int i= 0; i < (int) P_MAX; i++)
{
property &pr= prop_list[i];
if (pr.set)
{
*pr.var= pr.old;
pr.set= 0;
var_set_int(pr.env_name, (pr.old != pr.reverse));
}
}
once_property=FALSE;
}
/*
Set variable from the result of a query
SYNOPSIS
var_query_set()
var variable to set from query
query start of query string to execute
query_end end of the query string to execute
DESCRIPTION
let @<var_name> = `<query>`
Execute the query and assign the first row of result to var as
a tab separated strings
Also assign each column of the result set to
variable "$<var_name>_<column_name>"
Thus the tab separated output can be read from $<var_name> and
and each individual column can be read as $<var_name>_<col_name>
*/
void var_query_set(VAR *var, const char *query, const char** query_end)
{
char *end = (char*)((query_end && *query_end) ?
*query_end : query + strlen(query));
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL* mysql = cur_con->mysql;
DYNAMIC_STRING ds_query;
DBUG_ENTER("var_query_set");
LINT_INIT(res);
if (!mysql)
{
struct st_command command;
memset(&command, 0, sizeof(command));
command.query= (char*)query;
command.first_word_len= (*query_end - query);
command.first_argument= command.query + command.first_word_len;
command.end= (char*)*query_end;
command.abort_on_error= 1; /* avoid uninitialized variables */
handle_no_active_connection(&command, cur_con, &ds_res);
DBUG_VOID_RETURN;
}
/* Only white space or ) allowed past ending ` */
while (end > query && *end != '`')
{
if (*end && (*end != ' ' && *end != '\t' && *end != '\n' && *end != ')'))
die("Spurious text after `query` expression");
--end;
}
if (query == end)
die("Syntax error in query, missing '`'");
++query;
/* Eval the query, thus replacing all environment variables */
init_dynamic_string(&ds_query, 0, (end - query) + 32, 256);
do_eval(&ds_query, query, end, FALSE);
if (mysql_real_query(mysql, ds_query.str, ds_query.length))
{
handle_error(curr_command, mysql_errno(mysql), mysql_error(mysql),
mysql_sqlstate(mysql), &ds_res);
/* If error was acceptable, return empty string */
dynstr_free(&ds_query);
eval_expr(var, "", 0);
DBUG_VOID_RETURN;
}
if (!(res= mysql_store_result(mysql)))
{
report_or_die("Query '%s' didn't return a result set", ds_query.str);
dynstr_free(&ds_query);
eval_expr(var, "", 0);
return;
}
dynstr_free(&ds_query);
if ((row= mysql_fetch_row(res)) && row[0])
{
/*
Concatenate all fields in the first row with tab in between
and assign that string to the $variable
*/
DYNAMIC_STRING result;
uint i;
ulong *lengths;
init_dynamic_string(&result, "", 512, 512);
lengths= mysql_fetch_lengths(res);
for (i= 0; i < mysql_num_fields(res); i++)
{
if (row[i])
{
/* Add column to tab separated string */
char *val= row[i];
int len= lengths[i];
if (glob_replace_regex)
{
/* Regex replace */
if (!multi_reg_replace(glob_replace_regex, (char*)val))
{
val= glob_replace_regex->buf;
len= strlen(val);
}
}
if (glob_replace)
replace_strings_append(glob_replace, &result, val, len);
else
dynstr_append_mem(&result, val, len);
}
dynstr_append_mem(&result, "\t", 1);
}
end= result.str + result.length-1;
/* Evaluation should not recurse via backtick */
eval_expr(var, result.str, (const char**) &end, false, false);
dynstr_free(&result);
}
else
eval_expr(var, "", 0);
mysql_free_result(res);
DBUG_VOID_RETURN;
}
static void
set_result_format_version(ulong new_version)
{
switch (new_version){
case 1:
/* The first format */
break;
case 2:
/* New format that also writes comments and empty lines
from test file to result */
break;
default:
die("Version format %lu has not yet been implemented", new_version);
break;
}
opt_result_format_version= new_version;
}
/*
Set the result format version to use when generating
the .result file
*/
static void
do_result_format_version(struct st_command *command)
{
long version;
static DYNAMIC_STRING ds_version;
const struct command_arg result_format_args[] = {
{"version", ARG_STRING, TRUE, &ds_version, "Version to use"}
};
DBUG_ENTER("do_result_format_version");
check_command_args(command, command->first_argument,
result_format_args,
sizeof(result_format_args)/sizeof(struct command_arg),
',');
/* Convert version number to int */
if (!str2int(ds_version.str, 10, (long) 0, (long) INT_MAX, &version))
die("Invalid version number: '%s'", ds_version.str);
set_result_format_version(version);
dynstr_append(&ds_res, "result_format: ");
dynstr_append_mem(&ds_res, ds_version.str, ds_version.length);
dynstr_append(&ds_res, "\n");
dynstr_free(&ds_version);
}
/*
Set variable from the result of a field in a query
This function is useful when checking for a certain value
in the output from a query that can't be restricted to only
return some values. A very good example of that is most SHOW
commands.
SYNOPSIS
var_set_query_get_value()
DESCRIPTION
let $variable= query_get_value(<query to run>,<column name>,<row no>);
<query to run> - The query that should be sent to the server
<column name> - Name of the column that holds the field be compared
against the expected value
<row no> - Number of the row that holds the field to be
compared against the expected value
*/
void var_set_query_get_value(struct st_command *command, VAR *var)
{
long row_no;
int col_no= -1;
MYSQL_RES* res;
MYSQL* mysql= cur_con->mysql;
static DYNAMIC_STRING ds_query;
static DYNAMIC_STRING ds_col;
static DYNAMIC_STRING ds_row;
const struct command_arg query_get_value_args[] = {
{"query", ARG_STRING, TRUE, &ds_query, "Query to run"},
{"column name", ARG_STRING, TRUE, &ds_col, "Name of column"},
{"row number", ARG_STRING, TRUE, &ds_row, "Number for row"}
};
DBUG_ENTER("var_set_query_get_value");
LINT_INIT(res);
if (!mysql)
{
handle_no_active_connection(command, cur_con, &ds_res);
DBUG_VOID_RETURN;
}
strip_parentheses(command);
DBUG_PRINT("info", ("query: %s", command->query));
check_command_args(command, command->first_argument, query_get_value_args,
sizeof(query_get_value_args)/sizeof(struct command_arg),
',');
DBUG_PRINT("info", ("query: %s", ds_query.str));
DBUG_PRINT("info", ("col: %s", ds_col.str));
/* Convert row number to int */
if (!str2int(ds_row.str, 10, (long) 0, (long) INT_MAX, &row_no))
die("Invalid row number: '%s'", ds_row.str);
DBUG_PRINT("info", ("row: %s, row_no: %ld", ds_row.str, row_no));
dynstr_free(&ds_row);
/* Remove any surrounding "'s from the query - if there is any */
if (strip_surrounding(ds_query.str, '"', '"'))
die("Mismatched \"'s around query '%s'", ds_query.str);
/* Run the query */
if (mysql_real_query(mysql, ds_query.str, ds_query.length))
{
handle_error(curr_command, mysql_errno(mysql), mysql_error(mysql),
mysql_sqlstate(mysql), &ds_res);
/* If error was acceptable, return empty string */
dynstr_free(&ds_query);
dynstr_free(&ds_col);
eval_expr(var, "", 0);
DBUG_VOID_RETURN;
}
if (!(res= mysql_store_result(mysql)))
{
report_or_die("Query '%s' didn't return a result set", ds_query.str);
dynstr_free(&ds_query);
dynstr_free(&ds_col);
eval_expr(var, "", 0);
return;
}
{
/* Find column number from the given column name */
uint i;
uint num_fields= mysql_num_fields(res);
MYSQL_FIELD *fields= mysql_fetch_fields(res);
for (i= 0; i < num_fields; i++)
{
if (strcmp(fields[i].name, ds_col.str) == 0 &&
strlen(fields[i].name) == ds_col.length)
{
col_no= i;
break;
}
}
if (col_no == -1)
{
mysql_free_result(res);
report_or_die("Could not find column '%s' in the result of '%s'",
ds_col.str, ds_query.str);
dynstr_free(&ds_query);
dynstr_free(&ds_col);
return;
}
DBUG_PRINT("info", ("Found column %d with name '%s'",
i, fields[i].name));
}
dynstr_free(&ds_col);
{
/* Get the value */
MYSQL_ROW row;
long rows= 0;
const char* value= "No such row";
while ((row= mysql_fetch_row(res)))
{
if (++rows == row_no)
{
DBUG_PRINT("info", ("At row %ld, column %d is '%s'",
row_no, col_no, row[col_no]));
/* Found the row to get */
if (row[col_no])
value= row[col_no];
else
value= "NULL";
break;
}
}
eval_expr(var, value, 0, false, false);
}
dynstr_free(&ds_query);
mysql_free_result(res);
DBUG_VOID_RETURN;
}
void var_copy(VAR *dest, VAR *src)
{
dest->int_val= src->int_val;
dest->is_int= src->is_int;
dest->int_dirty= src->int_dirty;
/* Alloc/realloc data for str_val in dest */
if (dest->alloced_len < src->alloced_len &&
!(dest->str_val= dest->str_val
? (char*)my_realloc(dest->str_val, src->alloced_len, MYF(MY_WME))
: (char*)my_malloc(src->alloced_len, MYF(MY_WME))))
die("Out of memory");
else
dest->alloced_len= src->alloced_len;
/* Copy str_val data to dest */
dest->str_val_len= src->str_val_len;
if (src->str_val_len)
memcpy(dest->str_val, src->str_val, src->str_val_len);
}
void eval_expr(VAR *v, const char *p, const char **p_end,
bool open_end, bool do_eval)
{
DBUG_ENTER("eval_expr");
DBUG_PRINT("enter", ("p: '%s'", p));
/* Skip to treat as pure string if no evaluation */
if (! do_eval)
goto NO_EVAL;
if (*p == '$')
{
VAR *vp;
const char* expected_end= *p_end; // Remember var end
if ((vp= var_get(p, p_end, 0, 0)))
var_copy(v, vp);
/* Apparently it is not safe to assume null-terminated string */
v->str_val[v->str_val_len]= 0;
/* Make sure there was just a $variable and nothing else */
const char* end= *p_end + 1;
if (end < expected_end && !open_end)
die("Found junk '%.*s' after $variable in expression",
(int)(expected_end - end - 1), end);
DBUG_VOID_RETURN;
}
if (*p == '`')
{
var_query_set(v, p, p_end);
DBUG_VOID_RETURN;
}
{
/* Check if this is a "let $var= query_get_value()" */
const char* get_value_str= "query_get_value";
const size_t len= strlen(get_value_str);
if (strncmp(p, get_value_str, len)==0)
{
struct st_command command;
memset(&command, 0, sizeof(command));
command.query= (char*)p;
command.first_word_len= len;
command.first_argument= command.query + len;
command.end= (char*)*p_end;
command.abort_on_error= 1; /* avoid uninitialized variables */
var_set_query_get_value(&command, v);
DBUG_VOID_RETURN;
}
}
NO_EVAL:
{
int new_val_len = (p_end && *p_end) ?
(int) (*p_end - p) : (int) strlen(p);
if (new_val_len + 1 >= v->alloced_len)
{
static int MIN_VAR_ALLOC= 32;
v->alloced_len = (new_val_len < MIN_VAR_ALLOC - 1) ?
MIN_VAR_ALLOC : new_val_len + 1;
if (!(v->str_val =
v->str_val ?
(char*)my_realloc(v->str_val, v->alloced_len+1, MYF(MY_WME)) :
(char*)my_malloc(v->alloced_len+1, MYF(MY_WME))))
die("Out of memory");
}
v->str_val_len = new_val_len;
memcpy(v->str_val, p, new_val_len);
v->str_val[new_val_len] = 0;
var_check_int(v);
}
DBUG_VOID_RETURN;
}
bool open_and_set_current(const char *name)
{
FILE *opened= fopen(name, "rb");
if (!opened)
return false;
cur_file++;
cur_file->file= opened;
cur_file->file_name= my_strdup(name, MYF(MY_FAE));
cur_file->lineno=1;
return true;
}
void open_file(const char *name)
{
char buff[FN_REFLEN];
size_t length;
const char *curname= cur_file->file_name;
DBUG_ENTER("open_file");
DBUG_PRINT("enter", ("name: %s", name));
if (cur_file == file_stack_end)
die("Source directives are nesting too deep");
if (test_if_hard_path(name))
{
if (open_and_set_current(name))
DBUG_VOID_RETURN;
}
else
{
/*
if overlay-dir is specified, and the file is located somewhere
under overlay-dir or under suite-dir, the search works as follows:
0.let suffix be current file dirname relative to siute-dir or overlay-dir
1.try in overlay-dir/suffix
2.try in suite-dir/suffix
3.try in overlay-dir
4.try in suite-dir
5.try in basedir
consider an example: 'rty' overlay of the 'qwe' suite,
file qwe/include/some.inc contains the line
--source thing.inc
we look for it in this order:
0.suffix is "include/"
1.try in rty/include/thing.inc
2.try in qwe/include/thing.inc
3.try in try/thing.inc | this is useful when t/a.test has
4.try in qwe/thing.inc | source include/b.inc;
5.try in mysql-test/include/thing.inc
otherwise the search is as follows
1.try in current file dirname
3.try in overlay-dir (if any)
4.try in suite-dir
5.try in basedir
*/
#ifdef __WIN__
fix_win_paths(curname, sizeof(curname));
#endif
bool in_overlay= opt_overlay_dir &&
!strncmp(curname, opt_overlay_dir, overlay_dir_len);
bool in_suiteir= opt_overlay_dir && !in_overlay &&
!strncmp(curname, opt_suite_dir, suite_dir_len);
if (in_overlay || in_suiteir)
{
size_t prefix_len = in_overlay ? overlay_dir_len : suite_dir_len;
char buf2[FN_REFLEN], *suffix= buf2 + prefix_len;
dirname_part(buf2, curname, &length);
/* 1. first we look in the overlay dir */
strxnmov(buff, sizeof(buff), opt_overlay_dir, suffix, name, NullS);
/*
Overlayed rty/include/thing.inc can contain the line
--source thing.inc
which would mean to include qwe/include/thing.inc.
But it looks like including "itself", so don't try to open the file,
if buff contains the same file name as curname.
*/
if (strcmp(buff, curname) && open_and_set_current(buff))
DBUG_VOID_RETURN;
/* 2. if that failed, we look in the suite dir */
strxnmov(buff, sizeof(buff), opt_suite_dir, suffix, name, NullS);
/* buff can not be equal to curname, as a file can never include itself */
if (open_and_set_current(buff))
DBUG_VOID_RETURN;
}
else
{
/* 1. try in current file dirname */
dirname_part(buff, curname, &length);
strxnmov(buff, sizeof(buff), buff, name, NullS);
if (open_and_set_current(buff))
DBUG_VOID_RETURN;
}
/* 3. now, look in the overlay dir */
if (opt_overlay_dir)
{
strxmov(buff, opt_overlay_dir, name, NullS);
if (open_and_set_current(buff))
DBUG_VOID_RETURN;
}
/* 4. if that failed - look in the suite dir */
strxmov(buff, opt_suite_dir, name, NullS);
if (open_and_set_current(buff))
DBUG_VOID_RETURN;
/* 5. the last resort - look in the base dir */
strxnmov(buff, sizeof(buff), opt_basedir, name, NullS);
if (open_and_set_current(buff))
DBUG_VOID_RETURN;
}
die("Could not open '%s' for reading, errno: %d", name, errno);
DBUG_VOID_RETURN;
}
/*
Source and execute the given file
SYNOPSIS
do_source()
query called command
DESCRIPTION
source <file_name>
Open the file <file_name> and execute it
*/
void do_source(struct st_command *command)
{
static DYNAMIC_STRING ds_filename;
const struct command_arg source_args[] = {
{ "filename", ARG_STRING, TRUE, &ds_filename, "File to source" }
};
DBUG_ENTER("do_source");
check_command_args(command, command->first_argument, source_args,
sizeof(source_args)/sizeof(struct command_arg),
' ');
/*
If this file has already been sourced, don't source it again.
It's already available in the q_lines cache.
*/
if (parser.current_line < (parser.read_lines - 1))
; /* Do nothing */
else
{
DBUG_PRINT("info", ("sourcing file: %s", ds_filename.str));
open_file(ds_filename.str);
}
dynstr_free(&ds_filename);
DBUG_VOID_RETURN;
}
#if defined __WIN__
#ifdef USE_CYGWIN
/* Variables used for temporary sh files used for emulating Unix on Windows */
char tmp_sh_name[64], tmp_sh_cmd[70];
#endif
void init_tmp_sh_file()
{
#ifdef USE_CYGWIN
/* Format a name for the tmp sh file that is unique for this process */
my_snprintf(tmp_sh_name, sizeof(tmp_sh_name), "tmp_%d.sh", getpid());
/* Format the command to execute in order to run the script */
my_snprintf(tmp_sh_cmd, sizeof(tmp_sh_cmd), "sh %s", tmp_sh_name);
#endif
}
void free_tmp_sh_file()
{
#ifdef USE_CYGWIN
my_delete(tmp_sh_name, MYF(0));
#endif
}
#endif
FILE* my_popen(DYNAMIC_STRING *ds_cmd, const char *mode)
{
#if defined __WIN__ && defined USE_CYGWIN
/* Dump the command into a sh script file and execute with popen */
str_to_file(tmp_sh_name, ds_cmd->str, ds_cmd->length);
return popen(tmp_sh_cmd, mode);
#else
return popen(ds_cmd->str, mode);
#endif
}
static void init_builtin_echo(void)
{
#ifdef __WIN__
size_t echo_length;
/* Look for "echo.exe" in same dir as mysqltest was started from */
dirname_part(builtin_echo, my_progname, &echo_length);
fn_format(builtin_echo, ".\\echo.exe",
builtin_echo, "", MYF(MY_REPLACE_DIR));
/* Make sure echo.exe exists */
if (access(builtin_echo, F_OK) != 0)
builtin_echo[0]= 0;
return;
#else
builtin_echo[0]= 0;
return;
#endif
}
/*
Replace a substring
SYNOPSIS
replace
ds_str The string to search and perform the replace in
search_str The string to search for
search_len Length of the string to search for
replace_str The string to replace with
replace_len Length of the string to replace with
RETURN
0 String replaced
1 Could not find search_str in str
*/
static int replace(DYNAMIC_STRING *ds_str,
const char *search_str, ulong search_len,
const char *replace_str, ulong replace_len)
{
DYNAMIC_STRING ds_tmp;
const char *start= strstr(ds_str->str, search_str);
if (!start)
return 1;
init_dynamic_string(&ds_tmp, "",
ds_str->length + replace_len, 256);
dynstr_append_mem(&ds_tmp, ds_str->str, start - ds_str->str);
dynstr_append_mem(&ds_tmp, replace_str, replace_len);
dynstr_append(&ds_tmp, start + search_len);
dynstr_set(ds_str, ds_tmp.str);
dynstr_free(&ds_tmp);
return 0;
}
/*
Execute given command.
SYNOPSIS
do_exec()
query called command
DESCRIPTION
exec <command>
Execute the text between exec and end of line in a subprocess.
The error code returned from the subprocess is checked against the
expected error array, previously set with the --error command.
It can thus be used to execute a command that shall fail.
NOTE
Although mysqltest is executed from cygwin shell, the command will be
executed in "cmd.exe". Thus commands like "rm" etc can NOT be used, use
mysqltest commmand(s) like "remove_file" for that
*/
void do_exec(struct st_command *command)
{
int error;
char buf[512];
FILE *res_file;
char *cmd= command->first_argument;
DYNAMIC_STRING ds_cmd;
DYNAMIC_STRING ds_sorted, *ds_result;
DBUG_ENTER("do_exec");
DBUG_PRINT("enter", ("cmd: '%s'", cmd));
/* Skip leading space */
while (*cmd && my_isspace(charset_info, *cmd))
cmd++;
if (!*cmd)
{
report_or_die("Missing argument in exec");
return;
}
command->last_argument= command->end;
init_dynamic_string(&ds_cmd, 0, command->query_len+256, 256);
/* Eval the command, thus replacing all environment variables */
do_eval(&ds_cmd, cmd, command->end, !is_windows);
/* Check if echo should be replaced with "builtin" echo */
if (builtin_echo[0] && strncmp(cmd, "echo", 4) == 0)
{
/* Replace echo with our "builtin" echo */
replace(&ds_cmd, "echo", 4, builtin_echo, strlen(builtin_echo));
}
#ifdef __WIN__
#ifndef USE_CYGWIN
/* Replace /dev/null with NUL */
while(replace(&ds_cmd, "/dev/null", 9, "NUL", 3) == 0)
;
/* Replace "closed stdout" with non existing output fd */
while(replace(&ds_cmd, ">&-", 3, ">&4", 3) == 0)
;
#endif
#endif
DBUG_PRINT("info", ("Executing '%s' as '%s'",
command->first_argument, ds_cmd.str));
if (!(res_file= my_popen(&ds_cmd, "r")))
{
dynstr_free(&ds_cmd);
if (command->abort_on_error)
report_or_die("popen(\"%s\", \"r\") failed", command->first_argument);
return;
}
ds_result= &ds_res;
if (display_result_sorted)
{
init_dynamic_string(&ds_sorted, "", 1024, 1024);
ds_result= &ds_sorted;
}
while (fgets(buf, sizeof(buf), res_file))
{
if (disable_result_log)
{
buf[strlen(buf)-1]=0;
DBUG_PRINT("exec_result",("%s", buf));
}
else
{
replace_dynstr_append(ds_result, buf);
}
}
error= pclose(res_file);
if (display_result_sorted)
{
dynstr_append_sorted(&ds_res, &ds_sorted, 0);
dynstr_free(&ds_sorted);
}
if (error > 0)
{
uint status= WEXITSTATUS(error);
int i;
if (command->abort_on_error)
{
report_or_die("exec of '%s' failed, error: %d, status: %d, errno: %d\n"
"Output from before failure:\n%s\n",
ds_cmd.str, error, status, errno,
ds_res.str);
dynstr_free(&ds_cmd);
return;
}
DBUG_PRINT("info",
("error: %d, status: %d", error, status));
i= match_expected_error(command, status, NULL);
if (i >= 0)
DBUG_PRINT("info", ("command \"%s\" failed with expected error: %d",
command->first_argument, status));
else
{
dynstr_free(&ds_cmd);
if (command->expected_errors.count > 0)
report_or_die("command \"%s\" failed with wrong error: %d",
command->first_argument, status);
}
}
else if (command->expected_errors.err[0].type == ERR_ERRNO &&
command->expected_errors.err[0].code.errnum != 0)
{
/* Error code we wanted was != 0, i.e. not an expected success */
log_msg("exec of '%s failed, error: %d, errno: %d",
ds_cmd.str, error, errno);
dynstr_free(&ds_cmd);
report_or_die("command \"%s\" succeeded - should have failed with "
"errno %d...",
command->first_argument,
command->expected_errors.err[0].code.errnum);
}
dynstr_free(&ds_cmd);
DBUG_VOID_RETURN;
}
enum enum_operator
{
DO_DEC,
DO_INC
};
/*
Decrease or increase the value of a variable
SYNOPSIS
do_modify_var()
query called command
op operation to perform on the var
DESCRIPTION
dec $var_name
inc $var_name
*/
int do_modify_var(struct st_command *command,
enum enum_operator op)
{
const char *p= command->first_argument;
VAR* v;
if (!*p)
die("Missing argument to %.*s", command->first_word_len,
command->query);
if (*p != '$')
die("The argument to %.*s must be a variable (start with $)",
command->first_word_len, command->query);
v= var_get(p, &p, 1, 0);
if (! v->is_int)
die("Cannot perform inc/dec on a non-numeric value");
switch (op) {
case DO_DEC:
v->int_val--;
break;
case DO_INC:
v->int_val++;
break;
default:
die("Invalid operator to do_modify_var");
break;
}
v->int_dirty= true;
command->last_argument= (char*)++p;
return 0;
}
/*
Wrapper for 'system' function
NOTE
If mysqltest is executed from cygwin shell, the command will be
executed in the "windows command interpreter" cmd.exe and we prepend "sh"
to make it be executed by cygwins "bash". Thus commands like "rm",
"mkdir" as well as shellscripts can executed by "system" in Windows.
*/
int my_system(DYNAMIC_STRING* ds_cmd)
{
#if defined __WIN__ && defined USE_CYGWIN
/* Dump the command into a sh script file and execute with system */
str_to_file(tmp_sh_name, ds_cmd->str, ds_cmd->length);
return system(tmp_sh_cmd);
#else
return system(ds_cmd->str);
#endif
}
/*
SYNOPSIS
do_system
command called command
DESCRIPTION
system <command>
Eval the query to expand any $variables in the command.
Execute the command with the "system" command.
*/
void do_system(struct st_command *command)
{
DYNAMIC_STRING ds_cmd;
DBUG_ENTER("do_system");
if (strlen(command->first_argument) == 0)
{
report_or_die("Missing arguments to system, nothing to do!");
return;
}
init_dynamic_string(&ds_cmd, 0, command->query_len + 64, 256);
/* Eval the system command, thus replacing all environment variables */
do_eval(&ds_cmd, command->first_argument, command->end, !is_windows);
#ifdef __WIN__
#ifndef USE_CYGWIN
/* Replace /dev/null with NUL */
while(replace(&ds_cmd, "/dev/null", 9, "NUL", 3) == 0)
;
#endif
#endif
DBUG_PRINT("info", ("running system command '%s' as '%s'",
command->first_argument, ds_cmd.str));
if (my_system(&ds_cmd))
{
if (command->abort_on_error)
report_or_die("system command '%s' failed", command->first_argument);
else
{
/* If ! abort_on_error, log message and continue */
dynstr_append(&ds_res, "system command '");
replace_dynstr_append(&ds_res, command->first_argument);
dynstr_append(&ds_res, "' failed\n");
}
}
command->last_argument= command->end;
dynstr_free(&ds_cmd);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
set_wild_chars
set true to set * etc. as wild char, false to reset
DESCRIPTION
Auxiliary function to set "our" wild chars before calling wild_compare
This is needed because the default values are changed to SQL syntax
in mysqltest_embedded.
*/
void set_wild_chars (my_bool set)
{
static char old_many= 0, old_one, old_prefix;
if (set)
{
if (wild_many == '*') return; // No need
old_many= wild_many;
old_one= wild_one;
old_prefix= wild_prefix;
wild_many= '*';
wild_one= '?';
wild_prefix= 0;
}
else
{
if (! old_many) return; // Was not set
wild_many= old_many;
wild_one= old_one;
wild_prefix= old_prefix;
}
}
/*
SYNOPSIS
do_remove_file
command called command
DESCRIPTION
remove_file <file_name>
Remove the file <file_name>
*/
void do_remove_file(struct st_command *command)
{
int error;
static DYNAMIC_STRING ds_filename;
const struct command_arg rm_args[] = {
{ "filename", ARG_STRING, TRUE, &ds_filename, "File to delete" }
};
DBUG_ENTER("do_remove_file");
check_command_args(command, command->first_argument,
rm_args, sizeof(rm_args)/sizeof(struct command_arg),
' ');
DBUG_PRINT("info", ("removing file: %s", ds_filename.str));
error= my_delete(ds_filename.str, MYF(disable_warnings ? 0 : MY_WME)) != 0;
handle_command_error(command, error, my_errno);
dynstr_free(&ds_filename);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_remove_files_wildcard
command called command
DESCRIPTION
remove_files_wildcard <directory> [<file_name_pattern>]
Remove the files in <directory> optionally matching <file_name_pattern>
*/
void do_remove_files_wildcard(struct st_command *command)
{
int error= 0, sys_errno= 0;
uint i;
size_t directory_length;
MY_DIR *dir_info;
FILEINFO *file;
char dir_separator[2];
static DYNAMIC_STRING ds_directory;
static DYNAMIC_STRING ds_wild;
static DYNAMIC_STRING ds_file_to_remove;
char dirname[FN_REFLEN];
const struct command_arg rm_args[] = {
{ "directory", ARG_STRING, TRUE, &ds_directory,
"Directory containing files to delete" },
{ "filename", ARG_STRING, FALSE, &ds_wild, "File pattern to delete" }
};
DBUG_ENTER("do_remove_files_wildcard");
check_command_args(command, command->first_argument,
rm_args, sizeof(rm_args)/sizeof(struct command_arg),
' ');
fn_format(dirname, ds_directory.str, "", "", MY_UNPACK_FILENAME);
DBUG_PRINT("info", ("listing directory: %s", dirname));
if (!(dir_info= my_dir(dirname, MYF(MY_DONT_SORT | MY_WANT_STAT | MY_WME))))
{
error= 1;
sys_errno= my_errno;
goto end;
}
init_dynamic_string(&ds_file_to_remove, dirname, 1024, 1024);
dir_separator[0]= FN_LIBCHAR;
dynstr_append_mem(&ds_file_to_remove, dir_separator, 1);
directory_length= ds_file_to_remove.length;
/* Set default wild chars for wild_compare, is changed in embedded mode */
set_wild_chars(1);
for (i= 0; i < (uint) dir_info->number_of_files; i++)
{
file= dir_info->dir_entry + i;
/* Remove only regular files, i.e. no directories etc. */
/* if (!MY_S_ISREG(file->mystat->st_mode)) */
/* MY_S_ISREG does not work here on Windows, just skip directories */
if (MY_S_ISDIR(file->mystat->st_mode))
continue;
if (ds_wild.length &&
wild_compare(file->name, ds_wild.str, 0))
continue;
ds_file_to_remove.length= directory_length;
dynstr_append(&ds_file_to_remove, file->name);
DBUG_PRINT("info", ("removing file: %s", ds_file_to_remove.str));
if ((error= (my_delete(ds_file_to_remove.str, MYF(MY_WME)) != 0)))
sys_errno= my_errno;
if (error)
break;
}
set_wild_chars(0);
my_dirend(dir_info);
end:
handle_command_error(command, error, sys_errno);
dynstr_free(&ds_directory);
dynstr_free(&ds_wild);
dynstr_free(&ds_file_to_remove);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_copy_file
command command handle
DESCRIPTION
copy_file <from_file> <to_file>
Copy <from_file> to <to_file>
NOTE! Will fail if <to_file> exists
*/
void do_copy_file(struct st_command *command)
{
int error;
static DYNAMIC_STRING ds_from_file;
static DYNAMIC_STRING ds_to_file;
const struct command_arg copy_file_args[] = {
{ "from_file", ARG_STRING, TRUE, &ds_from_file, "Filename to copy from" },
{ "to_file", ARG_STRING, TRUE, &ds_to_file, "Filename to copy to" }
};
DBUG_ENTER("do_copy_file");
check_command_args(command, command->first_argument,
copy_file_args,
sizeof(copy_file_args)/sizeof(struct command_arg),
' ');
DBUG_PRINT("info", ("Copy %s to %s", ds_from_file.str, ds_to_file.str));
/* MY_HOLD_ORIGINAL_MODES prevents attempts to chown the file */
error= (my_copy(ds_from_file.str, ds_to_file.str,
MYF(MY_DONT_OVERWRITE_FILE | MY_WME | MY_HOLD_ORIGINAL_MODES)) != 0);
handle_command_error(command, error, my_errno);
dynstr_free(&ds_from_file);
dynstr_free(&ds_to_file);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_move_file
command command handle
DESCRIPTION
move_file <from_file> <to_file>
Move <from_file> to <to_file>
*/
void do_move_file(struct st_command *command)
{
int error;
static DYNAMIC_STRING ds_from_file;
static DYNAMIC_STRING ds_to_file;
const struct command_arg move_file_args[] = {
{ "from_file", ARG_STRING, TRUE, &ds_from_file, "Filename to move from" },
{ "to_file", ARG_STRING, TRUE, &ds_to_file, "Filename to move to" }
};
DBUG_ENTER("do_move_file");
check_command_args(command, command->first_argument,
move_file_args,
sizeof(move_file_args)/sizeof(struct command_arg),
' ');
DBUG_PRINT("info", ("Move %s to %s", ds_from_file.str, ds_to_file.str));
error= (my_rename(ds_from_file.str, ds_to_file.str,
MYF(disable_warnings ? 0 : MY_WME)) != 0);
handle_command_error(command, error, my_errno);
dynstr_free(&ds_from_file);
dynstr_free(&ds_to_file);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_chmod_file
command command handle
DESCRIPTION
chmod <octal> <file_name>
Change file permission of <file_name>
*/
void do_chmod_file(struct st_command *command)
{
long mode= 0;
int err_code;
static DYNAMIC_STRING ds_mode;
static DYNAMIC_STRING ds_file;
const struct command_arg chmod_file_args[] = {
{ "mode", ARG_STRING, TRUE, &ds_mode, "Mode of file(octal) ex. 0660"},
{ "filename", ARG_STRING, TRUE, &ds_file, "Filename of file to modify" }
};
DBUG_ENTER("do_chmod_file");
check_command_args(command, command->first_argument,
chmod_file_args,
sizeof(chmod_file_args)/sizeof(struct command_arg),
' ');
/* Parse what mode to set */
if (ds_mode.length != 4 ||
str2int(ds_mode.str, 8, 0, INT_MAX, &mode) == NullS)
die("You must write a 4 digit octal number for mode");
DBUG_PRINT("info", ("chmod %o %s", (uint)mode, ds_file.str));
err_code= chmod(ds_file.str, mode);
if (err_code < 0)
err_code= 1;
handle_command_error(command, err_code, errno);
dynstr_free(&ds_mode);
dynstr_free(&ds_file);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_file_exists
command called command
DESCRIPTION
fiile_exist <file_name>
Check if file <file_name> exists
*/
void do_file_exist(struct st_command *command)
{
int error;
static DYNAMIC_STRING ds_filename;
const struct command_arg file_exist_args[] = {
{ "filename", ARG_STRING, TRUE, &ds_filename, "File to check if it exist" }
};
DBUG_ENTER("do_file_exist");
check_command_args(command, command->first_argument,
file_exist_args,
sizeof(file_exist_args)/sizeof(struct command_arg),
' ');
DBUG_PRINT("info", ("Checking for existence of file: %s", ds_filename.str));
error= (access(ds_filename.str, F_OK) != 0);
handle_command_error(command, error, errno);
dynstr_free(&ds_filename);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_mkdir
command called command
DESCRIPTION
mkdir <dir_name>
Create the directory <dir_name>
*/
void do_mkdir(struct st_command *command)
{
int error;
static DYNAMIC_STRING ds_dirname;
const struct command_arg mkdir_args[] = {
{"dirname", ARG_STRING, TRUE, &ds_dirname, "Directory to create"}
};
DBUG_ENTER("do_mkdir");
check_command_args(command, command->first_argument,
mkdir_args, sizeof(mkdir_args)/sizeof(struct command_arg),
' ');
DBUG_PRINT("info", ("creating directory: %s", ds_dirname.str));
error= my_mkdir(ds_dirname.str, 0777, MYF(MY_WME)) != 0;
handle_command_error(command, error, my_errno);
dynstr_free(&ds_dirname);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_rmdir
command called command
DESCRIPTION
rmdir <dir_name>
Remove the empty directory <dir_name>
*/
void do_rmdir(struct st_command *command)
{
int error;
static DYNAMIC_STRING ds_dirname;
const struct command_arg rmdir_args[] = {
{ "dirname", ARG_STRING, TRUE, &ds_dirname, "Directory to remove" }
};
DBUG_ENTER("do_rmdir");
check_command_args(command, command->first_argument,
rmdir_args, sizeof(rmdir_args)/sizeof(struct command_arg),
' ');
DBUG_PRINT("info", ("removing directory: %s", ds_dirname.str));
error= rmdir(ds_dirname.str) != 0;
handle_command_error(command, error, errno);
dynstr_free(&ds_dirname);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
get_list_files
ds output
ds_dirname dir to list
ds_wild wild-card file pattern (can be empty)
DESCRIPTION
list all entries in directory (matching ds_wild if given)
*/
static int get_list_files(DYNAMIC_STRING *ds, const DYNAMIC_STRING *ds_dirname,
const DYNAMIC_STRING *ds_wild)
{
uint i;
MY_DIR *dir_info;
FILEINFO *file;
DBUG_ENTER("get_list_files");
DBUG_PRINT("info", ("listing directory: %s", ds_dirname->str));
if (!(dir_info= my_dir(ds_dirname->str, MYF(MY_WANT_SORT))))
DBUG_RETURN(1);
set_wild_chars(1);
for (i= 0; i < (uint) dir_info->number_of_files; i++)
{
file= dir_info->dir_entry + i;
if (ds_wild && ds_wild->length &&
wild_compare(file->name, ds_wild->str, 0))
continue;
replace_dynstr_append(ds, file->name);
dynstr_append(ds, "\n");
}
set_wild_chars(0);
my_dirend(dir_info);
DBUG_RETURN(0);
}
/*
SYNOPSIS
do_list_files
command called command
DESCRIPTION
list_files <dir_name> [<file_name>]
List files and directories in directory <dir_name> (like `ls`)
[Matching <file_name>, where wild-cards are allowed]
*/
static void do_list_files(struct st_command *command)
{
int error;
static DYNAMIC_STRING ds_dirname;
static DYNAMIC_STRING ds_wild;
const struct command_arg list_files_args[] = {
{"dirname", ARG_STRING, TRUE, &ds_dirname, "Directory to list"},
{"file", ARG_STRING, FALSE, &ds_wild, "Filename (incl. wildcard)"}
};
DBUG_ENTER("do_list_files");
command->used_replace= 1;
check_command_args(command, command->first_argument,
list_files_args,
sizeof(list_files_args)/sizeof(struct command_arg), ' ');
error= get_list_files(&ds_res, &ds_dirname, &ds_wild);
handle_command_error(command, error, my_errno);
dynstr_free(&ds_dirname);
dynstr_free(&ds_wild);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_list_files_write_file_command
command called command
append append file, or create new
DESCRIPTION
list_files_{write|append}_file <filename> <dir_name> [<match_file>]
List files and directories in directory <dir_name> (like `ls`)
[Matching <match_file>, where wild-cards are allowed]
Note: File will be truncated if exists and append is not true.
*/
static void do_list_files_write_file_command(struct st_command *command,
my_bool append)
{
int error;
static DYNAMIC_STRING ds_content;
static DYNAMIC_STRING ds_filename;
static DYNAMIC_STRING ds_dirname;
static DYNAMIC_STRING ds_wild;
const struct command_arg list_files_args[] = {
{"filename", ARG_STRING, TRUE, &ds_filename, "Filename for write"},
{"dirname", ARG_STRING, TRUE, &ds_dirname, "Directory to list"},
{"file", ARG_STRING, FALSE, &ds_wild, "Filename (incl. wildcard)"}
};
DBUG_ENTER("do_list_files_write_file");
command->used_replace= 1;
check_command_args(command, command->first_argument,
list_files_args,
sizeof(list_files_args)/sizeof(struct command_arg), ' ');
init_dynamic_string(&ds_content, "", 1024, 1024);
error= get_list_files(&ds_content, &ds_dirname, &ds_wild);
handle_command_error(command, error, my_errno);
str_to_file2(ds_filename.str, ds_content.str, ds_content.length, append);
dynstr_free(&ds_content);
dynstr_free(&ds_filename);
dynstr_free(&ds_dirname);
dynstr_free(&ds_wild);
DBUG_VOID_RETURN;
}
/*
Read characters from line buffer or file. This is needed to allow
my_ungetc() to buffer MAX_DELIMITER_LENGTH characters for a file
NOTE:
This works as long as one doesn't change files (with 'source file_name')
when there is things pushed into the buffer. This should however not
happen for any tests in the test suite.
*/
int my_getc(FILE *file)
{
if (line_buffer_pos == line_buffer)
return fgetc(file);
return *--line_buffer_pos;
}
void my_ungetc(int c)
{
*line_buffer_pos++= (char) c;
}
void read_until_delimiter(DYNAMIC_STRING *ds,
DYNAMIC_STRING *ds_delimiter)
{
char c;
DBUG_ENTER("read_until_delimiter");
DBUG_PRINT("enter", ("delimiter: %s, length: %u",
ds_delimiter->str, (uint) ds_delimiter->length));
if (ds_delimiter->length > MAX_DELIMITER_LENGTH)
die("Max delimiter length(%d) exceeded", MAX_DELIMITER_LENGTH);
/* Read from file until delimiter is found */
while (1)
{
c= my_getc(cur_file->file);
if (c == '\n')
{
cur_file->lineno++;
/* Skip newline from the same line as the command */
if (start_lineno == (cur_file->lineno - 1))
continue;
}
else if (start_lineno == cur_file->lineno)
{
/*
No characters except \n are allowed on
the same line as the command
*/
report_or_die("Trailing characters found after command");
}
if (feof(cur_file->file))
report_or_die("End of file encountered before '%s' delimiter was found",
ds_delimiter->str);
if (match_delimiter(c, ds_delimiter->str, ds_delimiter->length))
{
DBUG_PRINT("exit", ("Found delimiter '%s'", ds_delimiter->str));
break;
}
dynstr_append_mem(ds, (const char*)&c, 1);
}
DBUG_PRINT("exit", ("ds: %s", ds->str));
DBUG_VOID_RETURN;
}
void do_write_file_command(struct st_command *command, my_bool append)
{
static DYNAMIC_STRING ds_content;
static DYNAMIC_STRING ds_filename;
static DYNAMIC_STRING ds_delimiter;
const struct command_arg write_file_args[] = {
{ "filename", ARG_STRING, TRUE, &ds_filename, "File to write to" },
{ "delimiter", ARG_STRING, FALSE, &ds_delimiter, "Delimiter to read until" }
};
DBUG_ENTER("do_write_file");
check_command_args(command,
command->first_argument,
write_file_args,
sizeof(write_file_args)/sizeof(struct command_arg),
' ');
if (!append && access(ds_filename.str, F_OK) == 0)
{
/* The file should not be overwritten */
die("File already exist: '%s'", ds_filename.str);
}
ds_content= command->content;
/* If it hasn't been done already by a loop iteration, fill it in */
if (! ds_content.str)
{
/* If no delimiter was provided, use EOF */
if (ds_delimiter.length == 0)
dynstr_set(&ds_delimiter, "EOF");
init_dynamic_string(&ds_content, "", 1024, 1024);
read_until_delimiter(&ds_content, &ds_delimiter);
command->content= ds_content;
}
/* This function could be called even if "false", so check before printing */
if (cur_block->ok)
{
DBUG_PRINT("info", ("Writing to file: %s", ds_filename.str));
str_to_file2(ds_filename.str, ds_content.str, ds_content.length, append);
}
dynstr_free(&ds_filename);
dynstr_free(&ds_delimiter);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_write_file
command called command
DESCRIPTION
write_file <file_name> [<delimiter>];
<what to write line 1>
<...>
< what to write line n>
EOF
--write_file <file_name>;
<what to write line 1>
<...>
< what to write line n>
EOF
Write everything between the "write_file" command and 'delimiter'
to "file_name"
NOTE! Will fail if <file_name> exists
Default <delimiter> is EOF
*/
void do_write_file(struct st_command *command)
{
do_write_file_command(command, FALSE);
}
/*
SYNOPSIS
do_append_file
command called command
DESCRIPTION
append_file <file_name> [<delimiter>];
<what to write line 1>
<...>
< what to write line n>
EOF
--append_file <file_name>;
<what to write line 1>
<...>
< what to write line n>
EOF
Append everything between the "append_file" command
and 'delimiter' to "file_name"
Default <delimiter> is EOF
*/
void do_append_file(struct st_command *command)
{
do_write_file_command(command, TRUE);
}
/*
SYNOPSIS
do_cat_file
command called command
DESCRIPTION
cat_file <file_name>;
Print the given file to result log
*/
void do_cat_file(struct st_command *command)
{
int error;
static DYNAMIC_STRING ds_filename;
const struct command_arg cat_file_args[] = {
{ "filename", ARG_STRING, TRUE, &ds_filename, "File to read from" }
};
DBUG_ENTER("do_cat_file");
check_command_args(command,
command->first_argument,
cat_file_args,
sizeof(cat_file_args)/sizeof(struct command_arg),
' ');
DBUG_PRINT("info", ("Reading from, file: %s", ds_filename.str));
error= cat_file(&ds_res, ds_filename.str);
handle_command_error(command, error, my_errno);
dynstr_free(&ds_filename);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_diff_files
command called command
DESCRIPTION
diff_files <file1> <file2>;
Fails if the two files differ.
*/
void do_diff_files(struct st_command *command)
{
int error= 0;
static DYNAMIC_STRING ds_filename;
static DYNAMIC_STRING ds_filename2;
const struct command_arg diff_file_args[] = {
{ "file1", ARG_STRING, TRUE, &ds_filename, "First file to diff" },
{ "file2", ARG_STRING, TRUE, &ds_filename2, "Second file to diff" }
};
DBUG_ENTER("do_diff_files");
check_command_args(command,
command->first_argument,
diff_file_args,
sizeof(diff_file_args)/sizeof(struct command_arg),
' ');
if (access(ds_filename.str, F_OK) != 0)
die("command \"diff_files\" failed, file '%s' does not exist",
ds_filename.str);
if (access(ds_filename2.str, F_OK) != 0)
die("command \"diff_files\" failed, file '%s' does not exist",
ds_filename2.str);
if ((error= compare_files(ds_filename.str, ds_filename2.str)) &&
match_expected_error(command, error, NULL) < 0)
{
/*
Compare of the two files failed, append them to output
so the failure can be analyzed, but only if it was not
expected to fail.
*/
show_diff(&ds_res, ds_filename.str, ds_filename2.str);
log_file.write(&ds_res);
log_file.flush();
dynstr_set(&ds_res, 0);
}
dynstr_free(&ds_filename);
dynstr_free(&ds_filename2);
handle_command_error(command, error, -1);
DBUG_VOID_RETURN;
}
struct st_connection * find_connection_by_name(const char *name)
{
struct st_connection *con;
for (con= connections; con < next_con; con++)
{
if (!strcmp(con->name, name))
{
return con;
}
}
return 0; /* Connection not found */
}
/*
SYNOPSIS
do_send_quit
command called command
DESCRIPTION
Sends a simple quit command to the server for the named connection.
*/
void do_send_quit(struct st_command *command)
{
char *p= command->first_argument, *name;
struct st_connection *con;
DBUG_ENTER("do_send_quit");
DBUG_PRINT("enter",("name: '%s'",p));
if (!*p)
die("Missing connection name in send_quit");
name= p;
while (*p && !my_isspace(charset_info,*p))
p++;
if (*p)
*p++= 0;
command->last_argument= p;
if (!(con= find_connection_by_name(name)))
die("connection '%s' not found in connection pool", name);
simple_command(con->mysql,COM_QUIT,0,0,1);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_change_user
command called command
DESCRIPTION
change_user [<user>], [<passwd>], [<db>]
<user> - user to change to
<passwd> - user password
<db> - default database
Changes the user and causes the database specified by db to become
the default (current) database for the the current connection.
*/
void do_change_user(struct st_command *command)
{
MYSQL *mysql = cur_con->mysql;
/* static keyword to make the NetWare compiler happy. */
static DYNAMIC_STRING ds_user, ds_passwd, ds_db;
const struct command_arg change_user_args[] = {
{ "user", ARG_STRING, FALSE, &ds_user, "User to connect as" },
{ "password", ARG_STRING, FALSE, &ds_passwd, "Password used when connecting" },
{ "database", ARG_STRING, FALSE, &ds_db, "Database to select after connect" },
};
DBUG_ENTER("do_change_user");
check_command_args(command, command->first_argument,
change_user_args,
sizeof(change_user_args)/sizeof(struct command_arg),
',');
if (cur_con->stmt)
{
mysql_stmt_close(cur_con->stmt);
cur_con->stmt= NULL;
}
if (!ds_user.length)
{
dynstr_set(&ds_user, mysql->user);
if (!ds_passwd.length)
dynstr_set(&ds_passwd, mysql->passwd);
if (!ds_db.length)
dynstr_set(&ds_db, mysql->db);
}
DBUG_PRINT("info",("connection: '%s' user: '%s' password: '%s' database: '%s'",
cur_con->name, ds_user.str, ds_passwd.str, ds_db.str));
if (mysql_change_user(mysql, ds_user.str, ds_passwd.str, ds_db.str))
handle_error(command, mysql_errno(mysql), mysql_error(mysql),
mysql_sqlstate(mysql), &ds_res);
else
handle_no_error(command);
dynstr_free(&ds_user);
dynstr_free(&ds_passwd);
dynstr_free(&ds_db);
DBUG_VOID_RETURN;
}
/*
SYNOPSIS
do_perl
command command handle
DESCRIPTION
perl [<delimiter>];
<perlscript line 1>
<...>
<perlscript line n>
EOF
Execute everything after "perl" until <delimiter> as perl.
Useful for doing more advanced things
but still being able to execute it on all platforms.
Default <delimiter> is EOF
*/
void do_perl(struct st_command *command)
{
int error;
File fd;
FILE *res_file;
char buf[FN_REFLEN];
char temp_file_path[FN_REFLEN];
static DYNAMIC_STRING ds_script;
static DYNAMIC_STRING ds_delimiter;
const struct command_arg perl_args[] = {
{ "delimiter", ARG_STRING, FALSE, &ds_delimiter, "Delimiter to read until" }
};
DBUG_ENTER("do_perl");
check_command_args(command,
command->first_argument,
perl_args,
sizeof(perl_args)/sizeof(struct command_arg),
' ');
ds_script= command->content;
/* If it hasn't been done already by a loop iteration, fill it in */
if (! ds_script.str)
{
/* If no delimiter was provided, use EOF */
if (ds_delimiter.length == 0)
dynstr_set(&ds_delimiter, "EOF");
init_dynamic_string(&ds_script, "", 1024, 1024);
read_until_delimiter(&ds_script, &ds_delimiter);
command->content= ds_script;
}
/* This function could be called even if "false", so check before doing */
if (cur_block->ok)
{
DBUG_PRINT("info", ("Executing perl: %s", ds_script.str));
/* Create temporary file name */
if ((fd= create_temp_file(temp_file_path, getenv("MYSQLTEST_VARDIR"),
"tmp", O_CREAT | O_SHARE | O_RDWR,
MYF(MY_WME))) < 0)
die("Failed to create temporary file for perl command");
my_close(fd, MYF(0));
str_to_file(temp_file_path, ds_script.str, ds_script.length);
/* Format the "perl <filename>" command */
my_snprintf(buf, sizeof(buf), "perl %s", temp_file_path);
if (!(res_file= popen(buf, "r")))
{
if (command->abort_on_error)
die("popen(\"%s\", \"r\") failed", buf);
dynstr_free(&ds_delimiter);
return;
}
while (fgets(buf, sizeof(buf), res_file))
{
if (disable_result_log)
{
buf[strlen(buf)-1]=0;
DBUG_PRINT("exec_result",("%s", buf));
}
else
{
replace_dynstr_append(&ds_res, buf);
}
}
error= pclose(res_file);
/* Remove the temporary file, but keep it if perl failed */
if (!error)
my_delete(temp_file_path, MYF(MY_WME));
/* Check for error code that indicates perl could not be started */
int exstat= WEXITSTATUS(error);
#ifdef __WIN__
if (exstat == 1)
/* Text must begin 'perl not found' as mtr looks for it */
abort_not_supported_test("perl not found in path or did not start");
#else
if (exstat == 127)
abort_not_supported_test("perl not found in path");
#endif
else
handle_command_error(command, exstat, my_errno);
}
dynstr_free(&ds_delimiter);
DBUG_VOID_RETURN;
}
/*
Print the content between echo and <delimiter> to result file.
Evaluate all variables in the string before printing, allow
for variable names to be escaped using \
SYNOPSIS
do_echo()
command called command
DESCRIPTION
echo text
Print the text after echo until end of command to result file
echo $<var_name>
Print the content of the variable <var_name> to result file
echo Some text $<var_name>
Print "Some text" plus the content of the variable <var_name> to
result file
echo Some text \$<var_name>
Print "Some text" plus $<var_name> to result file
*/
int do_echo(struct st_command *command)
{
DYNAMIC_STRING ds_echo;
DBUG_ENTER("do_echo");
init_dynamic_string(&ds_echo, "", command->query_len, 256);
do_eval(&ds_echo, command->first_argument, command->end, FALSE);
dynstr_append_mem(&ds_res, ds_echo.str, ds_echo.length);
dynstr_append_mem(&ds_res, "\n", 1);
dynstr_free(&ds_echo);
command->last_argument= command->end;
DBUG_RETURN(0);
}
void do_wait_for_slave_to_stop(struct st_command *c __attribute__((unused)))
{
static int SLAVE_POLL_INTERVAL= 300000;
MYSQL* mysql = cur_con->mysql;
for (;;)
{
MYSQL_RES *UNINIT_VAR(res);
MYSQL_ROW row;
int done;
if (mysql_query(mysql,"show status like 'Slave_running'") ||
!(res=mysql_store_result(mysql)))
die("Query failed while probing slave for stop: %s",
mysql_error(mysql));
if (!(row=mysql_fetch_row(res)) || !row[1])
{
mysql_free_result(res);
die("Strange result from query while probing slave for stop");
}
done = !strcmp(row[1],"OFF");
mysql_free_result(res);
if (done)
break;
my_sleep(SLAVE_POLL_INTERVAL);
}
return;
}
void do_sync_with_master2(struct st_command *command, long offset,
const char *connection_name)
{
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL *mysql= cur_con->mysql;
char query_buf[FN_REFLEN+128];
int timeout= opt_wait_for_pos_timeout;
if (!master_pos.file[0])
die("Calling 'sync_with_master' without calling 'save_master_pos'");
sprintf(query_buf, "select master_pos_wait('%s', %ld, %d, '%s')",
master_pos.file, master_pos.pos + offset, timeout,
connection_name);
if (mysql_query(mysql, query_buf))
die("failed in '%s': %d: %s", query_buf, mysql_errno(mysql),
mysql_error(mysql));
if (!(res= mysql_store_result(mysql)))
die("mysql_store_result() returned NULL for '%s'", query_buf);
if (!(row= mysql_fetch_row(res)))
{
mysql_free_result(res);
die("empty result in %s", query_buf);
}
int result= -99;
const char* result_str= row[0];
if (result_str)
result= atoi(result_str);
mysql_free_result(res);
if (!result_str || result < 0)
{
/* master_pos_wait returned NULL or < 0 */
show_query(mysql, "SHOW MASTER STATUS");
show_query(mysql, "SHOW SLAVE STATUS");
show_query(mysql, "SHOW PROCESSLIST");
fprintf(stderr, "analyze: sync_with_master\n");
if (!result_str)
{
/*
master_pos_wait returned NULL. This indicates that
slave SQL thread is not started, the slave's master
information is not initialized, the arguments are
incorrect, or an error has occurred
*/
die("%.*s failed: '%s' returned NULL " \
"indicating slave SQL thread failure",
command->first_word_len, command->query, query_buf);
}
if (result == -1)
die("%.*s failed: '%s' returned -1 " \
"indicating timeout after %d seconds",
command->first_word_len, command->query, query_buf, timeout);
else
die("%.*s failed: '%s' returned unknown result :%d",
command->first_word_len, command->query, query_buf, result);
}
return;
}
void do_sync_with_master(struct st_command *command)
{
long offset= 0;
char *p= command->first_argument;
const char *offset_start= p;
char *start, *buff= 0;
start= (char*) "";
if (*offset_start)
{
for (; my_isdigit(charset_info, *p); p++)
offset = offset * 10 + *p - '0';
if (*p && !my_isspace(charset_info, *p) && *p != ',')
die("Invalid integer argument \"%s\"", offset_start);
while (*p && my_isspace(charset_info, *p))
p++;
if (*p == ',')
{
p++;
while (*p && my_isspace(charset_info, *p))
p++;
start= buff= (char*)my_malloc(strlen(p)+1,MYF(MY_WME | MY_FAE));
get_string(&buff, &p, command);
}
command->last_argument= p;
}
do_sync_with_master2(command, offset, start);
if (buff)
my_free(start);
return;
}
/*
when ndb binlog is on, this call will wait until last updated epoch
(locally in the mysqld) has been received into the binlog
*/
int do_save_master_pos()
{
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL *mysql = cur_con->mysql;
const char *query;
DBUG_ENTER("do_save_master_pos");
#ifdef HAVE_NDB_BINLOG
/*
Wait for ndb binlog to be up-to-date with all changes
done on the local mysql server
*/
{
ulong have_ndbcluster;
if (mysql_query(mysql, query= "show variables like 'have_ndbcluster'"))
die("'%s' failed: %d %s", query,
mysql_errno(mysql), mysql_error(mysql));
if (!(res= mysql_store_result(mysql)))
die("mysql_store_result() returned NULL for '%s'", query);
if (!(row= mysql_fetch_row(res)))
die("Query '%s' returned empty result", query);
have_ndbcluster= strcmp("YES", row[1]) == 0;
mysql_free_result(res);
if (have_ndbcluster)
{
ulonglong start_epoch= 0, handled_epoch= 0,
latest_epoch=0, latest_trans_epoch=0,
latest_handled_binlog_epoch= 0, latest_received_binlog_epoch= 0,
latest_applied_binlog_epoch= 0;
int count= 0;
int do_continue= 1;
while (do_continue)
{
const char binlog[]= "binlog";
const char latest_epoch_str[]=
"latest_epoch=";
const char latest_trans_epoch_str[]=
"latest_trans_epoch=";
const char latest_received_binlog_epoch_str[]=
"latest_received_binlog_epoch";
const char latest_handled_binlog_epoch_str[]=
"latest_handled_binlog_epoch=";
const char latest_applied_binlog_epoch_str[]=
"latest_applied_binlog_epoch=";
if (count)
my_sleep(100*1000); /* 100ms */
if (mysql_query(mysql, query= "show engine ndb status"))
die("failed in '%s': %d %s", query,
mysql_errno(mysql), mysql_error(mysql));
if (!(res= mysql_store_result(mysql)))
die("mysql_store_result() returned NULL for '%s'", query);
while ((row= mysql_fetch_row(res)))
{
if (strcmp(row[1], binlog) == 0)
{
const char *status= row[2];
/* latest_epoch */
while (*status && strncmp(status, latest_epoch_str,
sizeof(latest_epoch_str)-1))
status++;
if (*status)
{
status+= sizeof(latest_epoch_str)-1;
latest_epoch= strtoull(status, (char**) 0, 10);
}
else
die("result does not contain '%s' in '%s'",
latest_epoch_str, query);
/* latest_trans_epoch */
while (*status && strncmp(status, latest_trans_epoch_str,
sizeof(latest_trans_epoch_str)-1))
status++;
if (*status)
{
status+= sizeof(latest_trans_epoch_str)-1;
latest_trans_epoch= strtoull(status, (char**) 0, 10);
}
else
die("result does not contain '%s' in '%s'",
latest_trans_epoch_str, query);
/* latest_received_binlog_epoch */
while (*status &&
strncmp(status, latest_received_binlog_epoch_str,
sizeof(latest_received_binlog_epoch_str)-1))
status++;
if (*status)
{
status+= sizeof(latest_received_binlog_epoch_str)-1;
latest_received_binlog_epoch= strtoull(status, (char**) 0, 10);
}
else
die("result does not contain '%s' in '%s'",
latest_received_binlog_epoch_str, query);
/* latest_handled_binlog */
while (*status &&
strncmp(status, latest_handled_binlog_epoch_str,
sizeof(latest_handled_binlog_epoch_str)-1))
status++;
if (*status)
{
status+= sizeof(latest_handled_binlog_epoch_str)-1;
latest_handled_binlog_epoch= strtoull(status, (char**) 0, 10);
}
else
die("result does not contain '%s' in '%s'",
latest_handled_binlog_epoch_str, query);
/* latest_applied_binlog_epoch */
while (*status &&
strncmp(status, latest_applied_binlog_epoch_str,
sizeof(latest_applied_binlog_epoch_str)-1))
status++;
if (*status)
{
status+= sizeof(latest_applied_binlog_epoch_str)-1;
latest_applied_binlog_epoch= strtoull(status, (char**) 0, 10);
}
else
die("result does not contain '%s' in '%s'",
latest_applied_binlog_epoch_str, query);
if (count == 0)
start_epoch= latest_trans_epoch;
break;
}
}
if (!row)
die("result does not contain '%s' in '%s'",
binlog, query);
if (latest_handled_binlog_epoch > handled_epoch)
count= 0;
handled_epoch= latest_handled_binlog_epoch;
count++;
if (latest_handled_binlog_epoch >= start_epoch)
do_continue= 0;
else if (count > 300) /* 30s */
{
break;
}
mysql_free_result(res);
}
}
}
#endif
if (mysql_query(mysql, query= "show master status"))
die("failed in 'show master status': %d %s",
mysql_errno(mysql), mysql_error(mysql));
if (!(res = mysql_store_result(mysql)))
die("mysql_store_result() retuned NULL for '%s'", query);
if (!(row = mysql_fetch_row(res)))
die("empty result in show master status");
strnmov(master_pos.file, row[0], sizeof(master_pos.file)-1);
master_pos.pos = strtoul(row[1], (char**) 0, 10);
mysql_free_result(res);
DBUG_RETURN(0);
}
/*
Assign the variable <var_name> with <var_val>
SYNOPSIS
do_let()
query called command
DESCRIPTION
let $<var_name>=<var_val><delimiter>
<var_name> - is the string string found between the $ and =
<var_val> - is the content between the = and <delimiter>, it may span
multiple line and contain any characters except <delimiter>
<delimiter> - is a string containing of one or more chars, default is ;
RETURN VALUES
Program will die if error detected
*/
void do_let(struct st_command *command)
{
char *p= command->first_argument;
char *var_name, *var_name_end;
DYNAMIC_STRING let_rhs_expr;
DBUG_ENTER("do_let");
init_dynamic_string(&let_rhs_expr, "", 512, 2048);
/* Find <var_name> */
if (!*p)
die("Missing arguments to let");
var_name= p;
while (*p && (*p != '=') && !my_isspace(charset_info,*p))
p++;
var_name_end= p;
if (var_name == var_name_end ||
(var_name+1 == var_name_end && *var_name == '$'))
die("Missing variable name in let");
while (my_isspace(charset_info,*p))
p++;
if (*p++ != '=')
die("Missing assignment operator in let");
/* Find start of <var_val> */
while (*p && my_isspace(charset_info,*p))
p++;
do_eval(&let_rhs_expr, p, command->end, FALSE);
command->last_argument= command->end;
/* Assign var_val to var_name */
var_set(var_name, var_name_end, let_rhs_expr.str,
(let_rhs_expr.str + let_rhs_expr.length));
dynstr_free(&let_rhs_expr);
revert_properties();
DBUG_VOID_RETURN;
}
/*
Sleep the number of specified seconds
SYNOPSIS
do_sleep()
q called command
real_sleep use the value from opt_sleep as number of seconds to sleep
if real_sleep is false
DESCRIPTION
sleep <seconds>
real_sleep <seconds>
The difference between the sleep and real_sleep commands is that sleep
uses the delay from the --sleep command-line option if there is one.
(If the --sleep option is not given, the sleep command uses the delay
specified by its argument.) The real_sleep command always uses the
delay specified by its argument. The logic is that sometimes delays are
cpu-dependent, and --sleep can be used to set this delay. real_sleep is
used for cpu-independent delays.
*/
int do_sleep(struct st_command *command, my_bool real_sleep)
{
int error= 0;
char *sleep_start, *sleep_end;
double sleep_val;
char *p;
static DYNAMIC_STRING ds_sleep;
const struct command_arg sleep_args[] = {
{ "sleep_delay", ARG_STRING, TRUE, &ds_sleep, "Number of seconds to sleep." }
};
check_command_args(command, command->first_argument, sleep_args,
sizeof(sleep_args)/sizeof(struct command_arg),
' ');
p= ds_sleep.str;
sleep_end= ds_sleep.str + ds_sleep.length;
while (my_isspace(charset_info, *p))
p++;
if (!*p)
die("Missing argument to %.*s", command->first_word_len,
command->query);
sleep_start= p;
/* Check that arg starts with a digit, not handled by my_strtod */
if (!my_isdigit(charset_info, *sleep_start))
die("Invalid argument to %.*s \"%s\"", command->first_word_len,
command->query, sleep_start);
sleep_val= my_strtod(sleep_start, &sleep_end, &error);
check_eol_junk_line(sleep_end);
if (error)
die("Invalid argument to %.*s \"%s\"", command->first_word_len,
command->query, command->first_argument);
dynstr_free(&ds_sleep);
/* Fixed sleep time selected by --sleep option */
if (opt_sleep >= 0 && !real_sleep)
sleep_val= opt_sleep;
DBUG_PRINT("info", ("sleep_val: %f", sleep_val));
if (sleep_val)
my_sleep((ulong) (sleep_val * 1000000L));
return 0;
}
void do_get_file_name(struct st_command *command,
char* dest, uint dest_max_len)
{
char *p= command->first_argument, *name;
if (!*p)
die("Missing file name argument");
name= p;
while (*p && !my_isspace(charset_info,*p))
p++;
if (*p)
*p++= 0;
command->last_argument= p;
strmake(dest, name, dest_max_len - 1);
}
void do_set_charset(struct st_command *command)
{
char *charset_name= command->first_argument;
char *p;
if (!charset_name || !*charset_name)
die("Missing charset name in 'character_set'");
/* Remove end space */
p= charset_name;
while (*p && !my_isspace(charset_info,*p))
p++;
if(*p)
*p++= 0;
command->last_argument= p;
charset_info= get_charset_by_csname(charset_name,MY_CS_PRIMARY,MYF(MY_WME));
if (!charset_info)
abort_not_supported_test("Test requires charset '%s'", charset_name);
}
/*
Run query and return one field in the result set from the
first row and <column>
*/
int query_get_string(MYSQL* mysql, const char* query,
int column, DYNAMIC_STRING* ds)
{
MYSQL_RES *res= NULL;
MYSQL_ROW row;
if (mysql_query(mysql, query))
{
report_or_die("'%s' failed: %d %s", query,
mysql_errno(mysql), mysql_error(mysql));
return 1;
}
if ((res= mysql_store_result(mysql)) == NULL)
{
report_or_die("Failed to store result: %d %s",
mysql_errno(mysql), mysql_error(mysql));
return 1;
}
if ((row= mysql_fetch_row(res)) == NULL)
{
mysql_free_result(res);
return 1;
}
init_dynamic_string(ds, (row[column] ? row[column] : "NULL"), ~0, 32);
mysql_free_result(res);
return 0;
}
static int my_kill(int pid, int sig)
{
#ifdef __WIN__
HANDLE proc;
if ((proc= OpenProcess(SYNCHRONIZE|PROCESS_TERMINATE, FALSE, pid)) == NULL)
return -1;
if (sig == 0)
{
DWORD wait_result= WaitForSingleObject(proc, 0);
CloseHandle(proc);
return wait_result == WAIT_OBJECT_0?-1:0;
}
(void)TerminateProcess(proc, 201);
CloseHandle(proc);
return 1;
#else
return kill(pid, sig);
#endif
}
/*
Shutdown the server of current connection and
make sure it goes away within <timeout> seconds
NOTE! Currently only works with local server
SYNOPSIS
do_shutdown_server()
command called command
DESCRIPTION
shutdown_server [<timeout>]
*/
void do_shutdown_server(struct st_command *command)
{
long timeout=60;
int pid;
DYNAMIC_STRING ds_pidfile_name;
MYSQL* mysql = cur_con->mysql;
static DYNAMIC_STRING ds_timeout;
const struct command_arg shutdown_args[] = {
{"timeout", ARG_STRING, FALSE, &ds_timeout, "Timeout before killing server"}
};
DBUG_ENTER("do_shutdown_server");
check_command_args(command, command->first_argument, shutdown_args,
sizeof(shutdown_args)/sizeof(struct command_arg),
' ');
if (ds_timeout.length)
{
char* endptr;
timeout= strtol(ds_timeout.str, &endptr, 10);
if (*endptr != '\0')
die("Illegal argument for timeout: '%s'", ds_timeout.str);
}
dynstr_free(&ds_timeout);
/* Get the servers pid_file name and use it to read pid */
if (query_get_string(mysql, "SHOW VARIABLES LIKE 'pid_file'", 1,
&ds_pidfile_name))
die("Failed to get pid_file from server");
/* Read the pid from the file */
{
int fd;
char buff[32];
if ((fd= my_open(ds_pidfile_name.str, O_RDONLY, MYF(0))) < 0)
die("Failed to open file '%s'", ds_pidfile_name.str);
dynstr_free(&ds_pidfile_name);
if (my_read(fd, (uchar*)&buff,
sizeof(buff), MYF(0)) <= 0){
my_close(fd, MYF(0));
die("pid file was empty");
}
my_close(fd, MYF(0));
pid= atoi(buff);
if (pid == 0)
die("Pidfile didn't contain a valid number");
}
DBUG_PRINT("info", ("Got pid %d", pid));
/* Tell server to shutdown if timeout > 0*/
if (timeout && mysql_shutdown(mysql, SHUTDOWN_DEFAULT))
die("mysql_shutdown failed");
/* Check that server dies */
while(timeout--){
if (my_kill(pid, 0) < 0){
DBUG_PRINT("info", ("Process %d does not exist anymore", pid));
DBUG_VOID_RETURN;
}
DBUG_PRINT("info", ("Sleeping, timeout: %ld", timeout));
my_sleep(1000000L);
}
/* Kill the server */
DBUG_PRINT("info", ("Killing server, pid: %d", pid));
(void)my_kill(pid, 9);
DBUG_VOID_RETURN;
}
/* List of error names to error codes */
typedef struct
{
const char *name;
uint code;
const char *text;
} st_error;
static st_error global_error_names[] =
{
{ "<No error>", ~0U, "" },
#include <mysqld_ername.h>
{ 0, 0, 0 }
};
#include <my_base.h>
static st_error handler_error_names[] =
{
{ "<No error>", UINT_MAX, "" },
#include <handler_ername.h>
{ 0, 0, 0 }
};
uint get_errcode_from_name(const char *error_name, const char *error_end,
st_error *e)
{
DBUG_ENTER("get_errcode_from_name");
DBUG_PRINT("enter", ("error_name: %s", error_name));
/* Loop through the array of known error names */
for (; e->name; e++)
{
/*
If we get a match, we need to check the length of the name we
matched against in case it was longer than what we are checking
(as in ER_WRONG_VALUE vs. ER_WRONG_VALUE_COUNT).
*/
if (!strncmp(error_name, e->name, (int) (error_end - error_name)) &&
(uint) strlen(e->name) == (uint) (error_end - error_name))
{
DBUG_RETURN(e->code);
}
}
DBUG_RETURN(0);
}
uint get_errcode_from_name(const char *error_name, const char *error_end)
{
uint tmp;
if ((tmp= get_errcode_from_name(error_name, error_end,
global_error_names)))
return tmp;
if ((tmp= get_errcode_from_name(error_name, error_end,
handler_error_names)))
return tmp;
die("Unknown SQL error name '%s'", error_name);
}
const char *unknown_error= "<Unknown>";
const char *get_errname_from_code (uint error_code, st_error *e)
{
DBUG_ENTER("get_errname_from_code");
DBUG_PRINT("enter", ("error_code: %d", error_code));
if (! error_code)
{
DBUG_RETURN("");
}
for (; e->name; e++)
{
if (e->code == error_code)
{
DBUG_RETURN(e->name);
}
}
/* Apparently, errors without known names may occur */
DBUG_RETURN(unknown_error);
}
const char *get_errname_from_code(uint error_code)
{
const char *name;
if ((name= get_errname_from_code(error_code, global_error_names)) !=
unknown_error)
return name;
return get_errname_from_code(error_code, handler_error_names);
}
void do_get_errcodes(struct st_command *command)
{
struct st_match_err *to= saved_expected_errors.err;
DBUG_ENTER("do_get_errcodes");
if (!*command->first_argument)
die("Missing argument(s) to 'error'");
/* TODO: Potentially, there is a possibility of variables
being expanded twice, e.g.
let $errcodes = 1,\$a;
let $a = 1051;
error $errcodes;
DROP TABLE unknown_table;
...
Got one of the listed errors
But since it requires manual escaping, it does not seem
particularly dangerous or error-prone.
*/
DYNAMIC_STRING ds;
init_dynamic_string(&ds, 0, command->query_len + 64, 256);
do_eval(&ds, command->first_argument, command->end, !is_windows);
char *p= ds.str;
uint count= 0;
char *next;
do
{
char *end;
/* Skip leading spaces */
while (*p && *p == ' ')
p++;
/* Find end */
end= p;
while (*end && *end != ',' && *end != ' ')
end++;
next=end;
/* code to handle variables passed to mysqltest */
if( *p == '$')
{
const char* fin;
VAR *var = var_get(p,&fin,0,0);
p=var->str_val;
end=p+var->str_val_len;
}
if (*p == 'S')
{
char *to_ptr= to->code.sqlstate;
/*
SQLSTATE string
- Must be SQLSTATE_LENGTH long
- May contain only digits[0-9] and _uppercase_ letters
*/
p++; /* Step past the S */
if ((end - p) != SQLSTATE_LENGTH)
die("The sqlstate must be exactly %d chars long", SQLSTATE_LENGTH);
/* Check sqlstate string validity */
while (*p && p < end)
{
if (my_isdigit(charset_info, *p) || my_isupper(charset_info, *p))
*to_ptr++= *p++;
else
die("The sqlstate may only consist of digits[0-9] " \
"and _uppercase_ letters");
}
*to_ptr= 0;
to->type= ERR_SQLSTATE;
DBUG_PRINT("info", ("ERR_SQLSTATE: %s", to->code.sqlstate));
}
else if (*p == 's')
{
die("The sqlstate definition must start with an uppercase S");
}
else if (*p == 'E' || *p == 'W' || *p == 'H')
{
/* Error name string */
DBUG_PRINT("info", ("Error name: %s", p));
to->code.errnum= get_errcode_from_name(p, end);
to->type= ERR_ERRNO;
DBUG_PRINT("info", ("ERR_ERRNO: %d", to->code.errnum));
}
else if (*p == 'e' || *p == 'w' || *p == 'h')
{
die("The error name definition must start with an uppercase E or W or H");
}
else
{
long val;
char *start= p;
/* Check that the string passed to str2int only contain digits */
while (*p && p != end)
{
if (!my_isdigit(charset_info, *p))
die("Invalid argument to error: '%s' - " \
"the errno may only consist of digits[0-9]",
command->first_argument);
p++;
}
/* Convert the sting to int */
if (!str2int(start, 10, (long) INT_MIN, (long) INT_MAX, &val))
die("Invalid argument to error: '%s'", command->first_argument);
to->code.errnum= (uint) val;
to->type= ERR_ERRNO;
DBUG_PRINT("info", ("ERR_ERRNO: %d", to->code.errnum));
}
to++;
count++;
if (count >= (sizeof(saved_expected_errors.err) /
sizeof(struct st_match_err)))
die("Too many errorcodes specified");
/* Set pointer to the end of the last error code */
p= next;
/* Find next ',' */
while (*p && *p != ',')
p++;
if (*p)
p++; /* Step past ',' */
} while (*p);
command->last_argument= command->first_argument;
while (*command->last_argument)
command->last_argument++;
to->type= ERR_EMPTY; /* End of data */
DBUG_PRINT("info", ("Expected errors: %d", count));
saved_expected_errors.count= count;
dynstr_free(&ds);
DBUG_VOID_RETURN;
}
/*
Get a string; Return ptr to end of string
Strings may be surrounded by " or '
If string is a '$variable', return the value of the variable.
*/
static char *get_string(char **to_ptr, char **from_ptr,
struct st_command *command)
{
char c, sep;
char *to= *to_ptr, *from= *from_ptr, *start=to;
DBUG_ENTER("get_string");
/* Find separator */
if (*from == '"' || *from == '\'')
sep= *from++;
else
sep=' '; /* Separated with space */
for ( ; (c=*from) ; from++)
{
if (c == '\\' && from[1])
{ /* Escaped character */
/* We can't translate \0 -> ASCII 0 as replace can't handle ASCII 0 */
switch (*++from) {
case 'n':
*to++= '\n';
break;
case 't':
*to++= '\t';
break;
case 'r':
*to++ = '\r';
break;
case 'b':
*to++ = '\b';
break;
case 'Z': /* ^Z must be escaped on Win32 */
*to++='\032';
break;
default:
*to++ = *from;
break;
}
}
else if (c == sep)
{
if (c == ' ' || c != *++from)
break; /* Found end of string */
*to++=c; /* Copy duplicated separator */
}
else
*to++=c;
}
if (*from != ' ' && *from)
die("Wrong string argument in %s", command->query);
while (my_isspace(charset_info,*from)) /* Point to next string */
from++;
*to =0; /* End of string marker */
*to_ptr= to+1; /* Store pointer to end */
*from_ptr= from;
/* Check if this was a variable */
if (*start == '$')
{
const char *end= to;
VAR *var=var_get(start, &end, 0, 1);
if (var && to == (char*) end+1)
{
DBUG_PRINT("info",("var: '%s' -> '%s'", start, var->str_val));
DBUG_RETURN(var->str_val); /* return found variable value */
}
}
DBUG_RETURN(start);
}
void set_reconnect(MYSQL* mysql, my_bool val)
{
my_bool reconnect= val;
DBUG_ENTER("set_reconnect");
DBUG_PRINT("info", ("val: %d", (int) val));
#if MYSQL_VERSION_ID < 50000
mysql->reconnect= reconnect;
#else
mysql_options(mysql, MYSQL_OPT_RECONNECT, (char *)&reconnect);
#endif
DBUG_VOID_RETURN;
}
/**
Change the current connection to the given st_connection, and update
$mysql_get_server_version and $CURRENT_CONNECTION accordingly.
*/
void set_current_connection(struct st_connection *con)
{
cur_con= con;
/* Update $mysql_get_server_version to that of current connection */
var_set_int("$mysql_get_server_version",
mysql_get_server_version(con->mysql));
/* Update $CURRENT_CONNECTION to the name of the current connection */
var_set_string("$CURRENT_CONNECTION", con->name);
}
void select_connection_name(const char *name)
{
DBUG_ENTER("select_connection_name");
DBUG_PRINT("enter",("name: '%s'", name));
st_connection *con= find_connection_by_name(name);
if (!con)
die("connection '%s' not found in connection pool", name);
set_current_connection(con);
/* Connection logging if enabled */
if (!disable_connect_log && !disable_query_log)
{
DYNAMIC_STRING *ds= &ds_res;
dynstr_append_mem(ds, "connection ", 11);
replace_dynstr_append(ds, name);
dynstr_append_mem(ds, ";\n", 2);
}
DBUG_VOID_RETURN;
}
void select_connection(struct st_command *command)
{
DBUG_ENTER("select_connection");
static DYNAMIC_STRING ds_connection;
const struct command_arg connection_args[] = {
{ "connection_name", ARG_STRING, TRUE, &ds_connection, "Name of the connection that we switch to." }
};
check_command_args(command, command->first_argument, connection_args,
sizeof(connection_args)/sizeof(struct command_arg),
' ');
DBUG_PRINT("info", ("changing connection: %s", ds_connection.str));
select_connection_name(ds_connection.str);
dynstr_free(&ds_connection);
DBUG_VOID_RETURN;
}
void do_close_connection(struct st_command *command)
{
DBUG_ENTER("do_close_connection");
struct st_connection *con;
static DYNAMIC_STRING ds_connection;
const struct command_arg close_connection_args[] = {
{ "connection_name", ARG_STRING, TRUE, &ds_connection,
"Name of the connection to close." }
};
check_command_args(command, command->first_argument,
close_connection_args,
sizeof(close_connection_args)/sizeof(struct command_arg),
' ');
DBUG_PRINT("enter",("connection name: '%s'", ds_connection.str));
if (!(con= find_connection_by_name(ds_connection.str)))
die("connection '%s' not found in connection pool", ds_connection.str);
DBUG_PRINT("info", ("Closing connection %s", con->name));
#ifndef EMBEDDED_LIBRARY
if (command->type == Q_DIRTY_CLOSE)
{
if (con->mysql->net.vio)
{
vio_delete(con->mysql->net.vio);
con->mysql->net.vio = 0;
}
}
#endif /*!EMBEDDED_LIBRARY*/
if (con->stmt)
do_stmt_close(con);
con->stmt= 0;
#ifdef EMBEDDED_LIBRARY
/*
As query could be still executed in a separate theread
we need to check if the query's thread was finished and probably wait
(embedded-server specific)
*/
emb_close_connection(con);
#endif /*EMBEDDED_LIBRARY*/
mysql_close(con->mysql);
con->mysql= 0;
if (con->util_mysql)
mysql_close(con->util_mysql);
con->util_mysql= 0;
con->pending= FALSE;
my_free(con->name);
/*
When the connection is closed set name to "-closed_connection-"
to make it possible to reuse the connection name.
*/
if (!(con->name = my_strdup("-closed_connection-", MYF(MY_WME))))
die("Out of memory");
if (con == cur_con)
{
/* Current connection was closed */
var_set_int("$mysql_get_server_version", 0xFFFFFFFF);
var_set_string("$CURRENT_CONNECTION", con->name);
}
/* Connection logging if enabled */
if (!disable_connect_log && !disable_query_log)
{
DYNAMIC_STRING *ds= &ds_res;
dynstr_append_mem(ds, "disconnect ", 11);
replace_dynstr_append(ds, ds_connection.str);
dynstr_append_mem(ds, ";\n", 2);
}
dynstr_free(&ds_connection);
DBUG_VOID_RETURN;
}
/*
Connect to a server doing several retries if needed.
SYNOPSIS
safe_connect()
con - connection structure to be used
host, user, pass, - connection parameters
db, port, sock
NOTE
Sometimes in a test the client starts before
the server - to solve the problem, we try again
after some sleep if connection fails the first
time
This function will try to connect to the given server
"opt_max_connect_retries" times and sleep "connection_retry_sleep"
seconds between attempts before finally giving up.
This helps in situation when the client starts
before the server (which happens sometimes).
It will only ignore connection errors during these retries.
*/
void safe_connect(MYSQL* mysql, const char *name, const char *host,
const char *user, const char *pass, const char *db,
int port, const char *sock)
{
int failed_attempts= 0;
DBUG_ENTER("safe_connect");
verbose_msg("Connecting to server %s:%d (socket %s) as '%s'"
", connection '%s', attempt %d ...",
host, port, sock, user, name, failed_attempts);
mysql_options(mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0);
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD,
"program_name", "mysqltest");
while(!mysql_real_connect(mysql, host,user, pass, db, port, sock,
CLIENT_MULTI_STATEMENTS | CLIENT_REMEMBER_OPTIONS))
{
/*
Connect failed
Only allow retry if this was an error indicating the server
could not be contacted. Error code differs depending
on protocol/connection type
*/
if ((mysql_errno(mysql) == CR_CONN_HOST_ERROR ||
mysql_errno(mysql) == CR_CONNECTION_ERROR) &&
failed_attempts < opt_max_connect_retries)
{
verbose_msg("Connect attempt %d/%d failed: %d: %s", failed_attempts,
opt_max_connect_retries, mysql_errno(mysql),
mysql_error(mysql));
my_sleep(connection_retry_sleep);
}
else
{
if (failed_attempts > 0)
die("Could not open connection '%s' after %d attempts: %d %s", name,
failed_attempts, mysql_errno(mysql), mysql_error(mysql));
else
die("Could not open connection '%s': %d %s", name,
mysql_errno(mysql), mysql_error(mysql));
}
failed_attempts++;
}
verbose_msg("... Connected.");
DBUG_VOID_RETURN;
}
/*
Connect to a server and handle connection errors in case they occur.
SYNOPSIS
connect_n_handle_errors()
q - context of connect "query" (command)
con - connection structure to be used
host, user, pass, - connection parameters
db, port, sock
DESCRIPTION
This function will try to establish a connection to server and handle
possible errors in the same manner as if "connect" was usual SQL-statement
(If error is expected it will ignore it once it occurs and log the
"statement" to the query log).
Unlike safe_connect() it won't do several attempts.
RETURN VALUES
1 - Connected
0 - Not connected
*/
int connect_n_handle_errors(struct st_command *command,
MYSQL* con, const char* host,
const char* user, const char* pass,
const char* db, int port, const char* sock)
{
DYNAMIC_STRING *ds;
int failed_attempts= 0;
ds= &ds_res;
/* Only log if an error is expected */
if (command->expected_errors.count > 0 &&
!disable_query_log)
{
/*
Log the connect to result log
*/
dynstr_append_mem(ds, "connect(", 8);
replace_dynstr_append(ds, host);
dynstr_append_mem(ds, ",", 1);
replace_dynstr_append(ds, user);
dynstr_append_mem(ds, ",", 1);
replace_dynstr_append(ds, pass);
dynstr_append_mem(ds, ",", 1);
if (db)
replace_dynstr_append(ds, db);
dynstr_append_mem(ds, ",", 1);
replace_dynstr_append_uint(ds, port);
dynstr_append_mem(ds, ",", 1);
if (sock)
replace_dynstr_append(ds, sock);
dynstr_append_mem(ds, ")", 1);
dynstr_append_mem(ds, delimiter, delimiter_length);
dynstr_append_mem(ds, "\n", 1);
}
/* Simlified logging if enabled */
if (!disable_connect_log && !disable_query_log)
{
replace_dynstr_append(ds, command->query);
dynstr_append_mem(ds, ";\n", 2);
}
mysql_options(con, MYSQL_OPT_CONNECT_ATTR_RESET, 0);
mysql_options4(con, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "mysqltest");
while (!mysql_real_connect(con, host, user, pass, db, port, sock ? sock: 0,
CLIENT_MULTI_STATEMENTS))
{
/*
If we have used up all our connections check whether this
is expected (by --error). If so, handle the error right away.
Otherwise, give it some extra time to rule out race-conditions.
If extra-time doesn't help, we have an unexpected error and
must abort -- just proceeding to handle_error() when second
and third chances are used up will handle that for us.
There are various user-limits of which only max_user_connections
and max_connections_per_hour apply at connect time. For the
the second to create a race in our logic, we'd need a limits
test that runs without a FLUSH for longer than an hour, so we'll
stay clear of trying to work out which exact user-limit was
exceeded.
*/
if (((mysql_errno(con) == ER_TOO_MANY_USER_CONNECTIONS) ||
(mysql_errno(con) == ER_USER_LIMIT_REACHED)) &&
(failed_attempts++ < opt_max_connect_retries))
{
int i;
i= match_expected_error(command, mysql_errno(con), mysql_sqlstate(con));
if (i >= 0)
goto do_handle_error; /* expected error, handle */
my_sleep(connection_retry_sleep); /* unexpected error, wait */
continue; /* and give it 1 more chance */
}
do_handle_error:
var_set_errno(mysql_errno(con));
handle_error(command, mysql_errno(con), mysql_error(con),
mysql_sqlstate(con), ds);
return 0; /* Not connected */
}
var_set_errno(0);
handle_no_error(command);
revert_properties();
return 1; /* Connected */
}
/*
Open a new connection to MySQL Server with the parameters
specified. Make the new connection the current connection.
SYNOPSIS
do_connect()
q called command
DESCRIPTION
connect(<name>,<host>,<user>,[<pass>,[<db>,[<port>,<sock>[<opts>]]]]);
connect <name>,<host>,<user>,[<pass>,[<db>,[<port>,<sock>[<opts>]]]];
<name> - name of the new connection
<host> - hostname of server
<user> - user to connect as
<pass> - password used when connecting
<db> - initial db when connected
<port> - server port
<sock> - server socket
<opts> - options to use for the connection
* SSL - use SSL if available
* COMPRESS - use compression if available
* SHM - use shared memory if available
* PIPE - use named pipe if available
*/
void do_connect(struct st_command *command)
{
int con_port= opt_port;
char *con_options;
char *ssl_cipher __attribute__((unused))= 0;
my_bool con_ssl= 0, con_compress= 0;
my_bool con_pipe= 0;
my_bool con_shm __attribute__ ((unused))= 0;
int read_timeout= 0;
int write_timeout= 0;
struct st_connection* con_slot;
static DYNAMIC_STRING ds_connection_name;
static DYNAMIC_STRING ds_host;
static DYNAMIC_STRING ds_user;
static DYNAMIC_STRING ds_password;
static DYNAMIC_STRING ds_database;
static DYNAMIC_STRING ds_port;
static DYNAMIC_STRING ds_sock;
static DYNAMIC_STRING ds_options;
static DYNAMIC_STRING ds_default_auth;
#ifdef HAVE_SMEM
static DYNAMIC_STRING ds_shm;
#endif
const struct command_arg connect_args[] = {
{ "connection name", ARG_STRING, TRUE, &ds_connection_name, "Name of the connection" },
{ "host", ARG_STRING, TRUE, &ds_host, "Host to connect to" },
{ "user", ARG_STRING, FALSE, &ds_user, "User to connect as" },
{ "passsword", ARG_STRING, FALSE, &ds_password, "Password used when connecting" },
{ "database", ARG_STRING, FALSE, &ds_database, "Database to select after connect" },
{ "port", ARG_STRING, FALSE, &ds_port, "Port to connect to" },
{ "socket", ARG_STRING, FALSE, &ds_sock, "Socket to connect with" },
{ "options", ARG_STRING, FALSE, &ds_options, "Options to use while connecting" },
{ "default_auth", ARG_STRING, FALSE, &ds_default_auth, "Default authentication to use" }
};
DBUG_ENTER("do_connect");
DBUG_PRINT("enter",("connect: %s", command->first_argument));
strip_parentheses(command);
check_command_args(command, command->first_argument, connect_args,
sizeof(connect_args)/sizeof(struct command_arg),
',');
/* Port */
if (ds_port.length)
{
con_port= atoi(ds_port.str);
if (con_port == 0)
die("Illegal argument for port: '%s'", ds_port.str);
}
#ifdef HAVE_SMEM
/* Shared memory */
init_dynamic_string(&ds_shm, ds_sock.str, 0, 0);
#endif
/* Sock */
if (ds_sock.length)
{
/*
If the socket is specified just as a name without path
append tmpdir in front
*/
if (*ds_sock.str != FN_LIBCHAR)
{
char buff[FN_REFLEN];
fn_format(buff, ds_sock.str, TMPDIR, "", 0);
dynstr_set(&ds_sock, buff);
}
}
else
{
/* No socket specified, use default */
dynstr_set(&ds_sock, unix_sock);
}
DBUG_PRINT("info", ("socket: %s", ds_sock.str));
/* Options */
con_options= ds_options.str;
while (*con_options)
{
size_t length;
char *end;
/* Step past any spaces in beginning of option*/
while (*con_options && my_isspace(charset_info, *con_options))
con_options++;
/* Find end of this option */
end= con_options;
while (*end && !my_isspace(charset_info, *end))
end++;
length= (size_t) (end - con_options);
if (length == 3 && !strncmp(con_options, "SSL", 3))
con_ssl= 1;
else if (!strncmp(con_options, "SSL-CIPHER=", 11))
{
con_ssl= 1;
ssl_cipher=con_options + 11;
}
else if (length == 8 && !strncmp(con_options, "COMPRESS", 8))
con_compress= 1;
else if (length == 4 && !strncmp(con_options, "PIPE", 4))
con_pipe= 1;
else if (length == 3 && !strncmp(con_options, "SHM", 3))
con_shm= 1;
else if (strncasecmp(con_options, "read_timeout=",
sizeof("read_timeout=")-1) == 0)
{
read_timeout= atoi(con_options + sizeof("read_timeout=")-1);
}
else if (strncasecmp(con_options, "write_timeout=",
sizeof("write_timeout=")-1) == 0)
{
write_timeout= atoi(con_options + sizeof("write_timeout=")-1);
}
else
die("Illegal option to connect: %.*s",
(int) (end - con_options), con_options);
/* Process next option */
con_options= end;
}
if (find_connection_by_name(ds_connection_name.str))
die("Connection %s already exists", ds_connection_name.str);
if (next_con != connections_end)
con_slot= next_con;
else
{
if (!(con_slot= find_connection_by_name("-closed_connection-")))
die("Connection limit exhausted, you can have max %d connections",
opt_max_connections);
my_free(con_slot->name);
con_slot->name= 0;
}
init_connection_thd(con_slot);
if (!(con_slot->mysql= mysql_init(0)))
die("Failed on mysql_init()");
if (opt_connect_timeout)
mysql_options(con_slot->mysql, MYSQL_OPT_CONNECT_TIMEOUT,
(void *) &opt_connect_timeout);
#ifndef MY_CONTEXT_DISABLE
if (mysql_options(con_slot->mysql, MYSQL_OPT_NONBLOCK, 0))
die("Failed to initialise non-blocking API");
#endif
if (opt_compress || con_compress)
mysql_options(con_slot->mysql, MYSQL_OPT_COMPRESS, NullS);
mysql_options(con_slot->mysql, MYSQL_OPT_LOCAL_INFILE, 0);
mysql_options(con_slot->mysql, MYSQL_SET_CHARSET_NAME,
charset_info->csname);
if (opt_charsets_dir)
mysql_options(con_slot->mysql, MYSQL_SET_CHARSET_DIR,
opt_charsets_dir);
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
if (opt_use_ssl)
con_ssl= 1;
#endif
if (con_ssl)
{
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
mysql_ssl_set(con_slot->mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, ssl_cipher ? ssl_cipher : opt_ssl_cipher);
mysql_options(con_slot->mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl);
mysql_options(con_slot->mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);
#if MYSQL_VERSION_ID >= 50000
/* Turn on ssl_verify_server_cert only if host is "localhost" */
opt_ssl_verify_server_cert= !strcmp(ds_host.str, "localhost");
mysql_options(con_slot->mysql, MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
&opt_ssl_verify_server_cert);
#endif
#endif
}
if (con_pipe)
{
#ifdef __WIN__
opt_protocol= MYSQL_PROTOCOL_PIPE;
#endif
}
if (opt_protocol)
mysql_options(con_slot->mysql, MYSQL_OPT_PROTOCOL, (char*) &opt_protocol);
if (read_timeout)
{
mysql_options(con_slot->mysql, MYSQL_OPT_READ_TIMEOUT,
(char*)&read_timeout);
}
if (write_timeout)
{
mysql_options(con_slot->mysql, MYSQL_OPT_WRITE_TIMEOUT,
(char*)&write_timeout);
}
#ifdef HAVE_SMEM
if (con_shm)
{
uint protocol= MYSQL_PROTOCOL_MEMORY;
if (!ds_shm.length)
die("Missing shared memory base name");
mysql_options(con_slot->mysql, MYSQL_SHARED_MEMORY_BASE_NAME, ds_shm.str);
mysql_options(con_slot->mysql, MYSQL_OPT_PROTOCOL, &protocol);
}
else if (shared_memory_base_name)
{
mysql_options(con_slot->mysql, MYSQL_SHARED_MEMORY_BASE_NAME,
shared_memory_base_name);
}
#endif
/* Use default db name */
if (ds_database.length == 0)
dynstr_set(&ds_database, opt_db);
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(con_slot->mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);
if (ds_default_auth.length)
mysql_options(con_slot->mysql, MYSQL_DEFAULT_AUTH, ds_default_auth.str);
/* Special database to allow one to connect without a database name */
if (ds_database.length && !strcmp(ds_database.str,"*NO-ONE*"))
dynstr_set(&ds_database, "");
if (connect_n_handle_errors(command, con_slot->mysql,
ds_host.str,ds_user.str,
ds_password.str, ds_database.str,
con_port, ds_sock.str))
{
DBUG_PRINT("info", ("Inserting connection %s in connection pool",
ds_connection_name.str));
if (!(con_slot->name= my_strdup(ds_connection_name.str, MYF(MY_WME))))
die("Out of memory");
con_slot->name_len= strlen(con_slot->name);
set_current_connection(con_slot);
if (con_slot == next_con)
next_con++; /* if we used the next_con slot, advance the pointer */
}
dynstr_free(&ds_connection_name);
dynstr_free(&ds_host);
dynstr_free(&ds_user);
dynstr_free(&ds_password);
dynstr_free(&ds_database);
dynstr_free(&ds_port);
dynstr_free(&ds_sock);
dynstr_free(&ds_options);
dynstr_free(&ds_default_auth);
#ifdef HAVE_SMEM
dynstr_free(&ds_shm);
#endif
DBUG_VOID_RETURN;
}
int do_done(struct st_command *command)
{
/* Check if empty block stack */
if (cur_block == block_stack)
{
if (*command->query != '}')
die("Stray 'end' command - end of block before beginning");
die("Stray '}' - end of block before beginning");
}
/* Test if inner block has been executed */
if (cur_block->ok && cur_block->cmd == cmd_while)
{
/* Pop block from stack, re-execute outer block */
cur_block--;
parser.current_line = cur_block->line;
}
else
{
if (*cur_block->delim)
{
/* Restore "old" delimiter after false if block */
strcpy (delimiter, cur_block->delim);
delimiter_length= strlen(delimiter);
}
/* Pop block from stack, goto next line */
cur_block--;
parser.current_line++;
}
return 0;
}
/* Operands available in if or while conditions */
enum block_op {
EQ_OP,
NE_OP,
GT_OP,
GE_OP,
LT_OP,
LE_OP,
ILLEG_OP
};
enum block_op find_operand(const char *start)
{
char first= *start;
char next= *(start+1);
if (first == '=' && next == '=')
return EQ_OP;
if (first == '!' && next == '=')
return NE_OP;
if (first == '>' && next == '=')
return GE_OP;
if (first == '>')
return GT_OP;
if (first == '<' && next == '=')
return LE_OP;
if (first == '<')
return LT_OP;
return ILLEG_OP;
}
/*
Process start of a "if" or "while" statement
SYNOPSIS
do_block()
cmd Type of block
q called command
DESCRIPTION
if ([!]<expr>)
{
<block statements>
}
while ([!]<expr>)
{
<block statements>
}
Evaluates the <expr> and if it evaluates to
greater than zero executes the following code block.
A '!' can be used before the <expr> to indicate it should
be executed if it evaluates to zero.
<expr> can also be a simple comparison condition:
<variable> <op> <expr>
The left hand side must be a variable, the right hand side can be a
variable, number, string or `query`. Operands are ==, !=, <, <=, >, >=.
== and != can be used for strings, all can be used for numerical values.
*/
void do_block(enum block_cmd cmd, struct st_command* command)
{
char *p= command->first_argument;
const char *expr_start, *expr_end;
VAR v;
const char *cmd_name= (cmd == cmd_while ? "while" : "if");
my_bool not_expr= FALSE;
DBUG_ENTER("do_block");
DBUG_PRINT("enter", ("%s", cmd_name));
/* Check stack overflow */
if (cur_block == block_stack_end)
die("Nesting too deeply");
/* Set way to find outer block again, increase line counter */
cur_block->line= parser.current_line++;
/* If this block is ignored */
if (!cur_block->ok)
{
/* Inner block should be ignored too */
cur_block++;
cur_block->cmd= cmd;
cur_block->ok= FALSE;
cur_block->delim[0]= '\0';
DBUG_VOID_RETURN;
}
/* Parse and evaluate test expression */
expr_start= strchr(p, '(');
if (!expr_start++)
die("missing '(' in %s", cmd_name);
while (my_isspace(charset_info, *expr_start))
expr_start++;
/* Check for !<expr> */
if (*expr_start == '!')
{
not_expr= TRUE;
expr_start++; /* Step past the '!', then any whitespace */
while (*expr_start && my_isspace(charset_info, *expr_start))
expr_start++;
}
/* Find ending ')' */
expr_end= strrchr(expr_start, ')');
if (!expr_end)
die("missing ')' in %s", cmd_name);
p= (char*)expr_end+1;
while (*p && my_isspace(charset_info, *p))
p++;
if (*p && *p != '{')
die("Missing '{' after %s. Found \"%s\"", cmd_name, p);
var_init(&v,0,0,0,0);
/* If expression starts with a variable, it may be a compare condition */
if (*expr_start == '$')
{
const char *curr_ptr= expr_end;
eval_expr(&v, expr_start, &curr_ptr, true);
while (my_isspace(charset_info, *++curr_ptr))
{}
/* If there was nothing past the variable, skip condition part */
if (curr_ptr == expr_end)
goto NO_COMPARE;
enum block_op operand= find_operand(curr_ptr);
if (operand == ILLEG_OP)
die("Found junk '%.*s' after $variable in condition",
(int)(expr_end - curr_ptr), curr_ptr);
/* We could silently allow this, but may be confusing */
if (not_expr)
die("Negation and comparison should not be combined, please rewrite");
/* Skip the 1 or 2 chars of the operand, then white space */
if (operand == LT_OP || operand == GT_OP)
{
curr_ptr++;
}
else
{
curr_ptr+= 2;
}
while (my_isspace(charset_info, *curr_ptr))
curr_ptr++;
if (curr_ptr == expr_end)
die("Missing right operand in comparison");
/* Strip off trailing white space */
while (my_isspace(charset_info, expr_end[-1]))
expr_end--;
/* strip off ' or " around the string */
if (*curr_ptr == '\'' || *curr_ptr == '"')
{
if (expr_end[-1] != *curr_ptr)
die("Unterminated string value");
curr_ptr++;
expr_end--;
}
VAR v2;
var_init(&v2,0,0,0,0);
eval_expr(&v2, curr_ptr, &expr_end);
if ((operand!=EQ_OP && operand!=NE_OP) && ! (v.is_int && v2.is_int))
die("Only == and != are supported for string values");
/* Now we overwrite the first variable with 0 or 1 (for false or true) */
switch (operand)
{
case EQ_OP:
if (v.is_int)
v.int_val= (v2.is_int && v2.int_val == v.int_val);
else
v.int_val= !strcmp (v.str_val, v2.str_val);
break;
case NE_OP:
if (v.is_int)
v.int_val= ! (v2.is_int && v2.int_val == v.int_val);
else
v.int_val= (strcmp (v.str_val, v2.str_val) != 0);
break;
case LT_OP:
v.int_val= (v.int_val < v2.int_val);
break;
case LE_OP:
v.int_val= (v.int_val <= v2.int_val);
break;
case GT_OP:
v.int_val= (v.int_val > v2.int_val);
break;
case GE_OP:
v.int_val= (v.int_val >= v2.int_val);
break;
case ILLEG_OP:
die("Impossible operator, this cannot happen");
}
v.is_int= TRUE;
var_free(&v2);
} else
{
if (*expr_start != '`' && ! my_isdigit(charset_info, *expr_start))
die("Expression in if/while must beging with $, ` or a number");
eval_expr(&v, expr_start, &expr_end);
}
NO_COMPARE:
/* Define inner block */
cur_block++;
cur_block->cmd= cmd;
if (v.is_int)
{
cur_block->ok= (v.int_val != 0);
} else
/* Any non-empty string which does not begin with 0 is also TRUE */
{
p= v.str_val;
/* First skip any leading white space or unary -+ */
while (*p && ((my_isspace(charset_info, *p) || *p == '-' || *p == '+')))
p++;
cur_block->ok= (*p && *p != '0') ? TRUE : FALSE;
}
if (not_expr)
cur_block->ok = !cur_block->ok;
if (cur_block->ok)
{
cur_block->delim[0]= '\0';
} else
{
/* Remember "old" delimiter if entering a false if block */
strcpy (cur_block->delim, delimiter);
}
DBUG_PRINT("info", ("OK: %d", cur_block->ok));
var_free(&v);
DBUG_VOID_RETURN;
}
void do_delimiter(struct st_command* command)
{
char* p= command->first_argument;
DBUG_ENTER("do_delimiter");
DBUG_PRINT("enter", ("first_argument: %s", command->first_argument));
while (*p && my_isspace(charset_info, *p))
p++;
if (!(*p))
die("Can't set empty delimiter");
delimiter_length= strmake_buf(delimiter, p) - delimiter;
DBUG_PRINT("exit", ("delimiter: %s", delimiter));
command->last_argument= p + delimiter_length;
DBUG_VOID_RETURN;
}
my_bool match_delimiter(int c, const char *delim, uint length)
{
uint i;
char tmp[MAX_DELIMITER_LENGTH];
if (c != *delim)
return 0;
for (i= 1; i < length &&
(c= my_getc(cur_file->file)) == *(delim + i);
i++)
tmp[i]= c;
if (i == length)
return 1; /* Found delimiter */
/* didn't find delimiter, push back things that we read */
my_ungetc(c);
while (i > 1)
my_ungetc(tmp[--i]);
return 0;
}
my_bool end_of_query(int c)
{
return match_delimiter(c, delimiter, delimiter_length);
}
/*
Read one "line" from the file
SYNOPSIS
read_line
buf buffer for the read line
size size of the buffer i.e max size to read
DESCRIPTION
This function actually reads several lines and adds them to the
buffer buf. It continues to read until it finds what it believes
is a complete query.
Normally that means it will read lines until it reaches the
"delimiter" that marks end of query. Default delimiter is ';'
The function should be smart enough not to detect delimiter's
found inside strings surrounded with '"' and '\'' escaped strings.
If the first line in a query starts with '#' or '-' this line is treated
as a comment. A comment is always terminated when end of line '\n' is
reached.
*/
int read_line(char *buf, int size)
{
char c, UNINIT_VAR(last_quote), last_char= 0;
char *p= buf, *buf_end= buf + size - 1;
int skip_char= 0;
my_bool have_slash= FALSE;
enum {R_NORMAL, R_Q, R_SLASH_IN_Q,
R_COMMENT, R_LINE_START} state= R_LINE_START;
DBUG_ENTER("read_line");
start_lineno= cur_file->lineno;
DBUG_PRINT("info", ("Starting to read at lineno: %d", start_lineno));
for (; p < buf_end ;)
{
skip_char= 0;
c= my_getc(cur_file->file);
if (feof(cur_file->file))
{
found_eof:
if (cur_file->file != stdin)
{
fclose(cur_file->file);
cur_file->file= 0;
}
my_free(cur_file->file_name);
cur_file->file_name= 0;
if (cur_file == file_stack)
{
/* We're back at the first file, check if
all { have matching }
*/
if (cur_block != block_stack)
die("Missing end of block");
*p= 0;
DBUG_PRINT("info", ("end of file at line %d", cur_file->lineno));
DBUG_RETURN(1);
}
cur_file--;
start_lineno= cur_file->lineno;
continue;
}
if (c == '\n')
{
/* Line counting is independent of state */
cur_file->lineno++;
/* Convert cr/lf to lf */
if (p != buf && *(p-1) == '\r')
p--;
}
switch(state) {
case R_NORMAL:
if (end_of_query(c))
{
*p= 0;
DBUG_PRINT("exit", ("Found delimiter '%s' at line %d",
delimiter, cur_file->lineno));
DBUG_RETURN(0);
}
else if ((c == '{' &&
(!my_strnncoll_simple(charset_info, (const uchar*) "while", 5,
(uchar*) buf, MY_MIN(5, p - buf), 0) ||
!my_strnncoll_simple(charset_info, (const uchar*) "if", 2,
(uchar*) buf, MY_MIN(2, p - buf), 0))))
{
/* Only if and while commands can be terminated by { */
*p++= c;
*p= 0;
DBUG_PRINT("exit", ("Found '{' indicating start of block at line %d",
cur_file->lineno));
DBUG_RETURN(0);
}
else if (c == '\'' || c == '"' || c == '`')
{
if (! have_slash)
{
last_quote= c;
state= R_Q;
}
}
have_slash= (c == '\\');
break;
case R_COMMENT:
if (c == '\n')
{
/* Comments are terminated by newline */
*p= 0;
DBUG_PRINT("exit", ("Found newline in comment at line: %d",
cur_file->lineno));
DBUG_RETURN(0);
}
break;
case R_LINE_START:
if (c == '#' || c == '-')
{
/* A # or - in the first position of the line - this is a comment */
state = R_COMMENT;
}
else if (my_isspace(charset_info, c))
{
if (c == '\n')
{
if (last_char == '\n')
{
/* Two new lines in a row, return empty line */
DBUG_PRINT("info", ("Found two new lines in a row"));
*p++= c;
*p= 0;
DBUG_RETURN(0);
}
/* Query hasn't started yet */
start_lineno= cur_file->lineno;
DBUG_PRINT("info", ("Query hasn't started yet, start_lineno: %d",
start_lineno));
}
/* Skip all space at begining of line */
skip_char= 1;
}
else if (end_of_query(c))
{
*p= 0;
DBUG_PRINT("exit", ("Found delimiter '%s' at line: %d",
delimiter, cur_file->lineno));
DBUG_RETURN(0);
}
else if (c == '}')
{
/* A "}" need to be by itself in the begining of a line to terminate */
*p++= c;
*p= 0;
DBUG_PRINT("exit", ("Found '}' in begining of a line at line: %d",
cur_file->lineno));
DBUG_RETURN(0);
}
else if (c == '\'' || c == '"' || c == '`')
{
last_quote= c;
state= R_Q;
}
else
state= R_NORMAL;
break;
case R_Q:
if (c == last_quote)
state= R_NORMAL;
else if (c == '\\')
state= R_SLASH_IN_Q;
break;
case R_SLASH_IN_Q:
state= R_Q;
break;
}
last_char= c;
if (!skip_char)
{
/* Could be a multibyte character */
/* This code is based on the code in "sql_load.cc" */
#ifdef USE_MB
int charlen = my_mbcharlen(charset_info, (unsigned char) c);
/* We give up if multibyte character is started but not */
/* completed before we pass buf_end */
if ((charlen > 1) && (p + charlen) <= buf_end)
{
int i;
char* mb_start = p;
*p++ = c;
for (i= 1; i < charlen; i++)
{
c= my_getc(cur_file->file);
if (feof(cur_file->file))
goto found_eof;
*p++ = c;
}
if (! my_ismbchar(charset_info, mb_start, p))
{
/* It was not a multiline char, push back the characters */
/* We leave first 'c', i.e. pretend it was a normal char */
while (p-1 > mb_start)
my_ungetc(*--p);
}
}
else
#endif
*p++= c;
}
}
die("The input buffer is too small for this query.x\n" \
"check your query or increase MAX_QUERY and recompile");
DBUG_RETURN(0);
}
/*
Convert the read query to result format version 1
That is: After newline, all spaces need to be skipped
unless the previous char was a quote
This is due to an old bug that has now been fixed, but the
version 1 output format is preserved by using this function
*/
void convert_to_format_v1(char* query)
{
int last_c_was_quote= 0;
char *p= query, *to= query;
char *end= strend(query);
char last_c;
while (p <= end)
{
if (*p == '\n' && !last_c_was_quote)
{
*to++ = *p++; /* Save the newline */
/* Skip any spaces on next line */
while (*p && my_isspace(charset_info, *p))
p++;
last_c_was_quote= 0;
}
else if (*p == '\'' || *p == '"' || *p == '`')
{
last_c= *p;
*to++ = *p++;
/* Copy anything until the next quote of same type */
while (*p && *p != last_c)
*to++ = *p++;
*to++ = *p++;
last_c_was_quote= 1;
}
else
{
*to++ = *p++;
last_c_was_quote= 0;
}
}
}
/*
Check for unexpected "junk" after the end of query
This is normally caused by missing delimiters or when
switching between different delimiters
*/
void check_eol_junk_line(const char *line)
{
const char *p= line;
DBUG_ENTER("check_eol_junk_line");
DBUG_PRINT("enter", ("line: %s", line));
/* Check for extra delimiter */
if (*p && !strncmp(p, delimiter, delimiter_length))
die("Extra delimiter \"%s\" found", delimiter);
/* Allow trailing # comment */
if (*p && *p != '#')
{
if (*p == '\n')
die("Missing delimiter");
die("End of line junk detected: \"%s\"", p);
}
DBUG_VOID_RETURN;
}
void check_eol_junk(const char *eol)
{
const char *p= eol;
DBUG_ENTER("check_eol_junk");
DBUG_PRINT("enter", ("eol: %s", eol));
/* Skip past all spacing chars and comments */
while (*p && (my_isspace(charset_info, *p) || *p == '#' || *p == '\n'))
{
/* Skip past comments started with # and ended with newline */
if (*p && *p == '#')
{
p++;
while (*p && *p != '\n')
p++;
}
/* Check this line */
if (*p && *p == '\n')
check_eol_junk_line(p);
if (*p)
p++;
}
check_eol_junk_line(p);
DBUG_VOID_RETURN;
}
bool is_delimiter(const char* p)
{
uint match= 0;
char* delim= delimiter;
while (*p && *p == *delim++)
{
match++;
p++;
}
return (match == delimiter_length);
}
/*
Create a command from a set of lines
SYNOPSIS
read_command()
command_ptr pointer where to return the new query
DESCRIPTION
Converts lines returned by read_line into a command, this involves
parsing the first word in the read line to find the command type.
A -- comment may contain a valid query as the first word after the
comment start. Thus it's always checked to see if that is the case.
The advantage with this approach is to be able to execute commands
terminated by new line '\n' regardless how many "delimiter" it contain.
*/
#define MAX_QUERY (256*1024*2) /* 256K -- a test in sp-big is >128K */
static char read_command_buf[MAX_QUERY];
int read_command(struct st_command** command_ptr)
{
char *p= read_command_buf;
struct st_command* command;
DBUG_ENTER("read_command");
if (parser.current_line < parser.read_lines)
{
get_dynamic(&q_lines, (uchar*) command_ptr, parser.current_line) ;
DBUG_RETURN(0);
}
if (!(*command_ptr= command=
(struct st_command*) my_malloc(sizeof(*command),
MYF(MY_WME|MY_ZEROFILL))) ||
insert_dynamic(&q_lines, (uchar*) &command))
die("Out of memory");
command->type= Q_UNKNOWN;
read_command_buf[0]= 0;
if (read_line(read_command_buf, sizeof(read_command_buf)))
{
check_eol_junk(read_command_buf);
DBUG_RETURN(1);
}
if (opt_result_format_version == 1)
convert_to_format_v1(read_command_buf);
DBUG_PRINT("info", ("query: '%s'", read_command_buf));
if (*p == '#')
{
command->type= Q_COMMENT;
}
else if (p[0] == '-' && p[1] == '-')
{
command->type= Q_COMMENT_WITH_COMMAND;
p+= 2; /* Skip past -- */
}
else if (*p == '\n')
{
command->type= Q_EMPTY_LINE;
}
/* Skip leading spaces */
while (*p && my_isspace(charset_info, *p))
p++;
if (!(command->query_buf= command->query= my_strdup(p, MYF(MY_WME))))
die("Out of memory");
/*
Calculate first word length(the command), terminated
by 'space' , '(' or 'delimiter' */
p= command->query;
while (*p && !my_isspace(charset_info, *p) && *p != '(' && !is_delimiter(p))
p++;
command->first_word_len= (uint) (p - command->query);
DBUG_PRINT("info", ("first_word: %.*s",
command->first_word_len, command->query));
/* Skip spaces between command and first argument */
while (*p && my_isspace(charset_info, *p))
p++;
command->first_argument= p;
command->end= strend(command->query);
command->query_len= (command->end - command->query);
parser.read_lines++;
DBUG_RETURN(0);
}
static struct my_option my_long_options[] =
{
{"help", '?', "Display this help and exit.", 0, 0, 0, GET_NO_ARG, NO_ARG,
0, 0, 0, 0, 0, 0},
{"basedir", 'b', "Basedir for tests.", &opt_basedir,
&opt_basedir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"character-sets-dir", 0,
"Directory for character set files.", &opt_charsets_dir,
&opt_charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"compress", 'C', "Use the compressed server/client protocol.",
&opt_compress, &opt_compress, 0, GET_BOOL, NO_ARG, 0, 0, 0,
0, 0, 0},
{"continue-on-error", 0,
"Continue test even if we got an error. "
"This is mostly useful when testing a storage engine to see what from a test file it can execute, "
"or to find all syntax errors in a newly created big test file",
&opt_continue_on_error, &opt_continue_on_error, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"cursor-protocol", 0, "Use cursors for prepared statements.",
&cursor_protocol, &cursor_protocol, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"database", 'D', "Database to use.", &opt_db, &opt_db, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#ifdef DBUG_OFF
{"debug", '#', "This is a non-debug version. Catch this and exit",
0,0, 0, GET_DISABLED, OPT_ARG, 0, 0, 0, 0, 0, 0},
#else
{"debug", '#', "Output debug log. Often this is 'd:t:o,filename'.",
0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"debug-check", 0, "Check memory and open file usage at exit.",
&debug_check_flag, &debug_check_flag, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"debug-info", 0, "Print some debug info at exit.",
&debug_info_flag, &debug_info_flag,
0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"host", 'h', "Connect to host.", &opt_host, &opt_host, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"prologue", 0, "Include SQL before each test case.", &opt_prologue,
&opt_prologue, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"logdir", OPT_LOG_DIR, "Directory for log files", &opt_logdir,
&opt_logdir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"mark-progress", 0,
"Write line number and elapsed time to <testname>.progress.",
&opt_mark_progress, &opt_mark_progress, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"max-connect-retries", 0,
"Maximum number of attempts to connect to server.",
&opt_max_connect_retries, &opt_max_connect_retries, 0,
GET_INT, REQUIRED_ARG, 500, 1, 10000, 0, 0, 0},
{"max-connections", 0,
"Max number of open connections to server",
&opt_max_connections, &opt_max_connections, 0,
GET_INT, REQUIRED_ARG, DEFAULT_MAX_CONN, 8, 5120, 0, 0, 0},
{"password", 'p', "Password to use when connecting to server.",
0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
{"protocol", OPT_MYSQL_PROTOCOL, "The protocol of connection (tcp,socket,pipe,memory).",
0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"port", 'P', "Port number to use for connection or 0 for default to, in "
"order of preference, my.cnf, $MYSQL_TCP_PORT, "
#if MYSQL_PORT_DEFAULT == 0
"/etc/services, "
#endif
"built-in default (" STRINGIFY_ARG(MYSQL_PORT) ").",
&opt_port, &opt_port, 0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"ps-protocol", 0,
"Use prepared-statement protocol for communication.",
&ps_protocol, &ps_protocol, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"non-blocking-api", 0,
"Use the non-blocking client API for communication.",
&non_blocking_api_enabled, &non_blocking_api_enabled, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"quiet", 's', "Suppress all normal output.", &silent,
&silent, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"record", 'r', "Record output of test_file into result file.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"result-file", 'R', "Read/store result from/in this file.",
&result_file_name, &result_file_name, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"result-format-version", OPT_RESULT_FORMAT_VERSION,
"Version of the result file format to use",
&opt_result_format_version,
&opt_result_format_version, 0,
GET_INT, REQUIRED_ARG, 1, 1, 2, 0, 0, 0},
{"server-arg", 'A', "Send option value to embedded server as a parameter.",
0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"server-file", 'F', "Read embedded server arguments from file.",
0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"shared-memory-base-name", 0,
"Base name of shared memory.", &shared_memory_base_name,
&shared_memory_base_name, 0, GET_STR, REQUIRED_ARG, 0, 0, 0,
0, 0, 0},
{"silent", 's', "Suppress all normal output. Synonym for --quiet.",
&silent, &silent, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"sleep", 'T', "Always sleep this many seconds on sleep commands.",
&opt_sleep, &opt_sleep, 0, GET_INT, REQUIRED_ARG, -1, -1, 0,
0, 0, 0},
{"socket", 'S', "The socket file to use for connection.",
&unix_sock, &unix_sock, 0, GET_STR, REQUIRED_ARG, 0, 0, 0,
0, 0, 0},
{"sp-protocol", 0, "Use stored procedures for select.",
&sp_protocol, &sp_protocol, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
#include "sslopt-longopts.h"
{"tail-lines", 0,
"Number of lines of the result to include in a failure report.",
&opt_tail_lines, &opt_tail_lines, 0,
GET_INT, REQUIRED_ARG, 0, 0, 10000, 0, 0, 0},
{"test-file", 'x', "Read test from/in this file (default stdin).",
0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"timer-file", 'm', "File where the timing in microseconds is stored.",
0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"tmpdir", 't', "Temporary directory where sockets are put.",
0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"user", 'u', "User for login.", &opt_user, &opt_user, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"verbose", 'v', "Write more.", &verbose, &verbose, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"version", 'V', "Output version information and exit.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"view-protocol", 0, "Use views for select.",
&view_protocol, &view_protocol, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"connect_timeout", 0,
"Number of seconds before connection timeout.",
&opt_connect_timeout, &opt_connect_timeout, 0, GET_UINT, REQUIRED_ARG,
120, 0, 3600 * 12, 0, 0, 0},
{"wait_for_pos_timeout", 0,
"Number of seconds to wait for master_pos_wait",
&opt_wait_for_pos_timeout, &opt_wait_for_pos_timeout, 0, GET_UINT,
REQUIRED_ARG, 300, 0, 3600 * 12, 0, 0, 0},
{"plugin_dir", 0, "Directory for client-side plugins.",
&opt_plugin_dir, &opt_plugin_dir, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"overlay-dir", 0, "Overlay directory.", &opt_overlay_dir,
&opt_overlay_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"suite-dir", 0, "Suite directory.", &opt_suite_dir,
&opt_suite_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{ 0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
};
void print_version(void)
{
printf("%s Ver %s Distrib %s, for %s (%s)\n",my_progname,MTEST_VERSION,
MYSQL_SERVER_VERSION,SYSTEM_TYPE,MACHINE_TYPE);
}
void usage()
{
print_version();
puts(ORACLE_WELCOME_COPYRIGHT_NOTICE("2000"));
printf("Runs a test against the mysql server and compares output with a results file.\n\n");
printf("Usage: %s [OPTIONS] [database] < test_file\n", my_progname);
print_defaults("my",load_default_groups);
puts("");
my_print_help(my_long_options);
my_print_variables(my_long_options);
}
/*
Read arguments for embedded server and put them into
embedded_server_args[]
*/
void read_embedded_server_arguments(const char *name)
{
char argument[1024],buff[FN_REFLEN], *str=0;
FILE *file;
if (!test_if_hard_path(name))
{
strxmov(buff, opt_basedir, name, NullS);
name=buff;
}
fn_format(buff, name, "", "", MY_UNPACK_FILENAME);
if (!embedded_server_arg_count)
{
embedded_server_arg_count=1;
embedded_server_args[0]= (char*) ""; /* Progname */
}
if (!(file=my_fopen(buff, O_RDONLY | FILE_BINARY, MYF(MY_WME))))
die("Failed to open file '%s'", buff);
while (embedded_server_arg_count < MAX_EMBEDDED_SERVER_ARGS &&
(str=fgets(argument,sizeof(argument), file)))
{
*(strend(str)-1)=0; /* Remove end newline */
if (!(embedded_server_args[embedded_server_arg_count]=
(char*) my_strdup(str,MYF(MY_WME))))
{
my_fclose(file,MYF(0));
die("Out of memory");
}
embedded_server_arg_count++;
}
my_fclose(file,MYF(0));
if (str)
die("Too many arguments in option file: %s",name);
return;
}
static my_bool
get_one_option(int optid, const struct my_option *opt, char *argument)
{
switch(optid) {
case '#':
#ifndef DBUG_OFF
DBUG_PUSH(argument ? argument : "d:t:S:i:O,/tmp/mysqltest.trace");
debug_check_flag= 1;
debug_info_flag= 1;
#endif
break;
case 'r':
record = 1;
break;
case 'x':
{
char buff[FN_REFLEN];
if (!test_if_hard_path(argument))
{
strxmov(buff, opt_basedir, argument, NullS);
argument= buff;
}
fn_format(buff, argument, "", "", MY_UNPACK_FILENAME);
DBUG_ASSERT(cur_file == file_stack && cur_file->file == 0);
if (!(cur_file->file=
fopen(buff, "rb")))
die("Could not open '%s' for reading, errno: %d", buff, errno);
cur_file->file_name= my_strdup(buff, MYF(MY_FAE));
cur_file->lineno= 1;
break;
}
case 'm':
{
static char buff[FN_REFLEN];
if (!test_if_hard_path(argument))
{
strxmov(buff, opt_basedir, argument, NullS);
argument= buff;
}
fn_format(buff, argument, "", "", MY_UNPACK_FILENAME);
timer_file= buff;
unlink(timer_file); /* Ignore error, may not exist */
break;
}
case 'p':
if (argument == disabled_my_option)
argument= (char*) ""; // Don't require password
if (argument)
{
my_free(opt_pass);
opt_pass= my_strdup(argument, MYF(MY_FAE));
while (*argument) *argument++= 'x'; /* Destroy argument */
tty_password= 0;
}
else
tty_password= 1;
break;
#include <sslopt-case.h>
case 't':
strnmov(TMPDIR, argument, sizeof(TMPDIR));
break;
case 'A':
if (!embedded_server_arg_count)
{
embedded_server_arg_count=1;
embedded_server_args[0]= (char*) "";
}
if (embedded_server_arg_count == MAX_EMBEDDED_SERVER_ARGS-1 ||
!(embedded_server_args[embedded_server_arg_count++]=
my_strdup(argument, MYF(MY_FAE))))
{
die("Can't use server argument");
}
break;
case OPT_LOG_DIR:
/* Check that the file exists */
if (access(opt_logdir, F_OK) != 0)
die("The specified log directory does not exist: '%s'", opt_logdir);
break;
case 'F':
read_embedded_server_arguments(argument);
break;
case OPT_RESULT_FORMAT_VERSION:
set_result_format_version(opt_result_format_version);
break;
case 'V':
print_version();
exit(0);
case OPT_MYSQL_PROTOCOL:
#ifndef EMBEDDED_LIBRARY
opt_protocol= find_type_or_exit(argument, &sql_protocol_typelib,
opt->name);
#endif
break;
case '?':
usage();
exit(0);
}
return 0;
}
int parse_args(int argc, char **argv)
{
if (load_defaults("my",load_default_groups,&argc,&argv))
exit(1);
default_argv= argv;
if ((handle_options(&argc, &argv, my_long_options, get_one_option)))
exit(1);
if (argc > 1)
{
usage();
exit(1);
}
if (argc == 1)
opt_db= *argv;
if (tty_password)
opt_pass= get_tty_password(NullS); /* purify tested */
if (debug_info_flag)
my_end_arg= MY_CHECK_ERROR | MY_GIVE_INFO;
if (debug_check_flag)
my_end_arg|= MY_CHECK_ERROR;
if (global_subst != NULL)
{
char *comma= strstr(global_subst, ",");
if (comma == NULL)
die("wrong --global-subst, must be X,Y");
memcpy(global_subst_from, global_subst, (comma-global_subst));
global_subst_from[comma-global_subst]= 0;
memcpy(global_subst_to, comma+1, strlen(comma));
}
if (!opt_suite_dir)
opt_suite_dir= "./";
suite_dir_len= strlen(opt_suite_dir);
overlay_dir_len= opt_overlay_dir ? strlen(opt_overlay_dir) : 0;
if (!record)
{
/* Check that the result file exists */
if (result_file_name && access(result_file_name, F_OK) != 0)
die("The specified result file '%s' does not exist",
result_file_name);
}
return 0;
}
/*
Write the content of str into file
SYNOPSIS
str_to_file2
fname - name of file to truncate/create and write to
str - content to write to file
size - size of content witten to file
append - append to file instead of overwriting old file
*/
void str_to_file2(const char *fname, char *str, int size, my_bool append)
{
int fd;
char buff[FN_REFLEN];
int flags= O_WRONLY | O_CREAT;
if (!test_if_hard_path(fname))
{
strxmov(buff, opt_basedir, fname, NullS);
fname= buff;
}
fn_format(buff, fname, "", "", MY_UNPACK_FILENAME);
if (!append)
flags|= O_TRUNC;
if ((fd= my_open(buff, flags,
MYF(MY_WME | MY_FFNF))) < 0)
die("Could not open '%s' for writing, errno: %d", buff, errno);
if (append && my_seek(fd, 0, SEEK_END, MYF(0)) == MY_FILEPOS_ERROR)
die("Could not find end of file '%s', errno: %d", buff, errno);
if (my_write(fd, (uchar*)str, size, MYF(MY_WME|MY_FNABP)))
die("write failed, errno: %d", errno);
my_close(fd, MYF(0));
}
/*
Write the content of str into file
SYNOPSIS
str_to_file
fname - name of file to truncate/create and write to
str - content to write to file
size - size of content witten to file
*/
void str_to_file(const char *fname, char *str, int size)
{
str_to_file2(fname, str, size, FALSE);
}
void check_regerr(regex_t* r, int err)
{
char err_buf[1024];
if (err)
{
regerror(err,r,err_buf,sizeof(err_buf));
die("Regex error: %s\n", err_buf);
}
}
#ifdef __WIN__
DYNAMIC_ARRAY patterns;
/*
init_win_path_patterns
DESCRIPTION
Setup string patterns that will be used to detect filenames that
needs to be converted from Win to Unix format
*/
void init_win_path_patterns()
{
/* List of string patterns to match in order to find paths */
const char* paths[] = { "$MYSQL_TEST_DIR",
"$MYSQL_TMP_DIR",
"$MYSQLTEST_VARDIR",
"$MASTER_MYSOCK",
"$MYSQL_SHAREDIR",
"$MYSQL_LIBDIR",
"./test/" };
int num_paths= sizeof(paths)/sizeof(char*);
int i;
char* p;
DBUG_ENTER("init_win_path_patterns");
my_init_dynamic_array(&patterns, sizeof(const char*), 16, 16, MYF(0));
/* Loop through all paths in the array */
for (i= 0; i < num_paths; i++)
{
VAR* v;
if (*(paths[i]) == '$')
{
v= var_get(paths[i], 0, 0, 0);
p= my_strdup(v->str_val, MYF(MY_FAE));
}
else
p= my_strdup(paths[i], MYF(MY_FAE));
/* Don't insert zero length strings in patterns array */
if (strlen(p) == 0)
{
my_free(p);
continue;
}
if (insert_dynamic(&patterns, (uchar*) &p))
die("Out of memory");
DBUG_PRINT("info", ("p: %s", p));
while (*p)
{
if (*p == '/')
*p='\\';
p++;
}
}
DBUG_VOID_RETURN;
}
void free_win_path_patterns()
{
uint i= 0;
for (i=0 ; i < patterns.elements ; i++)
{
const char** pattern= dynamic_element(&patterns, i, const char**);
my_free((void *) *pattern);
}
delete_dynamic(&patterns);
}
/*
fix_win_paths
DESCRIPTION
Search the string 'val' for the patterns that are known to be
strings that contain filenames. Convert all \ to / in the
filenames that are found.
Ex:
val = 'Error "c:\mysql\mysql-test\var\test\t1.frm" didn't exist'
=> $MYSQL_TEST_DIR is found by strstr
=> all \ from c:\mysql\m... until next space is converted into /
*/
void fix_win_paths(const char *val, int len)
{
uint i;
char *p;
DBUG_ENTER("fix_win_paths");
for (i= 0; i < patterns.elements; i++)
{
const char** pattern= dynamic_element(&patterns, i, const char**);
DBUG_PRINT("info", ("pattern: %s", *pattern));
/* Search for the path in string */
while ((p= strstr((char*)val, *pattern)))
{
DBUG_PRINT("info", ("Found %s in val p: %s", *pattern, p));
while (*p && !my_isspace(charset_info, *p))
{
if (*p == '\\')
*p= '/';
p++;
}
DBUG_PRINT("info", ("Converted \\ to /, p: %s", p));
}
}
DBUG_PRINT("exit", (" val: %s, len: %d", val, len));
DBUG_VOID_RETURN;
}
#endif
/*
Append the result for one field to the dynamic string ds
*/
void append_field(DYNAMIC_STRING *ds, uint col_idx, MYSQL_FIELD* field,
char* val, ulonglong len, my_bool is_null)
{
char null[]= "NULL";
if (col_idx < max_replace_column && replace_column[col_idx])
{
val= replace_column[col_idx];
len= strlen(val);
}
else if (is_null)
{
val= null;
len= 4;
}
#ifdef __WIN__
else if ((field->type == MYSQL_TYPE_DOUBLE ||
field->type == MYSQL_TYPE_FLOAT ) &&
field->decimals >= 31)
{
/* Convert 1.2e+018 to 1.2e+18 and 1.2e-018 to 1.2e-18 */
char *start= strchr(val, 'e');
if (start && strlen(start) >= 5 &&
(start[1] == '-' || start[1] == '+') && start[2] == '0')
{
start+=2; /* Now points at first '0' */
if (field->flags & ZEROFILL_FLAG)
{
/* Move all chars before the first '0' one step right */
memmove(val + 1, val, start - val);
*val= '0';
}
else
{
/* Move all chars after the first '0' one step left */
memmove(start, start + 1, strlen(start));
len--;
}
}
}
#endif
if (!display_result_vertically)
{
if (col_idx)
dynstr_append_mem(ds, "\t", 1);
replace_dynstr_append_mem(ds, val, (int)len);
}
else
{
dynstr_append(ds, field->name);
dynstr_append_mem(ds, "\t", 1);
replace_dynstr_append_mem(ds, val, (int)len);
dynstr_append_mem(ds, "\n", 1);
}
}
/*
Append all results to the dynamic string separated with '\t'
Values may be converted with 'replace_column'
*/
void append_result(DYNAMIC_STRING *ds, MYSQL_RES *res)
{
MYSQL_ROW row;
uint num_fields= mysql_num_fields(res);
MYSQL_FIELD *fields= mysql_fetch_fields(res);
ulong *lengths;
while ((row = mysql_fetch_row(res)))
{
uint i;
lengths = mysql_fetch_lengths(res);
for (i = 0; i < num_fields; i++)
append_field(ds, i, &fields[i],
row[i], lengths[i], !row[i]);
if (!display_result_vertically)
dynstr_append_mem(ds, "\n", 1);
}
}
/*
Append all results from ps execution to the dynamic string separated
with '\t'. Values may be converted with 'replace_column'
*/
void append_stmt_result(DYNAMIC_STRING *ds, MYSQL_STMT *stmt,
MYSQL_FIELD *fields, uint num_fields)
{
MYSQL_BIND *my_bind;
my_bool *is_null;
ulong *length;
uint i;
int error;
/* Allocate array with bind structs, lengths and NULL flags */
my_bind= (MYSQL_BIND*) my_malloc(num_fields * sizeof(MYSQL_BIND),
MYF(MY_WME | MY_FAE | MY_ZEROFILL));
length= (ulong*) my_malloc(num_fields * sizeof(ulong),
MYF(MY_WME | MY_FAE));
is_null= (my_bool*) my_malloc(num_fields * sizeof(my_bool),
MYF(MY_WME | MY_FAE));
/* Allocate data for the result of each field */
for (i= 0; i < num_fields; i++)
{
uint max_length= fields[i].max_length + 1;
my_bind[i].buffer_type= MYSQL_TYPE_STRING;
my_bind[i].buffer= my_malloc(max_length, MYF(MY_WME | MY_FAE));
my_bind[i].buffer_length= max_length;
my_bind[i].is_null= &is_null[i];
my_bind[i].length= &length[i];
DBUG_PRINT("bind", ("col[%d]: buffer_type: %d, buffer_length: %lu",
i, my_bind[i].buffer_type, my_bind[i].buffer_length));
}
if (mysql_stmt_bind_result(stmt, my_bind))
die("mysql_stmt_bind_result failed: %d: %s",
mysql_stmt_errno(stmt), mysql_stmt_error(stmt));
while ((error=mysql_stmt_fetch(stmt)) == 0)
{
for (i= 0; i < num_fields; i++)
append_field(ds, i, &fields[i], (char*)my_bind[i].buffer,
*my_bind[i].length, *my_bind[i].is_null);
if (!display_result_vertically)
dynstr_append_mem(ds, "\n", 1);
}
if (error != MYSQL_NO_DATA)
die("mysql_fetch didn't end with MYSQL_NO_DATA from statement: "
"error: %d", error);
if (mysql_stmt_fetch(stmt) != MYSQL_NO_DATA)
die("mysql_fetch didn't end with MYSQL_NO_DATA from statement: %d %s",
mysql_stmt_errno(stmt), mysql_stmt_error(stmt));
for (i= 0; i < num_fields; i++)
{
/* Free data for output */
my_free(my_bind[i].buffer);
}
/* Free array with bind structs, lengths and NULL flags */
my_free(my_bind);
my_free(length);
my_free(is_null);
}
/*
Append metadata for fields to output
*/
void append_metadata(DYNAMIC_STRING *ds,
MYSQL_FIELD *field,
uint num_fields)
{
MYSQL_FIELD *field_end;
dynstr_append(ds,"Catalog\tDatabase\tTable\tTable_alias\tColumn\t"
"Column_alias\tType\tLength\tMax length\tIs_null\t"
"Flags\tDecimals\tCharsetnr\n");
for (field_end= field+num_fields ;
field < field_end ;
field++)
{
dynstr_append_mem(ds, field->catalog,
field->catalog_length);
dynstr_append_mem(ds, "\t", 1);
dynstr_append_mem(ds, field->db, field->db_length);
dynstr_append_mem(ds, "\t", 1);
dynstr_append_mem(ds, field->org_table,
field->org_table_length);
dynstr_append_mem(ds, "\t", 1);
dynstr_append_mem(ds, field->table,
field->table_length);
dynstr_append_mem(ds, "\t", 1);
dynstr_append_mem(ds, field->org_name,
field->org_name_length);
dynstr_append_mem(ds, "\t", 1);
dynstr_append_mem(ds, field->name, field->name_length);
dynstr_append_mem(ds, "\t", 1);
replace_dynstr_append_uint(ds, field->type);
dynstr_append_mem(ds, "\t", 1);
replace_dynstr_append_uint(ds, field->length);
dynstr_append_mem(ds, "\t", 1);
replace_dynstr_append_uint(ds, field->max_length);
dynstr_append_mem(ds, "\t", 1);
dynstr_append_mem(ds, (char*) (IS_NOT_NULL(field->flags) ?
"N" : "Y"), 1);
dynstr_append_mem(ds, "\t", 1);
replace_dynstr_append_uint(ds, field->flags);
dynstr_append_mem(ds, "\t", 1);
replace_dynstr_append_uint(ds, field->decimals);
dynstr_append_mem(ds, "\t", 1);
replace_dynstr_append_uint(ds, field->charsetnr);
dynstr_append_mem(ds, "\n", 1);
}
}
/*
Append affected row count and other info to output
*/
void append_info(DYNAMIC_STRING *ds, ulonglong affected_rows,
const char *info)
{
char buf[40], buff2[21];
sprintf(buf,"affected rows: %s\n", llstr(affected_rows, buff2));
dynstr_append(ds, buf);
if (info)
{
dynstr_append(ds, "info: ");
dynstr_append(ds, info);
dynstr_append_mem(ds, "\n", 1);
}
}
/*
Display the table headings with the names tab separated
*/
void append_table_headings(DYNAMIC_STRING *ds,
MYSQL_FIELD *field,
uint num_fields)
{
uint col_idx;
if (disable_column_names)
return;
for (col_idx= 0; col_idx < num_fields; col_idx++)
{
if (col_idx)
dynstr_append_mem(ds, "\t", 1);
replace_dynstr_append(ds, field[col_idx].name);
}
dynstr_append_mem(ds, "\n", 1);
}
/*
Fetch warnings from server and append to ds
RETURN VALUE
Number of warnings appended to ds
*/
int append_warnings(DYNAMIC_STRING *ds, MYSQL* mysql)
{
uint count;
MYSQL_RES *warn_res;
DYNAMIC_STRING res;
DBUG_ENTER("append_warnings");
if (!(count= mysql_warning_count(mysql)))
DBUG_RETURN(0);
/*
If one day we will support execution of multi-statements
through PS API we should not issue SHOW WARNINGS until
we have not read all results...
*/
DBUG_ASSERT(!mysql_more_results(mysql));
if (mysql_real_query(mysql, "SHOW WARNINGS", 13))
die("Error running query \"SHOW WARNINGS\": %s", mysql_error(mysql));
if (!(warn_res= mysql_store_result(mysql)))
die("Warning count is %u but didn't get any warnings",
count);
init_dynamic_string(&res, "", 1024, 1024);
append_result(&res, warn_res);
mysql_free_result(warn_res);
DBUG_PRINT("warnings", ("%s", res.str));
if (display_result_sorted)
dynstr_append_sorted(ds, &res, 0);
else
dynstr_append_mem(ds, res.str, res.length);
dynstr_free(&res);
DBUG_RETURN(count);
}
/*
Handle situation where query is sent but there is no active connection
(e.g directly after disconnect).
We emulate MySQL-compatible behaviour of sending something on a closed
connection.
*/
static void handle_no_active_connection(struct st_command *command,
struct st_connection *cn, DYNAMIC_STRING *ds)
{
handle_error(command, 2006, "MySQL server has gone away", "000000", ds);
cn->pending= FALSE;
var_set_errno(2006);
}
/*
Run query using MySQL C API
SYNOPSIS
run_query_normal()
mysql mysql handle
command current command pointer
flags flags indicating if we should SEND and/or REAP
query query string to execute
query_len length query string to execute
ds output buffer where to store result form query
*/
void run_query_normal(struct st_connection *cn, struct st_command *command,
int flags, char *query, int query_len,
DYNAMIC_STRING *ds, DYNAMIC_STRING *ds_warnings)
{
MYSQL_RES *res= 0;
MYSQL *mysql= cn->mysql;
int err= 0, counter= 0;
DBUG_ENTER("run_query_normal");
DBUG_PRINT("enter",("flags: %d", flags));
DBUG_PRINT("enter", ("query: '%-.60s'", query));
if (!mysql)
{
handle_no_active_connection(command, cn, ds);
DBUG_VOID_RETURN;
}
if (flags & QUERY_SEND_FLAG)
{
/*
Send the query
*/
if (do_send_query(cn, query, query_len))
{
handle_error(command, mysql_errno(mysql), mysql_error(mysql),
mysql_sqlstate(mysql), ds);
goto end;
}
}
if (!(flags & QUERY_REAP_FLAG))
{
cn->pending= TRUE;
DBUG_VOID_RETURN;
}
do
{
/*
When on first result set, call mysql_read_query_result to retrieve
answer to the query sent earlier
*/
if ((counter==0) && do_read_query_result(cn))
{
/* we've failed to collect the result set */
cn->pending= TRUE;
handle_error(command, mysql_errno(mysql), mysql_error(mysql),
mysql_sqlstate(mysql), ds);
goto end;
}
/*
Store the result of the query if it will return any fields
*/
if (mysql_field_count(mysql) && ((res= mysql_store_result(mysql)) == 0))
{
handle_error(command, mysql_errno(mysql), mysql_error(mysql),
mysql_sqlstate(mysql), ds);
goto end;
}
if (!disable_result_log)
{
if (res)
{
MYSQL_FIELD *fields= mysql_fetch_fields(res);
uint num_fields= mysql_num_fields(res);
if (display_metadata)
append_metadata(ds, fields, num_fields);
if (!display_result_vertically)
append_table_headings(ds, fields, num_fields);
append_result(ds, res);
}
/*
Need to call mysql_affected_rows() before the "new"
query to find the warnings.
*/
if (!disable_info)
append_info(ds, mysql_affected_rows(mysql), mysql_info(mysql));
/*
Add all warnings to the result. We can't do this if we are in
the middle of processing results from multi-statement, because
this will break protocol.
*/
if (!disable_warnings && !mysql_more_results(mysql))
{
if (append_warnings(ds_warnings, mysql) || ds_warnings->length)
{
dynstr_append_mem(ds, "Warnings:\n", 10);
dynstr_append_mem(ds, ds_warnings->str, ds_warnings->length);
}
}
}
if (res)
{
mysql_free_result(res);
res= 0;
}
counter++;
} while (!(err= mysql_next_result(mysql)));
if (err > 0)
{
/* We got an error from mysql_next_result, maybe expected */
handle_error(command, mysql_errno(mysql), mysql_error(mysql),
mysql_sqlstate(mysql), ds);
goto end;
}
DBUG_ASSERT(err == -1); /* Successful and there are no more results */
/* If we come here the query is both executed and read successfully */
handle_no_error(command);
revert_properties();
end:
cn->pending= FALSE;
/*
We save the return code (mysql_errno(mysql)) from the last call sent
to the server into the mysqltest builtin variable $mysql_errno. This
variable then can be used from the test case itself.
*/
var_set_errno(mysql_errno(mysql));
DBUG_VOID_RETURN;
}
/*
Check whether given error is in list of expected errors
SYNOPSIS
match_expected_error()
PARAMETERS
command the current command (and its expect-list)
err_errno error number of the error that actually occurred
err_sqlstate SQL-state that was thrown, or NULL for impossible
(file-ops, diff, etc.)
RETURNS
-1 for not in list, index in list of expected errors otherwise
NOTE
If caller needs to know whether the list was empty, they should
check command->expected_errors.count.
*/
static int match_expected_error(struct st_command *command,
unsigned int err_errno,
const char *err_sqlstate)
{
uint i;
for (i= 0 ; (uint) i < command->expected_errors.count ; i++)
{
if ((command->expected_errors.err[i].type == ERR_ERRNO) &&
(command->expected_errors.err[i].code.errnum == err_errno))
return i;
if (command->expected_errors.err[i].type == ERR_SQLSTATE)
{
/*
NULL is quite likely, but not in conjunction with a SQL-state expect!
*/
if (unlikely(err_sqlstate == NULL))
die("expecting a SQL-state (%s) from query '%s' which cannot "
"produce one...",
command->expected_errors.err[i].code.sqlstate, command->query);
if (strncmp(command->expected_errors.err[i].code.sqlstate,
err_sqlstate, SQLSTATE_LENGTH) == 0)
return i;
}
}
return -1;
}
/*
Handle errors which occurred during execution
SYNOPSIS
handle_error()
q - query context
err_errno - error number
err_error - error message
err_sqlstate - sql state
ds - dynamic string which is used for output buffer
NOTE
If there is an unexpected error this function will abort mysqltest
immediately.
*/
void handle_error(struct st_command *command,
unsigned int err_errno, const char *err_error,
const char *err_sqlstate, DYNAMIC_STRING *ds)
{
int i;
DBUG_ENTER("handle_error");
command->used_replace= 1;
if (command->require_file)
{
/*
The query after a "--require" failed. This is fine as long the server
returned a valid reponse. Don't allow 2013 or 2006 to trigger an
abort_not_supported_test
*/
if (err_errno == CR_SERVER_LOST ||
err_errno == CR_SERVER_GONE_ERROR)
die("require query '%s' failed: %d: %s", command->query,
err_errno, err_error);
/* Abort the run of this test, pass the failed query as reason */
abort_not_supported_test("Query '%s' failed, required functionality " \
"not supported", command->query);
}
if (command->abort_on_error)
{
report_or_die("query '%s' failed: %d: %s", command->query, err_errno,
err_error);
DBUG_VOID_RETURN;
}
DBUG_PRINT("info", ("expected_errors.count: %d",
command->expected_errors.count));
i= match_expected_error(command, err_errno, err_sqlstate);
if (i >= 0)
{
if (!disable_result_log)
{
if (command->expected_errors.count == 1)
{
/* Only log error if there is one possible error */
dynstr_append_mem(ds, "ERROR ", 6);
replace_dynstr_append(ds, err_sqlstate);
dynstr_append_mem(ds, ": ", 2);
replace_dynstr_append(ds, err_error);
dynstr_append_mem(ds,"\n",1);
}
/* Don't log error if we may not get an error */
else if (command->expected_errors.err[0].type == ERR_SQLSTATE ||
(command->expected_errors.err[0].type == ERR_ERRNO &&
command->expected_errors.err[0].code.errnum != 0))
dynstr_append(ds,"Got one of the listed errors\n");
}
/* OK */
revert_properties();
DBUG_VOID_RETURN;
}
DBUG_PRINT("info",("i: %d expected_errors: %d", i,
command->expected_errors.count));
if (!disable_result_log)
{
dynstr_append_mem(ds, "ERROR ",6);
replace_dynstr_append(ds, err_sqlstate);
dynstr_append_mem(ds, ": ", 2);
replace_dynstr_append(ds, err_error);
dynstr_append_mem(ds, "\n", 1);
}
if (command->expected_errors.count > 0)
{
if (command->expected_errors.err[0].type == ERR_ERRNO)
report_or_die("query '%s' failed with wrong errno %d: '%s', instead of "
"%d...",
command->query, err_errno, err_error,
command->expected_errors.err[0].code.errnum);
else
report_or_die("query '%s' failed with wrong sqlstate %s: '%s', "
"instead of %s...",
command->query, err_sqlstate, err_error,
command->expected_errors.err[0].code.sqlstate);
}
revert_properties();
DBUG_VOID_RETURN;
}
/*
Handle absence of errors after execution
SYNOPSIS
handle_no_error()
q - context of query
RETURN VALUE
error - function will not return
*/
void handle_no_error(struct st_command *command)
{
DBUG_ENTER("handle_no_error");
if (command->expected_errors.err[0].type == ERR_ERRNO &&
command->expected_errors.err[0].code.errnum != 0)
{
/* Error code we wanted was != 0, i.e. not an expected success */
report_or_die("query '%s' succeeded - should have failed with errno %d...",
command->query, command->expected_errors.err[0].code.errnum);
}
else if (command->expected_errors.err[0].type == ERR_SQLSTATE &&
strcmp(command->expected_errors.err[0].code.sqlstate,"00000") != 0)
{
/* SQLSTATE we wanted was != "00000", i.e. not an expected success */
report_or_die("query '%s' succeeded - should have failed with "
"sqlstate %s...",
command->query,
command->expected_errors.err[0].code.sqlstate);
}
DBUG_VOID_RETURN;
}
/*
Run query using prepared statement C API
SYNPOSIS
run_query_stmt
mysql - mysql handle
command - currrent command pointer
query - query string to execute
query_len - length query string to execute
ds - output buffer where to store result form query
RETURN VALUE
error - function will not return
*/
void run_query_stmt(struct st_connection *cn, struct st_command *command,
char *query, int query_len, DYNAMIC_STRING *ds,
DYNAMIC_STRING *ds_warnings)
{
MYSQL_RES *res= NULL; /* Note that here 'res' is meta data result set */
MYSQL *mysql= cn->mysql;
MYSQL_STMT *stmt;
DYNAMIC_STRING ds_prepare_warnings;
DYNAMIC_STRING ds_execute_warnings;
DBUG_ENTER("run_query_stmt");
DBUG_PRINT("query", ("'%-.60s'", query));
/*
Init a new stmt if it's not already one created for this connection
*/
if(!(stmt= cn->stmt))
{
if (!(stmt= mysql_stmt_init(mysql)))
die("unable to init stmt structure");
cn->stmt= stmt;
}
/* Init dynamic strings for warnings */
if (!disable_warnings)
{
init_dynamic_string(&ds_prepare_warnings, NULL, 0, 256);
init_dynamic_string(&ds_execute_warnings, NULL, 0, 256);
}
/*
Prepare the query
*/
if (do_stmt_prepare(cn, query, query_len))
{
handle_error(command, mysql_stmt_errno(stmt),
mysql_stmt_error(stmt), mysql_stmt_sqlstate(stmt), ds);
goto end;
}
/*
Get the warnings from mysql_stmt_prepare and keep them in a
separate string
*/
if (!disable_warnings)
append_warnings(&ds_prepare_warnings, mysql);
/*
No need to call mysql_stmt_bind_param() because we have no
parameter markers.
*/
#if MYSQL_VERSION_ID >= 50000
if (cursor_protocol_enabled)
{
/*
Use cursor when retrieving result
*/
ulong type= CURSOR_TYPE_READ_ONLY;
if (mysql_stmt_attr_set(stmt, STMT_ATTR_CURSOR_TYPE, (void*) &type))
die("mysql_stmt_attr_set(STMT_ATTR_CURSOR_TYPE) failed': %d %s",
mysql_stmt_errno(stmt), mysql_stmt_error(stmt));
}
#endif
/*
Execute the query
*/
if (do_stmt_execute(cn))
{
handle_error(command, mysql_stmt_errno(stmt),
mysql_stmt_error(stmt), mysql_stmt_sqlstate(stmt), ds);
goto end;
}
/*
When running in cursor_protocol get the warnings from execute here
and keep them in a separate string for later.
*/
if (cursor_protocol_enabled && !disable_warnings)
append_warnings(&ds_execute_warnings, mysql);
/*
We instruct that we want to update the "max_length" field in
mysql_stmt_store_result(), this is our only way to know how much
buffer to allocate for result data
*/
{
my_bool one= 1;
if (mysql_stmt_attr_set(stmt, STMT_ATTR_UPDATE_MAX_LENGTH, (void*) &one))
die("mysql_stmt_attr_set(STMT_ATTR_UPDATE_MAX_LENGTH) failed': %d %s",
mysql_stmt_errno(stmt), mysql_stmt_error(stmt));
}
/*
If we got here the statement succeeded and was expected to do so,
get data. Note that this can still give errors found during execution!
Store the result of the query if if will return any fields
*/
if (mysql_stmt_field_count(stmt) && mysql_stmt_store_result(stmt))
{
handle_error(command, mysql_stmt_errno(stmt),
mysql_stmt_error(stmt), mysql_stmt_sqlstate(stmt), ds);
goto end;
}
/* If we got here the statement was both executed and read successfully */
handle_no_error(command);
if (!disable_result_log)
{
/*
Not all statements creates a result set. If there is one we can
now create another normal result set that contains the meta
data. This set can be handled almost like any other non prepared
statement result set.
*/
if ((res= mysql_stmt_result_metadata(stmt)) != NULL)
{
/* Take the column count from meta info */
MYSQL_FIELD *fields= mysql_fetch_fields(res);
uint num_fields= mysql_num_fields(res);
if (display_metadata)
append_metadata(ds, fields, num_fields);
if (!display_result_vertically)
append_table_headings(ds, fields, num_fields);
append_stmt_result(ds, stmt, fields, num_fields);
mysql_free_result(res); /* Free normal result set with meta data */
/*
Normally, if there is a result set, we do not show warnings from the
prepare phase. This is because some warnings are generated both during
prepare and execute; this would generate different warning output
between normal and ps-protocol test runs.
The --enable_prepare_warnings command can be used to change this so
that warnings from both the prepare and execute phase are shown.
*/
if (!disable_warnings && !prepare_warnings_enabled)
dynstr_set(&ds_prepare_warnings, NULL);
}
else
{
/*
This is a query without resultset
*/
}
/*
Fetch info before fetching warnings, since it will be reset
otherwise.
*/
if (!disable_info)
append_info(ds, mysql_stmt_affected_rows(stmt), mysql_info(mysql));
if (!disable_warnings)
{
/* Get the warnings from execute */
/* Append warnings to ds - if there are any */
if (append_warnings(&ds_execute_warnings, mysql) ||
ds_execute_warnings.length ||
ds_prepare_warnings.length ||
ds_warnings->length)
{
dynstr_append_mem(ds, "Warnings:\n", 10);
if (ds_warnings->length)
dynstr_append_mem(ds, ds_warnings->str,
ds_warnings->length);
if (ds_prepare_warnings.length)
dynstr_append_mem(ds, ds_prepare_warnings.str,
ds_prepare_warnings.length);
if (ds_execute_warnings.length)
dynstr_append_mem(ds, ds_execute_warnings.str,
ds_execute_warnings.length);
}
}
}
end:
if (!disable_warnings)
{
dynstr_free(&ds_prepare_warnings);
dynstr_free(&ds_execute_warnings);
}
/*
We save the return code (mysql_stmt_errno(stmt)) from the last call sent
to the server into the mysqltest builtin variable $mysql_errno. This
variable then can be used from the test case itself.
*/
var_set_errno(mysql_stmt_errno(stmt));
revert_properties();
/* Close the statement if reconnect, need new prepare */
if (mysql->reconnect)
{
mysql_stmt_close(stmt);
cn->stmt= NULL;
}
DBUG_VOID_RETURN;
}
/*
Create a util connection if one does not already exists
and use that to run the query
This is done to avoid implict commit when creating/dropping objects such
as view, sp etc.
*/
int util_query(MYSQL* org_mysql, const char* query){
MYSQL* mysql;
DBUG_ENTER("util_query");
if(!(mysql= cur_con->util_mysql))
{
DBUG_PRINT("info", ("Creating util_mysql"));
if (!(mysql= mysql_init(mysql)))
die("Failed in mysql_init()");
if (opt_connect_timeout)
mysql_options(mysql, MYSQL_OPT_CONNECT_TIMEOUT,
(void *) &opt_connect_timeout);
/* enable local infile, in non-binary builds often disabled by default */
mysql_options(mysql, MYSQL_OPT_LOCAL_INFILE, 0);
mysql_options(mysql, MYSQL_OPT_NONBLOCK, 0);
safe_connect(mysql, "util", org_mysql->host, org_mysql->user,
org_mysql->passwd, org_mysql->db, org_mysql->port,
org_mysql->unix_socket);
cur_con->util_mysql= mysql;
}
int ret= mysql_query(mysql, query);
DBUG_RETURN(ret);
}
/*
Run query
SYNPOSIS
run_query()
mysql mysql handle
command currrent command pointer
flags control the phased/stages of query execution to be performed
if QUERY_SEND_FLAG bit is on, the query will be sent. If QUERY_REAP_FLAG
is on the result will be read - for regular query, both bits must be on
*/
void run_query(struct st_connection *cn, struct st_command *command, int flags)
{
MYSQL *mysql= cn->mysql;
DYNAMIC_STRING *ds;
DYNAMIC_STRING *save_ds= NULL;
DYNAMIC_STRING ds_result;
DYNAMIC_STRING ds_sorted;
DYNAMIC_STRING ds_warnings;
char *query;
int query_len;
my_bool view_created= 0, sp_created= 0;
my_bool complete_query= ((flags & QUERY_SEND_FLAG) &&
(flags & QUERY_REAP_FLAG));
DBUG_ENTER("run_query");
if (cn->pending && (flags & QUERY_SEND_FLAG))
die("Cannot run query on connection between send and reap");
if (!(flags & QUERY_SEND_FLAG) && !cn->pending)
die("Cannot reap on a connection without pending send");
init_dynamic_string(&ds_warnings, NULL, 0, 256);
ds_warn= &ds_warnings;
/*
Evaluate query if this is an eval command
*/
if (command->type == Q_EVAL || command->type == Q_SEND_EVAL ||
command->type == Q_EVALP)
{
if (!command->eval_query.str)
init_dynamic_string(&command->eval_query, "", command->query_len + 256,
1024);
else
dynstr_set(&command->eval_query, 0);
do_eval(&command->eval_query, command->query, command->end, FALSE);
query= command->eval_query.str;
query_len= command->eval_query.length;
}
else
{
query = command->query;
query_len = strlen(query);
}
/*
When command->require_file is set the output of _this_ query
should be compared with an already existing file
Create a temporary dynamic string to contain the output from
this query.
*/
if (command->require_file)
{
init_dynamic_string(&ds_result, "", 1024, 1024);
ds= &ds_result;
}
else
ds= &ds_res;
/*
Log the query into the output buffer
*/
if (!disable_query_log && (flags & QUERY_SEND_FLAG))
{
char *print_query= query;
int print_len= query_len;
if (flags & QUERY_PRINT_ORIGINAL_FLAG)
{
print_query= command->query;
print_len= command->end - command->query;
}
replace_dynstr_append_mem(ds, print_query, print_len);
dynstr_append_mem(ds, delimiter, delimiter_length);
dynstr_append_mem(ds, "\n", 1);
}
/* We're done with this flag */
flags &= ~QUERY_PRINT_ORIGINAL_FLAG;
/*
Write the command to the result file before we execute the query
This is needed to be able to analyse the log if something goes
wrong
*/
log_file.write(&ds_res);
log_file.flush();
dynstr_set(&ds_res, 0);
if (view_protocol_enabled &&
complete_query &&
match_re(&view_re, query))
{
/*
Create the query as a view.
Use replace since view can exist from a failed mysqltest run
*/
DYNAMIC_STRING query_str;
init_dynamic_string(&query_str,
"CREATE OR REPLACE VIEW mysqltest_tmp_v AS ",
query_len+64, 256);
dynstr_append_mem(&query_str, query, query_len);
if (util_query(mysql, query_str.str))
{
/*
Failed to create the view, this is not fatal
just run the query the normal way
*/
DBUG_PRINT("view_create_error",
("Failed to create view '%s': %d: %s", query_str.str,
mysql_errno(mysql), mysql_error(mysql)));
/* Log error to create view */
verbose_msg("Failed to create view '%s' %d: %s", query_str.str,
mysql_errno(mysql), mysql_error(mysql));
}
else
{
/*
Yes, it was possible to create this query as a view
*/
view_created= 1;
query= (char*)"SELECT * FROM mysqltest_tmp_v";
query_len = strlen(query);
/*
Collect warnings from create of the view that should otherwise
have been produced when the SELECT was executed
*/
append_warnings(&ds_warnings, cur_con->util_mysql);
}
dynstr_free(&query_str);
}
if (sp_protocol_enabled &&
complete_query &&
match_re(&sp_re, query))
{
/*
Create the query as a stored procedure
Drop first since sp can exist from a failed mysqltest run
*/
DYNAMIC_STRING query_str;
init_dynamic_string(&query_str,
"DROP PROCEDURE IF EXISTS mysqltest_tmp_sp;",
query_len+64, 256);
util_query(mysql, query_str.str);
dynstr_set(&query_str, "CREATE PROCEDURE mysqltest_tmp_sp()\n");
dynstr_append_mem(&query_str, query, query_len);
if (util_query(mysql, query_str.str))
{
/*
Failed to create the stored procedure for this query,
this is not fatal just run the query the normal way
*/
DBUG_PRINT("sp_create_error",
("Failed to create sp '%s': %d: %s", query_str.str,
mysql_errno(mysql), mysql_error(mysql)));
/* Log error to create sp */
verbose_msg("Failed to create sp '%s' %d: %s", query_str.str,
mysql_errno(mysql), mysql_error(mysql));
}
else
{
sp_created= 1;
query= (char*)"CALL mysqltest_tmp_sp()";
query_len = strlen(query);
}
dynstr_free(&query_str);
}
if (display_result_sorted)
{
/*
Collect the query output in a separate string
that can be sorted before it's added to the
global result string
*/
init_dynamic_string(&ds_sorted, "", 1024, 1024);
save_ds= ds; /* Remember original ds */
ds= &ds_sorted;
}
/*
Find out how to run this query
Always run with normal C API if it's not a complete
SEND + REAP
If it is a '?' in the query it may be a SQL level prepared
statement already and we can't do it twice
*/
if (ps_protocol_enabled &&
complete_query &&
match_re(&ps_re, query))
run_query_stmt(cn, command, query, query_len, ds, &ds_warnings);
else
run_query_normal(cn, command, flags, query, query_len,
ds, &ds_warnings);
dynstr_free(&ds_warnings);
ds_warn= 0;
if (display_result_sorted)
{
/* Sort the result set and append it to result */
dynstr_append_sorted(save_ds, &ds_sorted, 1);
ds= save_ds;
dynstr_free(&ds_sorted);
}
if (sp_created)
{
if (util_query(mysql, "DROP PROCEDURE mysqltest_tmp_sp "))
report_or_die("Failed to drop sp: %d: %s", mysql_errno(mysql),
mysql_error(mysql));
}
if (view_created)
{
if (util_query(mysql, "DROP VIEW mysqltest_tmp_v "))
report_or_die("Failed to drop view: %d: %s",
mysql_errno(mysql), mysql_error(mysql));
}
if (command->require_file)
{
/* A result file was specified for _this_ query
and the output should be checked against an already
existing file which has been specified using --require or --result
*/
check_require(ds, command->require_file);
}
if (ds == &ds_result)
dynstr_free(&ds_result);
DBUG_VOID_RETURN;
}
/****************************************************************************/
/*
Functions to detect different SQL statements
*/
char *re_eprint(int err)
{
static char epbuf[100];
size_t len __attribute__((unused))=
regerror(err, (regex_t *)NULL, epbuf, sizeof(epbuf));
assert(len <= sizeof(epbuf));
return(epbuf);
}
void init_re_comp(regex_t *re, const char* str)
{
int err= regcomp(re, str, (REG_EXTENDED | REG_ICASE | REG_NOSUB | REG_DOTALL));
if (err)
{
char erbuf[100];
int len= regerror(err, re, erbuf, sizeof(erbuf));
die("error %s, %d/%d `%s'\n",
re_eprint(err), (int)len, (int)sizeof(erbuf), erbuf);
}
}
void init_re(void)
{
/*
Filter for queries that can be run using the
MySQL Prepared Statements C API
*/
const char *ps_re_str =
"^("
"[[:space:]]*REPLACE[[:space:]]|"
"[[:space:]]*INSERT[[:space:]]|"
"[[:space:]]*UPDATE[[:space:]]|"
"[[:space:]]*DELETE[[:space:]]|"
"[[:space:]]*SELECT[[:space:]]|"
"[[:space:]]*CREATE[[:space:]]+TABLE[[:space:]]|"
"[[:space:]]*DO[[:space:]]|"
"[[:space:]]*SET[[:space:]]+OPTION[[:space:]]|"
"[[:space:]]*DELETE[[:space:]]+MULTI[[:space:]]|"
"[[:space:]]*UPDATE[[:space:]]+MULTI[[:space:]]|"
"[[:space:]]*INSERT[[:space:]]+SELECT[[:space:]])";
/*
Filter for queries that can be run using the
Stored procedures
*/
const char *sp_re_str =ps_re_str;
/*
Filter for queries that can be run as views
*/
const char *view_re_str =
"^("
"[[:space:]]*SELECT[[:space:]])";
init_re_comp(&ps_re, ps_re_str);
init_re_comp(&sp_re, sp_re_str);
init_re_comp(&view_re, view_re_str);
}
int match_re(regex_t *re, char *str)
{
while (my_isspace(charset_info, *str))
str++;
if (str[0] == '/' && str[1] == '*')
{
char *comm_end= strstr (str, "*/");
if (! comm_end)
die("Statement is unterminated comment");
str= comm_end + 2;
}
int err= regexec(re, str, (size_t)0, NULL, 0);
if (err == 0)
return 1;
else if (err == REG_NOMATCH)
return 0;
{
char erbuf[100];
int len= regerror(err, re, erbuf, sizeof(erbuf));
die("error %s, %d/%d `%s'\n",
re_eprint(err), (int)len, (int)sizeof(erbuf), erbuf);
}
return 0;
}
void free_re(void)
{
regfree(&ps_re);
regfree(&sp_re);
regfree(&view_re);
}
/****************************************************************************/
void get_command_type(struct st_command* command)
{
char save;
uint type;
DBUG_ENTER("get_command_type");
if (*command->query == '}')
{
command->type = Q_END_BLOCK;
DBUG_VOID_RETURN;
}
save= command->query[command->first_word_len];
command->query[command->first_word_len]= 0;
type= find_type(command->query, &command_typelib, FIND_TYPE_NO_PREFIX);
command->query[command->first_word_len]= save;
if (type > 0)
{
command->type=(enum enum_commands) type; /* Found command */
/*
Look for case where "query" was explicitly specified to
force command being sent to server
*/
if (type == Q_QUERY)
{
/* Skip the "query" part */
command->query= command->first_argument;
}
}
else
{
/* No mysqltest command matched */
if (command->type != Q_COMMENT_WITH_COMMAND)
{
/* A query that will sent to mysqld */
command->type= Q_QUERY;
}
else
{
/* -- "comment" that didn't contain a mysqltest command */
report_or_die("Found line beginning with -- that didn't contain " \
"a valid mysqltest command, check your syntax or " \
"use # if you intended to write a comment");
command->type= Q_COMMENT;
}
}
/* Set expected error on command */
memcpy(&command->expected_errors, &saved_expected_errors,
sizeof(saved_expected_errors));
DBUG_PRINT("info", ("There are %d expected errors",
command->expected_errors.count));
DBUG_VOID_RETURN;
}
/*
Record how many milliseconds it took to execute the test file
up until the current line and write it to .progress file
*/
void mark_progress(struct st_command* command __attribute__((unused)),
int line)
{
static ulonglong progress_start= 0; // < Beware
DYNAMIC_STRING ds_progress;
char buf[32], *end;
ulonglong timer= timer_now();
if (!progress_start)
progress_start= timer;
timer-= progress_start;
if (init_dynamic_string(&ds_progress, "", 256, 256))
die("Out of memory");
/* Milliseconds since start */
end= longlong10_to_str(timer, buf, 10);
dynstr_append_mem(&ds_progress, buf, (int)(end-buf));
dynstr_append_mem(&ds_progress, "\t", 1);
/* Parser line number */
end= int10_to_str(line, buf, 10);
dynstr_append_mem(&ds_progress, buf, (int)(end-buf));
dynstr_append_mem(&ds_progress, "\t", 1);
/* Filename */
dynstr_append(&ds_progress, cur_file->file_name);
dynstr_append_mem(&ds_progress, ":", 1);
/* Line in file */
end= int10_to_str(cur_file->lineno, buf, 10);
dynstr_append_mem(&ds_progress, buf, (int)(end-buf));
dynstr_append_mem(&ds_progress, "\n", 1);
progress_file.write(&ds_progress);
dynstr_free(&ds_progress);
}
#ifdef HAVE_STACKTRACE
static void dump_backtrace(void)
{
struct st_connection *conn= cur_con;
fprintf(stderr, "read_command_buf (%p): ", read_command_buf);
my_safe_print_str(read_command_buf, sizeof(read_command_buf));
fputc('\n', stderr);
if (conn)
{
fprintf(stderr, "conn->name (%p): ", conn->name);
my_safe_print_str(conn->name, conn->name_len);
fputc('\n', stderr);
#ifdef EMBEDDED_LIBRARY
fprintf(stderr, "conn->cur_query (%p): ", conn->cur_query);
my_safe_print_str(conn->cur_query, conn->cur_query_len);
fputc('\n', stderr);
#endif
}
fputs("Attempting backtrace...\n", stderr);
my_print_stacktrace(NULL, my_thread_stack_size);
}
#else
static void dump_backtrace(void)
{
fputs("Backtrace not available.\n", stderr);
}
#endif
static sig_handler signal_handler(int sig)
{
fprintf(stderr, "mysqltest got " SIGNAL_FMT "\n", sig);
dump_backtrace();
fprintf(stderr, "Writing a core file...\n");
fflush(stderr);
my_write_core(sig);
#ifndef __WIN__
exit(1); // Shouldn't get here but just in case
#endif
}
#ifdef __WIN__
LONG WINAPI exception_filter(EXCEPTION_POINTERS *exp)
{
__try
{
my_set_exception_pointers(exp);
signal_handler(exp->ExceptionRecord->ExceptionCode);
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
fputs("Got exception in exception handler!\n", stderr);
}
return EXCEPTION_CONTINUE_SEARCH;
}
static void init_signal_handling(void)
{
UINT mode;
/* Set output destination of messages to the standard error stream. */
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
/* Do not not display the a error message box. */
mode= SetErrorMode(0) | SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX;
SetErrorMode(mode);
SetUnhandledExceptionFilter(exception_filter);
}
#else /* __WIN__ */
static void init_signal_handling(void)
{
struct sigaction sa;
DBUG_ENTER("init_signal_handling");
#ifdef HAVE_STACKTRACE
my_init_stacktrace();
#endif
sa.sa_flags = SA_RESETHAND | SA_NODEFER;
sigemptyset(&sa.sa_mask);
sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
sa.sa_handler= signal_handler;
sigaction(SIGSEGV, &sa, NULL);
sigaction(SIGABRT, &sa, NULL);
#ifdef SIGBUS
sigaction(SIGBUS, &sa, NULL);
#endif
sigaction(SIGILL, &sa, NULL);
sigaction(SIGFPE, &sa, NULL);
DBUG_VOID_RETURN;
}
#endif /* !__WIN__ */
int main(int argc, char **argv)
{
struct st_command *command;
my_bool q_send_flag= 0, abort_flag= 0;
uint command_executed= 0, last_command_executed= 0;
char save_file[FN_REFLEN];
bool empty_result= FALSE;
MY_INIT(argv[0]);
DBUG_ENTER("main");
/* mysqltest has no way to free all its memory correctly */
sf_leaking_memory= 1;
save_file[0]= 0;
TMPDIR[0]= 0;
init_signal_handling();
/* Init expected errors */
memset(&saved_expected_errors, 0, sizeof(saved_expected_errors));
#ifdef EMBEDDED_LIBRARY
/* set appropriate stack for the 'query' threads */
(void) pthread_attr_init(&cn_thd_attrib);
pthread_attr_setstacksize(&cn_thd_attrib, DEFAULT_THREAD_STACK);
#endif /*EMBEDDED_LIBRARY*/
/* Init file stack */
memset(file_stack, 0, sizeof(file_stack));
file_stack_end=
file_stack + (sizeof(file_stack)/sizeof(struct st_test_file)) - 1;
cur_file= file_stack;
/* Init block stack */
memset(block_stack, 0, sizeof(block_stack));
block_stack_end=
block_stack + (sizeof(block_stack)/sizeof(struct st_block)) - 1;
cur_block= block_stack;
cur_block->ok= TRUE; /* Outer block should always be executed */
cur_block->cmd= cmd_none;
my_init_dynamic_array(&q_lines, sizeof(struct st_command*), 1024, 1024, MYF(0));
if (my_hash_init2(&var_hash, 64, charset_info,
128, 0, 0, get_var_key, 0, var_free, MYF(0)))
die("Variable hash initialization failed");
{
char path_separator[]= { FN_LIBCHAR, 0 };
var_set_string("SYSTEM_PATH_SEPARATOR", path_separator);
}
var_set_string("MYSQL_SERVER_VERSION", MYSQL_SERVER_VERSION);
var_set_string("MYSQL_SYSTEM_TYPE", SYSTEM_TYPE);
var_set_string("MYSQL_MACHINE_TYPE", MACHINE_TYPE);
if (sizeof(void *) == 8) {
var_set_string("MYSQL_SYSTEM_ARCHITECTURE", "64");
} else {
var_set_string("MYSQL_SYSTEM_ARCHITECTURE", "32");
}
memset(&master_pos, 0, sizeof(master_pos));
parser.current_line= parser.read_lines= 0;
memset(&var_reg, 0, sizeof(var_reg));
init_builtin_echo();
#ifdef __WIN__
#ifndef USE_CYGWIN
is_windows= 1;
#endif
init_tmp_sh_file();
init_win_path_patterns();
#endif
init_dynamic_string(&ds_res, "", 2048, 2048);
init_alloc_root(&require_file_root, 1024, 1024, MYF(0));
parse_args(argc, argv);
log_file.open(opt_logdir, result_file_name, ".log");
verbose_msg("Logging to '%s'.", log_file.file_name());
if (opt_mark_progress)
{
progress_file.open(opt_logdir, result_file_name, ".progress");
verbose_msg("Tracing progress in '%s'.", progress_file.file_name());
}
/* Init connections, allocate 1 extra as buffer + 1 for default */
connections= (struct st_connection*)
my_malloc((opt_max_connections+2) * sizeof(struct st_connection),
MYF(MY_WME | MY_ZEROFILL));
connections_end= connections + opt_max_connections +1;
next_con= connections + 1;
var_set_int("$PS_PROTOCOL", ps_protocol);
var_set_int("$NON_BLOCKING_API", non_blocking_api_enabled);
var_set_int("$SP_PROTOCOL", sp_protocol);
var_set_int("$VIEW_PROTOCOL", view_protocol);
var_set_int("$CURSOR_PROTOCOL", cursor_protocol);
var_set_int("$ENABLED_QUERY_LOG", 1);
var_set_int("$ENABLED_ABORT_ON_ERROR", 1);
var_set_int("$ENABLED_RESULT_LOG", 1);
var_set_int("$ENABLED_CONNECT_LOG", 0);
var_set_int("$ENABLED_WARNINGS", 1);
var_set_int("$ENABLED_INFO", 0);
var_set_int("$ENABLED_METADATA", 0);
DBUG_PRINT("info",("result_file: '%s'",
result_file_name ? result_file_name : ""));
verbose_msg("Results saved in '%s'.",
result_file_name ? result_file_name : "");
if (mysql_server_init(embedded_server_arg_count,
embedded_server_args,
(char**) embedded_server_groups))
die("Can't initialize MySQL server");
server_initialized= 1;
if (cur_file == file_stack && cur_file->file == 0)
{
cur_file->file= stdin;
cur_file->file_name= my_strdup("<stdin>", MYF(MY_WME));
cur_file->lineno= 1;
}
var_set_string("MYSQLTEST_FILE", cur_file->file_name);
init_re();
/* Cursor protcol implies ps protocol */
if (cursor_protocol)
ps_protocol= 1;
ps_protocol_enabled= ps_protocol;
sp_protocol_enabled= sp_protocol;
view_protocol_enabled= view_protocol;
cursor_protocol_enabled= cursor_protocol;
st_connection *con= connections;
init_connection_thd(con);
if (! (con->mysql= mysql_init(0)))
die("Failed in mysql_init()");
if (opt_connect_timeout)
mysql_options(con->mysql, MYSQL_OPT_CONNECT_TIMEOUT,
(void *) &opt_connect_timeout);
if (opt_compress)
mysql_options(con->mysql,MYSQL_OPT_COMPRESS,NullS);
mysql_options(con->mysql, MYSQL_OPT_LOCAL_INFILE, 0);
mysql_options(con->mysql, MYSQL_SET_CHARSET_NAME,
charset_info->csname);
if (opt_charsets_dir)
mysql_options(con->mysql, MYSQL_SET_CHARSET_DIR,
opt_charsets_dir);
if (opt_protocol)
mysql_options(con->mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
if (opt_plugin_dir && *opt_plugin_dir)
mysql_options(con->mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir);
#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY)
if (opt_use_ssl)
{
mysql_ssl_set(con->mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
opt_ssl_capath, opt_ssl_cipher);
mysql_options(con->mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl);
mysql_options(con->mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath);
#if MYSQL_VERSION_ID >= 50000
/* Turn on ssl_verify_server_cert only if host is "localhost" */
opt_ssl_verify_server_cert= opt_host && !strcmp(opt_host, "localhost");
mysql_options(con->mysql, MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
&opt_ssl_verify_server_cert);
#endif
}
#endif
#ifdef HAVE_SMEM
if (shared_memory_base_name)
mysql_options(con->mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
#endif
if (!(con->name = my_strdup("default", MYF(MY_WME))))
die("Out of memory");
mysql_options(con->mysql, MYSQL_OPT_NONBLOCK, 0);
safe_connect(con->mysql, con->name, opt_host, opt_user, opt_pass,
opt_db, opt_port, unix_sock);
/* Use all time until exit if no explicit 'start_timer' */
timer_start= timer_now();
/*
Initialize $mysql_errno with -1, so we can
- distinguish it from valid values ( >= 0 ) and
- detect if there was never a command sent to the server
*/
var_set_errno(-1);
set_current_connection(con);
if (opt_prologue)
{
open_file(opt_prologue);
}
verbose_msg("Start processing test commands from '%s' ...", cur_file->file_name);
while (!read_command(&command) && !abort_flag)
{
my_bool ok_to_do;
int current_line_inc = 1, processed = 0;
if (command->type == Q_UNKNOWN || command->type == Q_COMMENT_WITH_COMMAND)
get_command_type(command);
if (parsing_disabled &&
command->type != Q_ENABLE_PARSING &&
command->type != Q_DISABLE_PARSING)
{
/* Parsing is disabled, silently convert this line to a comment */
command->type= Q_COMMENT;
}
/* (Re-)set abort_on_error for this command */
command->abort_on_error= (command->expected_errors.count == 0 &&
abort_on_error);
/*
some commmands need to be executed or at least parsed unconditionally,
because they change the grammar.
*/
ok_to_do= cur_block->ok || command->type == Q_DELIMITER
|| command->type == Q_PERL;
/*
Some commands need to be "done" the first time if they may get
re-iterated over in a true context. This can only happen if there's
a while loop at some level above the current block.
*/
if (!ok_to_do)
{
if (command->type == Q_SOURCE ||
command->type == Q_ERROR ||
command->type == Q_WRITE_FILE ||
command->type == Q_APPEND_FILE)
{
for (struct st_block *stb= cur_block-1; stb >= block_stack; stb--)
{
if (stb->cmd == cmd_while)
{
ok_to_do= 1;
break;
}
}
}
}
if (ok_to_do)
{
command->last_argument= command->first_argument;
processed = 1;
/* Need to remember this for handle_error() */
curr_command= command;
switch (command->type) {
case Q_CONNECT:
do_connect(command);
break;
case Q_CONNECTION: select_connection(command); break;
case Q_DISCONNECT:
case Q_DIRTY_CLOSE:
do_close_connection(command); break;
case Q_ENABLE_PREPARE_WARNINGS: prepare_warnings_enabled=1; break;
case Q_DISABLE_PREPARE_WARNINGS: prepare_warnings_enabled=0; break;
case Q_ENABLE_QUERY_LOG:
set_property(command, P_QUERY, 0);
break;
case Q_DISABLE_QUERY_LOG:
set_property(command, P_QUERY, 1);
break;
case Q_ENABLE_ABORT_ON_ERROR:
set_property(command, P_ABORT, 1);
break;
case Q_DISABLE_ABORT_ON_ERROR:
set_property(command, P_ABORT, 0);
break;
case Q_ENABLE_RESULT_LOG:
set_property(command, P_RESULT, 0);
break;
case Q_DISABLE_RESULT_LOG:
set_property(command, P_RESULT, 1);
break;
case Q_ENABLE_CONNECT_LOG:
set_property(command, P_CONNECT, 0);
break;
case Q_DISABLE_CONNECT_LOG:
set_property(command, P_CONNECT, 1);
break;
case Q_ENABLE_WARNINGS:
set_property(command, P_WARN, 0);
break;
case Q_DISABLE_WARNINGS:
set_property(command, P_WARN, 1);
break;
case Q_ENABLE_INFO:
set_property(command, P_INFO, 0);
break;
case Q_DISABLE_INFO:
set_property(command, P_INFO, 1);
break;
case Q_ENABLE_METADATA:
set_property(command, P_META, 1);
break;
case Q_DISABLE_METADATA:
set_property(command, P_META, 0);
break;
case Q_ENABLE_COLUMN_NAMES:
disable_column_names= 0;
var_set_int("$ENABLED_COLUMN_NAMES", 0);
break;
case Q_DISABLE_COLUMN_NAMES:
disable_column_names= 1;
var_set_int("$ENABLED_COLUMN_NAMES", 1);
break;
case Q_SOURCE: do_source(command); break;
case Q_SLEEP: do_sleep(command, 0); break;
case Q_REAL_SLEEP: do_sleep(command, 1); break;
case Q_WAIT_FOR_SLAVE_TO_STOP: do_wait_for_slave_to_stop(command); break;
case Q_INC: do_modify_var(command, DO_INC); break;
case Q_DEC: do_modify_var(command, DO_DEC); break;
case Q_ECHO: do_echo(command); command_executed++; break;
case Q_SYSTEM: do_system(command); break;
case Q_REMOVE_FILE: do_remove_file(command); break;
case Q_REMOVE_FILES_WILDCARD: do_remove_files_wildcard(command); break;
case Q_MKDIR: do_mkdir(command); break;
case Q_RMDIR: do_rmdir(command); break;
case Q_LIST_FILES: do_list_files(command); break;
case Q_LIST_FILES_WRITE_FILE:
do_list_files_write_file_command(command, FALSE);
break;
case Q_LIST_FILES_APPEND_FILE:
do_list_files_write_file_command(command, TRUE);
break;
case Q_FILE_EXIST: do_file_exist(command); break;
case Q_WRITE_FILE: do_write_file(command); break;
case Q_APPEND_FILE: do_append_file(command); break;
case Q_DIFF_FILES: do_diff_files(command); break;
case Q_SEND_QUIT: do_send_quit(command); break;
case Q_CHANGE_USER: do_change_user(command); break;
case Q_CAT_FILE: do_cat_file(command); break;
case Q_COPY_FILE: do_copy_file(command); break;
case Q_MOVE_FILE: do_move_file(command); break;
case Q_CHMOD_FILE: do_chmod_file(command); break;
case Q_PERL: do_perl(command); break;
case Q_RESULT_FORMAT_VERSION: do_result_format_version(command); break;
case Q_DELIMITER:
do_delimiter(command);
break;
case Q_DISPLAY_VERTICAL_RESULTS:
display_result_vertically= TRUE;
break;
case Q_DISPLAY_HORIZONTAL_RESULTS:
display_result_vertically= FALSE;
break;
case Q_SORTED_RESULT:
/*
Turn on sorting of result set, will be reset after next
command
*/
display_result_sorted= TRUE;
break;
case Q_LOWERCASE:
/*
Turn on lowercasing of result, will be reset after next
command
*/
display_result_lower= TRUE;
break;
case Q_LET: do_let(command); break;
case Q_EVAL_RESULT:
die("'eval_result' command is deprecated");
case Q_EVAL:
case Q_EVALP:
case Q_QUERY_VERTICAL:
case Q_QUERY_HORIZONTAL:
if (command->query == command->query_buf)
{
/* Skip the first part of command, i.e query_xxx */
command->query= command->first_argument;
command->first_word_len= 0;
}
/* fall through */
case Q_QUERY:
case Q_REAP:
{
my_bool old_display_result_vertically= display_result_vertically;
/* Default is full query, both reap and send */
int flags= QUERY_REAP_FLAG | QUERY_SEND_FLAG;
if (q_send_flag)
{
/* Last command was an empty 'send' */
flags= QUERY_SEND_FLAG;
q_send_flag= 0;
}
else if (command->type == Q_REAP)
{
flags= QUERY_REAP_FLAG;
}
if (command->type == Q_EVALP)
flags |= QUERY_PRINT_ORIGINAL_FLAG;
/* Check for special property for this query */
display_result_vertically|= (command->type == Q_QUERY_VERTICAL);
if (save_file[0])
{
if (!(command->require_file= strdup_root(&require_file_root,
save_file)))
die("out of memory for require_file");
save_file[0]= 0;
}
run_query(cur_con, command, flags);
command_executed++;
command->last_argument= command->end;
/* Restore settings */
display_result_vertically= old_display_result_vertically;
break;
}
case Q_SEND:
case Q_SEND_EVAL:
if (!*command->first_argument)
{
/*
This is a send without arguments, it indicates that _next_ query
should be send only
*/
q_send_flag= 1;
break;
}
/* Remove "send" if this is first iteration */
if (command->query == command->query_buf)
command->query= command->first_argument;
/*
run_query() can execute a query partially, depending on the flags.
QUERY_SEND_FLAG flag without QUERY_REAP_FLAG tells it to just send
the query and read the result some time later when reap instruction
is given on this connection.
*/
run_query(cur_con, command, QUERY_SEND_FLAG);
command_executed++;
command->last_argument= command->end;
break;
case Q_REQUIRE:
do_get_file_name(command, save_file, sizeof(save_file));
break;
case Q_ERROR:
do_get_errcodes(command);
break;
case Q_REPLACE:
do_get_replace(command);
break;
case Q_REPLACE_REGEX:
do_get_replace_regex(command);
break;
case Q_REPLACE_COLUMN:
do_get_replace_column(command);
break;
case Q_SAVE_MASTER_POS: do_save_master_pos(); break;
case Q_SYNC_WITH_MASTER: do_sync_with_master(command); break;
case Q_SYNC_SLAVE_WITH_MASTER:
{
do_save_master_pos();
if (*command->first_argument)
select_connection(command);
else
select_connection_name("slave");
do_sync_with_master2(command, 0, "");
break;
}
case Q_COMMENT:
{
command->last_argument= command->end;
/* Don't output comments in v1 */
if (opt_result_format_version == 1)
break;
/* Don't output comments if query logging is off */
if (disable_query_log)
break;
/* Write comment's with two starting #'s to result file */
const char* p= command->query;
if (p && *p == '#' && *(p+1) == '#')
{
dynstr_append_mem(&ds_res, command->query, command->query_len);
dynstr_append(&ds_res, "\n");
}
break;
}
case Q_EMPTY_LINE:
/* Don't output newline in v1 */
if (opt_result_format_version == 1)
break;
/* Don't output newline if query logging is off */
if (disable_query_log)
break;
dynstr_append(&ds_res, "\n");
break;
case Q_PING:
handle_command_error(command, mysql_ping(cur_con->mysql), -1);
break;
case Q_SEND_SHUTDOWN:
handle_command_error(command,
mysql_shutdown(cur_con->mysql,
SHUTDOWN_DEFAULT), -1);
break;
case Q_SHUTDOWN_SERVER:
do_shutdown_server(command);
break;
case Q_EXEC:
do_exec(command);
command_executed++;
break;
case Q_START_TIMER:
/* Overwrite possible earlier start of timer */
timer_start= timer_now();
break;
case Q_END_TIMER:
/* End timer before ending mysqltest */
timer_output();
break;
case Q_CHARACTER_SET:
do_set_charset(command);
break;
case Q_DISABLE_PS_PROTOCOL:
set_property(command, P_PS, 0);
/* Close any open statements */
close_statements();
break;
case Q_ENABLE_PS_PROTOCOL:
set_property(command, P_PS, ps_protocol);
break;
case Q_DISABLE_NON_BLOCKING_API:
non_blocking_api_enabled= 0;
break;
case Q_ENABLE_NON_BLOCKING_API:
non_blocking_api_enabled= 1;
break;
case Q_DISABLE_RECONNECT:
set_reconnect(cur_con->mysql, 0);
break;
case Q_ENABLE_RECONNECT:
set_reconnect(cur_con->mysql, 1);
/* Close any open statements - no reconnect, need new prepare */
close_statements();
break;
case Q_DISABLE_PARSING:
if (parsing_disabled == 0)
parsing_disabled= 1;
else
report_or_die("Parsing is already disabled");
break;
case Q_ENABLE_PARSING:
/*
Ensure we don't get parsing_disabled < 0 as this would accidentally
disable code we don't want to have disabled
*/
if (parsing_disabled == 1)
parsing_disabled= 0;
else
report_or_die("Parsing is already enabled");
break;
case Q_DIE:
/* Abort test with error code and error message */
die("%s", command->first_argument);
break;
case Q_EXIT:
/* Stop processing any more commands */
abort_flag= 1;
break;
case Q_SKIP:
/* Eval the query, thus replacing all environment variables */
dynstr_set(&ds_res, 0);
do_eval(&ds_res, command->first_argument, command->end, FALSE);
abort_not_supported_test("%s",ds_res.str);
break;
case Q_RESULT:
die("result, deprecated command");
break;
default:
processed= 0;
break;
}
}
if (!processed)
{
current_line_inc= 0;
switch (command->type) {
case Q_WHILE: do_block(cmd_while, command); break;
case Q_IF: do_block(cmd_if, command); break;
case Q_END_BLOCK: do_done(command); break;
default: current_line_inc = 1; break;
}
}
else
check_eol_junk(command->last_argument);
if (command->type != Q_ERROR &&
command->type != Q_COMMENT)
{
/*
As soon as any non "error" command or comment has been executed,
the array with expected errors should be cleared
*/
memset(&saved_expected_errors, 0, sizeof(saved_expected_errors));
}
if (command_executed != last_command_executed || command->used_replace)
{
/*
As soon as any command has been executed,
the replace structures should be cleared
*/
free_all_replace();
/* Also reset "sorted_result" and "lowercase"*/
display_result_sorted= FALSE;
display_result_lower= FALSE;
}
last_command_executed= command_executed;
parser.current_line += current_line_inc;
if ( opt_mark_progress )
mark_progress(command, parser.current_line);
/* Write result from command to log file immediately */
log_file.write(&ds_res);
log_file.flush();
dynstr_set(&ds_res, 0);
}
log_file.close();
start_lineno= 0;
verbose_msg("... Done processing test commands.");
if (parsing_disabled)
die("Test ended with parsing disabled");
/*
The whole test has been executed _sucessfully_.
Time to compare result or save it to record file.
The entire output from test is in the log file
*/
if (log_file.bytes_written())
{
if (result_file_name)
{
/* A result file has been specified */
if (record)
{
/* Recording */
/* save a copy of the log to result file */
if (my_copy(log_file.file_name(), result_file_name, MYF(0)) != 0)
die("Failed to copy '%s' to '%s', errno: %d",
log_file.file_name(), result_file_name, errno);
}
else
{
/* Check that the output from test is equal to result file */
check_result();
}
}
}
else
{
/* Empty output is an error *unless* we also have an empty result file */
if (! result_file_name || record ||
compare_files (log_file.file_name(), result_file_name))
{
die("The test didn't produce any output");
}
else
{
empty_result= TRUE; /* Meaning empty was expected */
}
}
if (!command_executed && result_file_name && !empty_result)
die("No queries executed but non-empty result file found!");
verbose_msg("Test has succeeded!");
timer_output();
/* Yes, if we got this far the test has suceeded! Sakila smiles */
cleanup_and_exit(0);
return 0; /* Keep compiler happy too */
}
/*
A primitive timer that give results in milliseconds if the
--timer-file=<filename> is given. The timer result is written
to that file when the result is available. To not confuse
mysql-test-run with an old obsolete result, we remove the file
before executing any commands. The time we measure is
- If no explicit 'start_timer' or 'end_timer' is given in the
test case, the timer measure how long we execute in mysqltest.
- If only 'start_timer' is given we measure how long we execute
from that point until we terminate mysqltest.
- If only 'end_timer' is given we measure how long we execute
from that we enter mysqltest to the 'end_timer' is command is
executed.
- If both 'start_timer' and 'end_timer' are given we measure
the time between executing the two commands.
*/
void timer_output(void)
{
if (timer_file)
{
char buf[32], *end;
ulonglong timer= timer_now() - timer_start;
end= longlong10_to_str(timer, buf, 10);
str_to_file(timer_file,buf, (int) (end-buf));
/* Timer has been written to the file, don't use it anymore */
timer_file= 0;
}
}
ulonglong timer_now(void)
{
return my_interval_timer() / 1000000;
}
/*
Get arguments for replace_columns. The syntax is:
replace-column column_number to_string [column_number to_string ...]
Where each argument may be quoted with ' or "
A argument may also be a variable, in which case the value of the
variable is replaced.
*/
void do_get_replace_column(struct st_command *command)
{
char *from= command->first_argument;
char *buff, *start;
DBUG_ENTER("get_replace_columns");
free_replace_column();
if (!*from)
die("Missing argument in %s", command->query);
/* Allocate a buffer for results */
start= buff= (char*)my_malloc(strlen(from)+1,MYF(MY_WME | MY_FAE));
while (*from)
{
char *to;
uint column_number;
to= get_string(&buff, &from, command);
if (!(column_number= atoi(to)) || column_number > MAX_COLUMNS)
die("Wrong column number to replace_column in '%s'", command->query);
if (!*from)
die("Wrong number of arguments to replace_column in '%s'",
command->query);
to= get_string(&buff, &from, command);
my_free(replace_column[column_number-1]);
replace_column[column_number-1]= my_strdup(to, MYF(MY_WME | MY_FAE));
set_if_bigger(max_replace_column, column_number);
}
my_free(start);
command->last_argument= command->end;
DBUG_VOID_RETURN;
}
void free_replace_column()
{
uint i;
for (i=0 ; i < max_replace_column ; i++)
{
if (replace_column[i])
{
my_free(replace_column[i]);
replace_column[i]= 0;
}
}
max_replace_column= 0;
}
/****************************************************************************/
/*
Replace functions
*/
/* Definitions for replace result */
typedef struct st_pointer_array { /* when using array-strings */
TYPELIB typelib; /* Pointer to strings */
uchar *str; /* Strings is here */
uint8 *flag; /* Flag about each var. */
uint array_allocs,max_count,length,max_length;
} POINTER_ARRAY;
struct st_replace *init_replace(char * *from, char * *to, uint count,
char * word_end_chars);
int insert_pointer_name(reg1 POINTER_ARRAY *pa,char * name);
void free_pointer_array(POINTER_ARRAY *pa);
/*
Get arguments for replace. The syntax is:
replace from to [from to ...]
Where each argument may be quoted with ' or "
A argument may also be a variable, in which case the value of the
variable is replaced.
*/
void do_get_replace(struct st_command *command)
{
uint i;
char *from= command->first_argument;
char *buff, *start;
char word_end_chars[256], *pos;
POINTER_ARRAY to_array, from_array;
DBUG_ENTER("get_replace");
free_replace();
bzero((char*) &to_array,sizeof(to_array));
bzero((char*) &from_array,sizeof(from_array));
if (!*from)
die("Missing argument in %s", command->query);
start= buff= (char*)my_malloc(strlen(from)+1,MYF(MY_WME | MY_FAE));
while (*from)
{
char *to= buff;
to= get_string(&buff, &from, command);
if (!*from)
die("Wrong number of arguments to replace_result in '%s'",
command->query);
#ifdef __WIN__
fix_win_paths(to, from - to);
#endif
insert_pointer_name(&from_array,to);
to= get_string(&buff, &from, command);
insert_pointer_name(&to_array,to);
}
for (i= 1,pos= word_end_chars ; i < 256 ; i++)
if (my_isspace(charset_info,i))
*pos++= i;
*pos=0; /* End pointer */
if (!(glob_replace= init_replace((char**) from_array.typelib.type_names,
(char**) to_array.typelib.type_names,
(uint) from_array.typelib.count,
word_end_chars)))
die("Can't initialize replace from '%s'", command->query);
free_pointer_array(&from_array);
free_pointer_array(&to_array);
my_free(start);
command->last_argument= command->end;
DBUG_VOID_RETURN;
}
void free_replace()
{
DBUG_ENTER("free_replace");
my_free(glob_replace);
glob_replace= NULL;
DBUG_VOID_RETURN;
}
typedef struct st_replace {
int found;
struct st_replace *next[256];
} REPLACE;
typedef struct st_replace_found {
int found;
uint to_offset;
int from_offset;
char *replace_string;
} REPLACE_STRING;
void replace_strings_append(REPLACE *rep, DYNAMIC_STRING* ds,
const char *str,
int len __attribute__((unused)))
{
reg1 REPLACE *rep_pos;
reg2 REPLACE_STRING *rep_str;
const char *start, *from;
DBUG_ENTER("replace_strings_append");
start= from= str;
rep_pos=rep+1;
for (;;)
{
/* Loop through states */
DBUG_PRINT("info", ("Looping through states"));
while (!rep_pos->found)
rep_pos= rep_pos->next[(uchar) *from++];
/* Does this state contain a string to be replaced */
if (!(rep_str = ((REPLACE_STRING*) rep_pos))->replace_string)
{
/* No match found */
dynstr_append_mem(ds, start, from - start - 1);
DBUG_PRINT("exit", ("Found no more string to replace, appended: %s", start));
DBUG_VOID_RETURN;
}
/* Found a string that needs to be replaced */
DBUG_PRINT("info", ("found: %d, to_offset: %u, from_offset: %d, string: %s",
rep_str->found, rep_str->to_offset,
rep_str->from_offset, rep_str->replace_string));
/* Append part of original string before replace string */
dynstr_append_mem(ds, start, (from - rep_str->to_offset) - start);
/* Append replace string */
dynstr_append_mem(ds, rep_str->replace_string,
strlen(rep_str->replace_string));
if (!*(from-=rep_str->from_offset) && rep_pos->found != 2)
{
/* End of from string */
DBUG_PRINT("exit", ("Found end of from string"));
DBUG_VOID_RETURN;
}
DBUG_ASSERT(from <= str+len);
start= from;
rep_pos=rep;
}
}
/*
Regex replace functions
*/
/* Stores regex substitutions */
struct st_regex
{
char* pattern; /* Pattern to be replaced */
char* replace; /* String or expression to replace the pattern with */
int icase; /* true if the match is case insensitive */
};
int reg_replace(char** buf_p, int* buf_len_p, char *pattern, char *replace,
char *string, int icase);
bool parse_re_part(char *start_re, char *end_re,
char **p, char *end, char **buf)
{
if (*start_re != *end_re)
{
switch ((*start_re= *(*p)++)) {
case '(': *end_re= ')'; break;
case '[': *end_re= ']'; break;
case '{': *end_re= '}'; break;
case '<': *end_re= '>'; break;
default: *end_re= *start_re;
}
}
while (*p < end && **p != *end_re)
{
if ((*p)[0] == '\\' && *p + 1 < end && (*p)[1] == *end_re)
(*p)++;
*(*buf)++= *(*p)++;
}
*(*buf)++= 0;
(*p)++;
return *p > end;
}
/*
Initializes the regular substitution expression to be used in the
result output of test.
Returns: st_replace_regex struct with pairs of substitutions
*/
struct st_replace_regex* init_replace_regex(char* expr)
{
struct st_replace_regex* res;
char* buf,*expr_end;
char* p, start_re, end_re= 1;
char* buf_p;
uint expr_len= strlen(expr);
struct st_regex reg;
/* my_malloc() will die on fail with MY_FAE */
res=(struct st_replace_regex*)my_malloc(
sizeof(*res)+expr_len ,MYF(MY_FAE+MY_WME));
my_init_dynamic_array(&res->regex_arr,sizeof(struct st_regex), 128, 128, MYF(0));
buf= (char*)res + sizeof(*res);
expr_end= expr + expr_len;
p= expr;
buf_p= buf;
/* for each regexp substitution statement */
while (p < expr_end)
{
bzero(®,sizeof(reg));
/* find the start of the statement */
while (my_isspace(charset_info, *p) && p < expr_end)
p++;
if (p >= expr_end)
{
if (res->regex_arr.elements)
break;
else
goto err;
}
start_re= 0;
reg.pattern= buf_p;
if (parse_re_part(&start_re, &end_re, &p, expr_end, &buf_p))
goto err;
reg.replace= buf_p;
if (parse_re_part(&start_re, &end_re, &p, expr_end, &buf_p))
goto err;
/* Check if we should do matching case insensitive */
if (p < expr_end && *p == 'i')
{
p++;
reg.icase= 1;
}
/* done parsing the statement, now place it in regex_arr */
if (insert_dynamic(&res->regex_arr,(uchar*) ®))
die("Out of memory");
}
res->odd_buf_len= res->even_buf_len= 8192;
res->even_buf= (char*)my_malloc(res->even_buf_len,MYF(MY_WME+MY_FAE));
res->odd_buf= (char*)my_malloc(res->odd_buf_len,MYF(MY_WME+MY_FAE));
res->buf= res->even_buf;
return res;
err:
my_free(res);
die("Error parsing replace_regex \"%s\"", expr);
return 0;
}
/*
Execute all substitutions on val.
Returns: true if substituition was made, false otherwise
Side-effect: Sets r->buf to be the buffer with all substitutions done.
IN:
struct st_replace_regex* r
char* val
Out:
struct st_replace_regex* r
r->buf points at the resulting buffer
r->even_buf and r->odd_buf might have been reallocated
r->even_buf_len and r->odd_buf_len might have been changed
TODO: at some point figure out if there is a way to do everything
in one pass
*/
int multi_reg_replace(struct st_replace_regex* r,char* val)
{
uint i;
char* in_buf, *out_buf;
int* buf_len_p;
in_buf= val;
out_buf= r->even_buf;
buf_len_p= &r->even_buf_len;
r->buf= 0;
/* For each substitution, do the replace */
for (i= 0; i < r->regex_arr.elements; i++)
{
struct st_regex re;
char* save_out_buf= out_buf;
get_dynamic(&r->regex_arr,(uchar*)&re,i);
if (!reg_replace(&out_buf, buf_len_p, re.pattern, re.replace,
in_buf, re.icase))
{
/* if the buffer has been reallocated, make adjustements */
if (save_out_buf != out_buf)
{
if (save_out_buf == r->even_buf)
r->even_buf= out_buf;
else
r->odd_buf= out_buf;
}
r->buf= out_buf;
if (in_buf == val)
in_buf= r->odd_buf;
swap_variables(char*,in_buf,out_buf);
buf_len_p= (out_buf == r->even_buf) ? &r->even_buf_len :
&r->odd_buf_len;
}
}
return (r->buf == 0);
}
/*
Parse the regular expression to be used in all result files
from now on.
The syntax is --replace_regex /from/to/i /from/to/i ...
i means case-insensitive match. If omitted, the match is
case-sensitive
*/
void do_get_replace_regex(struct st_command *command)
{
char *expr= command->first_argument;
free_replace_regex();
/* Allow variable for the *entire* list of replacements */
if (*expr == '$')
{
VAR *val= var_get(expr, NULL, 0, 1);
expr= val ? val->str_val : NULL;
}
if (expr && *expr && !(glob_replace_regex=init_replace_regex(expr)))
die("Could not init replace_regex");
command->last_argument= command->end;
}
void free_replace_regex()
{
if (glob_replace_regex)
{
delete_dynamic(&glob_replace_regex->regex_arr);
my_free(glob_replace_regex->even_buf);
my_free(glob_replace_regex->odd_buf);
my_free(glob_replace_regex);
glob_replace_regex=0;
}
}
/*
auxiluary macro used by reg_replace
makes sure the result buffer has sufficient length
*/
#define SECURE_REG_BUF if (buf_len < need_buf_len) \
{ \
int off= res_p - buf; \
buf= (char*)my_realloc(buf,need_buf_len,MYF(MY_WME+MY_FAE)); \
res_p= buf + off; \
buf_len= need_buf_len; \
} \
\
/*
Performs a regex substitution
IN:
buf_p - result buffer pointer. Will change if reallocated
buf_len_p - result buffer length. Will change if the buffer is reallocated
pattern - regexp pattern to match
replace - replacement expression
string - the string to perform substituions in
icase - flag, if set to 1 the match is case insensitive
*/
int reg_replace(char** buf_p, int* buf_len_p, char *pattern,
char *replace, char *string, int icase)
{
regex_t r;
regmatch_t *subs;
char *replace_end;
char *buf= *buf_p;
int len;
int buf_len, need_buf_len;
int cflags= REG_EXTENDED | REG_DOTALL;
int err_code;
char *res_p,*str_p,*str_end;
buf_len= *buf_len_p;
len= strlen(string);
str_end= string + len;
/* start with a buffer of a reasonable size that hopefully will not
need to be reallocated
*/
need_buf_len= len * 2 + 1;
res_p= buf;
SECURE_REG_BUF
if (icase)
cflags|= REG_ICASE;
if ((err_code= regcomp(&r,pattern,cflags)))
{
check_regerr(&r,err_code);
return 1;
}
subs= (regmatch_t*)my_malloc(sizeof(regmatch_t) * (r.re_nsub+1),
MYF(MY_WME+MY_FAE));
*res_p= 0;
str_p= string;
replace_end= replace + strlen(replace);
/* for each pattern match instance perform a replacement */
while (!err_code)
{
/* find the match */
err_code= regexec(&r,str_p, r.re_nsub+1, subs,
(str_p == string) ? REG_NOTBOL : 0);
/* if regular expression error (eg. bad syntax, or out of memory) */
if (err_code && err_code != REG_NOMATCH)
{
check_regerr(&r,err_code);
regfree(&r);
return 1;
}
/* if match found */
if (!err_code)
{
char* expr_p= replace;
int c;
/*
we need at least what we have so far in the buffer + the part
before this match
*/
need_buf_len= (res_p - buf) + (int) subs[0].rm_so;
/* on this pass, calculate the memory for the result buffer */
while (expr_p < replace_end)
{
int back_ref_num= -1;
c= *expr_p;
if (c == '\\' && expr_p + 1 < replace_end)
{
back_ref_num= (int) (expr_p[1] - '0');
}
/* found a valid back_ref (eg. \1)*/
if (back_ref_num >= 0 && back_ref_num <= (int)r.re_nsub)
{
regoff_t start_off, end_off;
if ((start_off=subs[back_ref_num].rm_so) > -1 &&
(end_off=subs[back_ref_num].rm_eo) > -1)
{
need_buf_len += (int) (end_off - start_off);
}
expr_p += 2;
}
else
{
expr_p++;
need_buf_len++;
}
}
need_buf_len++;
/*
now that we know the size of the buffer,
make sure it is big enough
*/
SECURE_REG_BUF
/* copy the pre-match part */
if (subs[0].rm_so)
{
memcpy(res_p, str_p, (size_t) subs[0].rm_so);
res_p+= subs[0].rm_so;
}
expr_p= replace;
/* copy the match and expand back_refs */
while (expr_p < replace_end)
{
int back_ref_num= -1;
c= *expr_p;
if (c == '\\' && expr_p + 1 < replace_end)
{
back_ref_num= expr_p[1] - '0';
}
if (back_ref_num >= 0 && back_ref_num <= (int)r.re_nsub)
{
regoff_t start_off, end_off;
if ((start_off=subs[back_ref_num].rm_so) > -1 &&
(end_off=subs[back_ref_num].rm_eo) > -1)
{
int block_len= (int) (end_off - start_off);
memcpy(res_p,str_p + start_off, block_len);
res_p += block_len;
}
expr_p += 2;
}
else
{
*res_p++ = *expr_p++;
}
}
/* handle the post-match part */
if (subs[0].rm_so == subs[0].rm_eo)
{
if (str_p + subs[0].rm_so >= str_end)
break;
str_p += subs[0].rm_eo ;
*res_p++ = *str_p++;
}
else
{
str_p += subs[0].rm_eo;
}
}
else /* no match this time, just copy the string as is */
{
int left_in_str= str_end-str_p;
need_buf_len= (res_p-buf) + left_in_str;
SECURE_REG_BUF
memcpy(res_p,str_p,left_in_str);
res_p += left_in_str;
str_p= str_end;
}
}
my_free(subs);
regfree(&r);
*res_p= 0;
*buf_p= buf;
*buf_len_p= buf_len;
return 0;
}
#ifndef WORD_BIT
#define WORD_BIT (8*sizeof(uint))
#endif
#define SET_MALLOC_HUNC 64
#define LAST_CHAR_CODE 259
typedef struct st_rep_set {
uint *bits; /* Pointer to used sets */
short next[LAST_CHAR_CODE]; /* Pointer to next sets */
uint found_len; /* Best match to date */
int found_offset;
uint table_offset;
uint size_of_bits; /* For convinience */
} REP_SET;
typedef struct st_rep_sets {
uint count; /* Number of sets */
uint extra; /* Extra sets in buffer */
uint invisible; /* Sets not chown */
uint size_of_bits;
REP_SET *set,*set_buffer;
uint *bit_buffer;
} REP_SETS;
typedef struct st_found_set {
uint table_offset;
int found_offset;
} FOUND_SET;
typedef struct st_follow {
int chr;
uint table_offset;
uint len;
} FOLLOWS;
int init_sets(REP_SETS *sets,uint states);
REP_SET *make_new_set(REP_SETS *sets);
void make_sets_invisible(REP_SETS *sets);
void free_last_set(REP_SETS *sets);
void free_sets(REP_SETS *sets);
void internal_set_bit(REP_SET *set, uint bit);
void internal_clear_bit(REP_SET *set, uint bit);
void or_bits(REP_SET *to,REP_SET *from);
void copy_bits(REP_SET *to,REP_SET *from);
int cmp_bits(REP_SET *set1,REP_SET *set2);
int get_next_bit(REP_SET *set,uint lastpos);
int find_set(REP_SETS *sets,REP_SET *find);
int find_found(FOUND_SET *found_set,uint table_offset,
int found_offset);
uint start_at_word(char * pos);
uint end_of_word(char * pos);
static uint found_sets=0;
uint replace_len(char * str)
{
uint len=0;
while (*str)
{
str++;
len++;
}
return len;
}
/* Init a replace structure for further calls */
REPLACE *init_replace(char * *from, char * *to,uint count,
char * word_end_chars)
{
static const int SPACE_CHAR= 256;
static const int END_OF_LINE= 258;
uint i,j,states,set_nr,len,result_len,max_length,found_end,bits_set,bit_nr;
int used_sets,chr,default_state;
char used_chars[LAST_CHAR_CODE],is_word_end[256];
char * pos, *to_pos, **to_array;
REP_SETS sets;
REP_SET *set,*start_states,*word_states,*new_set;
FOLLOWS *follow,*follow_ptr;
REPLACE *replace;
FOUND_SET *found_set;
REPLACE_STRING *rep_str;
DBUG_ENTER("init_replace");
/* Count number of states */
for (i=result_len=max_length=0 , states=2 ; i < count ; i++)
{
len=replace_len(from[i]);
if (!len)
{
errno=EINVAL;
DBUG_RETURN(0);
}
states+=len+1;
result_len+=(uint) strlen(to[i])+1;
if (len > max_length)
max_length=len;
}
bzero((char*) is_word_end,sizeof(is_word_end));
for (i=0 ; word_end_chars[i] ; i++)
is_word_end[(uchar) word_end_chars[i]]=1;
if (init_sets(&sets,states))
DBUG_RETURN(0);
found_sets=0;
if (!(found_set= (FOUND_SET*) my_malloc(sizeof(FOUND_SET)*max_length*count,
MYF(MY_WME))))
{
free_sets(&sets);
DBUG_RETURN(0);
}
(void) make_new_set(&sets); /* Set starting set */
make_sets_invisible(&sets); /* Hide previus sets */
used_sets=-1;
word_states=make_new_set(&sets); /* Start of new word */
start_states=make_new_set(&sets); /* This is first state */
if (!(follow=(FOLLOWS*) my_malloc((states+2)*sizeof(FOLLOWS),MYF(MY_WME))))
{
free_sets(&sets);
my_free(found_set);
DBUG_RETURN(0);
}
/* Init follow_ptr[] */
for (i=0, states=1, follow_ptr=follow+1 ; i < count ; i++)
{
if (from[i][0] == '\\' && from[i][1] == '^')
{
internal_set_bit(start_states,states+1);
if (!from[i][2])
{
start_states->table_offset=i;
start_states->found_offset=1;
}
}
else if (from[i][0] == '\\' && from[i][1] == '$')
{
internal_set_bit(start_states,states);
internal_set_bit(word_states,states);
if (!from[i][2] && start_states->table_offset == (uint) ~0)
{
start_states->table_offset=i;
start_states->found_offset=0;
}
}
else
{
internal_set_bit(word_states,states);
if (from[i][0] == '\\' && (from[i][1] == 'b' && from[i][2]))
internal_set_bit(start_states,states+1);
else
internal_set_bit(start_states,states);
}
for (pos=from[i], len=0; *pos ; pos++)
{
follow_ptr->chr= (uchar) *pos;
follow_ptr->table_offset=i;
follow_ptr->len= ++len;
follow_ptr++;
}
follow_ptr->chr=0;
follow_ptr->table_offset=i;
follow_ptr->len=len;
follow_ptr++;
states+=(uint) len+1;
}
for (set_nr=0,pos=0 ; set_nr < sets.count ; set_nr++)
{
set=sets.set+set_nr;
default_state= 0; /* Start from beginning */
/* If end of found-string not found or start-set with current set */
for (i= (uint) ~0; (i=get_next_bit(set,i)) ;)
{
if (!follow[i].chr)
{
if (! default_state)
default_state= find_found(found_set,set->table_offset,
set->found_offset+1);
}
}
copy_bits(sets.set+used_sets,set); /* Save set for changes */
if (!default_state)
or_bits(sets.set+used_sets,sets.set); /* Can restart from start */
/* Find all chars that follows current sets */
bzero((char*) used_chars,sizeof(used_chars));
for (i= (uint) ~0; (i=get_next_bit(sets.set+used_sets,i)) ;)
{
used_chars[follow[i].chr]=1;
if ((follow[i].chr == SPACE_CHAR && !follow[i+1].chr &&
follow[i].len > 1) || follow[i].chr == END_OF_LINE)
used_chars[0]=1;
}
/* Mark word_chars used if \b is in state */
if (used_chars[SPACE_CHAR])
for (pos= word_end_chars ; *pos ; pos++)
used_chars[(int) (uchar) *pos] = 1;
/* Handle other used characters */
for (chr= 0 ; chr < 256 ; chr++)
{
if (! used_chars[chr])
set->next[chr]= chr ? default_state : -1;
else
{
new_set=make_new_set(&sets);
set=sets.set+set_nr; /* if realloc */
new_set->table_offset=set->table_offset;
new_set->found_len=set->found_len;
new_set->found_offset=set->found_offset+1;
found_end=0;
for (i= (uint) ~0 ; (i=get_next_bit(sets.set+used_sets,i)) ; )
{
if (!follow[i].chr || follow[i].chr == chr ||
(follow[i].chr == SPACE_CHAR &&
(is_word_end[chr] ||
(!chr && follow[i].len > 1 && ! follow[i+1].chr))) ||
(follow[i].chr == END_OF_LINE && ! chr))
{
if ((! chr || (follow[i].chr && !follow[i+1].chr)) &&
follow[i].len > found_end)
found_end=follow[i].len;
if (chr && follow[i].chr)
internal_set_bit(new_set,i+1); /* To next set */
else
internal_set_bit(new_set,i);
}
}
if (found_end)
{
new_set->found_len=0; /* Set for testing if first */
bits_set=0;
for (i= (uint) ~0; (i=get_next_bit(new_set,i)) ;)
{
if ((follow[i].chr == SPACE_CHAR ||
follow[i].chr == END_OF_LINE) && ! chr)
bit_nr=i+1;
else
bit_nr=i;
if (follow[bit_nr-1].len < found_end ||
(new_set->found_len &&
(chr == 0 || !follow[bit_nr].chr)))
internal_clear_bit(new_set,i);
else
{
if (chr == 0 || !follow[bit_nr].chr)
{ /* best match */
new_set->table_offset=follow[bit_nr].table_offset;
if (chr || (follow[i].chr == SPACE_CHAR ||
follow[i].chr == END_OF_LINE))
new_set->found_offset=found_end; /* New match */
new_set->found_len=found_end;
}
bits_set++;
}
}
if (bits_set == 1)
{
set->next[chr] = find_found(found_set,
new_set->table_offset,
new_set->found_offset);
free_last_set(&sets);
}
else
set->next[chr] = find_set(&sets,new_set);
}
else
set->next[chr] = find_set(&sets,new_set);
}
}
}
/* Alloc replace structure for the replace-state-machine */
if ((replace=(REPLACE*) my_malloc(sizeof(REPLACE)*(sets.count)+
sizeof(REPLACE_STRING)*(found_sets+1)+
sizeof(char *)*count+result_len,
MYF(MY_WME | MY_ZEROFILL))))
{
rep_str=(REPLACE_STRING*) (replace+sets.count);
to_array= (char **) (rep_str+found_sets+1);
to_pos=(char *) (to_array+count);
for (i=0 ; i < count ; i++)
{
to_array[i]=to_pos;
to_pos=strmov(to_pos,to[i])+1;
}
rep_str[0].found=1;
rep_str[0].replace_string=0;
for (i=1 ; i <= found_sets ; i++)
{
pos=from[found_set[i-1].table_offset];
rep_str[i].found= !memcmp(pos, "\\^", 3) ? 2 : 1;
rep_str[i].replace_string=to_array[found_set[i-1].table_offset];
rep_str[i].to_offset=found_set[i-1].found_offset-start_at_word(pos);
rep_str[i].from_offset=found_set[i-1].found_offset-replace_len(pos)+
end_of_word(pos);
}
for (i=0 ; i < sets.count ; i++)
{
for (j=0 ; j < 256 ; j++)
if (sets.set[i].next[j] >= 0)
replace[i].next[j]=replace+sets.set[i].next[j];
else
replace[i].next[j]=(REPLACE*) (rep_str+(-sets.set[i].next[j]-1));
}
}
my_free(follow);
free_sets(&sets);
my_free(found_set);
DBUG_PRINT("exit",("Replace table has %d states",sets.count));
DBUG_RETURN(replace);
}
int init_sets(REP_SETS *sets,uint states)
{
bzero((char*) sets,sizeof(*sets));
sets->size_of_bits=((states+7)/8);
if (!(sets->set_buffer=(REP_SET*) my_malloc(sizeof(REP_SET)*SET_MALLOC_HUNC,
MYF(MY_WME))))
return 1;
if (!(sets->bit_buffer=(uint*) my_malloc(sizeof(uint)*sets->size_of_bits*
SET_MALLOC_HUNC,MYF(MY_WME))))
{
my_free(sets->set);
return 1;
}
return 0;
}
/* Make help sets invisible for nicer codeing */
void make_sets_invisible(REP_SETS *sets)
{
sets->invisible=sets->count;
sets->set+=sets->count;
sets->count=0;
}
REP_SET *make_new_set(REP_SETS *sets)
{
uint i,count,*bit_buffer;
REP_SET *set;
if (sets->extra)
{
sets->extra--;
set=sets->set+ sets->count++;
bzero((char*) set->bits,sizeof(uint)*sets->size_of_bits);
bzero((char*) &set->next[0],sizeof(set->next[0])*LAST_CHAR_CODE);
set->found_offset=0;
set->found_len=0;
set->table_offset= (uint) ~0;
set->size_of_bits=sets->size_of_bits;
return set;
}
count=sets->count+sets->invisible+SET_MALLOC_HUNC;
if (!(set=(REP_SET*) my_realloc((uchar*) sets->set_buffer,
sizeof(REP_SET)*count,
MYF(MY_WME))))
return 0;
sets->set_buffer=set;
sets->set=set+sets->invisible;
if (!(bit_buffer=(uint*) my_realloc((uchar*) sets->bit_buffer,
(sizeof(uint)*sets->size_of_bits)*count,
MYF(MY_WME))))
return 0;
sets->bit_buffer=bit_buffer;
for (i=0 ; i < count ; i++)
{
sets->set_buffer[i].bits=bit_buffer;
bit_buffer+=sets->size_of_bits;
}
sets->extra=SET_MALLOC_HUNC;
return make_new_set(sets);
}
void free_last_set(REP_SETS *sets)
{
sets->count--;
sets->extra++;
return;
}
void free_sets(REP_SETS *sets)
{
my_free(sets->set_buffer);
my_free(sets->bit_buffer);
return;
}
void internal_set_bit(REP_SET *set, uint bit)
{
set->bits[bit / WORD_BIT] |= 1 << (bit % WORD_BIT);
return;
}
void internal_clear_bit(REP_SET *set, uint bit)
{
set->bits[bit / WORD_BIT] &= ~ (1 << (bit % WORD_BIT));
return;
}
void or_bits(REP_SET *to,REP_SET *from)
{
reg1 uint i;
for (i=0 ; i < to->size_of_bits ; i++)
to->bits[i]|=from->bits[i];
return;
}
void copy_bits(REP_SET *to,REP_SET *from)
{
memcpy((uchar*) to->bits,(uchar*) from->bits,
(size_t) (sizeof(uint) * to->size_of_bits));
}
int cmp_bits(REP_SET *set1,REP_SET *set2)
{
return memcmp(set1->bits, set2->bits,
sizeof(uint) * set1->size_of_bits);
}
/* Get next set bit from set. */
int get_next_bit(REP_SET *set,uint lastpos)
{
uint pos,*start,*end,bits;
start=set->bits+ ((lastpos+1) / WORD_BIT);
end=set->bits + set->size_of_bits;
bits=start[0] & ~((1 << ((lastpos+1) % WORD_BIT)) -1);
while (! bits && ++start < end)
bits=start[0];
if (!bits)
return 0;
pos=(uint) (start-set->bits)*WORD_BIT;
while (! (bits & 1))
{
bits>>=1;
pos++;
}
return pos;
}
/* find if there is a same set in sets. If there is, use it and
free given set, else put in given set in sets and return its
position */
int find_set(REP_SETS *sets,REP_SET *find)
{
uint i;
for (i=0 ; i < sets->count-1 ; i++)
{
if (!cmp_bits(sets->set+i,find))
{
free_last_set(sets);
return i;
}
}
return i; /* return new position */
}
/* find if there is a found_set with same table_offset & found_offset
If there is return offset to it, else add new offset and return pos.
Pos returned is -offset-2 in found_set_structure because it is
saved in set->next and set->next[] >= 0 points to next set and
set->next[] == -1 is reserved for end without replaces.
*/
int find_found(FOUND_SET *found_set,uint table_offset, int found_offset)
{
int i;
for (i=0 ; (uint) i < found_sets ; i++)
if (found_set[i].table_offset == table_offset &&
found_set[i].found_offset == found_offset)
return -i-2;
found_set[i].table_offset=table_offset;
found_set[i].found_offset=found_offset;
found_sets++;
return -i-2; /* return new position */
}
/* Return 1 if regexp starts with \b or ends with \b*/
uint start_at_word(char * pos)
{
return (((!memcmp(pos, "\\b",2) && pos[2]) ||
!memcmp(pos, "\\^", 2)) ? 1 : 0);
}
uint end_of_word(char * pos)
{
char * end=strend(pos);
return ((end > pos+2 && !memcmp(end-2, "\\b", 2)) ||
(end >= pos+2 && !memcmp(end-2, "\\$",2))) ? 1 : 0;
}
/****************************************************************************
* Handle replacement of strings
****************************************************************************/
#define PC_MALLOC 256 /* Bytes for pointers */
#define PS_MALLOC 512 /* Bytes for data */
int insert_pointer_name(reg1 POINTER_ARRAY *pa,char * name)
{
uint i,length,old_count;
uchar *new_pos;
const char **new_array;
DBUG_ENTER("insert_pointer_name");
if (! pa->typelib.count)
{
if (!(pa->typelib.type_names=(const char **)
my_malloc(((PC_MALLOC-MALLOC_OVERHEAD)/
(sizeof(char *)+sizeof(*pa->flag))*
(sizeof(char *)+sizeof(*pa->flag))),MYF(MY_WME))))
DBUG_RETURN(-1);
if (!(pa->str= (uchar*) my_malloc((uint) (PS_MALLOC-MALLOC_OVERHEAD),
MYF(MY_WME))))
{
my_free(pa->typelib.type_names);
DBUG_RETURN (-1);
}
pa->max_count=(PC_MALLOC-MALLOC_OVERHEAD)/(sizeof(uchar*)+
sizeof(*pa->flag));
pa->flag= (uint8*) (pa->typelib.type_names+pa->max_count);
pa->length=0;
pa->max_length=PS_MALLOC-MALLOC_OVERHEAD;
pa->array_allocs=1;
}
length=(uint) strlen(name)+1;
if (pa->length+length >= pa->max_length)
{
if (!(new_pos= (uchar*) my_realloc((uchar*) pa->str,
(uint) (pa->length+length+PS_MALLOC),
MYF(MY_WME))))
DBUG_RETURN(1);
if (new_pos != pa->str)
{
my_ptrdiff_t diff=PTR_BYTE_DIFF(new_pos,pa->str);
for (i=0 ; i < pa->typelib.count ; i++)
pa->typelib.type_names[i]= ADD_TO_PTR(pa->typelib.type_names[i],diff,
char*);
pa->str=new_pos;
}
pa->max_length= pa->length+length+PS_MALLOC;
}
if (pa->typelib.count >= pa->max_count-1)
{
int len;
pa->array_allocs++;
len=(PC_MALLOC*pa->array_allocs - MALLOC_OVERHEAD);
if (!(new_array=(const char **) my_realloc((uchar*) pa->typelib.type_names,
(uint) len/
(sizeof(uchar*)+sizeof(*pa->flag))*
(sizeof(uchar*)+sizeof(*pa->flag)),
MYF(MY_WME))))
DBUG_RETURN(1);
pa->typelib.type_names=new_array;
old_count=pa->max_count;
pa->max_count=len/(sizeof(uchar*) + sizeof(*pa->flag));
pa->flag= (uint8*) (pa->typelib.type_names+pa->max_count);
memcpy((uchar*) pa->flag,(char *) (pa->typelib.type_names+old_count),
old_count*sizeof(*pa->flag));
}
pa->flag[pa->typelib.count]=0; /* Reset flag */
pa->typelib.type_names[pa->typelib.count++]= (char*) pa->str+pa->length;
pa->typelib.type_names[pa->typelib.count]= NullS; /* Put end-mark */
(void) strmov((char*) pa->str+pa->length,name);
pa->length+=length;
DBUG_RETURN(0);
} /* insert_pointer_name */
/* free pointer array */
void free_pointer_array(POINTER_ARRAY *pa)
{
if (pa->typelib.count)
{
pa->typelib.count=0;
my_free(pa->typelib.type_names);
pa->typelib.type_names=0;
my_free(pa->str);
}
} /* free_pointer_array */
/* Functions that uses replace and replace_regex */
/* Append the string to ds, with optional replace */
void replace_dynstr_append_mem(DYNAMIC_STRING *ds,
const char *val, int len)
{
char lower[512];
#ifdef __WIN__
fix_win_paths(val, len);
#endif
if (display_result_lower)
{
/* Convert to lower case, and do this first */
char *c= lower;
for (const char *v= val; *v; v++)
*c++= my_tolower(charset_info, *v);
*c= '\0';
/* Copy from this buffer instead */
val= lower;
}
if (glob_replace_regex)
{
/* Regex replace */
if (!multi_reg_replace(glob_replace_regex, (char*)val))
{
val= glob_replace_regex->buf;
len= strlen(val);
}
}
if (glob_replace)
{
/* Normal replace */
replace_strings_append(glob_replace, ds, val, len);
}
else
dynstr_append_mem(ds, val, len);
}
/* Append zero-terminated string to ds, with optional replace */
void replace_dynstr_append(DYNAMIC_STRING *ds, const char *val)
{
replace_dynstr_append_mem(ds, val, strlen(val));
}
/* Append uint to ds, with optional replace */
void replace_dynstr_append_uint(DYNAMIC_STRING *ds, uint val)
{
char buff[22]; /* This should be enough for any int */
char *end= longlong10_to_str(val, buff, 10);
replace_dynstr_append_mem(ds, buff, end - buff);
}
/*
Build a list of pointer to each line in ds_input, sort
the list and use the sorted list to append the strings
sorted to the output ds
SYNOPSIS
dynstr_append_sorted()
ds string where the sorted output will be appended
ds_input string to be sorted
keep_header If header should not be sorted
*/
static int comp_lines(const char **a, const char **b)
{
return (strcmp(*a,*b));
}
void dynstr_append_sorted(DYNAMIC_STRING* ds, DYNAMIC_STRING *ds_input,
bool keep_header)
{
unsigned i;
char *start= ds_input->str;
DYNAMIC_ARRAY lines;
DBUG_ENTER("dynstr_append_sorted");
if (!*start)
DBUG_VOID_RETURN; /* No input */
my_init_dynamic_array(&lines, sizeof(const char*), 32, 32, MYF(0));
if (keep_header)
{
/* First line is result header, skip past it */
while (*start && *start != '\n')
start++;
start++; /* Skip past \n */
dynstr_append_mem(ds, ds_input->str, start - ds_input->str);
}
/* Insert line(s) in array */
while (*start)
{
char* line_end= (char*)start;
/* Find end of line */
while (*line_end && *line_end != '\n')
line_end++;
*line_end= 0;
/* Insert pointer to the line in array */
if (insert_dynamic(&lines, (uchar*) &start))
die("Out of memory inserting lines to sort");
start= line_end+1;
}
/* Sort array */
qsort(lines.buffer, lines.elements,
sizeof(char**), (qsort_cmp)comp_lines);
/* Create new result */
for (i= 0; i < lines.elements ; i++)
{
const char **line= dynamic_element(&lines, i, const char**);
dynstr_append(ds, *line);
dynstr_append(ds, "\n");
}
delete_dynamic(&lines);
DBUG_VOID_RETURN;
}
#ifndef HAVE_SETENV
static int setenv(const char *name, const char *value, int overwrite)
{
size_t buflen= strlen(name) + strlen(value) + 2;
char *envvar= (char *)malloc(buflen);
if(!envvar)
return ENOMEM;
strcpy(envvar, name);
strcat(envvar, "=");
strcat(envvar, value);
putenv(envvar);
return 0;
}
#endif
/*
for the purpose of testing (see dialog.test)
we replace default mysql_authentication_dialog_ask function with the one,
that always reads from stdin with explicit echo.
*/
MYSQL_PLUGIN_EXPORT
char *mysql_authentication_dialog_ask(MYSQL *mysql, int type,
const char *prompt,
char *buf, int buf_len)
{
char *s=buf;
fputs(prompt, stdout);
fputs(" ", stdout);
if (!fgets(buf, buf_len-1, stdin))
buf[0]= 0;
else if (buf[0] && (s= strend(buf))[-1] == '\n')
s[-1]= 0;
for (s= buf; *s; s++)
fputc(type == 2 ? '*' : *s, stdout);
fputc('\n', stdout);
return buf;
}
| gpl-2.0 |
biergaizi/PhilNa-NG | app/yinheli_addrss.php | 1076 | <?php
function yinheli_addrss($content){
$options = get_option('philna_options');
if($options['rss_show_comment_state']):
global $id;
$comment_num = get_comments_number($id);
if($comment_num==0):
$rss_comment_tip="Here is no comments yet by the time your rss reader get this, Do you want to be the first commentor? Hurry up ";
elseif($comment_num>=1 && $comment_num<30):
$rss_comment_tip="By the time your rss reader get this post here is <strong> ".$comment_num." </strong>comments ,Welcome you come to leave your opinion !";
elseif($comment_num>=30):
$rss_comment_tip="By the time your rss reader get this post here is<strong> ".$comment_num." </strong>comments,Heated discussion,Why not to come to check it out ?!";
endif;
endif;
if($options['rss_copyright_show']){
$rss_copyright =$options['rss_copyright'];
$this_post_info="\n<p>This article addresses:".'<a href="'.get_permalink().'">'.get_permalink().'</a></p>';
}
if(is_feed())
$content =$content.$this_post_info.$rss_comment_tip.$rss_copyright;
return $content;
}
add_filter('the_content', 'yinheli_addrss');
?> | gpl-2.0 |
ineiti/cothorities | byzcoin/bcadmin/clicontracts/name.go | 6760 | package clicontracts
import (
"encoding/hex"
"fmt"
"github.com/urfave/cli"
"go.dedis.ch/cothority/v3"
"go.dedis.ch/cothority/v3/byzcoin"
"go.dedis.ch/cothority/v3/byzcoin/bcadmin/lib"
"go.dedis.ch/cothority/v3/darc"
"go.dedis.ch/onet/v3/log"
"go.dedis.ch/onet/v3/network"
"go.dedis.ch/protobuf"
"golang.org/x/xerrors"
)
// NameSpawn is used to spawn the name contract (can only be done once)
func NameSpawn(c *cli.Context) error {
bcArg := c.String("bc")
if bcArg == "" {
return xerrors.New("--bc flag is required")
}
cfg, cl, err := lib.LoadConfig(bcArg)
if err != nil {
return err
}
gDarc, err := cl.GetGenDarc()
if err != nil {
return xerrors.Errorf("failed to get genesis darc: %v", err)
}
var signer *darc.Signer
sstr := c.String("sign")
if sstr == "" {
signer, err = lib.LoadKey(cfg.AdminIdentity)
} else {
signer, err = lib.LoadKeyFromString(sstr)
}
if err != nil {
return err
}
counters, err := cl.GetSignerCounters(signer.Identity().String())
if err != nil {
return fmt.Errorf("couldn't get signer counters: %v", err)
}
ctx, err := cl.CreateTransaction(byzcoin.Instruction{
InstanceID: byzcoin.NewInstanceID(gDarc.GetBaseID()),
Spawn: &byzcoin.Spawn{
ContractID: byzcoin.ContractNamingID,
},
SignerCounter: []uint64{counters.Counters[0] + 1},
})
if err != nil {
return fmt.Errorf("couldn't create transaction: %v", err)
}
err = ctx.FillSignersAndSignWith(*signer)
if err != nil {
return xerrors.Errorf("failed to fill signer: %v", err)
}
_, err = cl.AddTransactionAndWait(ctx, 10)
if err != nil {
return xerrors.Errorf("failed to add transaction and wait: %v", err)
}
instID := ctx.Instructions[0].DeriveID("").Slice()
log.Infof("Spawned a new namne contract. Its instance id is:\n%x", instID)
return lib.WaitPropagation(c, cl)
}
// NameInvokeAdd is used to add a new name resolver
func NameInvokeAdd(c *cli.Context) error {
bcArg := c.String("bc")
if bcArg == "" {
return xerrors.New("--bc flag is required")
}
cfg, cl, err := lib.LoadConfig(bcArg)
if err != nil {
return err
}
var signer *darc.Signer
sstr := c.String("sign")
if sstr == "" {
signer, err = lib.LoadKey(cfg.AdminIdentity)
} else {
signer, err = lib.LoadKeyFromString(sstr)
}
if err != nil {
return err
}
counters, err := cl.GetSignerCounters(signer.Identity().String())
if err != nil {
return xerrors.Errorf("failed to get signer counters: %v", err)
}
name := c.String("name")
if name == "" {
return xerrors.New("--name flag is required")
}
instIDs := c.StringSlice("instid")
if len(instIDs) == 0 {
return xerrors.New("--instid flag is required")
}
append := c.Bool("append")
multiple := false
if len(instIDs) > 1 || append {
multiple = true
}
names := make([]string, len(instIDs))
instructions := make([]byzcoin.Instruction, len(instIDs))
for i, instID := range instIDs {
instIDBuf, err := hex.DecodeString(instID)
if err != nil {
return xerrors.New("failed to decode the instID string" + instID)
}
usedName := name
if multiple {
usedName = name + "-" + lib.RandString(16)
}
names[i] = usedName
instructions[i] = byzcoin.Instruction{
InstanceID: byzcoin.NamingInstanceID,
Invoke: &byzcoin.Invoke{
ContractID: byzcoin.ContractNamingID,
Command: "add",
Args: byzcoin.Arguments{
{
Name: "instanceID",
Value: instIDBuf,
},
{
Name: "name",
Value: []byte(usedName),
},
},
},
SignerCounter: []uint64{counters.Counters[0] + 1 + uint64(i)},
}
}
ctx, err := cl.CreateTransaction(instructions...)
if err != nil {
return err
}
err = ctx.FillSignersAndSignWith(*signer)
if err != nil {
return err
}
_, err = cl.AddTransactionAndWait(ctx, 10)
if err != nil {
return err
}
for i, inst := range ctx.Instructions {
instID := inst.DeriveID("").Slice()
log.Infof("Added a new naming instance with name '%s'. "+
"Its instance id is:\n%x", names[i], instID)
}
return lib.WaitPropagation(c, cl)
}
// NameInvokeRemove is used to remove a new name resolver
func NameInvokeRemove(c *cli.Context) error {
bcArg := c.String("bc")
if bcArg == "" {
return xerrors.New("--bc flag is required")
}
cfg, cl, err := lib.LoadConfig(bcArg)
if err != nil {
return err
}
var signer *darc.Signer
sstr := c.String("sign")
if sstr == "" {
signer, err = lib.LoadKey(cfg.AdminIdentity)
} else {
signer, err = lib.LoadKeyFromString(sstr)
}
if err != nil {
return err
}
counters, err := cl.GetSignerCounters(signer.Identity().String())
if err != nil {
return xerrors.Errorf("failed to get signer counters: %v", err)
}
name := c.String("name")
if name == "" {
return xerrors.New("--name flag is required")
}
instID := c.String("instid")
if instID == "" {
return xerrors.New("--instid flag required")
}
instIDBuf, err := hex.DecodeString(instID)
if err != nil {
return xerrors.New("failed to decode the instID string" + instID)
}
ctx, err := cl.CreateTransaction(byzcoin.Instruction{
InstanceID: byzcoin.NamingInstanceID,
Invoke: &byzcoin.Invoke{
ContractID: byzcoin.ContractNamingID,
Command: "remove",
Args: byzcoin.Arguments{
{
Name: "instanceID",
Value: instIDBuf,
},
{
Name: "name",
Value: []byte(name),
},
},
},
SignerCounter: []uint64{counters.Counters[0] + 1},
})
if err != nil {
return err
}
err = ctx.FillSignersAndSignWith(*signer)
if err != nil {
return err
}
_, err = cl.AddTransactionAndWait(ctx, 10)
if err != nil {
return err
}
newInstID := ctx.Instructions[0].DeriveID("").Slice()
log.Infof("Name entry deleted! (instance ID is %x)", newInstID)
return lib.WaitPropagation(c, cl)
}
// NameGet displays the name contract (which is a singleton). No need to provide
// the instance id since the name contract has a pre-determined one.
func NameGet(c *cli.Context) error {
bcArg := c.String("bc")
if bcArg == "" {
return xerrors.New("--bc flag is required")
}
_, cl, err := lib.LoadConfig(bcArg)
if err != nil {
return err
}
// Get the latest name instance value
pr, err := cl.GetProofFromLatest(byzcoin.NamingInstanceID.Slice())
if err != nil {
return xerrors.Errorf("couldn't get proof for NamingInstanceID: %v", err)
}
proof := pr.Proof
_, value, _, _, err := proof.KeyValue()
if err != nil {
return xerrors.Errorf("couldn't get value out of proof: %v", err)
}
namingBody := byzcoin.ContractNamingBody{}
err = protobuf.DecodeWithConstructors(value, &namingBody,
network.DefaultConstructors(cothority.Suite))
if err != nil {
return xerrors.Errorf("couldn't decode ContractNamingBody: %v", err)
}
log.Infof("Here is the naming data:\n%s", namingBody)
return nil
}
| gpl-2.0 |
doublesword/commuse | Source/W201621/Detours4.0.1/samples/talloc/tdll8x.cpp | 525 | //////////////////////////////////////////////////////////////////////////////
//
// Detours Test Program (tdll8x.cpp of talloc.exe/tdll8x.dll)
//
// Microsoft Research Detours Package
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//////////////////////////////////////////////////////////////////// DLL Stuff
//
__declspec(dllexport) unsigned long __stdcall Dll8Function(unsigned long Value)
{
return Value + 1;
}
///////////////////////////////////////////////////////////////// End of File.
| gpl-2.0 |
kyonetca/Pirate-Proxy | src/com/piratebayfree/adapters/LogAdapter.java | 3039 | package com.piratebayfree.adapters;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import com.piratebayfree.R;
import com.piratebayfree.Status;
public class LogAdapter extends ArrayAdapter<Status> {
private Context context;
private ImageView icon;
private TextView tag;
private TextView time;
private TextView content;
private Status log;
private List<Status> logs;
public LogAdapter(Context context, int layout, List<Status> logs) {
super(context, layout, logs);
this.context = context;
this.logs = logs;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
log = logs.get(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.log, parent, false);
icon = (ImageView) row.findViewById(R.id.log_icon);
tag = (TextView) row.findViewById(R.id.log_tag);
time = (TextView) row.findViewById(R.id.log_time);
content = (TextView) row.findViewById(R.id.log_content);
tag.setText(log.getTag());
content.setText(log.getContent());
if(log.isFirst()) {
// Tag
tag.setTypeface(null, Typeface.BOLD);
content.setTypeface(null, Typeface.BOLD);
time.setVisibility(View.GONE);
} else {
// Time
if(log.getTime() > 100) {
float seconds = ((int) log.getTime() + 99) / 100 * 100;
time.setText("+" + (seconds / 1000) + "s");
if(log.getTime() > 2500) time.setTextColor(content.getResources().getColor(R.color.warn));
if(log.getTime() > 5000) time.setTextColor(content.getResources().getColor(R.color.error));
} else if(log.getTime() > 0) {
float seconds = ((int) log.getTime() + 9) / 10 * 10;
time.setText("+" + (seconds / 1000) + "s");
}
}
if(log.getStatus() == Status.SUCCESS) {
tag.setTextColor(context.getResources().getColor(R.color.success));
content.setTextColor(context.getResources().getColor(R.color.success));
icon.setImageResource(R.drawable.success);
} else if(log.getStatus() == Status.WARNING) {
tag.setTextColor(context.getResources().getColor(R.color.warn));
content.setTextColor(context.getResources().getColor(R.color.warn));
icon.setImageResource(R.drawable.warn);
} else if(log.getStatus() == Status.ERROR) {
tag.setTextColor(context.getResources().getColor(R.color.error));
content.setTextColor(context.getResources().getColor(R.color.error));
icon.setImageResource(R.drawable.error);
}
return row;
}
} | gpl-2.0 |
wikimedia/wikidata-query-blazegraph | bigdata-rdf-test/src/test/java/com/bigdata/rdf/internal/AbstractEncodeDecodeMixedIVsTest.java | 49126 | /**
Copyright (C) SYSTAP, LLC DBA Blazegraph 2006-2016. All rights reserved.
Contact:
SYSTAP, LLC DBA Blazegraph
2501 Calvert ST NW #106
Washington, DC 20008
licenses@blazegraph.com
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
* Created on Oct 4, 2011
*/
package com.bigdata.rdf.internal;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.TimeZone;
import java.util.UUID;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import org.openrdf.model.URI;
import org.openrdf.model.impl.LiteralImpl;
import org.openrdf.model.impl.URIImpl;
import org.openrdf.model.vocabulary.RDF;
import com.bigdata.rdf.internal.ColorsEnumExtension.Color;
import com.bigdata.rdf.internal.impl.BlobIV;
import com.bigdata.rdf.internal.impl.bnode.FullyInlineUnicodeBNodeIV;
import com.bigdata.rdf.internal.impl.bnode.NumericBNodeIV;
import com.bigdata.rdf.internal.impl.bnode.SidIV;
import com.bigdata.rdf.internal.impl.bnode.UUIDBNodeIV;
import com.bigdata.rdf.internal.impl.extensions.DateTimeExtension;
import com.bigdata.rdf.internal.impl.extensions.DerivedNumericsExtension;
import com.bigdata.rdf.internal.impl.extensions.XSDStringExtension;
import com.bigdata.rdf.internal.impl.literal.FullyInlineTypedLiteralIV;
import com.bigdata.rdf.internal.impl.literal.PartlyInlineTypedLiteralIV;
import com.bigdata.rdf.internal.impl.literal.UUIDLiteralIV;
import com.bigdata.rdf.internal.impl.literal.XSDBooleanIV;
import com.bigdata.rdf.internal.impl.literal.XSDDecimalIV;
import com.bigdata.rdf.internal.impl.literal.XSDIntegerIV;
import com.bigdata.rdf.internal.impl.literal.XSDNumericIV;
import com.bigdata.rdf.internal.impl.literal.XSDUnsignedByteIV;
import com.bigdata.rdf.internal.impl.literal.XSDUnsignedIntIV;
import com.bigdata.rdf.internal.impl.literal.XSDUnsignedLongIV;
import com.bigdata.rdf.internal.impl.literal.XSDUnsignedShortIV;
import com.bigdata.rdf.internal.impl.uri.FullyInlineURIIV;
import com.bigdata.rdf.internal.impl.uri.PartlyInlineURIIV;
import com.bigdata.rdf.internal.impl.uri.URIExtensionIV;
import com.bigdata.rdf.internal.impl.uri.VocabURIByteIV;
import com.bigdata.rdf.internal.impl.uri.VocabURIShortIV;
import com.bigdata.rdf.model.BigdataBNode;
import com.bigdata.rdf.model.BigdataLiteral;
import com.bigdata.rdf.model.BigdataURI;
import com.bigdata.rdf.model.BigdataValue;
import com.bigdata.rdf.model.BigdataValueFactory;
import com.bigdata.rdf.model.BigdataValueFactoryImpl;
import com.bigdata.rdf.model.StatementEnum;
import com.bigdata.rdf.spo.SPO;
import com.bigdata.rdf.store.AbstractTripleStore;
/**
* Test of encode/decode and especially <em>comparator</em> semantics for mixed
* {@link IV}s.
*
* @author <a href="mailto:thompsonbry@users.sourceforge.net">Bryan Thompson</a>
* @version $Id$
*/
public abstract class AbstractEncodeDecodeMixedIVsTest extends AbstractEncodeDecodeKeysTestCase {
/**
*
*/
public AbstractEncodeDecodeMixedIVsTest() {
}
/**
* @param name
*/
public AbstractEncodeDecodeMixedIVsTest(String name) {
super(name);
}
/**
* Flag may be used to enable/disable the inclusion of the {@link IV}s
* having fully include Unicode data. These are the ones whose proper
* ordering is most problematic as they need to obey the collation order
* imposed by the {@link AbstractTripleStore.Options}.
*/
static private boolean fullyInlineUnicode = true;
protected List<IV<?,?>> prepareIVs() throws DatatypeConfigurationException {
final Random r = new Random();
final BigdataValueFactory vf = BigdataValueFactoryImpl.getInstance(getName());
final URI datatype = new URIImpl("http://www.bigdata.com");
final URI dt1 = new URIImpl("http://www.bigdata.com/mock-datatype-1");
final URI dt2 = new URIImpl("http://www.bigdata.com/mock-datatype-2");
final IV<?, ?> namespaceIV = newTermId(VTE.URI);
final IV<?, ?> datatypeIV = newTermId(VTE.URI);
final IV<?, ?> datatypeIV2 = newTermId(VTE.URI);
final IV<?, ?> colorIV = newTermId(VTE.URI);// ColorsEnumExtension.COLOR;
final IV<?, ?> xsdStringIV = newTermId(VTE.URI);// XSD.STRING;
final IV<?, ?> xsdDateTimeIV = newTermId(VTE.URI);// XSD.DATETIME;
final IDatatypeURIResolver resolver = new IDatatypeURIResolver() {
public BigdataURI resolve(final URI uri) {
final BigdataURI buri = vf.createURI(uri.stringValue());
if (ColorsEnumExtension.COLOR.equals(uri)) {
buri.setIV(colorIV);
} else if (XSD.STRING.equals(uri)) {
buri.setIV(xsdStringIV);
} else if (XSD.DATETIME.equals(uri)) {
buri.setIV(xsdDateTimeIV);
} else if (XSD.DATE.equals(uri)) {
buri.setIV(newTermId(VTE.URI));
} else if (XSD.TIME.equals(uri)) {
buri.setIV(newTermId(VTE.URI));
} else if (XSD.GDAY.equals(uri)) {
buri.setIV(newTermId(VTE.URI));
} else if (XSD.GMONTH.equals(uri)) {
buri.setIV(newTermId(VTE.URI));
} else if (XSD.GMONTHDAY.equals(uri)) {
buri.setIV(newTermId(VTE.URI));
} else if (XSD.GYEAR.equals(uri)) {
buri.setIV(newTermId(VTE.URI));
} else if (XSD.GYEARMONTH.equals(uri)) {
buri.setIV(newTermId(VTE.URI));
} else if (XSD.POSITIVE_INTEGER.equals(uri)) {
buri.setIV(newTermId(VTE.URI));
} else if (XSD.NEGATIVE_INTEGER.equals(uri)) {
buri.setIV(newTermId(VTE.URI));
} else if (XSD.NON_POSITIVE_INTEGER.equals(uri)) {
buri.setIV(newTermId(VTE.URI));
} else if (XSD.NON_NEGATIVE_INTEGER.equals(uri)) {
buri.setIV(newTermId(VTE.URI));
} else
throw new UnsupportedOperationException();
return buri;
}
};
final List<IV<?,?>> ivs = new LinkedList<IV<?,?>>();
{
// Fully inline
{
/*
* BNODEs
*/
if (fullyInlineUnicode) {
// blank nodes with Unicode IDs.
ivs.add(new FullyInlineUnicodeBNodeIV<BigdataBNode>("FOO"));
ivs.add(new FullyInlineUnicodeBNodeIV<BigdataBNode>("_bar"));
ivs.add(new FullyInlineUnicodeBNodeIV<BigdataBNode>("bar"));
ivs.add(new FullyInlineUnicodeBNodeIV<BigdataBNode>("baz"));
ivs.add(new FullyInlineUnicodeBNodeIV<BigdataBNode>("12"));
ivs.add(new FullyInlineUnicodeBNodeIV<BigdataBNode>("1298"));
ivs.add(new FullyInlineUnicodeBNodeIV<BigdataBNode>("asassdao"));
ivs.add(new FullyInlineUnicodeBNodeIV<BigdataBNode>("1"));
}
// blank nodes with numeric IDs.
ivs.add(new NumericBNodeIV<BigdataBNode>(-1));//
ivs.add(new NumericBNodeIV<BigdataBNode>(0));//
ivs.add(new NumericBNodeIV<BigdataBNode>(1));//
ivs.add(new NumericBNodeIV<BigdataBNode>(-52));//
ivs.add(new NumericBNodeIV<BigdataBNode>(52));//
ivs.add(new NumericBNodeIV<BigdataBNode>(Integer.MAX_VALUE));//
ivs.add(new NumericBNodeIV<BigdataBNode>(Integer.MIN_VALUE));//
// blank nodes with UUID IDs.
for (int i = 0; i < 100; i++) {
ivs.add(new UUIDBNodeIV<BigdataBNode>(UUID.randomUUID()));
}
/*
* URIs
*/
ivs.add(new FullyInlineURIIV<BigdataURI>(new URIImpl("http://www.bigdata.com")));
ivs.add(new FullyInlineURIIV<BigdataURI>(new URIImpl("http://www.bigdata.com/")));
ivs.add(new FullyInlineURIIV<BigdataURI>(new URIImpl("http://www.bigdata.com/foo")));
ivs.add(new FullyInlineURIIV<BigdataURI>(new URIImpl("http://www.bigdata.com:80/foo")));
ivs.add(new FullyInlineURIIV<BigdataURI>(new URIImpl("http://www.bigdata.com")));
if (fullyInlineUnicode) {
ivs.add(new FullyInlineURIIV<BigdataURI>(RDF.TYPE));
ivs.add(new FullyInlineURIIV<BigdataURI>(RDF.SUBJECT));
ivs.add(new FullyInlineURIIV<BigdataURI>(RDF.BAG));
ivs.add(new FullyInlineURIIV<BigdataURI>(RDF.OBJECT));
ivs.add(new URIExtensionIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>(
"http://www.example.com/"),
new VocabURIByteIV<BigdataURI>((byte) 1)));
ivs.add(new URIExtensionIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>(
"http://www.example.com/foo"),
new VocabURIByteIV<BigdataURI>((byte) 1)));
ivs.add(new URIExtensionIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>(
"http://www.example.com/foobar"),
new VocabURIByteIV<BigdataURI>((byte) 1)));
}
/*
* Literals
*/
if (fullyInlineUnicode) {
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"foo", null/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"bar", null/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"baz", null/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"123", null/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("23",
null/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("3",
null/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("",
null/* language */, null/* datatype */));
}
if (fullyInlineUnicode) {
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"foo", "en"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"bar", "en"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"goo", "en"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"baz", "en"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"foo", "de"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"bar", "de"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"goo", "de"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"baz", "de"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("",
"en"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("",
"de"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("1",
"en"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("1",
"de"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("12",
"en"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("12",
"de"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("2",
"en"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("2",
"de"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("23",
"en"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("23",
"de"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"123", "en"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"123", "de"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("3",
"en"/* language */, null/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("3",
"de"/* language */, null/* datatype */));
}
if (fullyInlineUnicode) {
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"foo", null/* language */, dt1));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"bar", null/* language */, dt1));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"baz", null/* language */, dt1));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"goo", null/* language */, dt1));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"foo", null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"bar", null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"baz", null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"goo", null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("",
null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("",
null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("1",
null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("1",
null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("12",
null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("12",
null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"123", null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(
"123", null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("23",
null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("23",
null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("3",
null/* language */, dt2));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("3",
null/* language */, dt2));
}
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("foo",
null/* language */, XSD.STRING/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("bar",
null/* language */, XSD.STRING/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("baz",
null/* language */, XSD.STRING/* datatype */));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(""));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(" "));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("1"));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("12"));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("123"));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("","en",null/*datatype*/));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(" ","en",null/*datatype*/));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("1","en",null/*datatype*/));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("12","fr",null/*datatype*/));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("123","de",null/*datatype*/));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("", null, datatype));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>(" ", null, datatype));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("1", null, datatype));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("12", null, datatype));
ivs.add(new FullyInlineTypedLiteralIV<BigdataLiteral>("123", null, datatype));
// xsd:boolean
ivs.add(new XSDBooleanIV<BigdataLiteral>(true));//
ivs.add(new XSDBooleanIV<BigdataLiteral>(false));//
// xsd:byte
ivs.add(new XSDNumericIV<BigdataLiteral>((byte)Byte.MIN_VALUE));
ivs.add(new XSDNumericIV<BigdataLiteral>((byte)-1));
ivs.add(new XSDNumericIV<BigdataLiteral>((byte)0));
ivs.add(new XSDNumericIV<BigdataLiteral>((byte)1));
ivs.add(new XSDNumericIV<BigdataLiteral>((byte)Byte.MAX_VALUE));
// xsd:short
ivs.add(new XSDNumericIV<BigdataLiteral>((short)-1));
ivs.add(new XSDNumericIV<BigdataLiteral>((short)0));
ivs.add(new XSDNumericIV<BigdataLiteral>((short)1));
ivs.add(new XSDNumericIV<BigdataLiteral>((short)Short.MIN_VALUE));
ivs.add(new XSDNumericIV<BigdataLiteral>((short)Short.MAX_VALUE));
// xsd:int
ivs.add(new XSDNumericIV<BigdataLiteral>(1));
ivs.add(new XSDNumericIV<BigdataLiteral>(0));
ivs.add(new XSDNumericIV<BigdataLiteral>(-1));
ivs.add(new XSDNumericIV<BigdataLiteral>(Integer.MAX_VALUE));
ivs.add(new XSDNumericIV<BigdataLiteral>(Integer.MIN_VALUE));
// xsd:long
ivs.add(new XSDNumericIV<BigdataLiteral>(1L));
ivs.add(new XSDNumericIV<BigdataLiteral>(0L));
ivs.add(new XSDNumericIV<BigdataLiteral>(-1L));
ivs.add(new XSDNumericIV<BigdataLiteral>(Long.MIN_VALUE));
ivs.add(new XSDNumericIV<BigdataLiteral>(Long.MAX_VALUE));
// xsd:float
ivs.add(new XSDNumericIV<BigdataLiteral>(1f));
ivs.add(new XSDNumericIV<BigdataLiteral>(-1f));
ivs.add(new XSDNumericIV<BigdataLiteral>(+0f));
ivs.add(new XSDNumericIV<BigdataLiteral>(Float.MAX_VALUE));
ivs.add(new XSDNumericIV<BigdataLiteral>(Float.MIN_VALUE));
ivs.add(new XSDNumericIV<BigdataLiteral>(Float.MIN_NORMAL));
ivs.add(new XSDNumericIV<BigdataLiteral>(Float.POSITIVE_INFINITY));
ivs.add(new XSDNumericIV<BigdataLiteral>(Float.NEGATIVE_INFINITY));
ivs.add(new XSDNumericIV<BigdataLiteral>(Float.NaN));
// xsd:double
ivs.add(new XSDNumericIV<BigdataLiteral>(1d));
ivs.add(new XSDNumericIV<BigdataLiteral>(-1d));
ivs.add(new XSDNumericIV<BigdataLiteral>(+0d));
ivs.add(new XSDNumericIV<BigdataLiteral>(Double.MAX_VALUE));
ivs.add(new XSDNumericIV<BigdataLiteral>(Double.MIN_VALUE));
ivs.add(new XSDNumericIV<BigdataLiteral>(Double.MIN_NORMAL));
ivs.add(new XSDNumericIV<BigdataLiteral>(Double.POSITIVE_INFINITY));
ivs.add(new XSDNumericIV<BigdataLiteral>(Double.NEGATIVE_INFINITY));
ivs.add(new XSDNumericIV<BigdataLiteral>(Double.NaN));
// uuid (not an official xsd type, but one we handle natively).
for (int i = 0; i < 100; i++) {
ivs.add(new UUIDLiteralIV<BigdataLiteral>(UUID.randomUUID()));
}
// xsd:unsignedByte
ivs.add(new XSDUnsignedByteIV<BigdataLiteral>(Byte.MIN_VALUE));
ivs.add(new XSDUnsignedByteIV<BigdataLiteral>((byte) -1));
ivs.add(new XSDUnsignedByteIV<BigdataLiteral>((byte) 0));
ivs.add(new XSDUnsignedByteIV<BigdataLiteral>((byte) 1));
ivs.add(new XSDUnsignedByteIV<BigdataLiteral>(Byte.MAX_VALUE));
// xsd:unsignedShort
ivs.add(new XSDUnsignedShortIV<BigdataLiteral>(Short.MIN_VALUE));
ivs.add(new XSDUnsignedShortIV<BigdataLiteral>((short) -1));
ivs.add(new XSDUnsignedShortIV<BigdataLiteral>((short) 0));
ivs.add(new XSDUnsignedShortIV<BigdataLiteral>((short) 1));
ivs.add(new XSDUnsignedShortIV<BigdataLiteral>(Short.MAX_VALUE));
// xsd:unsignedInt
ivs.add(new XSDUnsignedIntIV<BigdataLiteral>(Integer.MIN_VALUE));
ivs.add(new XSDUnsignedIntIV<BigdataLiteral>(-1));
ivs.add(new XSDUnsignedIntIV<BigdataLiteral>(0));
ivs.add(new XSDUnsignedIntIV<BigdataLiteral>(1));
ivs.add(new XSDUnsignedIntIV<BigdataLiteral>(Integer.MAX_VALUE));
// xsd:unsignedLong
ivs.add(new XSDUnsignedLongIV<BigdataLiteral>(Long.MIN_VALUE));
ivs.add(new XSDUnsignedLongIV<BigdataLiteral>(-1L));
ivs.add(new XSDUnsignedLongIV<BigdataLiteral>(0L));
ivs.add(new XSDUnsignedLongIV<BigdataLiteral>(1L));
ivs.add(new XSDUnsignedLongIV<BigdataLiteral>(Long.MAX_VALUE));
// xsd:integer
ivs.add(new XSDIntegerIV<BigdataLiteral>(BigInteger.valueOf(-1L)));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(BigInteger.valueOf(0L)));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(BigInteger.valueOf(1L)));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(BigInteger.valueOf(Long.MAX_VALUE)));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(BigInteger.valueOf(Long.MIN_VALUE)));//
// xsd:decimal
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(1.01)));
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(2.01)));//
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(0.01)));
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(1.01)));//
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(-1.01)));
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(0.01)));//
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(-2.01)));
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(-1.01)));//
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(10.01)));
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(11.01)));//
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(258.01)));
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(259.01)));//
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(3.01)));
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(259.01)));//
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(383.01)));
ivs.add(new XSDDecimalIV<BigdataLiteral>(BigDecimal.valueOf(383.02)));//
ivs.add(new XSDDecimalIV<BigdataLiteral>(new BigDecimal("1.5")));//
ivs.add(new XSDDecimalIV<BigdataLiteral>(new BigDecimal("1.51")));//
ivs.add(new XSDDecimalIV<BigdataLiteral>(new BigDecimal("-1.5")));//
ivs.add(new XSDDecimalIV<BigdataLiteral>(new BigDecimal("-1.51")));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(BigInteger.valueOf(-1L)));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(BigInteger.valueOf(0L)));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(BigInteger.valueOf(1L)));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(BigInteger.valueOf(Long.MAX_VALUE)));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(BigInteger.valueOf(Long.MIN_VALUE)));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(new BigInteger("15")));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(new BigInteger("151")));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(new BigInteger("-15")));//
ivs.add(new XSDIntegerIV<BigdataLiteral>(new BigInteger("-151")));//
// byte vocabulary IVs.
ivs.add(new VocabURIByteIV<BigdataURI>((byte) Byte.MIN_VALUE));
ivs.add(new VocabURIByteIV<BigdataURI>((byte) -1));
ivs.add(new VocabURIByteIV<BigdataURI>((byte) 0));
ivs.add(new VocabURIByteIV<BigdataURI>((byte) 1));
ivs.add(new VocabURIByteIV<BigdataURI>((byte) Byte.MAX_VALUE));
// short vocabulary IVs.
ivs.add(new VocabURIShortIV<BigdataURI>((short) Short.MIN_VALUE));
ivs.add(new VocabURIShortIV<BigdataURI>((short) -1));
ivs.add(new VocabURIShortIV<BigdataURI>((short) 0));
ivs.add(new VocabURIShortIV<BigdataURI>((short) 1));
ivs.add(new VocabURIShortIV<BigdataURI>((short) Short.MAX_VALUE));
// SIDs
{
final IV<?,?> s1 = newTermId(VTE.URI);
final IV<?,?> s2 = newTermId(VTE.URI);
final IV<?,?> p1 = newTermId(VTE.URI);
final IV<?,?> p2 = newTermId(VTE.URI);
final IV<?,?> o1 = newTermId(VTE.URI);
final IV<?,?> o2 = newTermId(VTE.BNODE);
final IV<?,?> o3 = newTermId(VTE.LITERAL);
final SPO spo1 = new SPO(s1, p1, o1, StatementEnum.Explicit);
final SPO spo2 = new SPO(s1, p1, o2, StatementEnum.Explicit);
final SPO spo3 = new SPO(s1, p1, o3, StatementEnum.Explicit);
final SPO spo4 = new SPO(s1, p2, o1, StatementEnum.Explicit);
final SPO spo5 = new SPO(s1, p2, o2, StatementEnum.Explicit);
final SPO spo6 = new SPO(s1, p2, o3, StatementEnum.Explicit);
final SPO spo7 = new SPO(s2, p1, o1, StatementEnum.Explicit);
final SPO spo8 = new SPO(s2, p1, o2, StatementEnum.Explicit);
final SPO spo9 = new SPO(s2, p1, o3, StatementEnum.Explicit);
final SPO spo10 = new SPO(s2, p2, o1, StatementEnum.Explicit);
final SPO spo11 = new SPO(s2, p2, o2, StatementEnum.Explicit);
final SPO spo12 = new SPO(s2, p2, o3, StatementEnum.Explicit);
// spo1.setStatementIdentifier(true);
// spo2.setStatementIdentifier(true);
// spo3.setStatementIdentifier(true);
// spo6.setStatementIdentifier(true);
final SPO spo13 = new SPO(spo1.getStatementIdentifier(), p1, o1,
StatementEnum.Explicit);
final SPO spo14 = new SPO(spo2.getStatementIdentifier(), p2, o2,
StatementEnum.Explicit);
final SPO spo15 = new SPO(s1, p1, spo3.getStatementIdentifier(),
StatementEnum.Explicit);
// spo15.setStatementIdentifier(true);
final SPO spo16 = new SPO(s1, p1, spo6.getStatementIdentifier(),
StatementEnum.Explicit);
final SPO spo17 = new SPO(spo1.getStatementIdentifier(), p1, spo15
.getStatementIdentifier(), StatementEnum.Explicit);
final IV<?, ?>[] e = {//
new SidIV<BigdataBNode>(spo1),//
new SidIV<BigdataBNode>(spo2),//
new SidIV<BigdataBNode>(spo3),//
new SidIV<BigdataBNode>(spo4),//
new SidIV<BigdataBNode>(spo5),//
new SidIV<BigdataBNode>(spo6),//
new SidIV<BigdataBNode>(spo7),//
new SidIV<BigdataBNode>(spo8),//
new SidIV<BigdataBNode>(spo9),//
new SidIV<BigdataBNode>(spo10),//
new SidIV<BigdataBNode>(spo11),//
new SidIV<BigdataBNode>(spo12),//
new SidIV<BigdataBNode>(spo13),//
new SidIV<BigdataBNode>(spo14),//
new SidIV<BigdataBNode>(spo15),//
new SidIV<BigdataBNode>(spo16),//
new SidIV<BigdataBNode>(spo17),//
};
ivs.addAll(Arrays.asList(e));
}
}
// Not inline
{
/*
* TermIds
*/
for (int i = 0; i < 100; i++) {
for (VTE vte : VTE.values()) {
// // 64 bit random term identifier.
// final long termId = r.nextLong();
//
// final TermId<?> v = new TermId<BigdataValue>(vte,
// termId);
//
// ivs.add(v);
ivs.add(newTermId(vte));
}
}
/*
* BLOBS
*/
{
for (int i = 0; i < 100; i++) {
for (VTE vte : VTE.values()) {
final int hashCode = r.nextInt();
final int counter = Short.MAX_VALUE
- r.nextInt(2 ^ 16);
@SuppressWarnings("rawtypes")
final BlobIV<?> v = new BlobIV(vte, hashCode,
(short) counter);
ivs.add(v);
}
}
}
} // Not inline.
/*
* Partly inline
*/
{
// URIs
if (fullyInlineUnicode) {
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("bar"),
namespaceIV));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("baz"),
namespaceIV));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("123"),
namespaceIV));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("23"),
namespaceIV));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("3"),
namespaceIV));
}
// LITERALs
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>(""),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("abc"),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>(" "),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("1"),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("12"),
datatypeIV));
if (fullyInlineUnicode) {
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>(""),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>(" "),
datatypeIV2));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("1"),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("1"),
datatypeIV2));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("12"),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("12"),
datatypeIV2));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("123"),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("123"),
datatypeIV2));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("23"),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("23"),
datatypeIV2));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("3"),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("3"),
datatypeIV2));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("bar"),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("baz"),
datatypeIV));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("bar"),
datatypeIV2));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("baz"),
datatypeIV2));
}
if(fullyInlineUnicode){
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("bar"),// localName
new VocabURIShortIV<BigdataURI>((short) 1) // namespace
));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("baz"),// localName
new VocabURIShortIV<BigdataURI>((short) 1) // namespace
));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("bar"),// localName
new VocabURIShortIV<BigdataURI>((short) 2) // namespace
));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("baz"),// localName
new VocabURIShortIV<BigdataURI>((short) 2) // namespace
));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("123"),// localName
new VocabURIShortIV<BigdataURI>((short) 2) // namespace
));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("123"),// localName
new VocabURIShortIV<BigdataURI>((short) 2) // namespace
));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("23"),// localName
new VocabURIShortIV<BigdataURI>((short) 2) // namespace
));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("23"),// localName
new VocabURIShortIV<BigdataURI>((short) 2) // namespace
));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("3"),// localName
new VocabURIShortIV<BigdataURI>((short) 2) // namespace
));
ivs.add(new PartlyInlineURIIV<BigdataURI>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("3"),// localName
new VocabURIShortIV<BigdataURI>((short) 2) // namespace
));
}
if (fullyInlineUnicode) {
final IV<?, ?> datatypeIVa = new VocabURIShortIV<BigdataURI>(
(short) 1);
final IV<?, ?> datatypeIVa2 = new VocabURIShortIV<BigdataURI>(
(short) 2);
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("bar"),
datatypeIVa));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("bar"),
datatypeIVa2));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("baz"),
datatypeIVa));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("baz"),
datatypeIVa2));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("123"),
datatypeIVa));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("123"),
datatypeIVa2));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("23"),
datatypeIVa));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("23"),
datatypeIVa2));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("3"),
datatypeIVa));
ivs.add(new PartlyInlineTypedLiteralIV<BigdataLiteral>(
new FullyInlineTypedLiteralIV<BigdataLiteral>("3"),
datatypeIVa2));
}
} // partly inline.
/*
* Extension IVs
*/
{
// xsd:dateTime extension
{
final DatatypeFactory df = DatatypeFactory.newInstance();
final DateTimeExtension<BigdataValue> ext = new DateTimeExtension<BigdataValue>(
resolver, TimeZone.getDefault());
final BigdataLiteral[] dt = {
vf.createLiteral(df
.newXMLGregorianCalendar("2001-10-26T21:32:52")),
vf.createLiteral(df
.newXMLGregorianCalendar("2001-10-26T21:32:52+02:00")),
vf.createLiteral(df
.newXMLGregorianCalendar("2001-10-26T19:32:52Z")),
vf.createLiteral(df
.newXMLGregorianCalendar("2001-10-26T19:32:52+00:00")),
vf.createLiteral(df
.newXMLGregorianCalendar("-2001-10-26T21:32:52")),
vf.createLiteral(df
.newXMLGregorianCalendar("2001-10-26T21:32:52.12679")),
vf.createLiteral(df
.newXMLGregorianCalendar("1901-10-26T21:32:52")), };
for (int i = 0; i < dt.length; i++) {
ivs.add(ext.createIV(dt[i]));
}
}
// derived numerics extension
{
final DatatypeFactory df = DatatypeFactory.newInstance();
final DerivedNumericsExtension<BigdataValue> ext =
new DerivedNumericsExtension<BigdataValue>(resolver);
final BigdataLiteral[] dt = {
vf.createLiteral("1", XSD.POSITIVE_INTEGER),
vf.createLiteral("-1", XSD.NEGATIVE_INTEGER),
vf.createLiteral("-1", XSD.NON_POSITIVE_INTEGER),
vf.createLiteral("1", XSD.NON_NEGATIVE_INTEGER),
vf.createLiteral("0", XSD.NON_POSITIVE_INTEGER),
vf.createLiteral("0", XSD.NON_NEGATIVE_INTEGER),
};
for (int i = 0; i < dt.length; i++) {
ivs.add(ext.createIV(dt[i]));
}
}
// xsd:string extension IVs
if (fullyInlineUnicode) {
final int maxInlineStringLength = 128;
final XSDStringExtension<BigdataValue> ext = new XSDStringExtension<BigdataValue>(
resolver, maxInlineStringLength);
final IV<?, ?>[] e = {//
ext.createIV(new LiteralImpl("", XSD.STRING)), //
ext.createIV(new LiteralImpl(" ", XSD.STRING)), //
ext.createIV(new LiteralImpl(" ", XSD.STRING)), //
ext.createIV(new LiteralImpl("1", XSD.STRING)), //
ext.createIV(new LiteralImpl("12", XSD.STRING)), //
ext.createIV(new LiteralImpl("123", XSD.STRING)), //
ext.createIV(new LiteralImpl("234", XSD.STRING)), //
ext.createIV(new LiteralImpl("34", XSD.STRING)), //
ext.createIV(new LiteralImpl("4", XSD.STRING)), //
ext.createIV(new LiteralImpl("a", XSD.STRING)), //
ext.createIV(new LiteralImpl("ab", XSD.STRING)), //
ext.createIV(new LiteralImpl("abc", XSD.STRING)), //
};
ivs.addAll(Arrays.asList(e));
}
// "color" extension IV.
if (true) {
final ColorsEnumExtension<BigdataValue> ext = new ColorsEnumExtension<BigdataValue>(
resolver);
for (Color c : ColorsEnumExtension.Color.values()) {
ivs.add(ext.createIV(new LiteralImpl(c.name(),
ColorsEnumExtension.COLOR)));
}
}
}
}
return ivs;
}
}
| gpl-2.0 |
OuhscBbmc/redcap-playground | noauth-delete.php | 1252 | <?php
/**
* PLUGIN NAME: Insert Unit Test Cleanup
* DESCRIPTION: delete redcap record inserted by a REDCapR unit test
* VERSION: 1.0
* AUTHOR: Will Beasley, OUHSC, BBMC
*/
// Prevent caching; this code is copied from /redcap/api/index.php
header("Expires: 0");
header("cache-control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
// Disable REDCap's authentication
define("NOAUTH", true);
// Call the REDCap Connect file in the main "redcap" directory
require_once "../../redcap_connect.php";
// OPTIONAL: Your custom PHP code goes here. You may use any constants/variables listed in redcap_info().
// OPTIONAL: Display the header
$HtmlPage = new HtmlPage();
$HtmlPage->PrintHeaderExt();
// Your HTML page content goes here
?>
<h3 style="color:#800000;">
Plugin Example Page with Authentication Disabled
</h3>
<p>
This is an example plugin page that has REDCap's <b>authentication disabled</b>.
So no one will be forced to login to this page because it is fully public and available to the web (supposing this
web server isn't locked down behind a firewall).
</p>
<?php
db_query("DELETE FROM redcap.redcap_data WHERE project_id=12 and record=5;");
// OPTIONAL: Display the footer
$HtmlPage->PrintFooterExt();
?>
| gpl-2.0 |
ranrolls/refine-ras-admin | administrator/components/com_judirectory/views/category/tmpl/edit_custom_js.php | 6086 | <?php
/**
* ------------------------------------------------------------------------
* JUDirectory for Joomla 2.5, 3.x
* ------------------------------------------------------------------------
*
* @copyright Copyright (C) 2010-2015 JoomUltra Co., Ltd. All Rights Reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author JoomUltra Co., Ltd
* @website http://www.joomultra.com
* @----------------------------------------------------------------------@
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
if(JUDirectoryHelper::isJoomla3x()){
$jsJoomla3x = 1;
}else{
$jsJoomla3x = 0;
}
?>
<script type="text/javascript">
jQuery(document).ready(function($){
var taskSubmit = null;
var cat_id = <?php echo $this->item->id ? $this->item->id : 0; ?>;
var old_parent_id = <?php echo $this->item->parent_id; ?>;
var isJoomla3x = <?php echo $jsJoomla3x; ?>;
Joomla.submitbutton = function (task) {
if (task == 'category.cancel') {
<?php echo $this->form->getField('description')->save(); ?>
Joomla.submitform(task, document.getElementById('adminForm'));
} else if(document.formvalidator.isValid(document.id('adminForm'))){
<?php echo $this->form->getField('description')->save(); ?>
if(old_parent_id != 0){
var new_parent_id = jQuery('#jform_parent_id').val();
if(old_parent_id != new_parent_id){
checkInheritedDataWhenChangeParentCat(task);
taskSubmit = task;
}else{
Joomla.submitform(task, document.getElementById('adminForm'));
}
}else{
Joomla.submitform(task, document.getElementById('adminForm'));
}
}
};
function checkInheritedDataWhenChangeParentCat(task){
var objectPost = {};
objectPost.id = cat_id;
objectPost.parent_id = jQuery('#jform_parent_id').val();
objectPost.selected_fieldgroup = jQuery('#jform_selected_fieldgroup').val();
objectPost.selected_criteriagroup = jQuery('#jform_selected_criteriagroup').val();
objectPost.style_id = jQuery('#jform_style_id').val();
jQuery.ajax({
type: "POST",
url : "index.php?option=com_judirectory&task=category.checkInheritedDataWhenChangeParentCat",
data: objectPost
}).done(function (data) {
var data = jQuery.parseJSON(data);
if (!data) return false;
if (data) {
if(data.status == 1){
if(data.fieldGroupChanged == 1){
jQuery('#warningFieldGroup').show();
jQuery('#fieldGroupMessage').html(data.fieldGroupMessage);
}else{
jQuery('#warningFieldGroup').hide();
}
if(data.criteriaGroupChanged == 1){
jQuery('#warningCriteriaGroup').show();
jQuery('#criteriaGroupMessage').html(data.criteriaGroupMessage);
}else{
jQuery('#warningCriteriaGroup').hide();
}
if(data.templateStyleChanged == 1){
jQuery('#warningTemplateStyle').show();
jQuery('#templateStyleMessage').html(data.templateStyleMessage);
}else{
jQuery('#warningTemplateStyle').hide();
}
jQuery('#confirmModal').modal();
}else{
Joomla.submitform(task, document.getElementById('adminForm'));
}
}
});
}
$('#acceptConfirm').on('click',function(e){
e.preventDefault();
var task = taskSubmit;
<?php echo $this->form->getField('description')->save(); ?>
Joomla.submitform(task, document.getElementById('adminForm'));
});
$('#jform_parent_id').on('change', function (e) {
e.preventDefault();
var objectPost = {};
objectPost.id = cat_id;
objectPost.parent_id = $('#jform_parent_id').val();
$.ajax({
type: "POST",
url: "index.php?option=com_judirectory&task=category.updateInheritField",
data: objectPost
}).done(function (data) {
var data = $.parseJSON(data);
if (data) {
$('#jform_selected_fieldgroup').find("option[value='-1']").html(data.message_fieldgroup);
$('#jform_selected_criteriagroup').find("option[value='-1']").html(data.message_criteriagroup);
$('#jform_style_id').find("option[value='-1']").html(data.message_style);
if(isJoomla3x == 1)
{
$("#jform_selected_fieldgroup").trigger("liszt:updated");
$("#jform_selected_criteriagroup").trigger("liszt:updated");
$("#jform_style_id").trigger("liszt:updated");
}
}
});
});
$('#jform_style_id').on('change',function(e){
e.preventDefault();
var objectPost = {};
objectPost.id = cat_id;
objectPost.parent_id = $('#jform_parent_id').val();
objectPost.style_id = $('#jform_style_id').val();
$.ajax({
type: "POST",
url : "index.php?option=com_judirectory&task=category.checkTemplateChange",
data: objectPost
}).done(function (data) {
var data = $.parseJSON(data);
if (data) {
if(data.templateStyleChanged == 1){
alert(data.templateStyleMessage);
}
}
});
});
$('#jform_selected_fieldgroup').on('change',function(e){
e.preventDefault();
var objectPost = {};
objectPost.id = cat_id;
objectPost.parent_id = $('#jform_parent_id').val();
objectPost.selected_fieldgroup = $('#jform_selected_fieldgroup').val();
$.ajax({
type: "POST",
url : "index.php?option=com_judirectory&task=category.checkFieldGroupChange",
data: objectPost
}).done(function (data) {
var data = $.parseJSON(data);
if (data) {
if(data.fieldGroupChanged == 1){
alert(data.fieldGroupMessage);
}
}
});
});
$('#jform_selected_criteriagroup').on('change',function(e){
e.preventDefault();
var objectPost = {};
objectPost.id = cat_id;
objectPost.parent_id = $('#jform_parent_id').val();
objectPost.selected_criteriagroup = $('#jform_selected_criteriagroup').val();
$.ajax({
type: "POST",
url : "index.php?option=com_judirectory&task=category.checkCriteriaGroupChange",
data: objectPost
}).done(function (data) {
var data = $.parseJSON(data);
if (data) {
if(data.criteriaGroupChanged == 1){
alert(data.criteriaGroupMessage);
}
}
});
});
});
</script> | gpl-2.0 |
VKiril/zencart | admin21/includes/languages/english.php | 40961 | <?php
/**
* @package admin
* @copyright Copyright 2003-2012 Zen Cart Development Team
* @copyright Portions Copyright 2003 osCommerce
* @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
* @version GIT: $Id: Author: DrByte Wed Sep 5 10:59:13 2012 -0400 Modified in v1.5.1 $
*/
if (!defined('IS_ADMIN_FLAG'))
{
die('Illegal Access');
}
// added defines for header alt and text
define('BOX_MODULES_FEEDIFY', 'Feedify');
define('HEADER_ALT_TEXT', 'Admin Powered by Zen Cart :: The Art of E-Commerce');
define('HEADER_LOGO_WIDTH', '200px');
define('HEADER_LOGO_HEIGHT', '70px');
define('HEADER_LOGO_IMAGE', 'logo.gif');
// look in your $PATH_LOCALE/locale directory for available locales..
setlocale(LC_TIME, 'en_US');
define('DATE_FORMAT_SHORT', '%m/%d/%Y'); // this is used for strftime()
define('DATE_FORMAT_LONG', '%A %d %B, %Y'); // this is used for strftime()
define('DATE_FORMAT', 'm/d/Y'); // this is used for date()
define('PHP_DATE_TIME_FORMAT', 'm/d/Y H:i:s'); // this is used for date()
define('DATE_TIME_FORMAT', DATE_FORMAT_SHORT . ' %H:%M:%S');
define('DATE_FORMAT_SPIFFYCAL', 'MM/dd/yyyy'); //Use only 'dd', 'MM' and 'yyyy' here in any order
////
// Return date in raw format
// $date should be in format mm/dd/yyyy
// raw date is in format YYYYMMDD, or DDMMYYYY
function zen_date_raw($date, $reverse = false) {
if ($reverse) {
return substr($date, 3, 2) . substr($date, 0, 2) . substr($date, 6, 4);
} else {
return substr($date, 6, 4) . substr($date, 0, 2) . substr($date, 3, 2);
}
}
// removed for meta tags
// page title
//define('TITLE', 'Zen Cart');
// include template specific meta tags defines
if (file_exists(DIR_FS_CATALOG_LANGUAGES . $_SESSION['language'] . '/' . $template_dir . '/meta_tags.php')) {
$template_dir_select = $template_dir . '/';
} else {
$template_dir_select = '';
}
require(DIR_FS_CATALOG_LANGUAGES . $_SESSION['language'] . '/' . $template_dir_select . 'meta_tags.php');
// meta tags
define('ICON_METATAGS_ON', 'Meta Tags Defined');
define('ICON_METATAGS_OFF', 'Meta Tags Undefined');
define('TEXT_LEGEND_META_TAGS', 'Meta Tags Defined:');
define('TEXT_INFO_META_TAGS_USAGE', '<strong>NOTE:</strong> The Site/Tagline is your defined definition for your site in the meta_tags.php file.');
// Global entries for the <html> tag
define('HTML_PARAMS','dir="ltr" lang="en"');
// charset for web pages and emails
define('CHARSET', 'utf-8');
// header text in includes/header.php
define('HEADER_TITLE_TOP', 'Admin Home');
define('HEADER_TITLE_SUPPORT_SITE', 'Support Site');
define('HEADER_TITLE_ONLINE_CATALOG', 'Online Catalog');
define('HEADER_TITLE_VERSION', 'Version');
define('HEADER_TITLE_ACCOUNT', 'Account');
define('HEADER_TITLE_LOGOFF', 'Logoff');
//define('HEADER_TITLE_ADMINISTRATION', 'Administration');
// Define the name of your Gift Certificate as Gift Voucher, Gift Certificate, Zen Cart Dollars, etc. here for use through out the shop
define('TEXT_GV_NAME','Gift Certificate');
define('TEXT_GV_NAMES','Gift Certificates');
define('TEXT_DISCOUNT_COUPON', 'Discount Coupon');
// used for redeem code, redemption code, or redemption id
define('TEXT_GV_REDEEM','Redemption Code');
// text for gender
define('MALE', 'Male');
define('FEMALE', 'Female');
// text for date of birth example
define('DOB_FORMAT_STRING', 'mm/dd/yyyy');
// configuration box text
define('BOX_HEADING_CONFIGURATION', 'Configuration');
define('BOX_CONFIGURATION_MY_STORE', 'My Store');
define('BOX_CONFIGURATION_MINIMUM_VALUES', 'Minimum Values');
define('BOX_CONFIGURATION_MAXIMUM_VALUES', 'Maximum Values');
define('BOX_CONFIGURATION_IMAGES', 'Images');
define('BOX_CONFIGURATION_CUSTOMER_DETAILS', 'Customer Details');
define('BOX_CONFIGURATION_SHIPPING_PACKAGING', 'Shipping/Packaging');
define('BOX_CONFIGURATION_PRODUCT_LISTING', 'Product Listing');
define('BOX_CONFIGURATION_STOCK', 'Stock');
define('BOX_CONFIGURATION_LOGGING', 'Logging');
define('BOX_CONFIGURATION_EMAIL_OPTIONS', 'E-Mail Options');
define('BOX_CONFIGURATION_ATTRIBUTE_OPTIONS', 'Attribute Settings');
define('BOX_CONFIGURATION_GZIP_COMPRESSION', 'GZip Compression');
define('BOX_CONFIGURATION_SESSIONS', 'Sessions');
define('BOX_CONFIGURATION_REGULATIONS', 'Regulations');
define('BOX_CONFIGURATION_GV_COUPONS', 'GV Coupons');
define('BOX_CONFIGURATION_CREDIT_CARDS', 'Credit Cards');
define('BOX_CONFIGURATION_PRODUCT_INFO', 'Product Info');
define('BOX_CONFIGURATION_LAYOUT_SETTINGS', 'Layout Settings');
define('BOX_CONFIGURATION_WEBSITE_MAINTENANCE', 'Website Maintenance');
define('BOX_CONFIGURATION_NEW_LISTING', 'New Listing');
define('BOX_CONFIGURATION_FEATURED_LISTING', 'Featured Listing');
define('BOX_CONFIGURATION_ALL_LISTING', 'All Listing');
define('BOX_CONFIGURATION_INDEX_LISTING', 'Index Listing');
define('BOX_CONFIGURATION_DEFINE_PAGE_STATUS', 'Define Page Status');
define('BOX_CONFIGURATION_EZPAGES_SETTINGS', 'EZ-Pages Settings');
// modules box text
define('BOX_HEADING_MODULES', 'Modules');
define('BOX_MODULES_PAYMENT', 'Payment');
define('BOX_MODULES_SHIPPING', 'Shipping');
define('BOX_MODULES_ORDER_TOTAL', 'Order Total');
define('BOX_MODULES_PRODUCT_TYPES', 'Product Types');
// categories box text
define('BOX_HEADING_CATALOG', 'Catalog');
define('BOX_CATALOG_CATEGORIES_PRODUCTS', 'Categories/Products');
define('BOX_CATALOG_PRODUCT_TYPES', 'Product Types');
define('BOX_CATALOG_CATEGORIES_OPTIONS_NAME_MANAGER', 'Option Name Manager');
define('BOX_CATALOG_CATEGORIES_OPTIONS_VALUES_MANAGER', 'Option Value Manager');
define('BOX_CATALOG_MANUFACTURERS', 'Manufacturers');
define('BOX_CATALOG_REVIEWS', 'Reviews');
define('BOX_CATALOG_SPECIALS', 'Specials');
define('BOX_CATALOG_PRODUCTS_EXPECTED', 'Products Expected');
define('BOX_CATALOG_SALEMAKER', 'SaleMaker');
define('BOX_CATALOG_PRODUCTS_PRICE_MANAGER', 'Products Price Manager');
define('BOX_CATALOG_PRODUCT', 'Product');
define('BOX_CATALOG_PRODUCTS_TO_CATEGORIES', 'Products to Categories');
// customers box text
define('BOX_HEADING_CUSTOMERS', 'Customers');
define('BOX_CUSTOMERS_CUSTOMERS', 'Customers');
define('BOX_CUSTOMERS_ORDERS', 'Orders');
define('BOX_CUSTOMERS_GROUP_PRICING', 'Group Pricing');
define('BOX_CUSTOMERS_PAYPAL', 'PayPal IPN');
define('BOX_CUSTOMERS_INVOICE', 'Invoice');
define('BOX_CUSTOMERS_PACKING_SLIP', 'Packing Slip');
// taxes box text
define('BOX_HEADING_LOCATION_AND_TAXES', 'Locations / Taxes');
define('BOX_TAXES_COUNTRIES', 'Countries');
define('BOX_TAXES_ZONES', 'Zones');
define('BOX_TAXES_GEO_ZONES', 'Zones Definitions');
define('BOX_TAXES_TAX_CLASSES', 'Tax Classes');
define('BOX_TAXES_TAX_RATES', 'Tax Rates');
// reports box text
define('BOX_HEADING_REPORTS', 'Reports');
define('BOX_REPORTS_PRODUCTS_VIEWED', 'Products Viewed');
define('BOX_REPORTS_PRODUCTS_PURCHASED', 'Products Purchased');
define('BOX_REPORTS_ORDERS_TOTAL', 'Customer Orders-Total');
define('BOX_REPORTS_PRODUCTS_LOWSTOCK', 'Products Low Stock');
define('BOX_REPORTS_CUSTOMERS_REFERRALS', 'Customers Referral');
// tools text
define('BOX_HEADING_TOOLS', 'Tools');
define('BOX_TOOLS_TEMPLATE_SELECT', 'Template Selection');
define('BOX_TOOLS_BACKUP', 'Database Backup');
define('BOX_TOOLS_BANNER_MANAGER', 'Banner Manager');
define('BOX_TOOLS_CACHE', 'Cache Control');
define('BOX_TOOLS_DEFINE_LANGUAGE', 'Define Languages');
define('BOX_TOOLS_FILE_MANAGER', 'File Manager');
define('BOX_TOOLS_MAIL', 'Send Email');
define('BOX_TOOLS_NEWSLETTER_MANAGER', 'Newsletter and Product Notifications Manager');
define('BOX_TOOLS_SERVER_INFO', 'Server/Version Info');
define('BOX_TOOLS_WHOS_ONLINE', 'Who\'s Online');
define('BOX_TOOLS_STORE_MANAGER', 'Store Manager');
define('BOX_TOOLS_DEVELOPERS_TOOL_KIT', 'Developers Tool Kit');
define('BOX_TOOLS_SQLPATCH','Install SQL Patches');
define('BOX_TOOLS_EZPAGES','EZ-Pages');
define('BOX_HEADING_EXTRAS', 'Extras');
// define pages editor files
define('BOX_TOOLS_DEFINE_PAGES_EDITOR','Define Pages Editor');
define('BOX_TOOLS_DEFINE_MAIN_PAGE', 'Main Page');
define('BOX_TOOLS_DEFINE_CONTACT_US','Contact Us');
define('BOX_TOOLS_DEFINE_PRIVACY','Privacy');
define('BOX_TOOLS_DEFINE_SHIPPINGINFO','Shipping & Returns');
define('BOX_TOOLS_DEFINE_CONDITIONS','Conditions of Use');
define('BOX_TOOLS_DEFINE_CHECKOUT_SUCCESS','Checkout Success');
define('BOX_TOOLS_DEFINE_PAGE_2','Page 2');
define('BOX_TOOLS_DEFINE_PAGE_3','Page 3');
define('BOX_TOOLS_DEFINE_PAGE_4','Page 4');
// localization box text
define('BOX_HEADING_LOCALIZATION', 'Localization');
define('BOX_LOCALIZATION_CURRENCIES', 'Currencies');
define('BOX_LOCALIZATION_LANGUAGES', 'Languages');
define('BOX_LOCALIZATION_ORDERS_STATUS', 'Orders Status');
// gift vouchers box text
define('BOX_HEADING_GV_ADMIN', TEXT_GV_NAME . '/Coupons');
define('BOX_GV_ADMIN_QUEUE', TEXT_GV_NAMES . ' Queue');
define('BOX_GV_ADMIN_MAIL', 'Mail ' . TEXT_GV_NAME);
define('BOX_GV_ADMIN_SENT', TEXT_GV_NAMES . ' sent');
define('BOX_COUPON_ADMIN','Coupon Admin');
define('BOX_COUPON_RESTRICT','Coupon Restrictions');
// admin access box text
define('BOX_HEADING_ADMIN_ACCESS', 'Admin Access Management');
define('BOX_ADMIN_ACCESS_USERS', 'Admin Users');
define('BOX_ADMIN_ACCESS_PROFILES', 'Admin Profiles');
define('BOX_ADMIN_ACCESS_PAGE_REGISTRATION', 'Admin Page Registration');
define('BOX_ADMIN_ACCESS_LOGS', 'Admin Activity Logs');
define('IMAGE_RELEASE', 'Redeem ' . TEXT_GV_NAME);
// javascript messages
define('JS_ERROR', 'Errors have occurred during the processing of your form!\nPlease make the following corrections:\n\n');
define('JS_OPTIONS_VALUE_PRICE', '* The new product attribute needs a price value\n');
define('JS_OPTIONS_VALUE_PRICE_PREFIX', '* The new product attribute needs a price prefix\n');
define('JS_PRODUCTS_NAME', '* The new product needs a name\n');
define('JS_PRODUCTS_DESCRIPTION', '* The new product needs a description\n');
define('JS_PRODUCTS_PRICE', '* The new product needs a price value\n');
define('JS_PRODUCTS_WEIGHT', '* The new product needs a weight value\n');
define('JS_PRODUCTS_QUANTITY', '* The new product needs a quantity value\n');
define('JS_PRODUCTS_MODEL', '* The new product needs a model value\n');
define('JS_PRODUCTS_IMAGE', '* The new product needs an image value\n');
define('JS_SPECIALS_PRODUCTS_PRICE', '* A new price for this product needs to be set\n');
define('JS_GENDER', '* The \'Gender\' value must be chosen.\n');
define('JS_FIRST_NAME', '* The \'First Name\' entry must have at least ' . ENTRY_FIRST_NAME_MIN_LENGTH . ' characters.\n');
define('JS_LAST_NAME', '* The \'Last Name\' entry must have at least ' . ENTRY_LAST_NAME_MIN_LENGTH . ' characters.\n');
define('JS_DOB', '* The \'Date of Birth\' entry must be in the format: xx/xx/xxxx (month/date/year).\n');
define('JS_EMAIL_ADDRESS', '* The \'E-Mail Address\' entry must have at least ' . ENTRY_EMAIL_ADDRESS_MIN_LENGTH . ' characters.\n');
define('JS_ADDRESS', '* The \'Street Address\' entry must have at least ' . ENTRY_STREET_ADDRESS_MIN_LENGTH . ' characters.\n');
define('JS_POST_CODE', '* The \'Post Code\' entry must have at least ' . ENTRY_POSTCODE_MIN_LENGTH . ' characters.\n');
define('JS_CITY', '* The \'City\' entry must have at least ' . ENTRY_CITY_MIN_LENGTH . ' characters.\n');
define('JS_STATE', '* The \'State\' entry must be selected.\n');
define('JS_STATE_SELECT', '-- Select Above --');
define('JS_ZONE', '* The \'State\' entry must be selected from the list for this country.');
define('JS_COUNTRY', '* The \'Country\' value must be chosen.\n');
define('JS_TELEPHONE', '* The \'Telephone Number\' entry must have at least ' . ENTRY_TELEPHONE_MIN_LENGTH . ' characters.\n');
define('JS_ORDER_DOES_NOT_EXIST', 'Order Number %s does not exist!');
define('CATEGORY_PERSONAL', 'Personal');
define('CATEGORY_ADDRESS', 'Address');
define('CATEGORY_CONTACT', 'Contact');
define('CATEGORY_COMPANY', 'Company');
define('CATEGORY_OPTIONS', 'Options');
define('ENTRY_GENDER', 'Gender:');
define('ENTRY_GENDER_ERROR', ' <span class="errorText">required</span>');
define('ENTRY_FIRST_NAME', 'First Name:');
define('ENTRY_FIRST_NAME_ERROR', ' <span class="errorText">min ' . ENTRY_FIRST_NAME_MIN_LENGTH . ' chars</span>');
define('ENTRY_LAST_NAME', 'Last Name:');
define('ENTRY_LAST_NAME_ERROR', ' <span class="errorText">min ' . ENTRY_LAST_NAME_MIN_LENGTH . ' chars</span>');
define('ENTRY_DATE_OF_BIRTH', 'Date of Birth:');
define('ENTRY_DATE_OF_BIRTH_ERROR', ' <span class="errorText">(eg. 05/21/1970)</span>');
define('ENTRY_EMAIL_ADDRESS', 'E-Mail Address:');
define('ENTRY_EMAIL_ADDRESS_ERROR', ' <span class="errorText">min ' . ENTRY_EMAIL_ADDRESS_MIN_LENGTH . ' chars</span>');
define('ENTRY_EMAIL_ADDRESS_CHECK_ERROR', ' <span class="errorText">The email address doesn\'t appear to be valid!</span>');
define('ENTRY_EMAIL_ADDRESS_ERROR_EXISTS', ' <span class="errorText">This email address already exists!</span>');
define('ENTRY_COMPANY', 'Company name:');
define('ENTRY_COMPANY_ERROR', '');
define('ENTRY_PRICING_GROUP', 'Discount Pricing Group');
define('ENTRY_STREET_ADDRESS', 'Street Address:');
define('ENTRY_STREET_ADDRESS_ERROR', ' <span class="errorText">min ' . ENTRY_STREET_ADDRESS_MIN_LENGTH . ' chars</span>');
define('ENTRY_SUBURB', 'Suburb:');
define('ENTRY_SUBURB_ERROR', '');
define('ENTRY_POST_CODE', 'Post Code:');
define('ENTRY_POST_CODE_ERROR', ' <span class="errorText">min ' . ENTRY_POSTCODE_MIN_LENGTH . ' chars</span>');
define('ENTRY_CITY', 'City:');
define('ENTRY_CITY_ERROR', ' <span class="errorText">min ' . ENTRY_CITY_MIN_LENGTH . ' chars</span>');
define('ENTRY_STATE', 'State:');
define('ENTRY_STATE_ERROR', ' <span class="errorText">required</span>');
define('ENTRY_COUNTRY', 'Country:');
define('ENTRY_COUNTRY_ERROR', '');
define('ENTRY_TELEPHONE_NUMBER', 'Telephone Number:');
define('ENTRY_TELEPHONE_NUMBER_ERROR', ' <span class="errorText">min ' . ENTRY_TELEPHONE_MIN_LENGTH . ' chars</span>');
define('ENTRY_FAX_NUMBER', 'Fax Number:');
define('ENTRY_FAX_NUMBER_ERROR', '');
define('ENTRY_NEWSLETTER', 'Newsletter:');
define('ENTRY_NEWSLETTER_YES', 'Subscribed');
define('ENTRY_NEWSLETTER_NO', 'Unsubscribed');
define('ENTRY_NEWSLETTER_ERROR', '');
define('ERROR_PASSWORDS_NOT_MATCHING', 'Password and confirmation must match');
define('ENTRY_PASSWORD_CHANGE_ERROR', '<strong>Sorry, your new password was rejected.</strong><br />');
define('ERROR_PASSWORD_RULES', 'Passwords must contain both letters and numbers, must be at least %s characters long, and must not be the same as the last 4 passwords used. Passwords expire every 90 days, after which you will be prompted to choose a new password.');
define('ERROR_TOKEN_EXPIRED_PLEASE_RESUBMIT', 'ERROR: Sorry, there was an error processing your data. Please re-submit the information again.');
// images
//define('IMAGE_ANI_SEND_EMAIL', 'Sending E-Mail');
define('IMAGE_BACK', 'Back');
define('IMAGE_BACKUP', 'Backup');
define('IMAGE_CANCEL', 'Cancel');
define('IMAGE_CONFIRM', 'Confirm');
define('IMAGE_COPY', 'Copy');
define('IMAGE_COPY_TO', 'Copy To');
define('IMAGE_DETAILS', 'Details');
define('IMAGE_DELETE', 'Delete');
define('IMAGE_EDIT', 'Edit');
define('IMAGE_EMAIL', 'Email');
define('IMAGE_GO', 'Go');
define('IMAGE_FILE_MANAGER', 'File Manager');
define('IMAGE_ICON_STATUS_GREEN', 'Active');
define('IMAGE_ICON_STATUS_GREEN_LIGHT', 'Set Active');
define('IMAGE_ICON_STATUS_RED', 'Inactive');
define('IMAGE_ICON_STATUS_RED_LIGHT', 'Set Inactive');
define('IMAGE_ICON_STATUS_RED_EZPAGES', 'Error -- too many URL/content types entered');
define('IMAGE_ICON_STATUS_RED_ERROR', 'Error');
define('IMAGE_ICON_INFO', 'Info');
define('IMAGE_INSERT', 'Insert');
define('IMAGE_LOCK', 'Lock');
define('IMAGE_MODULE_INSTALL', 'Install Module');
define('IMAGE_MODULE_REMOVE', 'Remove Module');
define('IMAGE_MOVE', 'Move');
define('IMAGE_NEW_BANNER', 'New Banner');
define('IMAGE_NEW_CATEGORY', 'New Category');
define('IMAGE_NEW_COUNTRY', 'New Country');
define('IMAGE_NEW_CURRENCY', 'New Currency');
define('IMAGE_NEW_FILE', 'New File');
define('IMAGE_NEW_FOLDER', 'New Folder');
define('IMAGE_NEW_LANGUAGE', 'New Language');
define('IMAGE_NEW_NEWSLETTER', 'New Newsletter');
define('IMAGE_NEW_PRODUCT', 'New Product');
define('IMAGE_NEW_SALE', 'New Sale');
define('IMAGE_NEW_TAX_CLASS', 'New Tax Class');
define('IMAGE_NEW_TAX_RATE', 'New Tax Rate');
define('IMAGE_NEW_TAX_ZONE', 'New Tax Zone');
define('IMAGE_NEW_ZONE', 'New Zone');
define('IMAGE_OPTION_NAMES', 'Option Names Manager');
define('IMAGE_OPTION_VALUES', 'Option Values Manager');
define('IMAGE_ORDERS', 'Orders');
define('IMAGE_ORDERS_INVOICE', 'Invoice');
define('IMAGE_ORDERS_PACKINGSLIP', 'Packing Slip');
define('IMAGE_PERMISSIONS', 'Edit Permissions');
define('IMAGE_PREVIEW', 'Preview');
define('IMAGE_RESTORE', 'Restore');
define('IMAGE_RESET', 'Reset');
define('IMAGE_SAVE', 'Save');
define('IMAGE_SEARCH', 'Search');
define('IMAGE_SELECT', 'Select');
define('IMAGE_SEND', 'Send');
define('IMAGE_SEND_EMAIL', 'Send Email');
define('IMAGE_SUBMIT', 'Submit');
define('IMAGE_UNLOCK', 'Unlock');
define('IMAGE_UPDATE', 'Update');
define('IMAGE_UPDATE_CURRENCIES', 'Update Exchange Rate');
define('IMAGE_UPLOAD', 'Upload');
define('IMAGE_TAX_RATES','Tax Rate');
define('IMAGE_DEFINE_ZONES','Define Zones');
define('IMAGE_PRODUCTS_PRICE_MANAGER', 'Products Price Manager');
define('IMAGE_UPDATE_PRICE_CHANGES', 'Update Price Changes');
define('IMAGE_ADD_BLANK_DISCOUNTS','Add ' . DISCOUNT_QTY_ADD . ' Blank Discount Qty');
define('IMAGE_CHECK_VERSION', 'Check for Updates to Zen Cart');
define('IMAGE_PRODUCTS_TO_CATEGORIES', 'Multiple Categories Link Manager');
define('IMAGE_ICON_STATUS_ON', 'Status - Enabled');
define('IMAGE_ICON_STATUS_OFF', 'Status - Disabled');
define('IMAGE_ICON_LINKED', 'Product is Linked');
define('IMAGE_REMOVE_SPECIAL','Remove Special Price Info');
define('IMAGE_REMOVE_FEATURED','Remove Featured Product Info');
define('IMAGE_INSTALL_SPECIAL', 'Add Special Price Info');
define('IMAGE_INSTALL_FEATURED', 'Add Featured Product Info');
define('ICON_PRODUCTS_PRICE_MANAGER','Products Price Manager');
define('ICON_COPY_TO', 'Copy to');
define('ICON_CROSS', 'False');
define('ICON_CURRENT_FOLDER', 'Current Folder');
define('ICON_DELETE', 'Delete');
define('ICON_EDIT', 'Edit');
define('ICON_ERROR', 'Error');
define('ICON_FILE', 'File');
define('ICON_FILE_DOWNLOAD', 'Download');
define('ICON_FOLDER', 'Folder');
//define('ICON_LOCKED', 'Locked');
define('ICON_MOVE', 'Move');
define('ICON_PERMISSIONS', 'Permissions');
define('ICON_PREVIOUS_LEVEL', 'Previous Level');
define('ICON_PREVIEW', 'Preview');
define('ICON_RESET', 'Reset');
define('ICON_STATISTICS', 'Statistics');
define('ICON_SUCCESS', 'Success');
define('ICON_TICK', 'True');
//define('ICON_UNLOCKED', 'Unlocked');
define('ICON_WARNING', 'Warning');
// constants for use in zen_prev_next_display function
define('TEXT_RESULT_PAGE', 'Page %s of %d');
define('TEXT_DISPLAY_NUMBER_OF_ADMINS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> admins)');
define('TEXT_DISPLAY_NUMBER_OF_BANNERS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> banners)');
define('TEXT_DISPLAY_NUMBER_OF_CATEGORIES', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> categories)');
define('TEXT_DISPLAY_NUMBER_OF_COUNTRIES', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> countries)');
define('TEXT_DISPLAY_NUMBER_OF_CUSTOMERS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> customers)');
define('TEXT_DISPLAY_NUMBER_OF_CURRENCIES', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> currencies)');
define('TEXT_DISPLAY_NUMBER_OF_FEATURED', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> products on featured)');
define('TEXT_DISPLAY_NUMBER_OF_LANGUAGES', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> languages)');
define('TEXT_DISPLAY_NUMBER_OF_MANUFACTURERS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> manufacturers)');
define('TEXT_DISPLAY_NUMBER_OF_NEWSLETTERS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> newsletters)');
define('TEXT_DISPLAY_NUMBER_OF_ORDERS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> orders)');
define('TEXT_DISPLAY_NUMBER_OF_ORDERS_STATUS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> orders status)');
define('TEXT_DISPLAY_NUMBER_OF_PRICING_GROUPS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> pricing groups)');
define('TEXT_DISPLAY_NUMBER_OF_PRODUCTS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> products)');
define('TEXT_DISPLAY_NUMBER_OF_PRODUCT_TYPES', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> product types)');
define('TEXT_DISPLAY_NUMBER_OF_PRODUCTS_EXPECTED', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> products expected)');
define('TEXT_DISPLAY_NUMBER_OF_REVIEWS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> product reviews)');
define('TEXT_DISPLAY_NUMBER_OF_SALES', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> sales)');
define('TEXT_DISPLAY_NUMBER_OF_SPECIALS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> products on special)');
define('TEXT_DISPLAY_NUMBER_OF_TAX_CLASSES', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> tax classes)');
define('TEXT_DISPLAY_NUMBER_OF_TEMPLATES', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> template associations)');
define('TEXT_DISPLAY_NUMBER_OF_TAX_ZONES', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> tax zones)');
define('TEXT_DISPLAY_NUMBER_OF_TAX_RATES', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> tax rates)');
define('TEXT_DISPLAY_NUMBER_OF_ZONES', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> zones)');
define('PREVNEXT_BUTTON_PREV', '<<');
define('PREVNEXT_BUTTON_NEXT', '>>');
define('TEXT_DEFAULT', 'default');
define('TEXT_SET_DEFAULT', 'Set as default');
define('TEXT_FIELD_REQUIRED', ' <span class="fieldRequired">* Required</span>');
define('ERROR_NO_DEFAULT_CURRENCY_DEFINED', 'Error: There is currently no default currency set. Please set one at: Administration Tools->Localization->Currencies');
define('TEXT_CACHE_CATEGORIES', 'Categories Box');
define('TEXT_CACHE_MANUFACTURERS', 'Manufacturers Box');
define('TEXT_CACHE_ALSO_PURCHASED', 'Also Purchased Module');
define('TEXT_NONE', '--none--');
define('TEXT_TOP', 'Top');
define('ERROR_DESTINATION_DOES_NOT_EXIST', 'Error: Destination does not exist %s');
define('ERROR_DESTINATION_NOT_WRITEABLE', 'Error: Destination not writeable %s');
define('ERROR_FILE_NOT_SAVED', 'Error: File upload not saved.');
define('ERROR_FILETYPE_NOT_ALLOWED', 'Error: File upload type not allowed %s');
define('SUCCESS_FILE_SAVED_SUCCESSFULLY', 'Success: File upload saved successfully %s');
define('WARNING_NO_FILE_UPLOADED', 'Warning: No file uploaded.');
define('WARNING_FILE_UPLOADS_DISABLED', 'Warning: File uploads are disabled in the php.ini configuration file.');
define('ERROR_ADMIN_SECURITY_WARNING', 'Warning: Your Admin login is not secure ... either you still have default login settings for: Admin admin or have not removed or changed: demo demoonly<br />The login(s) should be changed as soon as possible for the Security of your shop.');
define('WARNING_DATABASE_VERSION_OUT_OF_DATE','Your database appears to need patching to a higher level. See Tools->Server Information to review patch levels.');
define('WARN_DATABASE_VERSION_PROBLEM','true'); //set to false to turn off warnings about database version mismatches
define('WARNING_ADMIN_DOWN_FOR_MAINTENANCE', '<strong>WARNING:</strong> Site is currently set to Down for Maintenance ...<br />NOTE: You cannot test most Payment and Shipping Modules in Maintenance mode');
define('WARNING_BACKUP_CFG_FILES_TO_DELETE', 'WARNING: These files should be deleted to prevent security vulnerability: ');
define('WARNING_INSTALL_DIRECTORY_EXISTS', 'SECURITY WARNING: Installation directory exists at: ' . DIR_FS_CATALOG . 'zc_install. Please remove this directory for security reasons.');
define('WARNING_CONFIG_FILE_WRITEABLE', 'Warning: Your configuration file: %sincludes/configure.php. This is a potential security risk - please set the right user permissions on this file (read-only, CHMOD 644 or 444 are typical). <a href="http://tutorials.zen-cart.com/index.php?article=90" target="_blank">See this FAQ</a>');
define('WARNING_COULD_NOT_LOCATE_LANG_FILE', 'WARNING: Could not locate language file: ');
define('ERROR_MODULE_REMOVAL_PROHIBITED', 'ERROR: Module removal prohibited: ');
define('WARNING_REVIEW_ROGUE_ACTIVITY', 'ALERT: Please review for possible XSS activity:');
define('_JANUARY', 'January');
define('_FEBRUARY', 'February');
define('_MARCH', 'March');
define('_APRIL', 'April');
define('_MAY', 'May');
define('_JUNE', 'June');
define('_JULY', 'July');
define('_AUGUST', 'August');
define('_SEPTEMBER', 'September');
define('_OCTOBER', 'October');
define('_NOVEMBER', 'November');
define('_DECEMBER', 'December');
define('TEXT_DISPLAY_NUMBER_OF_GIFT_VOUCHERS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> gift vouchers)');
define('TEXT_DISPLAY_NUMBER_OF_COUPONS', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> coupons)');
define('TEXT_VALID_PRODUCTS_LIST', 'Products List');
define('TEXT_VALID_PRODUCTS_ID', 'Products ID');
define('TEXT_VALID_PRODUCTS_NAME', 'Products Name');
define('TEXT_VALID_PRODUCTS_MODEL', 'Products Model');
define('TEXT_VALID_CATEGORIES_LIST', 'Categories List');
define('TEXT_VALID_CATEGORIES_ID', 'Category ID');
define('TEXT_VALID_CATEGORIES_NAME', 'Category Name');
define('DEFINE_LANGUAGE','Define Language:');
define('BOX_ENTRY_COUNTER_DATE','Hit Counter Started:');
define('BOX_ENTRY_COUNTER','Hit Counter:');
// not installed
define('NOT_INSTALLED_TEXT','Not Installed');
// Product Options Values Sort Order - option_values.php
define('BOX_CATALOG_PRODUCT_OPTIONS_VALUES','Option Value Sorter ');
define('TEXT_UPDATE_SORT_ORDERS_OPTIONS','<strong>Update Attribute Sort Order from Option Value Defaults</strong> ');
define('TEXT_INFO_ATTRIBUTES_FEATURES_UPDATES','<strong>Update All Products\' Attribute Sort Orders</strong><br />to match Option Value Default Sort Orders:<br />');
// Product Options Name Sort Order - option_values.php
define('BOX_CATALOG_PRODUCT_OPTIONS_NAME','Option Name Sorter');
// Attributes only
define('BOX_CATALOG_CATEGORIES_ATTRIBUTES_CONTROLLER','Attributes Controller');
// generic model
define('TEXT_MODEL','Model:');
// column controller
define('BOX_TOOLS_LAYOUT_CONTROLLER','Layout Boxes Controller');
// check GV release queue and alert store owner
define('SHOW_GV_QUEUE',true);
define('TEXT_SHOW_GV_QUEUE','%s waiting approval ');
define('IMAGE_GIFT_QUEUE', TEXT_GV_NAME . ' Queue');
define('IMAGE_ORDER','Order');
define('IMAGE_DISPLAY','Display');
define('IMAGE_UPDATE_SORT','Update Sort Order');
define('IMAGE_EDIT_PRODUCT','Edit Product');
define('IMAGE_EDIT_ATTRIBUTES','Edit Attributes');
define('TEXT_NEW_PRODUCT', 'Product in Category: "%s"');
define('IMAGE_OPTIONS_VALUES','Option Names and Option Values');
define('TEXT_PRODUCTS_PRICE_MANAGER','PRODUCTS PRICE MANAGER');
define('TEXT_PRODUCT_EDIT','EDIT PRODUCT');
define('TEXT_ATTRIBUTE_EDIT','EDIT ATTRIBUTES');
define('TEXT_PRODUCT_DETAILS','VIEW DETAILS');
// sale maker
define('DEDUCTION_TYPE_DROPDOWN_0', 'Deduct amount');
define('DEDUCTION_TYPE_DROPDOWN_1', 'Percent');
define('DEDUCTION_TYPE_DROPDOWN_2', 'New Price');
// Min and Units
define('PRODUCTS_QUANTITY_MIN_TEXT_LISTING','Min:');
define('PRODUCTS_QUANTITY_UNIT_TEXT_LISTING','Units:');
define('PRODUCTS_QUANTITY_IN_CART_LISTING','In cart:');
define('PRODUCTS_QUANTITY_ADD_ADDITIONAL_LISTING','Add Additional:');
define('TEXT_PRODUCTS_MIX_OFF','*No Mixed Options');
define('TEXT_PRODUCTS_MIX_ON','*Yes Mixed Options');
// search filters
define('TEXT_INFO_SEARCH_DETAIL_FILTER','Search Filter: ');
define('HEADING_TITLE_SEARCH_DETAIL','Search: ');
define('HEADING_TITLE_SEARCH_DETAIL_REPORTS', 'Search for Product(s) - Delimited by commas');
define('HEADING_TITLE_SEARCH_DETAIL_REPORTS_NAME_MODEL', 'Search for Products Name/Model');
define('PREV_NEXT_PRODUCT', 'Products: ');
define('TEXT_CATEGORIES_STATUS_INFO_OFF', '<span class="alert">*Category is Disabled</span>');
define('TEXT_PRODUCTS_STATUS_INFO_OFF', '<span class="alert">*Product is Disabled</span>');
// admin demo
define('ADMIN_DEMO_ACTIVE','Admin Demo is currently Active. Some settings are will be disabled');
define('ADMIN_DEMO_ACTIVE_EXCLUSION','Admin Demo is currently Active. Some settings are will be disabled - <strong>NOTE: Admin Override Enabled</strong>');
define('ERROR_ADMIN_DEMO','Admin Demo is Active ... the feature(s) you are trying to perform have been disabled');
// Version Check notices
define('TEXT_VERSION_CHECK_NEW_VER','New Version Available v');
define('TEXT_VERSION_CHECK_NEW_PATCH','New PATCH Available: v');
define('TEXT_VERSION_CHECK_PATCH','patch');
define('TEXT_VERSION_CHECK_DOWNLOAD','Download Here');
define('TEXT_VERSION_CHECK_CURRENT','Your version of Zen Cart® appears to be current.');
// downloads manager
define('TEXT_DISPLAY_NUMBER_OF_PRODUCTS_DOWNLOADS_MANAGER', 'Displaying <b>%d</b> to <b>%d</b> (of <b>%d</b> downloads)');
define('BOX_CATALOG_CATEGORIES_ATTRIBUTES_DOWNLOADS_MANAGER', 'Downloads Manager');
define('BOX_CATALOG_FEATURED','Featured Products');
define('ERROR_NOTHING_SELECTED', 'Nothing was selected ... No changes have been made');
define('TEXT_STATUS_WARNING','<strong>NOTE:</strong> status is auto enabled/disabled when dates are set');
define('TEXT_LEGEND_LINKED', 'Linked Product');
define('TEXT_MASTER_CATEGORIES_ID','Product Master Category:');
define('TEXT_LEGEND', 'LEGEND: ');
define('TEXT_LEGEND_STATUS_OFF', 'Status OFF ');
define('TEXT_LEGEND_STATUS_ON', 'Status ON ');
define('TEXT_INFO_MASTER_CATEGORIES_ID', '<strong>NOTE: Master Category is used for pricing purposes where the<br />product category affects the pricing on linked products, example: Sales</strong>');
define('TEXT_YES', 'Yes');
define('TEXT_NO', 'No');
// shipping error messages
define('ERROR_SHIPPING_CONFIGURATION', '<strong>Shipping Configuration errors!</strong>');
define('ERROR_SHIPPING_ORIGIN_ZIP', '<strong>Warning:</strong> Store Zip Code is not defined. See Configuration | Shipping/Packaging to set it.');
define('ERROR_ORDER_WEIGHT_ZERO_STATUS', '<strong>Warning:</strong> 0 weight is configured for Free Shipping and Free Shipping Module is not enabled');
define('ERROR_USPS_STATUS', '<strong>Warning:</strong> USPS shipping module is either missing the username, or it is set to TEST rather than PRODUCTION and will not work.<br />If you cannot retrieve USPS Shipping Quotes, contact USPS to activate your Web Tools account on their production server. 1-800-344-7779 or icustomercare@usps.com');
define('ERROR_SHIPPING_MODULES_NOT_DEFINED', 'NOTE: You have no shipping modules activated. Please go to Modules->Shipping to configure.');
define('ERROR_PAYMENT_MODULES_NOT_DEFINED', 'NOTE: You have no payment modules activated. Please go to Modules->Payment to configure.');
// text pricing
define('TEXT_CHARGES_WORD','Calculated Charge:');
define('TEXT_PER_WORD','<br />Price per word: ');
define('TEXT_WORDS_FREE',' Word(s) free ');
define('TEXT_CHARGES_LETTERS','Calculated Charge:');
define('TEXT_PER_LETTER','<br />Price per letter: ');
define('TEXT_LETTERS_FREE',' Letter(s) free ');
define('TEXT_ONETIME_CHARGES','*onetime charges = ');
define('TEXT_ONETIME_CHARGES_EMAIL',"\t" . '*onetime charges = ');
define('TEXT_ATTRIBUTES_QTY_PRICES_HELP', 'Option Quantity Discounts');
define('TABLE_ATTRIBUTES_QTY_PRICE_QTY','QTY');
define('TABLE_ATTRIBUTES_QTY_PRICE_PRICE','PRICE');
define('TEXT_ATTRIBUTES_QTY_PRICES_ONETIME_HELP', 'Option Quantity Discounts Onetime Charges');
define('TEXT_CATEGORIES_PRODUCTS', 'Select a Category with Products ... Or move between the Products');
define('TEXT_PRODUCT_TO_VIEW', 'Select a Product to View and Press Display ...');
define('TEXT_INFO_SET_MASTER_CATEGORIES_ID', 'Invalid Master Category ID');
define('TEXT_INFO_ID', ' ID# ');
define('TEXT_INFO_SET_MASTER_CATEGORIES_ID_WARNING', '<strong>WARNING:</strong> This product is linked to multiple categories but no master category has been set!');
define('PRODUCTS_PRICE_IS_CALL_FOR_PRICE_TEXT', 'Product is Call for Price');
define('PRODUCTS_PRICE_IS_FREE_TEXT','Product is Free');
define('TEXT_PRODUCT_WEIGHT_UNIT','lbs');
// min, max, units
define('PRODUCTS_QUANTITY_MAX_TEXT_LISTING', 'Max:');
// Discount Savings
define('PRODUCT_PRICE_DISCOUNT_PREFIX','Save: ');
define('PRODUCT_PRICE_DISCOUNT_PERCENTAGE','% off');
define('PRODUCT_PRICE_DISCOUNT_AMOUNT',' off');
// Sale Maker Sale Price
define('PRODUCT_PRICE_SALE','Sale: ');
// Rich Text / HTML resources
define('TEXT_HTML_EDITOR_NOT_DEFINED','If you have no HTML editor defined or JavaScript disabled, you may enter raw HTML text here manually.');
define('TEXT_WARNING_HTML_DISABLED','<span class = "main">Note: You are using TEXT only email. If you would like to send HTML you need to enable "use MIME HTML" under Email Options</span>');
define('TEXT_WARNING_CANT_DISPLAY_HTML','<span class = "main">Note: You are using TEXT only email. If you would like to send HTML you need to enable "use MIME HTML" under Email Options</span>');
define('TEXT_EMAIL_CLIENT_CANT_DISPLAY_HTML',"You're seeing this text because we sent you an email in HTML format but your email client cannot display HTML messages.");
define('ENTRY_EMAIL_PREFERENCE','Email Format Pref:');
define('ENTRY_EMAIL_FORMAT_COMMENTS','Choosing "none" or "optout" disables ALL mail, including order details');
define('ENTRY_EMAIL_HTML_DISPLAY','HTML');
define('ENTRY_EMAIL_TEXT_DISPLAY','TEXT-Only');
define('ENTRY_EMAIL_NONE_DISPLAY','Never');
define('ENTRY_EMAIL_OPTOUT_DISPLAY','Opted Out of Newsletters');
define('ENTRY_NOTHING_TO_SEND','You haven\'t entered any content for your message');
define('EMAIL_SEND_FAILED','ERROR: Failed sending email to: "%s" <%s> with subject: "%s"');
define('EDITOR_NONE', 'Plain Text');
define('TEXT_EDITOR_INFO', 'Text Editor');
define('ERROR_EDITORS_FOLDER_NOT_FOUND', 'You have an HTML editor selected in \'My Store\' but the \'/editors/\' folder cannot be located. Please disable your selection or move your editor files into the \''.DIR_WS_CATALOG.'editors/\' folder');
define('TEXT_CATEGORIES_PRODUCTS_SORT_ORDER_INFO', 'Categories/Product Display Order: ');
define('TEXT_SORT_PRODUCTS_SORT_ORDER_PRODUCTS_NAME', 'Products Sort Order, Products Name');
define('TEXT_SORT_PRODUCTS_NAME', 'Products Name');
define('TEXT_SORT_PRODUCTS_MODEL', 'Products Model');
define('TEXT_SORT_PRODUCTS_QUANTITY', 'Products Qty+, Products Name');
define('TEXT_SORT_PRODUCTS_QUANTITY_DESC', 'Products Qty-, Products Name');
define('TEXT_SORT_PRODUCTS_PRICE', 'Products Price+, Products Name');
define('TEXT_SORT_PRODUCTS_PRICE_DESC', 'Products Price-, Products Name');
define('TEXT_SORT_CATEGORIES_SORT_ORDER_PRODUCTS_NAME', 'Categories Sort Order, Categories Name');
define('TEXT_SORT_CATEGORIES_NAME', 'Categories Name');
define('TABLE_HEADING_YES','Yes');
define('TABLE_HEADING_NO','No');
define('TEXT_PRODUCTS_IMAGE_MANUAL', '<br /><strong>Or, select an existing image file from server, filename:</strong>');
define('TEXT_IMAGES_OVERWRITE', '<br /><strong>Overwrite Existing Image on Server?</strong>');
define('TEXT_IMAGE_OVERWRITE_WARNING','WARNING: FILENAME was updated but not overwritten ');
define('TEXT_IMAGES_DELETE', '<strong>Delete Image?</strong> NOTE: Removes Image from Product, Image is NOT removed from server:');
define('TEXT_IMAGE_CURRENT', 'Image Name: ');
define('ERROR_DEFINE_OPTION_NAMES', 'Warning: No Option Names have been defined');
define('ERROR_DEFINE_OPTION_VALUES', 'Warning: No Option Values have been defined');
define('ERROR_DEFINE_PRODUCTS', 'Warning: No Products have been defined');
define('ERROR_DEFINE_PRODUCTS_MASTER_CATEGORIES_ID', 'Warning: No Master Categories ID has been set for this Product');
define('BUTTON_ADD_PRODUCT_TYPES_SUBCATEGORIES_ON','Add include SubCategories');
define('BUTTON_ADD_PRODUCT_TYPES_SUBCATEGORIES_OFF','Add without SubCategories');
define('BUTTON_PREVIOUS_ALT','Previous Product');
define('BUTTON_NEXT_ALT','Next Product');
define('BUTTON_PRODUCTS_TO_CATEGORIES', 'Multiple Categories Link Manager');
define('BUTTON_PRODUCTS_TO_CATEGORIES_ALT', 'Copy Product to Multiple Categories');
define('TEXT_INFO_OPTION_NAMES_VALUES_COPIER_STATUS', 'All Global Copy, Add and Delete Features Status is currently OFF');
define('TEXT_SHOW_OPTION_NAMES_VALUES_COPIER_ON', 'Display Global Features - ON');
define('TEXT_SHOW_OPTION_NAMES_VALUES_COPIER_OFF', 'Display Global Features - OFF');
// moved from categories and all product type language files
define('ERROR_CANNOT_LINK_TO_SAME_CATEGORY', 'Error: Can not link products in the same category.');
define('ERROR_CATALOG_IMAGE_DIRECTORY_NOT_WRITEABLE', 'Error: Catalog images directory is not writeable: ' . DIR_FS_CATALOG_IMAGES);
define('ERROR_CATALOG_IMAGE_DIRECTORY_DOES_NOT_EXIST', 'Error: Catalog images directory does not exist: ' . DIR_FS_CATALOG_IMAGES);
define('ERROR_CANNOT_MOVE_CATEGORY_TO_PARENT', 'Error: Category cannot be moved into child category.');
define('ERROR_CANNOT_MOVE_PRODUCT_TO_CATEGORY_SELF', 'Error: Cannot move product to the same category or into a category where it already exists.');
define('ERROR_CATEGORY_HAS_PRODUCTS', 'Error: Category has Products!<br /><br />While this can be done temporarily to build your Categories ... Categories hold either Products or Categories but never both!');
define('SUCCESS_CATEGORY_MOVED', 'Success! Category has successfully been moved ...');
define('ERROR_CANNOT_MOVE_CATEGORY_TO_CATEGORY_SELF', 'Error: Cannot move Category to the same Category! ID#');
// EZ-PAGES Alerts
define('TEXT_EZPAGES_STATUS_HEADER_ADMIN', 'WARNING: EZ-PAGES HEADER - On for Admin IP Only');
define('TEXT_EZPAGES_STATUS_FOOTER_ADMIN', 'WARNING: EZ-PAGES FOOTER - On for Admin IP Only');
define('TEXT_EZPAGES_STATUS_SIDEBOX_ADMIN', 'WARNING: EZ-PAGES SIDEBOX - On for Admin IP Only');
// moved from product types
// warnings on Virtual and Always Free Shipping
define('TEXT_VIRTUAL_PREVIEW','Warning: This product is marked - Free Shipping and Skips Shipping Address<br />No shipping will be requested when all products in the order are Virtual Products');
define('TEXT_VIRTUAL_EDIT','Warning: This product is marked - Free Shipping and Skips Shipping Address<br />No shipping will be requested when all products in the order are Virtual Products');
define('TEXT_FREE_SHIPPING_PREVIEW','Warning: This product is marked - Free Shipping, Shipping Address Required<br />Free Shipping Module is required when all products in the order are Always Free Shipping Products');
define('TEXT_FREE_SHIPPING_EDIT','Warning: Yes makes the product - Free Shipping, Shipping Address Required<br />Free Shipping Module is required when all products in the order are Always Free Shipping Products');
// admin activity log warnings
define('WARNING_ADMIN_ACTIVITY_LOG_DATE', 'WARNING: The Admin Activity Log table has records over 2 months old and should be archived to conserve space ... ');
define('WARNING_ADMIN_ACTIVITY_LOG_RECORDS', 'WARNING: The Admin Activity Log table has over 50,000 records and should be archived to conserve space ... ');
define('RESET_ADMIN_ACTIVITY_LOG', 'You can view and archive Admin Activity details via the Admin Access Management menu, if you have appropriate permissions.');
define('CATEGORY_HAS_SUBCATEGORIES', 'NOTE: Category has SubCategories<br />Products cannot be added');
define('WARNING_WELCOME_DISCOUNT_COUPON_EXPIRES_IN', 'WARNING! Welcome Email Discount Coupon expires in %s days');
define('WARNING_ADMIN_FOLDERNAME_VULNERABLE', 'CAUTION: <a href="http://tutorials.zen-cart.com/index.php?article=33" target="_blank">Your /admin/ foldername should be renamed to something less common</a>, to prevent unauthorized access.');
define('WARNING_EMAIL_SYSTEM_DISABLED', 'WARNING: The email subsystem is turned off. No emails will be sent until it is re-enabled in Admin->Configuration->Email Options.');
define('TEXT_CURRENT_VER_IS', 'You are presently using: ');
define('ERROR_NO_DATA_TO_SAVE', 'ERROR: The data you submitted was found to be empty. YOUR CHANGES HAVE *NOT* BEEN SAVED. You may have a problem with your browser or your internet connection.');
define('TEXT_HIDDEN', 'Hidden');
define('TEXT_VISIBLE', 'Visible');
define('TEXT_HIDE', 'Hide');
define('TEXT_EMAIL', 'Email');
define('TEXT_NOEMAIL', 'No Email');
define('BOX_HEADING_PRODUCT_TYPES', 'Product Types');
///////////////////////////////////////////////////////////
// include additional files:
require(DIR_WS_LANGUAGES . $_SESSION['language'] . '/' . FILENAME_EMAIL_EXTRAS);
include(zen_get_file_directory(DIR_FS_CATALOG_LANGUAGES . $_SESSION['language'] . '/', FILENAME_OTHER_IMAGES_NAMES, 'false'));
| gpl-2.0 |
KylePreston/Soft-Hills-Website | wp-content/themes/mckinley/index.php | 1008 | <?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme and one of the
* two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* For example, it puts together the home page when no home.php file exists.
*
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package WordPress
* @subpackage McKinley
* @since McKinley 1.0
*/
get_header(); ?>
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php if ( have_posts() ) : ?>
<?php /* The loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php mckinley_paging_nav(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
</div><!-- #content -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?> | gpl-2.0 |
ctrueden/bioformats | components/forks/jai/src/jj2000/j2k/wavelet/WaveletTransform.java | 5803 | /*
* #%L
* Fork of JAI Image I/O Tools.
* %%
* Copyright (C) 2008 - 2013 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
/*
* $RCSfile: WaveletTransform.java,v $
* $Revision: 1.1 $
* $Date: 2005/02/11 05:02:28 $
* $State: Exp $
*
* Class: WaveletTransform
*
* Description: Interface that defines how a forward or
* inverse wavelet transform should present
* itself.
*
*
*
* COPYRIGHT:
*
* This software module was originally developed by Raphaël Grosbois and
* Diego Santa Cruz (Swiss Federal Institute of Technology-EPFL); Joel
* Askelöf (Ericsson Radio Systems AB); and Bertrand Berthelot, David
* Bouchard, Félix Henry, Gerard Mozelle and Patrice Onno (Canon Research
* Centre France S.A) in the course of development of the JPEG2000
* standard as specified by ISO/IEC 15444 (JPEG 2000 Standard). This
* software module is an implementation of a part of the JPEG 2000
* Standard. Swiss Federal Institute of Technology-EPFL, Ericsson Radio
* Systems AB and Canon Research Centre France S.A (collectively JJ2000
* Partners) agree not to assert against ISO/IEC and users of the JPEG
* 2000 Standard (Users) any of their rights under the copyright, not
* including other intellectual property rights, for this software module
* with respect to the usage by ISO/IEC and Users of this software module
* or modifications thereof for use in hardware or software products
* claiming conformance to the JPEG 2000 Standard. Those intending to use
* this software module in hardware or software products are advised that
* their use may infringe existing patents. The original developers of
* this software module, JJ2000 Partners and ISO/IEC assume no liability
* for use of this software module or modifications thereof. No license
* or right to this software module is granted for non JPEG 2000 Standard
* conforming products. JJ2000 Partners have full right to use this
* software module for his/her own purpose, assign or donate this
* software module to any third party and to inhibit third parties from
* using this software module for non JPEG 2000 Standard conforming
* products. This copyright notice must be included in all copies or
* derivative works of this software module.
*
* Copyright (c) 1999/2000 JJ2000 Partners.
*
*
*
*/
package jj2000.j2k.wavelet;
import jj2000.j2k.image.*;
/**
* This interface defines how a forward or inverse wavelet transform
* should present itself. As specified in the ImgData interface,
* from which this class inherits, all operations are confined to the
* current tile, and all coordinates are relative to it.
*
* <P>The definition of the methods in this interface allows for
* different types of implementation, reversibility and levels of
* decompositions for each component and each tile. An implementation
* of this interface does not need to support all this flexibility
* (e.g., it may provide the same implementation type and
* decomposition levels for all tiles and components).
* */
public interface WaveletTransform extends ImgData {
/**
* ID for line based implementations of wavelet transforms.
*/
public final static int WT_IMPL_LINE = 0;
/**
* ID for full-page based implementations of wavelet transforms. Full-page
* based implementations should be avoided since they require
* large amounts of memory. */
public final static int WT_IMPL_FULL = 2;
/**
* Returns the reversibility of the wavelet transform for the
* specified component and tile. A wavelet transform is reversible
* when it is suitable for lossless and lossy-to-lossless
* compression.
*
* @param t The index of the tile.
*
* @param c The index of the component.
*
* @return true is the wavelet transform is reversible, false if not.
*
*
* */
public boolean isReversible(int t,int c);
/**
* Returns the implementation type of this wavelet transform
* (WT_IMPL_LINE or WT_IMPL_FRAME) for the specified component,
* in the current tile.
*
* @param n The index of the component.
*
* @return WT_IMPL_LINE or WT_IMPL_FULL for line,
* block or full-page based transforms.
*
*
* */
public int getImplementationType(int n);
}
| gpl-2.0 |
kalev/anaconda | pyanaconda/packages.py | 12756 | #
# packages.py: package management - mainly package installation
#
# Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006 Red Hat, Inc.
# All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Author(s): Erik Troan <ewt@redhat.com>
# Matt Wilson <msw@redhat.com>
# Michael Fulbright <msf@redhat.com>
# Jeremy Katz <katzj@redhat.com>
#
import itertools
import glob
import iutil
import isys
import os
import time
import sys
import string
import language
import shutil
import traceback
from flags import flags
from product import *
from constants import *
from upgrade import bindMountDevDirectory
from storage.errors import *
import logging
log = logging.getLogger("anaconda")
import gettext
_ = lambda x: gettext.ldgettext("anaconda", x)
def doPostAction(anaconda):
anaconda.instClass.postAction(anaconda)
def firstbootConfiguration(anaconda):
if anaconda.firstboot == FIRSTBOOT_RECONFIG:
f = open(ROOT_PATH + '/etc/reconfigSys', 'w+')
f.close()
elif anaconda.firstboot == FIRSTBOOT_SKIP:
f = open(ROOT_PATH + '/etc/sysconfig/firstboot', 'w+')
f.write('RUN_FIRSTBOOT=NO')
f.close()
return
def writeKSConfiguration(anaconda):
log.info("Writing autokickstart file")
fn = ROOT_PATH + "/root/anaconda-ks.cfg"
anaconda.writeKS(fn)
def copyAnacondaLogs(anaconda):
log.info("Copying anaconda logs")
if not os.path.isdir (ROOT_PATH + '/var/log/anaconda'):
os.mkdir(ROOT_PATH + '/var/log/anaconda')
for (fn, dest) in (("/tmp/anaconda.log", "anaconda.log"),
("/tmp/syslog", "anaconda.syslog"),
("/tmp/X.log", "anaconda.xlog"),
("/tmp/program.log", "anaconda.program.log"),
("/tmp/storage.log", "anaconda.storage.log"),
("/tmp/ifcfg.log", "anaconda.ifcfg.log"),
("/tmp/yum.log", "anaconda.yum.log")):
if os.access(fn, os.R_OK):
try:
shutil.copyfile(fn, "%s/var/log/anaconda/%s" %(ROOT_PATH, dest))
os.chmod("%s/var/log/anaconda/%s" %(ROOT_PATH, dest), 0600)
except:
pass
def turnOnFilesystems(anaconda):
if anaconda.dir == DISPATCH_BACK:
rc = anaconda.intf.messageWindow(_("Warning"),
_("Filesystems have already been activated. You "
"cannot go back past this point.\n\nWould you like to "
"continue with the installation?"),
type="custom", custom_icon=["error","error"],
custom_buttons=[_("_Exit installer"), _("_Continue")])
if rc == 0:
sys.exit(0)
return DISPATCH_FORWARD
if not anaconda.upgrade:
if (flags.livecdInstall and
not flags.imageInstall and
not anaconda.storage.fsset.active):
# turn off any swaps that we didn't turn on
# needed for live installs
iutil.execWithRedirect("swapoff", ["-a"],
stdout = "/dev/tty5", stderr="/dev/tty5")
anaconda.storage.devicetree.teardownAll()
upgrade_migrate = False
if anaconda.upgrade:
for d in anaconda.storage.migratableDevices:
if d.format.migrate:
upgrade_migrate = True
title = None
message = None
details = None
try:
anaconda.storage.doIt()
except FSResizeError as (msg, device):
title = _("Resizing Failed")
message = _("There was an error encountered while "
"resizing the device %s.") % (device,)
if os.path.exists("/tmp/resize.out"):
details = open("/tmp/resize.out", "r").read()
else:
details = "%s" %(msg,)
except FSMigrateError as (msg, device):
title = _("Migration Failed")
message = _("An error was encountered while "
"migrating filesystem on device %s.") % (device,)
details = msg
except Exception as e:
raise
if title:
rc = anaconda.intf.detailedMessageWindow(title, message, details,
type = "custom",
custom_buttons = [_("_File Bug"), _("_Exit installer")])
if rc == 0:
raise
elif rc == 1:
sys.exit(1)
if not anaconda.upgrade:
anaconda.storage.turnOnSwap()
anaconda.storage.mountFilesystems(raiseErrors=False,
readOnly=False,
skipRoot=anaconda.backend.skipFormatRoot)
else:
if upgrade_migrate:
# we should write out a new fstab with the migrated fstype
shutil.copyfile("%s/etc/fstab" % ROOT_PATH,
"%s/etc/fstab.anaconda" % ROOT_PATH)
anaconda.storage.fsset.write()
# and make sure /dev is mounted so we can read the bootloader
bindMountDevDirectory(ROOT_PATH)
def setupTimezone(anaconda):
# we don't need this on an upgrade or going backwards
if anaconda.upgrade or flags.imageInstall or anaconda.dir == DISPATCH_BACK:
return
os.environ["TZ"] = anaconda.timezone.tz
tzfile = "/usr/share/zoneinfo/" + anaconda.timezone.tz
tzlocalfile = "/etc/localtime"
if not os.access(tzfile, os.R_OK):
log.error("unable to set timezone")
else:
try:
os.remove(tzlocalfile)
except OSError:
pass
try:
shutil.copyfile(tzfile, tzlocalfile)
except OSError as e:
log.error("Error copying timezone (from %s): %s" %(tzfile, e.strerror))
if iutil.isS390():
return
args = [ "--hctosys" ]
if anaconda.timezone.utc:
args.append("-u")
try:
iutil.execWithRedirect("/sbin/hwclock", args, stdin = None,
stdout = "/dev/tty5", stderr = "/dev/tty5")
except RuntimeError:
log.error("Failed to set clock")
# FIXME: this is a huge gross hack. hard coded list of files
# created by anaconda so that we can not be killed by selinux
def setFileCons(anaconda):
def contextCB(arg, directory, files):
for file in files:
path = os.path.join(directory, file)
if not os.access(path, os.R_OK):
log.warning("%s doesn't exist" % path)
continue
# If the path begins with rootPath, matchPathCon will never match
# anything because policy doesn't contain that path.
if path.startswith(ROOT_PATH):
path = path.replace(ROOT_PATH, "")
ret = isys.resetFileContext(path, ROOT_PATH)
if flags.selinux:
log.info("setting SELinux contexts for anaconda created files")
# Add "/mnt/sysimage" to the front of every path so the glob works.
# Then run glob on each element of the list and flatten it into a
# single list we can run contextCB across.
files = itertools.chain(*map(lambda f: glob.glob("%s%s" % (ROOT_PATH, f)),
relabelFiles))
contextCB(None, "", files)
for dir in relabelDirs + ["/dev/%s" % vg.name for vg in anaconda.storage.vgs]:
# Add "/mnt/sysimage" for similar reasons to above.
dir = "%s%s" % (ROOT_PATH, dir)
os.path.walk(dir, contextCB, None)
# os.path.walk won't include the directory we start walking at,
# so that needs its context set separtely.
contextCB(None, "", [dir])
return
# FIXME: using rpm directly here is kind of lame, but in the yum backend
# we don't want to use the metadata as the info we need would require
# the filelists. and since we only ever call this after an install is
# done, we can be guaranteed this will work. put here because it's also
# used for livecd installs
def rpmKernelVersionList():
import rpm
def get_version(header):
for f in header['filenames']:
if f.startswith('/boot/vmlinuz-'):
return f[14:]
elif f.startswith('/boot/efi/EFI/redhat/vmlinuz-'):
return f[29:]
return ""
def get_tag(header):
if header['name'] == "kernel":
return "base"
elif header['name'].startswith("kernel-"):
return header['name'][7:]
return ""
versions = []
iutil.resetRpmDb()
ts = rpm.TransactionSet(ROOT_PATH)
mi = ts.dbMatch('provides', 'kernel')
for h in mi:
v = get_version(h)
tag = get_tag(h)
if v == "" or tag == "":
log.warning("Unable to determine kernel type/version for %s-%s-%s.%s" %(h['name'], h['version'], h['release'], h['arch']))
continue
# rpm really shouldn't return the same kernel more than once... but
# sometimes it does (#467822)
if (v, h['arch'], tag) in versions:
continue
versions.append( (v, h['arch'], tag) )
return versions
def rpmSetupGraphicalSystem(anaconda):
import rpm
iutil.resetRpmDb()
ts = rpm.TransactionSet(ROOT_PATH)
# Only add "rhgb quiet" on non-s390, non-serial installs
if iutil.isConsoleOnVirtualTerminal() and \
(ts.dbMatch('provides', 'rhgb').count() or \
ts.dbMatch('provides', 'plymouth').count()):
anaconda.bootloader.boot_args.update(["rhgb", "quiet"])
if ts.dbMatch('provides', 'service(graphical-login)').count() and \
ts.dbMatch('provides', 'xorg-x11-server-Xorg').count() and \
anaconda.displayMode == 'g' and not flags.usevnc:
anaconda.desktop.setDefaultRunLevel(5)
#Recreate initrd for use when driver disks add modules
def recreateInitrd (kernelTag, instRoot):
log.info("recreating initrd for %s" % (kernelTag,))
iutil.execWithRedirect("/sbin/new-kernel-pkg",
[ "--mkinitrd", "--dracut", "--depmod", "--install", kernelTag ],
stdout = "/dev/null", stderr = "/dev/null",
root = instRoot)
def betaNagScreen(anaconda):
publicBetas = { "Red Hat Linux": "Red Hat Linux Public Beta",
"Red Hat Enterprise Linux": "Red Hat Enterprise Linux Public Beta",
"Fedora Core": "Fedora Core",
"Fedora": "Fedora" }
if anaconda.dir == DISPATCH_BACK:
return DISPATCH_DEFAULT
fileagainst = None
for (key, val) in publicBetas.items():
if productName.startswith(key):
fileagainst = val
if fileagainst is None:
fileagainst = "%s Beta" %(productName,)
while 1:
rc = anaconda.intf.messageWindow(_("Warning"),
_("Warning! This is pre-release software!\n\n"
"Thank you for downloading this "
"pre-release of %(productName)s.\n\n"
"This is not a final "
"release and is not intended for use "
"on production systems. The purpose of "
"this release is to collect feedback "
"from testers, and it is not suitable "
"for day to day usage.\n\n"
"To report feedback, please visit:\n\n"
" %(bugzillaUrl)s\n\n"
"and file a report against '%(fileagainst)s'.\n")
% {'productName': productName,
'bugzillaUrl': bugzillaUrl,
'fileagainst': fileagainst},
type="custom", custom_icon="warning",
custom_buttons=[_("_Exit"), _("_Install Anyway")])
if not rc:
msg = _("Your system will now be rebooted...")
buttons = [_("_Back"), _("_Reboot")]
rc = anaconda.intf.messageWindow( _("Warning! This is pre-release software!"),
msg,
type="custom", custom_icon="warning",
custom_buttons=buttons)
if rc:
sys.exit(0)
else:
break
def doReIPL(anaconda):
if not iutil.isS390() or anaconda.dir == DISPATCH_BACK:
return DISPATCH_DEFAULT
anaconda.reIPLMessage = iutil.reIPL(anaconda, os.getppid())
return DISPATCH_FORWARD
| gpl-2.0 |
viollarr/alab | administrator/components/com_patch/patch/administrator/components/com_menus/wrapper/wrapper.class.php | 3508 | <?php
/**
* @version $Id: wrapper.class.php 10002 2008-02-08 10:56:57Z willebil $
* @package Joomla
* @subpackage Menus
* @copyright Copyright (C) 2005 Open Source Matters. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
// no direct access
defined( '_VALID_MOS' ) or die( 'Restricted access' );
/**
* Wrapper class
* @package Joomla
* @subpackage Menus
*/
class wrapper_menu {
function edit( &$uid, $menutype, $option ) {
global $database, $my, $mainframe;
$menu = new mosMenu( $database );
$menu->load( (int)$uid );
// fail if checked out not by 'me'
if ($menu->checked_out && $menu->checked_out != $my->id) {
mosErrorAlert( "The module ".$menu->title." is currently being edited by another administrator" );
}
if ( $uid ) {
$menu->checkout( $my->id );
} else {
$menu->type = 'wrapper';
$menu->menutype = $menutype;
$menu->ordering = 9999;
$menu->parent = intval( mosGetParam( $_POST, 'parent', 0 ) );
$menu->published = 1;
$menu->link = 'index.php?option=com_wrapper';
}
// build the html select list for ordering
$lists['ordering'] = mosAdminMenus::Ordering( $menu, $uid );
// build the html select list for the group access
$lists['access'] = mosAdminMenus::Access( $menu );
// build the html select list for paraent item
$lists['parent'] = mosAdminMenus::Parent( $menu );
// build published button option
$lists['published'] = mosAdminMenus::Published( $menu );
// build the url link output
$lists['link'] = mosAdminMenus::Link( $menu, $uid );
// get params definitions
$params = new mosParameters( $menu->params, $mainframe->getPath( 'menu_xml', $menu->type ), 'menu' );
if ( $uid ) {
$menu->url = $params->def( 'url', '' );
}
wrapper_menu_html::edit( $menu, $lists, $params, $option );
}
function saveMenu( $option, $task ) {
global $database;
$params = mosGetParam( $_POST, 'params', '' );
$params[url] = mosGetParam( $_POST, 'url', '' );
if (is_array( $params )) {
$txt = array();
foreach ($params as $k=>$v) {
$txt[] = "$k=$v";
}
$_POST['params'] = mosParameters::textareaHandling( $txt );
}
$row = new mosMenu( $database );
if (!$row->bind( $_POST )) {
echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
exit();
}
if (!$row->check()) {
echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
exit();
}
if (!$row->store()) {
echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
exit();
}
$row->checkin();
$row->updateOrder( 'menutype = ' . $database->Quote( $row->menutype ) . ' AND parent = ' . (int) $row->parent );
$msg = 'Menu item Saved';
switch ( $task ) {
case 'apply':
mosRedirect( 'index2.php?option='. $option .'&menutype='. $row->menutype .'&task=edit&id='. $row->id, $msg );
break;
case 'save':
default:
mosRedirect( 'index2.php?option='. $option .'&menutype='. $row->menutype, $msg );
break;
}
}
}
?> | gpl-2.0 |
hekra01/mercurial | hgext/convert/hg.py | 17967 | # hg.py - hg backend for convert extension
#
# Copyright 2005-2009 Matt Mackall <mpm@selenic.com> and others
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
# Notes for hg->hg conversion:
#
# * Old versions of Mercurial didn't trim the whitespace from the ends
# of commit messages, but new versions do. Changesets created by
# those older versions, then converted, may thus have different
# hashes for changesets that are otherwise identical.
#
# * Using "--config convert.hg.saverev=true" will make the source
# identifier to be stored in the converted revision. This will cause
# the converted revision to have a different identity than the
# source.
import os, time, cStringIO
from mercurial.i18n import _
from mercurial.node import bin, hex, nullid
from mercurial import hg, util, context, bookmarks, error, scmutil, exchange
from common import NoRepo, commit, converter_source, converter_sink
import re
sha1re = re.compile(r'\b[0-9a-f]{12,40}\b')
class mercurial_sink(converter_sink):
def __init__(self, ui, path):
converter_sink.__init__(self, ui, path)
self.branchnames = ui.configbool('convert', 'hg.usebranchnames', True)
self.clonebranches = ui.configbool('convert', 'hg.clonebranches', False)
self.tagsbranch = ui.config('convert', 'hg.tagsbranch', 'default')
self.lastbranch = None
if os.path.isdir(path) and len(os.listdir(path)) > 0:
try:
self.repo = hg.repository(self.ui, path)
if not self.repo.local():
raise NoRepo(_('%s is not a local Mercurial repository')
% path)
except error.RepoError, err:
ui.traceback()
raise NoRepo(err.args[0])
else:
try:
ui.status(_('initializing destination %s repository\n') % path)
self.repo = hg.repository(self.ui, path, create=True)
if not self.repo.local():
raise NoRepo(_('%s is not a local Mercurial repository')
% path)
self.created.append(path)
except error.RepoError:
ui.traceback()
raise NoRepo(_("could not create hg repository %s as sink")
% path)
self.lock = None
self.wlock = None
self.filemapmode = False
def before(self):
self.ui.debug('run hg sink pre-conversion action\n')
self.wlock = self.repo.wlock()
self.lock = self.repo.lock()
def after(self):
self.ui.debug('run hg sink post-conversion action\n')
if self.lock:
self.lock.release()
if self.wlock:
self.wlock.release()
def revmapfile(self):
return self.repo.join("shamap")
def authorfile(self):
return self.repo.join("authormap")
def setbranch(self, branch, pbranches):
if not self.clonebranches:
return
setbranch = (branch != self.lastbranch)
self.lastbranch = branch
if not branch:
branch = 'default'
pbranches = [(b[0], b[1] and b[1] or 'default') for b in pbranches]
if pbranches:
pbranch = pbranches[0][1]
else:
pbranch = 'default'
branchpath = os.path.join(self.path, branch)
if setbranch:
self.after()
try:
self.repo = hg.repository(self.ui, branchpath)
except Exception:
self.repo = hg.repository(self.ui, branchpath, create=True)
self.before()
# pbranches may bring revisions from other branches (merge parents)
# Make sure we have them, or pull them.
missings = {}
for b in pbranches:
try:
self.repo.lookup(b[0])
except Exception:
missings.setdefault(b[1], []).append(b[0])
if missings:
self.after()
for pbranch, heads in sorted(missings.iteritems()):
pbranchpath = os.path.join(self.path, pbranch)
prepo = hg.peer(self.ui, {}, pbranchpath)
self.ui.note(_('pulling from %s into %s\n') % (pbranch, branch))
exchange.pull(self.repo, prepo,
[prepo.lookup(h) for h in heads])
self.before()
def _rewritetags(self, source, revmap, data):
fp = cStringIO.StringIO()
for line in data.splitlines():
s = line.split(' ', 1)
if len(s) != 2:
continue
revid = revmap.get(source.lookuprev(s[0]))
if not revid:
if s[0] == hex(nullid):
revid = s[0]
else:
continue
fp.write('%s %s\n' % (revid, s[1]))
return fp.getvalue()
def putcommit(self, files, copies, parents, commit, source, revmap, full,
cleanp2):
files = dict(files)
def getfilectx(repo, memctx, f):
if p2ctx and f in cleanp2 and f not in copies:
self.ui.debug('reusing %s from p2\n' % f)
return p2ctx[f]
try:
v = files[f]
except KeyError:
return None
data, mode = source.getfile(f, v)
if data is None:
return None
if f == '.hgtags':
data = self._rewritetags(source, revmap, data)
return context.memfilectx(self.repo, f, data, 'l' in mode,
'x' in mode, copies.get(f))
pl = []
for p in parents:
if p not in pl:
pl.append(p)
parents = pl
nparents = len(parents)
if self.filemapmode and nparents == 1:
m1node = self.repo.changelog.read(bin(parents[0]))[0]
parent = parents[0]
if len(parents) < 2:
parents.append(nullid)
if len(parents) < 2:
parents.append(nullid)
p2 = parents.pop(0)
text = commit.desc
sha1s = re.findall(sha1re, text)
for sha1 in sha1s:
oldrev = source.lookuprev(sha1)
newrev = revmap.get(oldrev)
if newrev is not None:
text = text.replace(sha1, newrev[:len(sha1)])
extra = commit.extra.copy()
for label in ('source', 'transplant_source', 'rebase_source'):
node = extra.get(label)
if node is None:
continue
# Only transplant stores its reference in binary
if label == 'transplant_source':
node = hex(node)
newrev = revmap.get(node)
if newrev is not None:
if label == 'transplant_source':
newrev = bin(newrev)
extra[label] = newrev
if self.branchnames and commit.branch:
extra['branch'] = commit.branch
if commit.rev:
extra['convert_revision'] = commit.rev
while parents:
p1 = p2
p2 = parents.pop(0)
p2ctx = None
if p2 != nullid:
p2ctx = self.repo[p2]
fileset = set(files)
if full:
fileset.update(self.repo[p1])
fileset.update(self.repo[p2])
ctx = context.memctx(self.repo, (p1, p2), text, fileset,
getfilectx, commit.author, commit.date, extra)
self.repo.commitctx(ctx)
text = "(octopus merge fixup)\n"
p2 = hex(self.repo.changelog.tip())
if self.filemapmode and nparents == 1:
man = self.repo.manifest
mnode = self.repo.changelog.read(bin(p2))[0]
closed = 'close' in commit.extra
if not closed and not man.cmp(m1node, man.revision(mnode)):
self.ui.status(_("filtering out empty revision\n"))
self.repo.rollback(force=True)
return parent
return p2
def puttags(self, tags):
try:
parentctx = self.repo[self.tagsbranch]
tagparent = parentctx.node()
except error.RepoError:
parentctx = None
tagparent = nullid
oldlines = set()
for branch, heads in self.repo.branchmap().iteritems():
for h in heads:
if '.hgtags' in self.repo[h]:
oldlines.update(
set(self.repo[h]['.hgtags'].data().splitlines(True)))
oldlines = sorted(list(oldlines))
newlines = sorted([("%s %s\n" % (tags[tag], tag)) for tag in tags])
if newlines == oldlines:
return None, None
# if the old and new tags match, then there is nothing to update
oldtags = set()
newtags = set()
for line in oldlines:
s = line.strip().split(' ', 1)
if len(s) != 2:
continue
oldtags.add(s[1])
for line in newlines:
s = line.strip().split(' ', 1)
if len(s) != 2:
continue
if s[1] not in oldtags:
newtags.add(s[1].strip())
if not newtags:
return None, None
data = "".join(newlines)
def getfilectx(repo, memctx, f):
return context.memfilectx(repo, f, data, False, False, None)
self.ui.status(_("updating tags\n"))
date = "%s 0" % int(time.mktime(time.gmtime()))
extra = {'branch': self.tagsbranch}
ctx = context.memctx(self.repo, (tagparent, None), "update tags",
[".hgtags"], getfilectx, "convert-repo", date,
extra)
self.repo.commitctx(ctx)
return hex(self.repo.changelog.tip()), hex(tagparent)
def setfilemapmode(self, active):
self.filemapmode = active
def putbookmarks(self, updatedbookmark):
if not len(updatedbookmark):
return
self.ui.status(_("updating bookmarks\n"))
destmarks = self.repo._bookmarks
for bookmark in updatedbookmark:
destmarks[bookmark] = bin(updatedbookmark[bookmark])
destmarks.write()
def hascommitfrommap(self, rev):
# the exact semantics of clonebranches is unclear so we can't say no
return rev in self.repo or self.clonebranches
def hascommitforsplicemap(self, rev):
if rev not in self.repo and self.clonebranches:
raise util.Abort(_('revision %s not found in destination '
'repository (lookups with clonebranches=true '
'are not implemented)') % rev)
return rev in self.repo
class mercurial_source(converter_source):
def __init__(self, ui, path, rev=None):
converter_source.__init__(self, ui, path, rev)
self.ignoreerrors = ui.configbool('convert', 'hg.ignoreerrors', False)
self.ignored = set()
self.saverev = ui.configbool('convert', 'hg.saverev', False)
try:
self.repo = hg.repository(self.ui, path)
# try to provoke an exception if this isn't really a hg
# repo, but some other bogus compatible-looking url
if not self.repo.local():
raise error.RepoError
except error.RepoError:
ui.traceback()
raise NoRepo(_("%s is not a local Mercurial repository") % path)
self.lastrev = None
self.lastctx = None
self._changescache = None, None
self.convertfp = None
# Restrict converted revisions to startrev descendants
startnode = ui.config('convert', 'hg.startrev')
hgrevs = ui.config('convert', 'hg.revs')
if hgrevs is None:
if startnode is not None:
try:
startnode = self.repo.lookup(startnode)
except error.RepoError:
raise util.Abort(_('%s is not a valid start revision')
% startnode)
startrev = self.repo.changelog.rev(startnode)
children = {startnode: 1}
for r in self.repo.changelog.descendants([startrev]):
children[self.repo.changelog.node(r)] = 1
self.keep = children.__contains__
else:
self.keep = util.always
if rev:
self._heads = [self.repo[rev].node()]
else:
self._heads = self.repo.heads()
else:
if rev or startnode is not None:
raise util.Abort(_('hg.revs cannot be combined with '
'hg.startrev or --rev'))
nodes = set()
parents = set()
for r in scmutil.revrange(self.repo, [hgrevs]):
ctx = self.repo[r]
nodes.add(ctx.node())
parents.update(p.node() for p in ctx.parents())
self.keep = nodes.__contains__
self._heads = nodes - parents
def changectx(self, rev):
if self.lastrev != rev:
self.lastctx = self.repo[rev]
self.lastrev = rev
return self.lastctx
def parents(self, ctx):
return [p for p in ctx.parents() if p and self.keep(p.node())]
def getheads(self):
return [hex(h) for h in self._heads if self.keep(h)]
def getfile(self, name, rev):
try:
fctx = self.changectx(rev)[name]
return fctx.data(), fctx.flags()
except error.LookupError:
return None, None
def getchanges(self, rev, full):
ctx = self.changectx(rev)
parents = self.parents(ctx)
if full or not parents:
files = copyfiles = ctx.manifest()
if parents:
if self._changescache[0] == rev:
m, a, r = self._changescache[1]
else:
m, a, r = self.repo.status(parents[0].node(), ctx.node())[:3]
if not full:
files = m + a + r
copyfiles = m + a
# getcopies() is also run for roots and before filtering so missing
# revlogs are detected early
copies = self.getcopies(ctx, parents, copyfiles)
cleanp2 = set()
if len(parents) == 2:
cleanp2.update(self.repo.status(parents[1].node(), ctx.node(),
clean=True).clean)
changes = [(f, rev) for f in files if f not in self.ignored]
changes.sort()
return changes, copies, cleanp2
def getcopies(self, ctx, parents, files):
copies = {}
for name in files:
if name in self.ignored:
continue
try:
copysource, _copynode = ctx.filectx(name).renamed()
if copysource in self.ignored:
continue
# Ignore copy sources not in parent revisions
found = False
for p in parents:
if copysource in p:
found = True
break
if not found:
continue
copies[name] = copysource
except TypeError:
pass
except error.LookupError, e:
if not self.ignoreerrors:
raise
self.ignored.add(name)
self.ui.warn(_('ignoring: %s\n') % e)
return copies
def getcommit(self, rev):
ctx = self.changectx(rev)
parents = [p.hex() for p in self.parents(ctx)]
if self.saverev:
crev = rev
else:
crev = None
return commit(author=ctx.user(),
date=util.datestr(ctx.date(), '%Y-%m-%d %H:%M:%S %1%2'),
desc=ctx.description(), rev=crev, parents=parents,
branch=ctx.branch(), extra=ctx.extra(),
sortkey=ctx.rev())
def gettags(self):
# This will get written to .hgtags, filter non global tags out.
tags = [t for t in self.repo.tagslist()
if self.repo.tagtype(t[0]) == 'global']
return dict([(name, hex(node)) for name, node in tags
if self.keep(node)])
def getchangedfiles(self, rev, i):
ctx = self.changectx(rev)
parents = self.parents(ctx)
if not parents and i is None:
i = 0
changes = [], ctx.manifest().keys(), []
else:
i = i or 0
changes = self.repo.status(parents[i].node(), ctx.node())[:3]
changes = [[f for f in l if f not in self.ignored] for l in changes]
if i == 0:
self._changescache = (rev, changes)
return changes[0] + changes[1] + changes[2]
def converted(self, rev, destrev):
if self.convertfp is None:
self.convertfp = open(self.repo.join('shamap'), 'a')
self.convertfp.write('%s %s\n' % (destrev, rev))
self.convertfp.flush()
def before(self):
self.ui.debug('run hg source pre-conversion action\n')
def after(self):
self.ui.debug('run hg source post-conversion action\n')
def hasnativeorder(self):
return True
def hasnativeclose(self):
return True
def lookuprev(self, rev):
try:
return hex(self.repo.lookup(rev))
except (error.RepoError, error.LookupError):
return None
def getbookmarks(self):
return bookmarks.listbookmarks(self.repo)
def checkrevformat(self, revstr, mapname='splicemap'):
""" Mercurial, revision string is a 40 byte hex """
self.checkhexformat(revstr, mapname)
| gpl-2.0 |
drazenzadravec/nequeo | Cross/Mono/Components/Cryptography/Nequeo.Cryptography/Nequeo.Cryptography.Key/crypto/macs/HMac.cs | 3279 | using System;
using System.Collections;
using Nequeo.Cryptography.Key.Crypto;
using Nequeo.Cryptography.Key.Crypto.Parameters;
namespace Nequeo.Cryptography.Key.Crypto.Macs
{
/**
* HMAC implementation based on RFC2104
*
* H(K XOR opad, H(K XOR ipad, text))
*/
public class HMac
: IMac
{
private const byte IPAD = (byte)0x36;
private const byte OPAD = (byte)0x5C;
private readonly IDigest digest;
private readonly int digestSize;
private readonly int blockLength;
private readonly byte[] inputPad;
private readonly byte[] outputPad;
public HMac(
IDigest digest)
{
this.digest = digest;
this.digestSize = digest.GetDigestSize();
this.blockLength = digest.GetByteLength();
this.inputPad = new byte[blockLength];
this.outputPad = new byte[blockLength];
}
public string AlgorithmName
{
get { return digest.AlgorithmName + "/HMAC"; }
}
public IDigest GetUnderlyingDigest()
{
return digest;
}
public void Init(
ICipherParameters parameters)
{
digest.Reset();
byte[] key = ((KeyParameter)parameters).GetKey();
int keyLength = key.Length;
if (keyLength > blockLength)
{
digest.BlockUpdate(key, 0, key.Length);
digest.DoFinal(inputPad, 0);
keyLength = digestSize;
}
else
{
Array.Copy(key, 0, inputPad, 0, keyLength);
}
Array.Clear(inputPad, keyLength, blockLength - keyLength);
Array.Copy(inputPad, 0, outputPad, 0, blockLength);
xor(inputPad, IPAD);
xor(outputPad, OPAD);
// Initialise the digest
digest.BlockUpdate(inputPad, 0, inputPad.Length);
}
public int GetMacSize()
{
return digestSize;
}
public void Update(
byte input)
{
digest.Update(input);
}
public void BlockUpdate(
byte[] input,
int inOff,
int len)
{
digest.BlockUpdate(input, inOff, len);
}
public int DoFinal(
byte[] output,
int outOff)
{
byte[] tmp = new byte[digestSize];
digest.DoFinal(tmp, 0);
digest.BlockUpdate(outputPad, 0, outputPad.Length);
digest.BlockUpdate(tmp, 0, tmp.Length);
int len = digest.DoFinal(output, outOff);
// Initialise the digest
digest.BlockUpdate(inputPad, 0, inputPad.Length);
return len;
}
/**
* Reset the mac generator.
*/
public void Reset()
{
// Reset underlying digest
digest.Reset();
// Initialise the digest
digest.BlockUpdate(inputPad, 0, inputPad.Length);
}
private static void xor(byte[] a, byte n)
{
for (int i = 0; i < a.Length; ++i)
{
a[i] ^= n;
}
}
}
}
| gpl-2.0 |
diamonddevgroup/CodenameOne | Samples/samples/GradientTest/GradientTest.java | 1983 | package com.codename1.samples;
import static com.codename1.ui.CN.*;
import com.codename1.ui.Display;
import com.codename1.ui.Form;
import com.codename1.ui.Dialog;
import com.codename1.ui.Label;
import com.codename1.ui.plaf.UIManager;
import com.codename1.ui.util.Resources;
import com.codename1.io.Log;
import com.codename1.ui.Toolbar;
import java.io.IOException;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.io.NetworkEvent;
/**
* This file was generated by <a href="https://www.codenameone.com/">Codename One</a> for the purpose
* of building native mobile applications using Java.
*/
public class GradientTest {
private Form current;
private Resources theme;
public void init(Object context) {
// use two network threads instead of one
updateNetworkThreadCount(2);
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature
Log.bindCrashProtection(true);
addNetworkErrorListener(err -> {
// prevent the event from propagating
err.consume();
if(err.getError() != null) {
Log.e(err.getError());
}
Log.sendLogAsync();
Dialog.show("Connection Error", "There was a networking error in the connection to " + err.getConnectionRequest().getUrl(), "OK", null);
});
}
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("Hi World", BoxLayout.y());
hi.getContentPane().setUIID("Gradient");
hi.add(new Label("Hi World"));
hi.show();
}
public void stop() {
current = getCurrentForm();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = getCurrentForm();
}
}
public void destroy() {
}
}
| gpl-2.0 |
glazzara/olena | scribo/scribo/primitive/link/with_single_left_link_dmax_ratio_aligned.hh | 6035 | // Copyright (C) 2009, 2010, 2011, 2013 EPITA Research and Development
// Laboratory (LRDE)
//
// This file is part of Olena.
//
// Olena is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation, version 2 of the License.
//
// Olena is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Olena. If not, see <http://www.gnu.org/licenses/>.
//
// As a special exception, you may use this file as part of a free
// software project without restriction. Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to produce
// an executable, this file does not by itself cause the resulting
// executable to be covered by the GNU General Public License. This
// exception does not however invalidate any other reasons why the
// executable file might be covered by the GNU General Public License.
#ifndef SCRIBO_PRIMITIVE_LINK_WITH_SINGLE_LEFT_LINK_DMAX_RATIO_ALIGNED_HH
# define SCRIBO_PRIMITIVE_LINK_WITH_SINGLE_LEFT_LINK_DMAX_RATIO_ALIGNED_HH
/// \file
///
/// \brief Link text objects with their left neighbor according to a
/// maximum distance.
# include <mln/core/concept/image.hh>
# include <mln/core/concept/neighborhood.hh>
# include <mln/accu/center.hh>
# include <mln/labeling/compute.hh>
# include <mln/math/abs.hh>
# include <mln/util/array.hh>
# include <scribo/core/macros.hh>
# include <scribo/core/component_set.hh>
# include <scribo/core/object_links.hh>
# include <scribo/primitive/link/internal/dmax_default.hh>
# include <scribo/primitive/link/internal/find_link.hh>
# include <scribo/primitive/link/internal/link_single_dmax_ratio_aligned_base.hh>
# include <scribo/primitive/link/compute.hh>
# include <scribo/filter/internal/component_aligned.hh>
namespace scribo
{
namespace primitive
{
namespace link
{
/*! \brief Link objects with their left neighbor if exists.
\param[in] components A component set.
\param[in] dmax_f A function defining the maximum lookup
distance.
\param[in] min_angle Minimum difference allowed for
alignement angle.
\param[in] max_angle Maximum difference allowed for
alignement angle.
\param[in] anchor Starting point for the neighbor lookup.
\return Object links data.
Look for a neighbor until a maximum distance defined by :
dmax = w / 2 + dmax_ratio * max(h, w)
where w is the bounding box width and h the bounding box height.
*/
template <typename L, typename F>
inline
object_links<L>
with_single_left_link_dmax_ratio_aligned(
const component_set<L>& components,
const DMax_Functor<F>& dmax_f,
float min_angle, float max_angle,
anchor::Type anchor);
/// \overload
/// anchor is set to MassCenter.
/// dmax_f functor is set to internal::dmax_default.
//
template <typename L>
inline
object_links<L>
with_single_left_link_dmax_ratio_aligned(
const component_set<L>& components,
float dmax_ratio,
float min_angle, float max_angle);
/// \overload
/// dmax_ratio is set to 3.
/// anchor is set to MassCenter.
//
template <typename L>
inline
object_links<L>
with_single_left_link_dmax_ratio_aligned(
const component_set<L>& components);
# ifndef MLN_INCLUDE_ONLY
namespace internal
{
// Functor
template <typename L, typename F>
class single_left_dmax_ratio_aligned_functor
: public link_single_dmax_ratio_aligned_base<L, F, single_left_dmax_ratio_aligned_functor<L,F> >
{
typedef single_left_dmax_ratio_aligned_functor<L,F> self_t;
typedef link_single_dmax_ratio_aligned_base<L, F, self_t> super_;
public:
typedef mln_site(L) P;
single_left_dmax_ratio_aligned_functor(
const component_set<L>& components,
const DMax_Functor<F>& dmax_f,
float min_angle,
float max_angle,
anchor::Type anchor)
: super_(components, dmax_f, min_angle,
max_angle, anchor)
{
}
void compute_next_site_(P& p)
{
--p.col();
}
};
} // end of namespace scribo::primitive::link::internal
// Facades
template <typename L, typename F>
inline
object_links<L>
with_single_left_link_dmax_ratio_aligned(
const component_set<L>& components,
const DMax_Functor<F>& dmax_f,
float min_angle, float max_angle,
anchor::Type anchor)
{
mln_trace("scribo::primitive::link::with_single_left_link_dmax_ratio_aligned");
mln_precondition(components.is_valid());
internal::single_left_dmax_ratio_aligned_functor<L,F>
functor(components, dmax_f, min_angle, max_angle, anchor);
object_links<L> output = compute(functor, anchor);
return output;
}
template <typename L>
inline
object_links<L>
with_single_left_link_dmax_ratio_aligned(
const component_set<L>& components,
float dmax_ratio,
float min_angle, float max_angle)
{
return
with_single_left_link_dmax_ratio_aligned(components,
internal::dmax_default(dmax_ratio),
min_angle,
max_angle,
anchor::MassCenter);
}
template <typename L>
inline
object_links<L>
with_single_left_link_dmax_ratio_aligned(
const component_set<L>& components)
{
return
with_single_left_link_dmax_ratio_aligned(components, 3, 3, 10);
}
# endif // ! MLN_INCLUDE_ONLY
} // end of namespace scribo::primitive::link
} // end of namespace scribo::primitive
} // end of namespace scribo
#endif // ! SCRIBO_PRIMITIVE_LINK_WITH_SINGLE_LEFT_LINK_DMAX_RATIO_ALIGNED_HH
| gpl-2.0 |
chrisws/scummvm | engines/kyra/sound_digital.cpp | 13663 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "kyra/sound.h"
#include "kyra/resource.h"
#include "kyra/kyra_mr.h"
#include "audio/audiostream.h"
#include "audio/decoders/mp3.h"
#include "audio/decoders/vorbis.h"
#include "audio/decoders/flac.h"
namespace Kyra {
class KyraAudioStream : public Audio::SeekableAudioStream {
public:
KyraAudioStream(Audio::SeekableAudioStream *impl) : _impl(impl), _rate(impl->getRate()), _fadeSamples(0), _fadeCount(0), _fading(0), _endOfData(false) {}
~KyraAudioStream() { delete _impl; _impl = 0; }
int readBuffer(int16 *buffer, const int numSamples);
bool isStereo() const { return _impl->isStereo(); }
bool endOfData() const { return _impl->endOfData() | _endOfData; }
int getRate() const { return _rate; }
void setRate(int newRate) { _rate = newRate; }
void beginFadeOut(uint32 millis);
bool seek(const Audio::Timestamp &where) { return _impl->seek(where); }
Audio::Timestamp getLength() const { return _impl->getLength(); }
private:
Audio::SeekableAudioStream *_impl;
int _rate;
int32 _fadeSamples;
int32 _fadeCount;
int _fading;
bool _endOfData;
};
void KyraAudioStream::beginFadeOut(uint32 millis) {
_fadeSamples = (millis * getRate()) / 1000;
if (_fading == 0)
_fadeCount = _fadeSamples;
_fading = -1;
}
int KyraAudioStream::readBuffer(int16 *buffer, const int numSamples) {
int samplesRead = _impl->readBuffer(buffer, numSamples);
if (_fading) {
int samplesProcessed = 0;
for (; samplesProcessed < samplesRead; ++samplesProcessed) {
// To help avoid overflows for long fade times, we divide both
// _fadeSamples and _fadeCount when calculating the new sample.
int32 div = _fadeSamples / 256;
if (_fading) {
*buffer = (*buffer * (_fadeCount / 256)) / div;
++buffer;
_fadeCount += _fading;
if (_fadeCount < 0) {
_fadeCount = 0;
_endOfData = true;
} else if (_fadeCount > _fadeSamples) {
_fadeCount = _fadeSamples;
_fading = 0;
}
}
}
if (_endOfData) {
memset(buffer, 0, (samplesRead - samplesProcessed) * sizeof(int16));
samplesRead = samplesProcessed;
}
}
return samplesRead;
}
// Thanks to Torbjorn Andersson (eriktorbjorn) for his aud player on which
// this code is based on
// TODO: cleanup of whole AUDStream
class AUDStream : public Audio::SeekableAudioStream {
public:
AUDStream(Common::SeekableReadStream *stream);
~AUDStream();
int readBuffer(int16 *buffer, const int numSamples);
bool isStereo() const { return false; }
bool endOfData() const { return _endOfData; }
int getRate() const { return _rate; }
bool seek(const Audio::Timestamp &where);
Audio::Timestamp getLength() const { return _length; }
private:
Common::SeekableReadStream *_stream;
uint32 _streamStart;
bool _endOfData;
int _rate;
uint _processedSize;
uint _totalSize;
Audio::Timestamp _length;
int _bytesLeft;
byte *_outBuffer;
int _outBufferOffset;
uint _outBufferSize;
byte *_inBuffer;
uint _inBufferSize;
int readChunk(int16 *buffer, const int maxSamples);
static const int8 WSTable2Bit[];
static const int8 WSTable4Bit[];
};
const int8 AUDStream::WSTable2Bit[] = { -2, -1, 0, 1 };
const int8 AUDStream::WSTable4Bit[] = {
-9, -8, -6, -5, -4, -3, -2, -1,
0, 1, 2, 3, 4, 5, 6, 8
};
AUDStream::AUDStream(Common::SeekableReadStream *stream) : _stream(stream), _endOfData(true), _rate(0),
_processedSize(0), _totalSize(0), _length(0, 1), _bytesLeft(0), _outBuffer(0),
_outBufferOffset(0), _outBufferSize(0), _inBuffer(0), _inBufferSize(0) {
_rate = _stream->readUint16LE();
_totalSize = _stream->readUint32LE();
// TODO?: add checks
int flags = _stream->readByte(); // flags
int type = _stream->readByte(); // type
_streamStart = stream->pos();
debugC(5, kDebugLevelSound, "AUD Info: rate: %d, totalSize: %d, flags: %d, type: %d, streamStart: %d", _rate, _totalSize, flags, type, _streamStart);
_length = Audio::Timestamp(0, _rate);
for (uint32 i = 0; i < _totalSize;) {
uint16 size = _stream->readUint16LE();
uint16 outSize = _stream->readUint16LE();
_length = _length.addFrames(outSize);
stream->seek(size + 4, SEEK_CUR);
i += size + 8;
}
stream->seek(_streamStart, SEEK_SET);
if (type == 1 && !flags)
_endOfData = false;
else
warning("No AUD file (rate: %d, size: %d, flags: 0x%X, type: %d)", _rate, _totalSize, flags, type);
}
AUDStream::~AUDStream() {
delete[] _outBuffer;
delete[] _inBuffer;
delete _stream;
}
int AUDStream::readBuffer(int16 *buffer, const int numSamples) {
int samplesRead = 0, samplesLeft = numSamples;
while (samplesLeft > 0 && !_endOfData) {
int samples = readChunk(buffer, samplesLeft);
samplesRead += samples;
samplesLeft -= samples;
buffer += samples;
}
return samplesRead;
}
inline int16 clip8BitSample(int16 sample) {
if (sample > 255)
return 255;
if (sample < 0)
return 0;
return sample;
}
int AUDStream::readChunk(int16 *buffer, const int maxSamples) {
int samplesProcessed = 0;
// if no bytes of the old chunk are left, read the next one
if (_bytesLeft <= 0) {
if (_processedSize >= _totalSize) {
_endOfData = true;
return 0;
}
uint16 size = _stream->readUint16LE();
uint16 outSize = _stream->readUint16LE();
uint32 id = _stream->readUint32LE();
assert(id == 0x0000DEAF);
_processedSize += 8 + size;
_outBufferOffset = 0;
if (size == outSize) {
if (outSize > _outBufferSize) {
_outBufferSize = outSize;
delete[] _outBuffer;
_outBuffer = new uint8[_outBufferSize];
assert(_outBuffer);
}
_bytesLeft = size;
_stream->read(_outBuffer, _bytesLeft);
} else {
_bytesLeft = outSize;
if (outSize > _outBufferSize) {
_outBufferSize = outSize;
delete[] _outBuffer;
_outBuffer = new uint8[_outBufferSize];
assert(_outBuffer);
}
if (size > _inBufferSize) {
_inBufferSize = size;
delete[] _inBuffer;
_inBuffer = new uint8[_inBufferSize];
assert(_inBuffer);
}
if (_stream->read(_inBuffer, size) != size) {
_endOfData = true;
return 0;
}
int16 curSample = 0x80;
byte code = 0;
int8 count = 0;
uint16 input = 0;
int j = 0;
int i = 0;
while (outSize > 0) {
input = _inBuffer[i++] << 2;
code = (input >> 8) & 0xff;
count = (input & 0xff) >> 2;
switch (code) {
case 2:
if (count & 0x20) {
/* NOTE: count is signed! */
count <<= 3;
curSample += (count >> 3);
_outBuffer[j++] = curSample & 0xFF;
outSize--;
} else {
for (; count >= 0; count--) {
_outBuffer[j++] = _inBuffer[i++];
outSize--;
}
curSample = _inBuffer[i - 1];
}
break;
case 1:
for (; count >= 0; count--) {
code = _inBuffer[i++];
curSample += WSTable4Bit[code & 0x0f];
curSample = clip8BitSample(curSample);
_outBuffer[j++] = curSample;
curSample += WSTable4Bit[code >> 4];
curSample = clip8BitSample(curSample);
_outBuffer[j++] = curSample;
outSize -= 2;
}
break;
case 0:
for (; count >= 0; count--) {
code = (uint8)_inBuffer[i++];
curSample += WSTable2Bit[code & 0x03];
curSample = clip8BitSample(curSample);
_outBuffer[j++] = curSample & 0xFF;
curSample += WSTable2Bit[(code >> 2) & 0x03];
curSample = clip8BitSample(curSample);
_outBuffer[j++] = curSample & 0xFF;
curSample += WSTable2Bit[(code >> 4) & 0x03];
curSample = clip8BitSample(curSample);
_outBuffer[j++] = curSample & 0xFF;
curSample += WSTable2Bit[(code >> 6) & 0x03];
curSample = clip8BitSample(curSample);
_outBuffer[j++] = curSample & 0xFF;
outSize -= 4;
}
break;
default:
for (; count >= 0; count--) {
_outBuffer[j++] = curSample & 0xFF;
outSize--;
}
}
}
}
}
// copies the chunk data to the output buffer
if (_bytesLeft > 0) {
int samples = MIN(_bytesLeft, maxSamples);
samplesProcessed += samples;
_bytesLeft -= samples;
while (samples--) {
int16 sample = (_outBuffer[_outBufferOffset++] << 8) ^ 0x8000;
*buffer++ = sample;
}
}
return samplesProcessed;
}
bool AUDStream::seek(const Audio::Timestamp &where) {
const uint32 seekSample = Audio::convertTimeToStreamPos(where, getRate(), isStereo()).totalNumberOfFrames();
_stream->seek(_streamStart);
_processedSize = 0;
_bytesLeft = 0;
_endOfData = false;
uint32 curSample = 0;
while (!endOfData()) {
uint16 size = _stream->readUint16LE();
uint16 outSize = _stream->readUint16LE();
if (curSample + outSize > seekSample) {
_stream->seek(-4, SEEK_CUR);
uint32 samples = seekSample - curSample;
int16 *temp = new int16[samples];
assert(temp);
readChunk(temp, samples);
delete[] temp;
curSample += samples;
break;
} else {
curSample += outSize;
_processedSize += 8 + size;
_stream->seek(size + 4, SEEK_CUR);
}
}
_endOfData = (_processedSize >= _totalSize);
return (curSample == seekSample);
}
#pragma mark -
SoundDigital::SoundDigital(KyraEngine_MR *vm, Audio::Mixer *mixer) : _vm(vm), _mixer(mixer) {
for (uint i = 0; i < ARRAYSIZE(_sounds); ++i)
_sounds[i].stream = 0;
}
SoundDigital::~SoundDigital() {
for (int i = 0; i < ARRAYSIZE(_sounds); ++i)
stopSound(i);
}
int SoundDigital::playSound(const char *filename, uint8 priority, Audio::Mixer::SoundType type, int volume, bool loop, int channel) {
Sound *use = 0;
if (channel != -1 && channel < ARRAYSIZE(_sounds)) {
stopSound(channel);
use = &_sounds[channel];
} else {
for (channel = 0; !use && channel < ARRAYSIZE(_sounds); ++channel) {
if (!isPlaying(channel)) {
stopSound(channel);
use = &_sounds[channel];
break;
}
}
for (channel = 0; !use && channel < ARRAYSIZE(_sounds); ++channel) {
if (strcmp(_sounds[channel].filename, filename) == 0) {
stopSound(channel);
use = &_sounds[channel];
break;
}
}
for (channel = 0; !use && channel < ARRAYSIZE(_sounds); ++channel) {
if (_sounds[channel].priority <= priority) {
stopSound(channel);
use = &_sounds[channel];
break;
}
}
if (!use) {
warning("no free sound channel");
return -1;
}
}
Common::SeekableReadStream *stream = 0;
int usedCodec = -1;
for (int i = 0; _supportedCodecs[i].fileext; ++i) {
Common::String file = filename;
file += _supportedCodecs[i].fileext;
if (!_vm->resource()->exists(file.c_str()))
continue;
stream = _vm->resource()->createReadStream(file);
usedCodec = i;
}
if (!stream) {
warning("Couldn't find soundfile '%s'", filename);
return -1;
}
Common::strlcpy(use->filename, filename, sizeof(use->filename));
use->priority = priority;
debugC(5, kDebugLevelSound, "playSound: \"%s\"", use->filename);
Audio::SeekableAudioStream *audioStream = _supportedCodecs[usedCodec].streamFunc(stream, DisposeAfterUse::YES);
if (!audioStream) {
warning("Couldn't create audio stream for file '%s'", filename);
return -1;
}
use->stream = new KyraAudioStream(audioStream);
assert(use->stream);
if (use->stream->endOfData()) {
delete use->stream;
use->stream = 0;
return -1;
}
if (volume > 255)
volume = 255;
volume = (volume * Audio::Mixer::kMaxChannelVolume) / 255;
if (type == Audio::Mixer::kSpeechSoundType && _vm->heliumMode())
use->stream->setRate(32765);
_mixer->playStream(type, &use->handle, makeLoopingAudioStream(use->stream, loop ? 0 : 1), -1, volume);
return use - _sounds;
}
bool SoundDigital::isPlaying(int channel) {
if (channel == -1)
return false;
assert(channel >= 0 && channel < ARRAYSIZE(_sounds));
if (!_sounds[channel].stream)
return false;
return _mixer->isSoundHandleActive(_sounds[channel].handle);
}
void SoundDigital::stopSound(int channel) {
if (channel == -1)
return;
assert(channel >= 0 && channel < ARRAYSIZE(_sounds));
_mixer->stopHandle(_sounds[channel].handle);
_sounds[channel].stream = 0;
}
void SoundDigital::stopAllSounds() {
for (int i = 0; i < ARRAYSIZE(_sounds); ++i) {
if (isPlaying(i))
stopSound(i);
}
}
void SoundDigital::beginFadeOut(int channel, int ticks) {
if (isPlaying(channel))
_sounds[channel].stream->beginFadeOut(ticks * _vm->tickLength());
}
// static res
namespace {
Audio::SeekableAudioStream *makeAUDStream(Common::SeekableReadStream *stream, DisposeAfterUse::Flag disposeAfterUse) {
return new AUDStream(stream);
}
} // end of anonymous namespace
const SoundDigital::AudioCodecs SoundDigital::_supportedCodecs[] = {
#ifdef USE_FLAC
{ ".FLA", Audio::makeFLACStream },
#endif // USE_FLAC
#ifdef USE_VORBIS
{ ".OGG", Audio::makeVorbisStream },
#endif // USE_VORBIS
#ifdef USE_MAD
{ ".MP3", Audio::makeMP3Stream },
#endif // USE_MAD
{ ".AUD", makeAUDStream },
{ 0, 0 }
};
} // End of namespace Kyra
| gpl-2.0 |
SIB-Colombia/biodiversidad_wp | wp-content/plugins/az_shortcodes/tinymce/shortcode_generator/js/upload.js | 2627 | /*global jQuery, document, redux_upload, formfield:true, preview:true, tb_show, window, imgurl:true, tb_remove, $relid:true*/
/*
This is the uploader for wordpress starting from version 3.5
*/
jQuery(document).ready(function(){
initUpload();
function initUpload(){
jQuery(".redux-opts-upload").on('click',function( event ) {
var activeFileUploadContext = jQuery(this).parent();
var relid = jQuery(this).attr('rel-id');
event.preventDefault();
// If the media frame already exists, reopen it.
/*if ( typeof(custom_file_frame)!=="undefined" ) {
custom_file_frame.open();
return;
}*/
// if its not null, its broking custom_file_frame's onselect "activeFileUploadContext"
custom_file_frame = null;
// Create the media frame.
custom_file_frame = wp.media.frames.customHeader = wp.media({
// Set the title of the modal.
title: jQuery(this).data("choose"),
// Tell the modal to show only images. Ignore if want ALL
library: {
type: ''
},
// Customize the submit button.
button: {
// Set the text of the button.
text: jQuery(this).data("update")
}
});
custom_file_frame.on( "select", function() {
// Grab the selected attachment.
var attachment = custom_file_frame.state().get("selection").first();
// Update value of the targetfield input with the attachment url.
jQuery('.redux-opts-screenshot',activeFileUploadContext).attr('src', attachment.attributes.url);
jQuery('#' + relid ).val(attachment.attributes.url).trigger('change');
jQuery('.redux-opts-upload',activeFileUploadContext).hide();
jQuery('.redux-opts-screenshot',activeFileUploadContext).show();
jQuery('.redux-opts-upload-remove',activeFileUploadContext).show();
});
custom_file_frame.open();
});
jQuery(".redux-opts-upload-remove").on('click', function( event ) {
var activeFileUploadContext = jQuery(this).parent();
var relid = jQuery(this).attr('rel-id');
event.preventDefault();
jQuery('#' + relid).val('');
jQuery(this).prev().fadeIn('slow');
jQuery('.redux-opts-screenshot',activeFileUploadContext).fadeOut('slow');
jQuery(this).fadeOut('slow');
});
}
});
| gpl-2.0 |
charismaticchiu/Robotics | examplelist/actionGroupExample.cpp | 5913 | /*
MobileRobots Advanced Robotics Interface for Applications (ARIA)
Copyright (C) 2004, 2005 ActivMedia Robotics LLC
Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
If you wish to redistribute ARIA under different terms, contact
MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
MobileRobots Inc, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481
*/
#include "Aria.h"
/** @example actionGroupExample.cpp Example of using ArActionGroup objects to switch
* between two different kinds of behavior.
*
* This program creates two action groups, a teleoperation
* group and a wander group. Each group contains actions
* that together effect the desired behavior: in teleoperation
* mode, input actions allow the robot to be driven by keyboard
* or joystick, and higher-priority limiter actions help avoid obstacles.
* In wander mode, a constant-velocity action drives the robot
* forward, but higher-priority avoidance actions make the robot
* turn away from obstacles, or back up if an obstacle is hit or
* the motors stall. Keyboard commands (the T and W keys) are
* used to switch between the two modes, by activating the
* action group for the chosen mode.
*
* @see ArActionGroup
* @see @ref actions overview
* @see actionExample.cpp
*/
ArActionGroup *teleop;
ArActionGroup *wander;
// Activate the teleop action group. activateExlcusive() causes
// all other active action groups to be deactivated.
void teleopMode(void)
{
teleop->activateExclusive();
printf("\n== Teleoperation Mode ==\n");
printf(" Use the arrow keys to drive, and the spacebar to stop.\n For joystick control hold the trigger button.\n Press 'w' to switch to wander mode.\n Press escape to exit.\n");
}
// Activate the wander action group. activateExlcusive() causes
// all other active action groups to be deactivated.
void wanderMode(void)
{
wander->activateExclusive();
printf("\n== Wander Mode ==\n");
printf(" The robot will now just wander around avoiding things.\n Press 't' to switch to teleop mode.\n Press escape to exit.\n");
}
int main(int argc, char** argv)
{
Aria::init();
ArArgumentParser argParser(&argc, argv);
ArSimpleConnector con(&argParser);
ArRobot robot;
ArSonarDevice sonar;
argParser.loadDefaultArguments();
if(!Aria::parseArgs() || !argParser.checkHelpAndWarnUnparsed())
{
Aria::logOptions();
return 1;
}
/* - the action group for teleoperation actions: */
teleop = new ArActionGroup(&robot);
// don't hit any tables (if the robot has IR table sensors)
teleop->addAction(new ArActionLimiterTableSensor, 100);
// limiter for close obstacles
teleop->addAction(new ArActionLimiterForwards("speed limiter near",
300, 600, 250), 95);
// limiter for far away obstacles
teleop->addAction(new ArActionLimiterForwards("speed limiter far",
300, 1100, 400), 90);
// limiter so we don't bump things backwards
teleop->addAction(new ArActionLimiterBackwards, 85);
// the joydrive action (drive from joystick)
ArActionJoydrive joydriveAct("joydrive", 400, 15);
teleop->addAction(&joydriveAct, 50);
// the keydrive action (drive from keyboard)
teleop->addAction(new ArActionKeydrive, 45);
/* - the action group for wander actions: */
wander = new ArActionGroup(&robot);
// if we're stalled we want to back up and recover
wander->addAction(new ArActionStallRecover, 100);
// react to bumpers
wander->addAction(new ArActionBumpers, 75);
// turn to avoid things closer to us
wander->addAction(new ArActionAvoidFront("Avoid Front Near", 225, 0), 50);
// turn avoid things further away
wander->addAction(new ArActionAvoidFront, 45);
// keep moving
wander->addAction(new ArActionConstantVelocity("Constant Velocity", 400), 25);
/* - use key commands to switch modes, and use keyboard
* and joystick as inputs for teleoperation actions. */
// create key handler if Aria does not already have one
ArKeyHandler *keyHandler = Aria::getKeyHandler();
if (keyHandler == NULL)
{
keyHandler = new ArKeyHandler;
Aria::setKeyHandler(keyHandler);
robot.attachKeyHandler(keyHandler);
}
// set the callbacks
ArGlobalFunctor teleopCB(&teleopMode);
ArGlobalFunctor wanderCB(&wanderMode);
keyHandler->addKeyHandler('w', &wanderCB);
keyHandler->addKeyHandler('W', &wanderCB);
keyHandler->addKeyHandler('t', &teleopCB);
keyHandler->addKeyHandler('T', &teleopCB);
// if we don't have a joystick, let 'em know
if (!joydriveAct.joystickInited())
printf("Note: Do not have a joystick, only the arrow keys on the keyboard will work.\n");
// set the joystick so it won't do anything if the button isn't pressed
joydriveAct.setStopIfNoButtonPressed(false);
/* - connect to the robot, then enter teleoperation mode. */
robot.addRangeDevice(&sonar);
if(!con.connectRobot(&robot))
{
ArLog::log(ArLog::Terse, "actionGroupExample: Could not connect to the robot.");
Aria::shutdown();
return 1;
}
robot.enableMotors();
teleopMode();
robot.run(true);
Aria::shutdown();
return 0;
}
| gpl-2.0 |
janusnic/Portfolio | hostweb/typo3conf/ext/rn_base/mod/class.tx_rnbase_mod_BaseModule.php | 17566 | <?php
/***************************************************************
* Copyright notice
*
* (c) 2009 Rene Nitzsche (rene@system25.de)
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
require_once(t3lib_extMgm::extPath('rn_base') . 'class.tx_rnbase.php');
tx_rnbase::load('tx_rnbase_util_TYPO3');
tx_rnbase::load('tx_rnbase_mod_IModule');
tx_rnbase::load('tx_rnbase_mod_IModFunc');
$GLOBALS['LANG']->includeLLFile('EXT:rn_base/mod/locallang.xml');
/**
* Fertige Implementierung eines BE-Moduls. Das Modul ist dabei nur eine Hülle für die einzelnen Modulfunktionen.
* Die Klasse stellt also lediglich eine Auswahlbox mit den verfügbaren Funktionen bereit. Neue Funktionen können
* dynamisch über die ext_tables.php angemeldet werden:
* t3lib_extMgm::insertModuleFunction('user_txmkmailerM1', 'tx_mkmailer_mod1_FuncOverview',
* t3lib_extMgm::extPath($_EXTKEY).'mod1/class.tx_mkmailer_mod1_FuncOverview.php',
* 'LLL:EXT:mkmailer/mod1/locallang_mod.xml:func_overview'
* );
* Die Funktionsklassen sollten das Interface tx_rnbase_mod_IModFunc implementieren. Eine Basisklasse mit nützlichen
* Methoden steht natürlich auch bereit: tx_rnbase_mod_BaseModFunc
*/
abstract class tx_rnbase_mod_BaseModule extends t3lib_SCbase implements tx_rnbase_mod_IModule {
public $doc;
private $configurations, $formTool;
/**
* Main function of the module. Write the content to $this->content
* If you chose "web" as main module, you will need to consider the $this->id parameter which will contain the uid-number of the page clicked in the page tree
*
* @return [type] ...
*/
function main() {
global $BE_USER, $LANG, $BACK_PATH, $TCA_DESCR, $TCA, $CLIENT, $TYPO3_CONF_VARS;
// Einbindung externer Funktionen
$this->checkExtObj();
// Access check!
// The page will show only if there is a valid page and if this page may be viewed by the user
$this->pageinfo = t3lib_BEfunc::readPageAccess($this->getPid(), $this->perms_clause);
$access = is_array($this->pageinfo) ? 1 : 0;
$this->initDoc($this->getDoc());
if(tx_rnbase_util_TYPO3::isTYPO42OrHigher()) {
$this->content .= $this->moduleContent(); // Muss vor der Erstellung des Headers geladen werden
$this->content .= $this->getDoc()->sectionEnd(); // Zur Sicherheit eine offene Section schließen
$header = $this->getDoc()->header($LANG->getLL('title'));
$this->content = $this->content; // ??
// ShortCut
if ($BE_USER->mayMakeShortcut()) {
$this->content.=$this->getDoc()->spacer(20).$this->getDoc()->section('', $this->getDoc()->makeShortcutIcon('id', implode(',', array_keys($this->MOD_MENU)), $this->MCONF['name']));
}
$this->content.=$this->getDoc()->spacer(10);
// Setting up the buttons and markers for docheader
$docHeaderButtons = $this->getButtons();
$markers['CSH'] = $docHeaderButtons['csh'];
$markers['HEADER'] = $header;
$markers['SELECTOR'] = $this->selector ? $this->selector : $this->subselector; // SubSelector is deprecated!!
// Das FUNC_MENU enthält die Modul-Funktionen, die per ext_tables.php registriert werden
$markers['FUNC_MENU'] = $this->getFuncMenu();
// SUBMENU sind zusätzliche Tabs die eine Modul-Funktion bei Bedarf einblenden kann.
$markers['SUBMENU'] = $this->tabs;
$markers['TABS'] = $this->tabs; // Deprecated use ###SUBMENU###
$markers['CONTENT'] = $this->content;
}
else {
// HeaderSection zeigt Icons und Seitenpfad
$headerSection = $this->getDoc()->getHeader('pages', $this->pageinfo, $this->pageinfo['_thePath']).'<br />'.$LANG->sL('LLL:EXT:lang/locallang_core.xml:labels.path').': '.t3lib_div::fixed_lgd_pre($this->pageinfo['_thePath'], 50);
$this->content .= $this->moduleContent(); // Muss vor der Erstellung des Headers geladen werden
$this->content .= $this->getDoc()->sectionEnd(); // Zur Sicherheit einen offene Section schließen
// startPage erzeugt alles bis Beginn Formular
$header.=$this->getDoc()->startPage($LANG->getLL('title'));
$header.=$this->getDoc()->header($LANG->getLL('title'));
$header.=$this->getDoc()->spacer(5);
$header.=$this->getDoc()->section('', $this->getDoc()->funcMenu($headerSection, t3lib_BEfunc::getFuncMenu($this->getPid(), 'SET[function]', $this->MOD_SETTINGS['function'], $this->MOD_MENU['function'])));
$header.=$this->getDoc()->divider(5);
$this->content = $header . $this->content;
// ShortCut
if ($BE_USER->mayMakeShortcut()) {
$this->content.=$this->getDoc()->spacer(20).$this->getDoc()->section('', $this->getDoc()->makeShortcutIcon('id', implode(',', array_keys($this->MOD_MENU)), $this->MCONF['name']));
}
$this->content.=$this->getDoc()->spacer(10);
}
if(tx_rnbase_util_TYPO3::isTYPO42OrHigher()) {
$content = $this->getDoc()->startPage($LANG->getLL('title'));
$content.= $this->getDoc()->moduleBody($this->pageinfo, $docHeaderButtons, $markers);
$this->content = $this->getDoc()->insertStylesAndJS($content);
}
}
/**
* Returns the module ident name
* @return string
*/
public function getName() {
return $this->MCONF['name'];
}
/**
* Generates the module content.
* Normaly we would call $this->extObjContent(); But this method writes the output to $this->content. We need
* the output directly so this is reimplementation of extObjContent()
*
* @return void
*/
function moduleContent() {
// Dummy-Button für automatisch Submit
$content = '<p style="position:absolute; top:-5000px; left:-5000px;">'
. '<input type="submit" />'
. '</p>';
$this->extObj->pObj = &$this;
if (is_callable(array($this->extObj, 'main'))) $content.=$this->extObj->main();
else $content .= 'Module has no method main.';
return $content;
}
function checkExtObj() {
if (is_array($this->extClassConf) && $this->extClassConf['name']) {
$this->extObj = t3lib_div::makeInstance($this->extClassConf['name']);
$this->extObj->init($this, $this->extClassConf);
// Re-write:
$this->MOD_SETTINGS = t3lib_BEfunc::getModuleData($this->MOD_MENU, t3lib_div::_GP('SET'), $this->MCONF['name'], $this->modMenu_type, $this->modMenu_dontValidateList, $this->modMenu_setDefaultList);
}
}
/**
* @see tx_rnbase_mod_IModule::getFormTool()
* @return tx_rnbase_util_FormTool
*/
public function getFormTool() {
if(!$this->formTool) {
$this->formTool = tx_rnbase::makeInstance('tx_rnbase_util_FormTool');
$this->formTool->init($this->getDoc());
}
return $this->formTool;
}
/**
* Liefert eine Instanz von tx_rnbase_configurations. Da wir uns im BE bewegen, wird diese mit einem
* Config-Array aus der TSConfig gefüttert. Dabei wird die Konfiguration unterhalb von mod.extkey. genommen.
* Für "extkey" wird der Wert der Methode getExtensionKey() verwendet.
* Zusätzlich wird auch die Konfiguration von "lib." bereitgestellt.
* Wenn Daten für BE-Nutzer oder Gruppen überschrieben werden sollen, dann darauf achten, daß die
* Konfiguration mit "page." beginnen muss. Also bspw. "page.lib.test = 42".
*
* Ein eigenes TS-Template für das BE wird in der ext_localconf.php mit dieser Anweisung eingebunden:
* t3lib_extMgm::addPageTSConfig('<INCLUDE_TYPOSCRIPT: source="FILE:EXT:myext/mod1/pageTSconfig.txt">');
* @return tx_rnbase_configurations
*/
public function getConfigurations() {
if(!$this->configurations) {
tx_rnbase::load('tx_rnbase_configurations');
tx_rnbase::load('tx_rnbase_util_Misc');
tx_rnbase_util_Misc::prepareTSFE(); // Ist bei Aufruf aus BE notwendig!
$cObj = t3lib_div::makeInstance('tslib_cObj');
$pageTSconfigFull = t3lib_BEfunc::getPagesTSconfig($this->getPid());
$pageTSconfig = $pageTSconfigFull['mod.'][$this->getExtensionKey().'.'];
$pageTSconfig['lib.'] = $pageTSconfigFull['lib.'];
$userTSconfig = $GLOBALS['BE_USER']->getTSConfig('mod.' . $this->getExtensionKey().'.');
if (!empty($userTSconfig['properties'])) {
$pageTSconfig = t3lib_div::array_merge_recursive_overrule($pageTSconfig, $userTSconfig['properties']);
}
$qualifier = $pageTSconfig['qualifier'] ? $pageTSconfig['qualifier'] : $this->getExtensionKey();
$this->configurations = new tx_rnbase_configurations();
$this->configurations->init($pageTSconfig, $cObj, $this->getExtensionKey(), $qualifier);
}
return $this->configurations;
}
/**
* Liefert bei Web-Modulen die aktuelle Pid
* @return int
*/
public function getPid() {
return $this->id;
}
public function setSubMenu($menuString) {
$this->tabs = $menuString;
}
/**
* Selector String for the marker ###SELECTOR###
* @param $selectorString
*/
public function setSelector($selectorString){
$this->selector = $selectorString;
}
/**
* Prints out the module HTML
*
* @return void
*/
function printContent() {
$this->content.=$this->getDoc()->endPage();
$params = Array();
tx_rnbase::load('tx_rnbase_util_BaseMarker');
tx_rnbase::load('tx_rnbase_util_Templates');
tx_rnbase_util_BaseMarker::callModules($this->content, $markerArray, $subpartArray, $wrappedSubpartArray, $params, $this->getConfigurations()->getFormatter());
$content = tx_rnbase_util_Templates::substituteMarkerArrayCached($this->content, $markerArray, $subpartArray, $wrappedSubpartArray);
echo $content;
}
/**
* Returns a template instance
* Liefert die Instanzvariable doc. Die muss immer Public bleiben, weil auch einige TYPO3-Funktionen
* direkt darauf zugreifen.
* @return template
*/
public function getDoc() {
if(!$this->doc) {
$this->doc = tx_rnbase_util_TYPO3::isTYPO42OrHigher() ? $GLOBALS['TBE_TEMPLATE'] : t3lib_div::makeInstance('bigDoc');
}
return $this->doc;
}
/**
* Erstellt das Menu mit den Submodulen. Die ist als Auswahlbox oder per Tabs möglich und kann per TS eingestellt werden:
* mod.mymod._cfg.funcmenu.useTabs
*/
protected function getFuncMenu() {
$items = $this->getFuncMenuItems($this->MOD_MENU['function']);
$useTabs = intval($this->getConfigurations()->get('_cfg.funcmenu.useTabs')) > 0;
if($useTabs)
$menu = $this->getFormTool()->showTabMenu($this->getPid(), 'function', $this->getName(), $items);
else
$menu = $this->getFormTool()->showMenu($this->getPid(), 'function', $this->getName(), $items, $this->getModuleScript());
return $menu['menu'];
}
/**
* index.php or empty
* @return string
*/
protected function getModuleScript() {
return '';
}
/**
* Find out all visible sub modules for the current user.
* mod.mymod._cfg.funcmenu.deny = className of submodules
* mod.mymod._cfg.funcmenu.allow = className of submodules
* @param array $items
* @return array
*/
protected function getFuncMenuItems($items) {
$visibleItems = $items;
if($denyItems = $this->getConfigurations()->get('_cfg.funcmenu.deny')) {
$denyItems = t3lib_div::trimExplode(',', $denyItems);
foreach ($denyItems As $item)
unset($visibleItems[$item]);
}
if($allowItems = $this->getConfigurations()->get('_cfg.funcmenu.allow')) {
$visibleItems = array();
$allowItems = t3lib_div::trimExplode(',', $allowItems);
foreach ($allowItems As $item)
$visibleItems[$item] = $items[$item];
}
return $visibleItems;
}
protected function getFormTag() {
// TODO: per TS einstellbar machen
return '<form action="" method="post" enctype="multipart/form-data">';
}
/**
* Returns the file for module HTML template. This can be overwritten.
* The first place to search for template is EXT:[your_ext_key]/mod1/template.html. If this file
* not exists the default from rn_base is used. Overwrite this method to set your own location.
* @return string
*/
protected function getModuleTemplate() {
$filename = $this->getConfigurations()->get('template');
if(file_exists(t3lib_div::getFileAbsFileName($filename, TRUE, TRUE))) {
return $filename;
}
// '../'.t3lib_extMgm::siteRelPath($this->getExtensionKey()) . 'mod1/template.html'
$filename = 'EXT:'.$this->getExtensionKey() . '/mod1/template.html';
if(file_exists(t3lib_div::getFileAbsFileName($filename, TRUE, TRUE))) {
return $filename;
}
return 'EXT:rn_base/mod/template.html';
}
protected function initDoc($doc) {
$doc->backPath = $GLOBALS['BACK_PATH'];
$doc->form= $this->getFormTag();
$doc->docType = 'xhtml_trans';
$doc->inDocStyles = $this->getDocStyles();
$doc->tableLayout = $this->getTableLayout();
if(tx_rnbase_util_TYPO3::isTYPO42OrHigher()) {
$doc->setModuleTemplate($this->getModuleTemplate());
$doc->loadJavascriptLib('contrib/prototype/prototype.js');
}
// JavaScript
$doc->JScode .= '
<script language="javascript" type="text/javascript">
script_ended = 0;
function jumpToUrl(URL) {
document.location = URL;
}
</script>
';
// TODO: Die Zeile könnte problematisch sein...
$doc->postCode='
<script language="javascript" type="text/javascript">
script_ended = 1;
if (top.fsMod) top.fsMod.recentIds["web"] = ' . $this->id . ';</script>';
}
/**
* Liefert den Extension-Key des Moduls
* @return string
*/
abstract function getExtensionKey();
function getDocStyles() {
if(tx_rnbase_util_TYPO3::isTYPO42OrHigher())
$css .= '
.rnbase_selector div {
float:left;
margin: 0 5px 10px 0;
}
.rnbase_content div {
float:left;
margin: 5px 5px 10px 0;
}
.cleardiv {clear:both;}
.rnbase_content .c-headLineTable td {
font-weight:bold;
color:#FFF!important;
}';
return $css;
}
function getTableLayout() {
return Array (
'table' => Array('<table class="typo3-dblist" width="100%" cellspacing="0" cellpadding="0" border="0">', '</table><br/>'),
'0' => Array( // Format für 1. Zeile
'tr' => Array('<tr class="t3-row-header c-headLineTable">', '</tr>'),
// Format für jede Spalte in der 1. Zeile
'defCol' => (tx_rnbase_util_TYPO3::isTYPO42OrHigher() ?
Array('<td>', '</td>') :
Array('<td class="c-headLineTable" style="font-weight:bold; color:white;">', '</td>'))
),
'defRow' => Array ( // Formate für alle Zeilen
// '0' => Array('<td valign="top">', '</td>'), // Format für 1. Spalte in jeder Zeile
'tr' => Array('<tr class="db_list_normal">', '</tr>'),
'defCol' => Array('<td>', '</td>') // Format für jede Spalte in jeder Zeile
),
'defRowEven' => Array ( // Formate für alle geraden Zeilen
'tr' => Array('<tr class="db_list_alt">', '</tr>'),
// Format für jede Spalte in jeder Zeile
'defCol' => Array((tx_rnbase_util_TYPO3::isTYPO42OrHigher() ? '<td>' :
'<td class="db_list_alt">'), '</td>')
)
);
}
/**
* Create the panel of buttons for submitting the form or otherwise perform operations.
*
* @return array all available buttons as an assoc. array
*/
function getButtons() {
global $TCA, $LANG, $BACK_PATH, $BE_USER;
$buttons = array(
'csh' => '',
'view' => '',
'record_list' => '',
'shortcut' => '',
);
// TODO: CSH
$buttons['csh'] = t3lib_BEfunc::cshItem('_MOD_'.$this->MCONF['name'], '', $GLOBALS['BACK_PATH'], '', TRUE);
if($this->id && is_array($this->pageinfo)) {
// View page
$buttons['view'] = '<a href="#" onclick="' . htmlspecialchars(t3lib_BEfunc::viewOnClick($this->pageinfo['uid'], $BACK_PATH, t3lib_BEfunc::BEgetRootLine($this->pageinfo['uid']))) . '">' .
'<img' . t3lib_iconWorks::skinImg($BACK_PATH, 'gfx/zoom.gif') . ' title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.showPage', 1) . '" hspace="3" alt="" />' .
'</a>';
// Shortcut
if ($BE_USER->mayMakeShortcut()) {
$buttons['shortcut'] = $this->getDoc()->makeShortcutIcon('id, edit_record, pointer, new_unique_uid, search_field, search_levels, showLimit', implode(',', array_keys($this->MOD_MENU)), $this->MCONF['name']);
}
// If access to Web>List for user, then link to that module.
if ($BE_USER->check('modules', 'web_list')) {
$href = $BACK_PATH . 'db_list.php?id=' . $this->pageinfo['uid'] . '&returnUrl=' . rawurlencode(t3lib_div::getIndpEnv('REQUEST_URI'));
$buttons['record_list'] = '<a href="' . htmlspecialchars($href) . '">' .
'<img' . t3lib_iconWorks::skinImg($BACK_PATH, 'gfx/list.gif') . ' title="' . $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.showList', 1) . '" alt="" />' .
'</a>';
}
}
return $buttons;
}
/*
* (Non PHP-doc)
*/
public function addMessage($message, $title = '', $severity = 0, $storeInSession = FALSE) {
$message = t3lib_div::makeInstance(
't3lib_FlashMessage',
$message,
$title,
$severity,
$storeInSession
);
t3lib_FlashMessageQueue::addMessage($message);
}
}
if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/rn_base/mod/class.tx_rnbase_mod_BaseModule.php']) {
include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['ext/rn_base/mod/class.tx_rnbase_mod_BaseModule.php']);
}
| gpl-2.0 |
CoordCulturaDigital-Minc/culturadigital.br | wp-content/themes/EvoeTheme/mobile/header.php | 764 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"
"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
<html <?php language_attributes(); ?> xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php wp_title('«', true, 'right'); ?> <?php bloginfo('name'); ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="<?php bloginfo('stylesheet_directory') ?>/global/css/mobile.css" media="all" />
<link rel="alternate" type="application/rss+xml" title="<?php bloginfo('name'); ?> RSS Feed" href="<?php bloginfo('rss2_url'); ?>" />
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" />
<?php wp_head(); ?>
</head>
| gpl-2.0 |
aisuhua/phalcon-jumpstart | libs/Fly/SearchEngine.php | 2002 | <?php
namespace Fly;
use Fly\Sphinx\SphinxClient;
use Phalcon\DI\FactoryDefault as DI;
class SearchEngine
{
public $indexedTables = ['manga'];
public $searchTables = [];
public $searcher = null;
protected $config;
public function __construct()
{
$this->config = DI::getDefault()->get('config');
$this->searcher = new SphinxClient();
$this->searcher->SetServer($this->config->app_sphinx->host, $this->config->app_sphinx->port);
$this->searcher->SetConnectTimeout(1);
$this->searcher->SetArrayResult(true);
$this->searcher->SetMatchMode(SPH_MATCH_EXTENDED2);
$this->searcher->SetRankingMode(SPH_RANK_PROXIMITY_BM25);
}
public function addtable($tablename)
{
if (in_array($tablename, $this->indexedTables) && !in_array($tablename, $this->searchTables)) {
$this->searchTables[] = $tablename;
return true;
} else {
return false;
}
}
public function search($keyword)
{
$output = [];
//query tu index
foreach ($this->searchTables as $tablename) {
$this->searcher->addQuery($this->searcher->EscapeString($keyword), "$tablename");
}
$result = $this->searcher->runQueries();
if (empty($result[0]['error'])) {
//lay gia tri tra ve theo index
$indexCount = count($result);
for ($i = 0; $i < $indexCount; $i++) {
if ($result[$i]['total_found'] > 0) {
$arrayId = [];
for ($k = 0; $k < count($result[$i]['matches']); $k++) {
$arrayId[] = $result[$i]['matches'][$k];
}
$arrayId['result_found'] = $result[$i]['total_found'];
$output[$this->searchTables[$i]] = $arrayId;
}
}
} else {
$output = $result[0]['error'];
}
return $output;
}
}
| gpl-2.0 |
shannah/cn1 | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/beans/src/test/support/java/org/apache/harmony/beans/tests/support/mock/MockFoo2ParentBeanInfo.java | 1510 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.harmony.beans.tests.support.mock;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
/**
* test for DefaultPersistenceDelegate
*/
public class MockFoo2ParentBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors() {
PropertyDescriptor[] pds = new PropertyDescriptor[1];
try {
PropertyDescriptor pd = new PropertyDescriptor("prop",
MockFoo2.class, "get", "set");
pd.setName(pd.getName() + ".BeanInfo");
pds[0] = pd;
} catch (IntrospectionException e) {
throw new Error(e);
}
return pds;
}
}
| gpl-2.0 |
conwayje/ase-python | ase/test/eam_test.py | 3162 | import numpy as np
from ase.calculators.eam import EAM
from ase.lattice import bulk
# test to generate an EAM potential file using a simplified
# approximation to the Mishin potential Al99.eam.alloy data
from scipy.interpolate import InterpolatedUnivariateSpline as spline
cutoff = 6.28721
n = 21
rs = np.arange(0, n) * (cutoff / n)
rhos = np.arange(0, 2, 2. / n)
# generated from
# mishin = EAM('../potentials/Al99.eam.alloy')
# m_density = mishin.electron_density[0](rs)
# m_embedded = mishin.embedded_energy[0](rhos)
# m_phi = mishin.phi[0,0](rs)
m_density = np.array([2.78589606e-01, 2.02694937e-01, 1.45334053e-01,
1.06069912e-01, 8.42517168e-02, 7.65140344e-02,
7.76263116e-02, 8.23214224e-02, 8.53322309e-02,
8.13915861e-02, 6.59095390e-02, 4.28915711e-02,
2.27910928e-02, 1.13713167e-02, 6.05020311e-03,
3.65836583e-03, 2.60587564e-03, 2.06750708e-03,
1.48749693e-03, 7.40019174e-04, 6.21225205e-05])
m_embedded = np.array([1.04222211e-10, -1.04142633e+00, -1.60359806e+00,
-1.89287637e+00, -2.09490167e+00, -2.26456628e+00,
-2.40590322e+00, -2.52245359e+00, -2.61385603e+00,
-2.67744693e+00, -2.71053295e+00, -2.71110418e+00,
-2.69287013e+00, -2.68464527e+00, -2.69204083e+00,
-2.68976209e+00, -2.66001244e+00, -2.60122024e+00,
-2.51338548e+00, -2.39650817e+00, -2.25058831e+00])
m_phi = np.array([6.27032242e+01, 3.49638589e+01, 1.79007014e+01,
8.69001383e+00, 4.51545250e+00, 2.83260884e+00,
1.93216616e+00, 1.06795515e+00, 3.37740836e-01,
1.61087890e-02, -6.20816372e-02, -6.51314297e-02,
-5.35210341e-02, -5.20950200e-02, -5.51709524e-02,
-4.89093894e-02, -3.28051688e-02, -1.13738785e-02,
2.33833655e-03, 4.19132033e-03, 1.68600692e-04])
m_densityf = spline(rs, m_density)
m_embeddedf = spline(rhos, m_embedded)
m_phif = spline(rs, m_phi)
a = 4.05 # Angstrom lattice spacing
al = bulk('Al', 'fcc', a=a)
mishin_approx = EAM(elements=['Al'], embedded_energy=np.array([m_embeddedf]),
electron_density=np.array([m_densityf]),
phi=np.array([[m_phif]]), cutoff=cutoff, form='alloy',
# the following terms are only required to write out a file
Z=[13], nr=n, nrho=n, dr=cutoff / n, drho=2. / n,
lattice=['fcc'], mass=[26.982], a=[a])
al.set_calculator(mishin_approx)
mishin_approx_energy = al.get_potential_energy()
mishin_approx.write_file('Al99-test.eam.alloy')
mishin_check = EAM('Al99-test.eam.alloy')
al.set_calculator(mishin_check)
mishin_check_energy = al.get_potential_energy()
print 'Cohesive Energy for Al = ', mishin_approx_energy, ' eV'
error = (mishin_approx_energy - mishin_check_energy) / mishin_approx_energy
print 'read/write check error = ', error
assert abs(error) < 1e-4
| gpl-2.0 |
riggtravis/aseprite | src/app/commands/cmd_layer_properties.cpp | 7482 | // Aseprite
// Copyright (C) 2001-2015 David Capello
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "app/app.h"
#include "app/cmd/set_layer_blend_mode.h"
#include "app/cmd/set_layer_name.h"
#include "app/cmd/set_layer_opacity.h"
#include "app/commands/command.h"
#include "app/console.h"
#include "app/context_access.h"
#include "app/modules/gui.h"
#include "app/transaction.h"
#include "app/ui_context.h"
#include "base/bind.h"
#include "base/scoped_value.h"
#include "doc/document.h"
#include "doc/document_event.h"
#include "doc/image.h"
#include "doc/layer.h"
#include "doc/sprite.h"
#include "ui/ui.h"
#include "generated_layer_properties.h"
namespace app {
using namespace ui;
class LayerPropertiesCommand : public Command {
public:
LayerPropertiesCommand();
Command* clone() const override { return new LayerPropertiesCommand(*this); }
protected:
bool onEnabled(Context* context) override;
void onExecute(Context* context) override;
};
class LayerPropertiesWindow;
static LayerPropertiesWindow* g_window = nullptr;
class LayerPropertiesWindow : public app::gen::LayerProperties
, public doc::ContextObserver
, public doc::DocumentObserver {
public:
LayerPropertiesWindow()
: m_timer(250, this)
, m_layer(nullptr)
, m_selfUpdate(false) {
name()->setMinSize(gfx::Size(128, 0));
name()->setExpansive(true);
mode()->addItem("Normal");
mode()->addItem("Multiply");
mode()->addItem("Screen");
mode()->addItem("Overlay");
mode()->addItem("Darken");
mode()->addItem("Lighten");
mode()->addItem("Color Dodge");
mode()->addItem("Color Burn");
mode()->addItem("Hard Light");
mode()->addItem("Soft Light");
mode()->addItem("Difference");
mode()->addItem("Exclusion");
mode()->addItem("Hue");
mode()->addItem("Saturation");
mode()->addItem("Color");
mode()->addItem("Luminosity");
name()->EntryChange.connect(Bind<void>(&LayerPropertiesWindow::onStartTimer, this));
mode()->Change.connect(Bind<void>(&LayerPropertiesWindow::onStartTimer, this));
opacity()->Change.connect(Bind<void>(&LayerPropertiesWindow::onStartTimer, this));
m_timer.Tick.connect(Bind<void>(&LayerPropertiesWindow::onCommitChange, this));
remapWindow();
centerWindow();
load_window_pos(this, "LayerProperties");
UIContext::instance()->addObserver(this);
}
~LayerPropertiesWindow() {
UIContext::instance()->removeObserver(this);
}
void setLayer(LayerImage* layer) {
// Save uncommited changes
if (m_layer) {
document()->removeObserver(this);
m_layer = nullptr;
}
m_timer.stop();
m_layer = const_cast<LayerImage*>(layer);
if (m_layer)
document()->addObserver(this);
updateFromLayer();
}
private:
app::Document* document() {
ASSERT(m_layer);
if (m_layer)
return static_cast<app::Document*>(m_layer->sprite()->document());
else
return nullptr;
}
std::string nameValue() const {
return name()->getText();
}
BlendMode blendModeValue() const {
return (BlendMode)mode()->getSelectedItemIndex();
}
int opacityValue() const {
return opacity()->getValue();
}
bool onProcessMessage(ui::Message* msg) override {
switch (msg->type()) {
case kKeyDownMessage:
if (name()->hasFocus() ||
opacity()->hasFocus() ||
mode()->hasFocus()) {
if (static_cast<KeyMessage*>(msg)->scancode() == kKeyEnter) {
onCommitChange();
closeWindow(this);
return true;
}
}
break;
case kCloseMessage:
// Save changes before we close the window
setLayer(nullptr);
save_window_pos(this, "LayerProperties");
deferDelete();
g_window = nullptr;
break;
}
return Window::onProcessMessage(msg);
}
void onStartTimer() {
if (m_selfUpdate)
return;
m_timer.start();
}
void onCommitChange() {
base::ScopedValue<bool> switchSelf(m_selfUpdate, true, false);
m_timer.stop();
std::string newName = nameValue();
int newOpacity = opacityValue();
BlendMode newBlendMode = blendModeValue();
if (newName != m_layer->name() ||
newOpacity != m_layer->opacity() ||
newBlendMode != m_layer->blendMode()) {
try {
ContextWriter writer(UIContext::instance());
Transaction transaction(writer.context(), "Set Layer Properties");
if (newName != m_layer->name())
transaction.execute(new cmd::SetLayerName(writer.layer(), newName));
if (newOpacity != m_layer->opacity())
transaction.execute(new cmd::SetLayerOpacity(static_cast<LayerImage*>(writer.layer()), newOpacity));
if (newBlendMode != m_layer->blendMode())
transaction.execute(new cmd::SetLayerBlendMode(static_cast<LayerImage*>(writer.layer()), newBlendMode));
transaction.commit();
}
catch (const std::exception& e) {
Console::showException(e);
}
update_screen_for_document(document());
}
}
// ContextObserver impl
void onActiveSiteChange(const Site& site) override {
if (isVisible())
setLayer(dynamic_cast<LayerImage*>(const_cast<Layer*>(site.layer())));
else if (m_layer)
setLayer(nullptr);
}
// DocumentObserver impl
void onLayerNameChange(DocumentEvent& ev) override {
if (m_layer == ev.layer())
updateFromLayer();
}
void onLayerOpacityChange(DocumentEvent& ev) override {
if (m_layer == ev.layer())
updateFromLayer();
}
void onLayerBlendModeChange(DocumentEvent& ev) override {
if (m_layer == ev.layer())
updateFromLayer();
}
void updateFromLayer() {
if (m_selfUpdate)
return;
m_timer.stop(); // Cancel current editions (just in case)
base::ScopedValue<bool> switchSelf(m_selfUpdate, true, false);
if (m_layer) {
name()->setText(m_layer->name().c_str());
name()->setEnabled(true);
mode()->setSelectedItemIndex((int)m_layer->blendMode());
mode()->setEnabled(!m_layer->isBackground());
opacity()->setValue(m_layer->opacity());
opacity()->setEnabled(!m_layer->isBackground());
}
else {
name()->setText("No Layer");
name()->setEnabled(false);
mode()->setEnabled(false);
opacity()->setEnabled(false);
}
}
Timer m_timer;
LayerImage* m_layer;
bool m_selfUpdate;
};
LayerPropertiesCommand::LayerPropertiesCommand()
: Command("LayerProperties",
"Layer Properties",
CmdRecordableFlag)
{
}
bool LayerPropertiesCommand::onEnabled(Context* context)
{
return context->checkFlags(ContextFlags::ActiveDocumentIsWritable |
ContextFlags::HasActiveLayer);
}
void LayerPropertiesCommand::onExecute(Context* context)
{
ContextReader reader(context);
LayerImage* layer = static_cast<LayerImage*>(reader.layer());
if (!g_window)
g_window = new LayerPropertiesWindow;
g_window->setLayer(layer);
g_window->openWindow();
// Focus layer name
g_window->name()->requestFocus();
}
Command* CommandFactory::createLayerPropertiesCommand()
{
return new LayerPropertiesCommand;
}
} // namespace app
| gpl-2.0 |
bwildenhain/virt-manager | virtinst/devicehostdev.py | 5336 | #
# Copyright 2009, 2013 Red Hat, Inc.
# Cole Robinson <crobinso@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
from .device import VirtualDevice
from .nodedev import NodeDevice
from .xmlbuilder import XMLProperty
class VirtualHostDevice(VirtualDevice):
virtual_device_type = VirtualDevice.VIRTUAL_DEV_HOSTDEV
def set_from_nodedev(self, nodedev):
"""
@use_full_usb: If set, and nodedev is USB, specify both
vendor and product. Used if user requests bus/add on virt-install
command line, or if virt-manager detects a dup USB device
and we need to differentiate
"""
if nodedev.device_type == NodeDevice.CAPABILITY_TYPE_PCI:
self.type = "pci"
self.domain = nodedev.domain
self.bus = nodedev.bus
self.slot = nodedev.slot
self.function = nodedev.function
elif nodedev.device_type == NodeDevice.CAPABILITY_TYPE_USBDEV:
self.type = "usb"
self.vendor = nodedev.vendor_id
self.product = nodedev.product_id
count = 0
for dev in self.conn.fetch_all_nodedevs():
if (dev.device_type == NodeDevice.CAPABILITY_TYPE_USBDEV and
dev.vendor_id == self.vendor and
dev.product_id == self.product):
count += 1
if not count:
raise RuntimeError(_("Could not find USB device "
"(vendorId: %s, productId: %s)")
% (self.vendor, self.product))
if count > 1:
self.bus = nodedev.bus
self.device = nodedev.device
elif nodedev.device_type == nodedev.CAPABILITY_TYPE_NET:
founddev = None
for checkdev in self.conn.fetch_all_nodedevs():
if checkdev.name == nodedev.parent:
founddev = checkdev
break
self.set_from_nodedev(founddev)
elif nodedev.device_type == nodedev.CAPABILITY_TYPE_SCSIDEV:
self.type = "scsi"
self.scsi_adapter = "scsi_host%s" % nodedev.host
self.scsi_bus = nodedev.bus
self.scsi_target = nodedev.target
self.scsi_unit = nodedev.lun
self.managed = False
else:
raise ValueError("Unknown node device type %s" % nodedev)
def pretty_name(self):
def dehex(val):
if val.startswith("0x"):
val = val[2:]
return val
def safeint(val, fmt="%.3d"):
try:
int(val)
except:
return str(val)
return fmt % int(val)
label = self.type.upper()
if self.vendor and self.product:
label += " %s:%s" % (dehex(self.vendor), dehex(self.product))
elif self.bus and self.device:
label += " %s:%s" % (safeint(self.bus), safeint(self.device))
elif self.bus and self.slot and self.function and self.domain:
label += (" %s:%s:%s.%s" %
(dehex(self.domain), dehex(self.bus),
dehex(self.slot), dehex(self.function)))
return label
_XML_PROP_ORDER = ["mode", "type", "managed", "vendor", "product",
"domain", "bus", "slot", "function"]
mode = XMLProperty("./@mode", default_cb=lambda s: "subsystem")
type = XMLProperty("./@type")
def _get_default_managed(self):
return self.conn.is_xen() and "no" or "yes"
managed = XMLProperty("./@managed", is_yesno=True,
default_cb=_get_default_managed)
vendor = XMLProperty("./source/vendor/@id")
product = XMLProperty("./source/product/@id")
device = XMLProperty("./source/address/@device")
bus = XMLProperty("./source/address/@bus")
def _get_default_domain(self):
if self.type == "pci":
return "0x0"
return None
domain = XMLProperty("./source/address/@domain",
default_cb=_get_default_domain)
function = XMLProperty("./source/address/@function")
slot = XMLProperty("./source/address/@slot")
driver_name = XMLProperty("./driver/@name")
rom_bar = XMLProperty("./rom/@bar", is_onoff=True)
# type=scsi handling
scsi_adapter = XMLProperty("./source/adapter/@name")
scsi_bus = XMLProperty("./source/address/@bus", is_int=True)
scsi_target = XMLProperty("./source/address/@target", is_int=True)
scsi_unit = XMLProperty("./source/address/@unit", is_int=True)
VirtualHostDevice.register_type()
| gpl-2.0 |
philipl/xbmc | xbmc/FileItem.cpp | 87612 | /*
* Copyright (C) 2005-2013 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBMC; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include <cstdlib>
#include "FileItem.h"
#include "guilib/LocalizeStrings.h"
#include "utils/StringUtils.h"
#include "utils/URIUtils.h"
#include "utils/Archive.h"
#include "Util.h"
#include "playlists/PlayListFactory.h"
#include "utils/Crc32.h"
#include "filesystem/Directory.h"
#include "filesystem/File.h"
#include "filesystem/StackDirectory.h"
#include "filesystem/CurlFile.h"
#include "filesystem/MultiPathDirectory.h"
#include "filesystem/MusicDatabaseDirectory.h"
#include "filesystem/VideoDatabaseDirectory.h"
#include "filesystem/VideoDatabaseDirectory/QueryParams.h"
#include "music/tags/MusicInfoTagLoaderFactory.h"
#include "CueDocument.h"
#include "video/VideoDatabase.h"
#include "music/MusicDatabase.h"
#include "epg/Epg.h"
#include "pvr/channels/PVRChannel.h"
#include "pvr/channels/PVRRadioRDSInfoTag.h"
#include "pvr/recordings/PVRRecording.h"
#include "pvr/timers/PVRTimerInfoTag.h"
#include "video/VideoInfoTag.h"
#include "threads/SingleLock.h"
#include "music/tags/MusicInfoTag.h"
#include "pictures/PictureInfoTag.h"
#include "music/Artist.h"
#include "music/Album.h"
#include "URL.h"
#include "settings/AdvancedSettings.h"
#include "settings/Settings.h"
#include "utils/RegExp.h"
#include "utils/log.h"
#include "utils/Variant.h"
#include "utils/Mime.h"
#include <assert.h>
#include <algorithm>
using namespace XFILE;
using namespace PLAYLIST;
using namespace MUSIC_INFO;
using namespace PVR;
using namespace EPG;
CFileItem::CFileItem(const CSong& song)
{
Initialize();
SetFromSong(song);
}
CFileItem::CFileItem(const CSong& song, const CMusicInfoTag& music)
{
Initialize();
SetFromSong(song);
*GetMusicInfoTag() = music;
}
CFileItem::CFileItem(const CURL &url, const CAlbum& album)
{
Initialize();
m_strPath = url.Get();
URIUtils::AddSlashAtEnd(m_strPath);
SetFromAlbum(album);
}
CFileItem::CFileItem(const std::string &path, const CAlbum& album)
{
Initialize();
m_strPath = path;
URIUtils::AddSlashAtEnd(m_strPath);
SetFromAlbum(album);
}
CFileItem::CFileItem(const CMusicInfoTag& music)
{
Initialize();
SetLabel(music.GetTitle());
m_strPath = music.GetURL();
m_bIsFolder = URIUtils::HasSlashAtEnd(m_strPath);
*GetMusicInfoTag() = music;
FillInDefaultIcon();
FillInMimeType(false);
}
CFileItem::CFileItem(const CVideoInfoTag& movie)
{
Initialize();
SetFromVideoInfoTag(movie);
}
CFileItem::CFileItem(const CEpgInfoTagPtr& tag)
{
assert(tag.get());
Initialize();
m_bIsFolder = false;
m_epgInfoTag = tag;
m_strPath = tag->Path();
SetLabel(tag->Title());
m_strLabel2 = tag->Plot();
m_dateTime = tag->StartAsLocalTime();
if (!tag->Icon().empty())
SetIconImage(tag->Icon());
else if (tag->HasPVRChannel() && !tag->ChannelTag()->IconPath().empty())
SetIconImage(tag->ChannelTag()->IconPath());
FillInMimeType(false);
}
CFileItem::CFileItem(const CPVRChannelPtr& channel)
{
assert(channel.get());
Initialize();
CEpgInfoTagPtr epgNow(channel->GetEPGNow());
m_strPath = channel->Path();
m_bIsFolder = false;
m_pvrChannelInfoTag = channel;
SetLabel(channel->ChannelName());
m_strLabel2 = epgNow ? epgNow->Title() :
CSettings::GetInstance().GetBool(CSettings::SETTING_EPG_HIDENOINFOAVAILABLE) ?
"" : g_localizeStrings.Get(19055); // no information available
if (channel->IsRadio())
{
CMusicInfoTag* musictag = GetMusicInfoTag();
if (musictag)
{
musictag->SetURL(channel->Path());
musictag->SetTitle(m_strLabel2);
musictag->SetArtist(channel->ChannelName());
musictag->SetAlbumArtist(channel->ChannelName());
if (epgNow)
musictag->SetGenre(epgNow->Genre());
musictag->SetDuration(epgNow ? epgNow->GetDuration() : 3600);
musictag->SetLoaded(true);
musictag->SetComment("");
musictag->SetLyrics("");
}
}
if (!channel->IconPath().empty())
SetIconImage(channel->IconPath());
SetProperty("channelid", channel->ChannelID());
SetProperty("path", channel->Path());
SetArt("thumb", channel->IconPath());
FillInMimeType(false);
}
CFileItem::CFileItem(const CPVRRecordingPtr& record)
{
assert(record.get());
Initialize();
m_bIsFolder = false;
m_pvrRecordingInfoTag = record;
m_strPath = record->m_strFileNameAndPath;
SetLabel(record->m_strTitle);
m_strLabel2 = record->m_strPlot;
FillInMimeType(false);
}
CFileItem::CFileItem(const CPVRTimerInfoTagPtr& timer)
{
assert(timer.get());
Initialize();
m_bIsFolder = timer->IsRepeating();
m_pvrTimerInfoTag = timer;
m_strPath = timer->Path();
SetLabel(timer->Title());
m_strLabel2 = timer->Summary();
m_dateTime = timer->StartAsLocalTime();
if (!timer->ChannelIcon().empty())
SetIconImage(timer->ChannelIcon());
FillInMimeType(false);
}
CFileItem::CFileItem(const CArtist& artist)
{
Initialize();
SetLabel(artist.strArtist);
m_strPath = artist.strArtist;
m_bIsFolder = true;
URIUtils::AddSlashAtEnd(m_strPath);
GetMusicInfoTag()->SetArtist(artist);
FillInMimeType(false);
}
CFileItem::CFileItem(const CGenre& genre)
{
Initialize();
SetLabel(genre.strGenre);
m_strPath = genre.strGenre;
m_bIsFolder = true;
URIUtils::AddSlashAtEnd(m_strPath);
GetMusicInfoTag()->SetGenre(genre.strGenre);
FillInMimeType(false);
}
CFileItem::CFileItem(const CFileItem& item)
: m_musicInfoTag(NULL),
m_videoInfoTag(NULL),
m_pictureInfoTag(NULL)
{
*this = item;
}
CFileItem::CFileItem(const CGUIListItem& item)
{
Initialize();
// not particularly pretty, but it gets around the issue of Initialize() defaulting
// parameters in the CGUIListItem base class.
*((CGUIListItem *)this) = item;
FillInMimeType(false);
}
CFileItem::CFileItem(void)
{
Initialize();
}
CFileItem::CFileItem(const std::string& strLabel)
{
Initialize();
SetLabel(strLabel);
}
CFileItem::CFileItem(const char* strLabel)
{
Initialize();
SetLabel(std::string(strLabel));
}
CFileItem::CFileItem(const CURL& path, bool bIsFolder)
{
Initialize();
m_strPath = path.Get();
m_bIsFolder = bIsFolder;
if (m_bIsFolder && !m_strPath.empty() && !IsFileFolder())
URIUtils::AddSlashAtEnd(m_strPath);
FillInMimeType(false);
}
CFileItem::CFileItem(const std::string& strPath, bool bIsFolder)
{
Initialize();
m_strPath = strPath;
m_bIsFolder = bIsFolder;
if (m_bIsFolder && !m_strPath.empty() && !IsFileFolder())
URIUtils::AddSlashAtEnd(m_strPath);
FillInMimeType(false);
}
CFileItem::CFileItem(const CMediaSource& share)
{
Initialize();
m_bIsFolder = true;
m_bIsShareOrDrive = true;
m_strPath = share.strPath;
if (!IsRSS()) // no slash at end for rss feeds
URIUtils::AddSlashAtEnd(m_strPath);
std::string label = share.strName;
if (!share.strStatus.empty())
label = StringUtils::Format("%s (%s)", share.strName.c_str(), share.strStatus.c_str());
SetLabel(label);
m_iLockMode = share.m_iLockMode;
m_strLockCode = share.m_strLockCode;
m_iHasLock = share.m_iHasLock;
m_iBadPwdCount = share.m_iBadPwdCount;
m_iDriveType = share.m_iDriveType;
SetArt("thumb", share.m_strThumbnailImage);
SetLabelPreformated(true);
if (IsDVD())
GetVideoInfoTag()->m_strFileNameAndPath = share.strDiskUniqueId; // share.strDiskUniqueId contains disc unique id
FillInMimeType(false);
}
CFileItem::~CFileItem(void)
{
delete m_musicInfoTag;
delete m_videoInfoTag;
delete m_pictureInfoTag;
m_musicInfoTag = NULL;
m_videoInfoTag = NULL;
m_pictureInfoTag = NULL;
}
const CFileItem& CFileItem::operator=(const CFileItem& item)
{
if (this == &item)
return *this;
CGUIListItem::operator=(item);
m_bLabelPreformated=item.m_bLabelPreformated;
FreeMemory();
m_strPath = item.GetPath();
m_bIsParentFolder = item.m_bIsParentFolder;
m_iDriveType = item.m_iDriveType;
m_bIsShareOrDrive = item.m_bIsShareOrDrive;
m_dateTime = item.m_dateTime;
m_dwSize = item.m_dwSize;
if (item.m_musicInfoTag)
{
if (m_musicInfoTag)
*m_musicInfoTag = *item.m_musicInfoTag;
else
m_musicInfoTag = new MUSIC_INFO::CMusicInfoTag(*item.m_musicInfoTag);
}
else
{
delete m_musicInfoTag;
m_musicInfoTag = NULL;
}
if (item.m_videoInfoTag)
{
if (m_videoInfoTag)
*m_videoInfoTag = *item.m_videoInfoTag;
else
m_videoInfoTag = new CVideoInfoTag(*item.m_videoInfoTag);
}
else
{
delete m_videoInfoTag;
m_videoInfoTag = NULL;
}
if (item.m_pictureInfoTag)
{
if (m_pictureInfoTag)
*m_pictureInfoTag = *item.m_pictureInfoTag;
else
m_pictureInfoTag = new CPictureInfoTag(*item.m_pictureInfoTag);
}
else
{
delete m_pictureInfoTag;
m_pictureInfoTag = NULL;
}
m_epgInfoTag = item.m_epgInfoTag;
m_pvrChannelInfoTag = item.m_pvrChannelInfoTag;
m_pvrRecordingInfoTag = item.m_pvrRecordingInfoTag;
m_pvrTimerInfoTag = item.m_pvrTimerInfoTag;
m_pvrRadioRDSInfoTag = item.m_pvrRadioRDSInfoTag;
m_lStartOffset = item.m_lStartOffset;
m_lStartPartNumber = item.m_lStartPartNumber;
m_lEndOffset = item.m_lEndOffset;
m_strDVDLabel = item.m_strDVDLabel;
m_strTitle = item.m_strTitle;
m_iprogramCount = item.m_iprogramCount;
m_idepth = item.m_idepth;
m_iLockMode = item.m_iLockMode;
m_strLockCode = item.m_strLockCode;
m_iHasLock = item.m_iHasLock;
m_iBadPwdCount = item.m_iBadPwdCount;
m_bCanQueue=item.m_bCanQueue;
m_mimetype = item.m_mimetype;
m_extrainfo = item.m_extrainfo;
m_specialSort = item.m_specialSort;
m_bIsAlbum = item.m_bIsAlbum;
return *this;
}
void CFileItem::Initialize()
{
m_musicInfoTag = NULL;
m_videoInfoTag = NULL;
m_pictureInfoTag = NULL;
m_bLabelPreformated = false;
m_bIsAlbum = false;
m_dwSize = 0;
m_bIsParentFolder = false;
m_bIsShareOrDrive = false;
m_iDriveType = CMediaSource::SOURCE_TYPE_UNKNOWN;
m_lStartOffset = 0;
m_lStartPartNumber = 1;
m_lEndOffset = 0;
m_iprogramCount = 0;
m_idepth = 1;
m_iLockMode = LOCK_MODE_EVERYONE;
m_iBadPwdCount = 0;
m_iHasLock = 0;
m_bCanQueue = true;
m_specialSort = SortSpecialNone;
m_doContentLookup = true;
}
void CFileItem::Reset()
{
// CGUIListItem members...
m_strLabel2.clear();
SetLabel("");
FreeIcons();
m_overlayIcon = ICON_OVERLAY_NONE;
m_bSelected = false;
m_bIsFolder = false;
m_strDVDLabel.clear();
m_strTitle.clear();
m_strPath.clear();
m_dateTime.Reset();
m_strLockCode.clear();
m_mimetype.clear();
delete m_musicInfoTag;
m_musicInfoTag=NULL;
delete m_videoInfoTag;
m_videoInfoTag=NULL;
m_epgInfoTag.reset();
m_pvrChannelInfoTag.reset();
m_pvrRecordingInfoTag.reset();
m_pvrTimerInfoTag.reset();
m_pvrRadioRDSInfoTag.reset();
delete m_pictureInfoTag;
m_pictureInfoTag=NULL;
m_extrainfo.clear();
ClearProperties();
Initialize();
SetInvalid();
}
void CFileItem::Archive(CArchive& ar)
{
CGUIListItem::Archive(ar);
if (ar.IsStoring())
{
ar << m_bIsParentFolder;
ar << m_bLabelPreformated;
ar << m_strPath;
ar << m_bIsShareOrDrive;
ar << m_iDriveType;
ar << m_dateTime;
ar << m_dwSize;
ar << m_strDVDLabel;
ar << m_strTitle;
ar << m_iprogramCount;
ar << m_idepth;
ar << m_lStartOffset;
ar << m_lStartPartNumber;
ar << m_lEndOffset;
ar << m_iLockMode;
ar << m_strLockCode;
ar << m_iBadPwdCount;
ar << m_bCanQueue;
ar << m_mimetype;
ar << m_extrainfo;
ar << m_specialSort;
if (m_musicInfoTag)
{
ar << 1;
ar << *m_musicInfoTag;
}
else
ar << 0;
if (m_videoInfoTag)
{
ar << 1;
ar << *m_videoInfoTag;
}
else
ar << 0;
if (m_pvrRadioRDSInfoTag)
{
ar << 1;
ar << *m_pvrRadioRDSInfoTag;
}
else
ar << 0;
if (m_pictureInfoTag)
{
ar << 1;
ar << *m_pictureInfoTag;
}
else
ar << 0;
}
else
{
ar >> m_bIsParentFolder;
ar >> m_bLabelPreformated;
ar >> m_strPath;
ar >> m_bIsShareOrDrive;
ar >> m_iDriveType;
ar >> m_dateTime;
ar >> m_dwSize;
ar >> m_strDVDLabel;
ar >> m_strTitle;
ar >> m_iprogramCount;
ar >> m_idepth;
ar >> m_lStartOffset;
ar >> m_lStartPartNumber;
ar >> m_lEndOffset;
int temp;
ar >> temp;
m_iLockMode = (LockType)temp;
ar >> m_strLockCode;
ar >> m_iBadPwdCount;
ar >> m_bCanQueue;
ar >> m_mimetype;
ar >> m_extrainfo;
ar >> temp;
m_specialSort = (SortSpecial)temp;
int iType;
ar >> iType;
if (iType == 1)
ar >> *GetMusicInfoTag();
ar >> iType;
if (iType == 1)
ar >> *GetVideoInfoTag();
ar >> iType;
if (iType == 1)
ar >> *m_pvrRadioRDSInfoTag;
ar >> iType;
if (iType == 1)
ar >> *GetPictureInfoTag();
SetInvalid();
}
}
void CFileItem::Serialize(CVariant& value) const
{
//CGUIListItem::Serialize(value["CGUIListItem"]);
value["strPath"] = m_strPath;
value["dateTime"] = (m_dateTime.IsValid()) ? m_dateTime.GetAsRFC1123DateTime() : "";
value["lastmodified"] = m_dateTime.IsValid() ? m_dateTime.GetAsDBDateTime() : "";
value["size"] = m_dwSize;
value["DVDLabel"] = m_strDVDLabel;
value["title"] = m_strTitle;
value["mimetype"] = m_mimetype;
value["extrainfo"] = m_extrainfo;
if (m_musicInfoTag)
(*m_musicInfoTag).Serialize(value["musicInfoTag"]);
if (m_videoInfoTag)
(*m_videoInfoTag).Serialize(value["videoInfoTag"]);
if (m_pvrRadioRDSInfoTag)
m_pvrRadioRDSInfoTag->Serialize(value["rdsInfoTag"]);
if (m_pictureInfoTag)
(*m_pictureInfoTag).Serialize(value["pictureInfoTag"]);
}
void CFileItem::ToSortable(SortItem &sortable, Field field) const
{
switch (field)
{
case FieldPath:
sortable[FieldPath] = m_strPath;
break;
case FieldDate:
sortable[FieldDate] = (m_dateTime.IsValid()) ? m_dateTime.GetAsDBDateTime() : "";
break;
case FieldSize:
sortable[FieldSize] = m_dwSize;
break;
case FieldDriveType:
sortable[FieldDriveType] = m_iDriveType;
break;
case FieldStartOffset:
sortable[FieldStartOffset] = m_lStartOffset;
break;
case FieldEndOffset:
sortable[FieldEndOffset] = m_lEndOffset;
break;
case FieldProgramCount:
sortable[FieldProgramCount] = m_iprogramCount;
break;
case FieldBitrate:
sortable[FieldBitrate] = m_dwSize;
break;
case FieldTitle:
sortable[FieldTitle] = m_strTitle;
break;
// If there's ever a need to convert more properties from CGUIListItem it might be
// worth to make CGUIListItem implement ISortable as well and call it from here
default:
break;
}
if (HasMusicInfoTag())
GetMusicInfoTag()->ToSortable(sortable, field);
if (HasVideoInfoTag())
GetVideoInfoTag()->ToSortable(sortable, field);
if (HasPictureInfoTag())
GetPictureInfoTag()->ToSortable(sortable, field);
if (HasPVRChannelInfoTag())
GetPVRChannelInfoTag()->ToSortable(sortable, field);
}
void CFileItem::ToSortable(SortItem &sortable, const Fields &fields) const
{
Fields::const_iterator it;
for (it = fields.begin(); it != fields.end(); it++)
ToSortable(sortable, *it);
/* FieldLabel is used as a fallback by all sorters and therefore has to be present as well */
sortable[FieldLabel] = GetLabel();
/* FieldSortSpecial and FieldFolder are required in conjunction with all other sorters as well */
sortable[FieldSortSpecial] = m_specialSort;
sortable[FieldFolder] = m_bIsFolder;
}
bool CFileItem::Exists(bool bUseCache /* = true */) const
{
if (m_strPath.empty()
|| IsPath("add")
|| IsInternetStream()
|| IsParentFolder()
|| IsVirtualDirectoryRoot()
|| IsPlugin())
return true;
if (IsVideoDb() && HasVideoInfoTag())
{
CFileItem dbItem(m_bIsFolder ? GetVideoInfoTag()->m_strPath : GetVideoInfoTag()->m_strFileNameAndPath, m_bIsFolder);
return dbItem.Exists();
}
std::string strPath = m_strPath;
if (URIUtils::IsMultiPath(strPath))
strPath = CMultiPathDirectory::GetFirstPath(strPath);
if (URIUtils::IsStack(strPath))
strPath = CStackDirectory::GetFirstStackedFile(strPath);
if (m_bIsFolder)
return CDirectory::Exists(strPath, bUseCache);
else
return CFile::Exists(strPath, bUseCache);
return false;
}
bool CFileItem::IsVideo() const
{
/* check preset mime type */
if(StringUtils::StartsWithNoCase(m_mimetype, "video/"))
return true;
if (HasVideoInfoTag())
return true;
if (HasMusicInfoTag())
return false;
if (HasPictureInfoTag())
return false;
if (IsPVRRecording())
return true;
if (URIUtils::IsDVD(m_strPath))
return true;
std::string extension;
if(StringUtils::StartsWithNoCase(m_mimetype, "application/"))
{ /* check for some standard types */
extension = m_mimetype.substr(12);
if( StringUtils::EqualsNoCase(extension, "ogg")
|| StringUtils::EqualsNoCase(extension, "mp4")
|| StringUtils::EqualsNoCase(extension, "mxf") )
return true;
}
return URIUtils::HasExtension(m_strPath, g_advancedSettings.m_videoExtensions);
}
bool CFileItem::IsEPG() const
{
return HasEPGInfoTag();
}
bool CFileItem::IsPVRChannel() const
{
return HasPVRChannelInfoTag();
}
bool CFileItem::IsPVRRecording() const
{
return HasPVRRecordingInfoTag();
}
bool CFileItem::IsUsablePVRRecording() const
{
return (m_pvrRecordingInfoTag && !m_pvrRecordingInfoTag->IsDeleted());
}
bool CFileItem::IsDeletedPVRRecording() const
{
return (m_pvrRecordingInfoTag && m_pvrRecordingInfoTag->IsDeleted());
}
bool CFileItem::IsPVRTimer() const
{
return HasPVRTimerInfoTag();
}
bool CFileItem::IsPVRRadioRDS() const
{
return HasPVRRadioRDSInfoTag();
}
bool CFileItem::IsDiscStub() const
{
if (IsVideoDb() && HasVideoInfoTag())
{
CFileItem dbItem(m_bIsFolder ? GetVideoInfoTag()->m_strPath : GetVideoInfoTag()->m_strFileNameAndPath, m_bIsFolder);
return dbItem.IsDiscStub();
}
return URIUtils::HasExtension(m_strPath, g_advancedSettings.m_discStubExtensions);
}
bool CFileItem::IsAudio() const
{
/* check preset mime type */
if(StringUtils::StartsWithNoCase(m_mimetype, "audio/"))
return true;
if (HasMusicInfoTag())
return true;
if (HasVideoInfoTag())
return false;
if (HasPictureInfoTag())
return false;
if (IsCDDA())
return true;
if(StringUtils::StartsWithNoCase(m_mimetype, "application/"))
{ /* check for some standard types */
std::string extension = m_mimetype.substr(12);
if( StringUtils::EqualsNoCase(extension, "ogg")
|| StringUtils::EqualsNoCase(extension, "mp4")
|| StringUtils::EqualsNoCase(extension, "mxf") )
return true;
}
return URIUtils::HasExtension(m_strPath, g_advancedSettings.GetMusicExtensions());
}
bool CFileItem::IsPicture() const
{
if(StringUtils::StartsWithNoCase(m_mimetype, "image/"))
return true;
if (HasPictureInfoTag())
return true;
if (HasMusicInfoTag())
return false;
if (HasVideoInfoTag())
return false;
return CUtil::IsPicture(m_strPath);
}
bool CFileItem::IsLyrics() const
{
return URIUtils::HasExtension(m_strPath, ".cdg|.lrc");
}
bool CFileItem::IsSubtitle() const
{
return URIUtils::HasExtension(m_strPath, g_advancedSettings.m_subtitlesExtensions);
}
bool CFileItem::IsCUESheet() const
{
return URIUtils::HasExtension(m_strPath, ".cue");
}
bool CFileItem::IsInternetStream(const bool bStrictCheck /* = false */) const
{
if (HasProperty("IsHTTPDirectory"))
return false;
return URIUtils::IsInternetStream(m_strPath, bStrictCheck);
}
bool CFileItem::IsFileFolder(EFileFolderType types) const
{
EFileFolderType always_type = EFILEFOLDER_TYPE_ALWAYS;
/* internet streams are not directly expanded */
if(IsInternetStream())
always_type = EFILEFOLDER_TYPE_ONCLICK;
if(types & always_type)
{
if(IsSmartPlayList()
|| (IsPlayList() && g_advancedSettings.m_playlistAsFolders)
|| IsAPK()
|| IsZIP()
|| IsRAR()
|| IsRSS()
|| IsType(".ogg|.oga|.nsf|.sid|.sap|.xbt|.xsp")
#if defined(TARGET_ANDROID)
|| IsType(".apk")
#endif
)
return true;
}
if(types & EFILEFOLDER_TYPE_ONBROWSE)
{
if((IsPlayList() && !g_advancedSettings.m_playlistAsFolders)
|| IsDiscImage())
return true;
}
return false;
}
bool CFileItem::IsSmartPlayList() const
{
if (HasProperty("library.smartplaylist") && GetProperty("library.smartplaylist").asBoolean())
return true;
return URIUtils::HasExtension(m_strPath, ".xsp");
}
bool CFileItem::IsLibraryFolder() const
{
if (HasProperty("library.filter") && GetProperty("library.filter").asBoolean())
return true;
return URIUtils::IsLibraryFolder(m_strPath);
}
bool CFileItem::IsPlayList() const
{
return CPlayListFactory::IsPlaylist(*this);
}
bool CFileItem::IsPythonScript() const
{
return URIUtils::HasExtension(m_strPath, ".py");
}
bool CFileItem::IsType(const char *ext) const
{
return URIUtils::HasExtension(m_strPath, ext);
}
bool CFileItem::IsNFO() const
{
return URIUtils::HasExtension(m_strPath, ".nfo");
}
bool CFileItem::IsDiscImage() const
{
return URIUtils::HasExtension(m_strPath, ".img|.iso|.nrg");
}
bool CFileItem::IsOpticalMediaFile() const
{
if (IsDVDFile(false, true))
return true;
return IsBDFile();
}
bool CFileItem::IsDVDFile(bool bVobs /*= true*/, bool bIfos /*= true*/) const
{
std::string strFileName = URIUtils::GetFileName(m_strPath);
if (bIfos)
{
if (StringUtils::EqualsNoCase(strFileName, "video_ts.ifo"))
return true;
if (StringUtils::StartsWithNoCase(strFileName, "vts_") && StringUtils::EndsWithNoCase(strFileName, "_0.ifo") && strFileName.length() == 12)
return true;
}
if (bVobs)
{
if (StringUtils::EqualsNoCase(strFileName, "video_ts.vob"))
return true;
if (StringUtils::StartsWithNoCase(strFileName, "vts_") && StringUtils::EndsWithNoCase(strFileName, ".vob"))
return true;
}
return false;
}
bool CFileItem::IsBDFile() const
{
std::string strFileName = URIUtils::GetFileName(m_strPath);
return (StringUtils::EqualsNoCase(strFileName, "index.bdmv") || StringUtils::EqualsNoCase(strFileName, "MovieObject.bdmv"));
}
bool CFileItem::IsRAR() const
{
return URIUtils::IsRAR(m_strPath);
}
bool CFileItem::IsAPK() const
{
return URIUtils::IsAPK(m_strPath);
}
bool CFileItem::IsZIP() const
{
return URIUtils::IsZIP(m_strPath);
}
bool CFileItem::IsCBZ() const
{
return URIUtils::HasExtension(m_strPath, ".cbz");
}
bool CFileItem::IsCBR() const
{
return URIUtils::HasExtension(m_strPath, ".cbr");
}
bool CFileItem::IsRSS() const
{
return StringUtils::StartsWithNoCase(m_strPath, "rss://") || URIUtils::HasExtension(m_strPath, ".rss")
|| m_mimetype == "application/rss+xml";
}
bool CFileItem::IsAndroidApp() const
{
return URIUtils::IsAndroidApp(m_strPath);
}
bool CFileItem::IsStack() const
{
return URIUtils::IsStack(m_strPath);
}
bool CFileItem::IsPlugin() const
{
return URIUtils::IsPlugin(m_strPath);
}
bool CFileItem::IsScript() const
{
return URIUtils::IsScript(m_strPath);
}
bool CFileItem::IsAddonsPath() const
{
return URIUtils::IsAddonsPath(m_strPath);
}
bool CFileItem::IsSourcesPath() const
{
return URIUtils::IsSourcesPath(m_strPath);
}
bool CFileItem::IsMultiPath() const
{
return URIUtils::IsMultiPath(m_strPath);
}
bool CFileItem::IsCDDA() const
{
return URIUtils::IsCDDA(m_strPath);
}
bool CFileItem::IsDVD() const
{
return URIUtils::IsDVD(m_strPath) || m_iDriveType == CMediaSource::SOURCE_TYPE_DVD;
}
bool CFileItem::IsOnDVD() const
{
return URIUtils::IsOnDVD(m_strPath) || m_iDriveType == CMediaSource::SOURCE_TYPE_DVD;
}
bool CFileItem::IsNfs() const
{
return URIUtils::IsNfs(m_strPath);
}
bool CFileItem::IsOnLAN() const
{
return URIUtils::IsOnLAN(m_strPath);
}
bool CFileItem::IsISO9660() const
{
return URIUtils::IsISO9660(m_strPath);
}
bool CFileItem::IsRemote() const
{
return URIUtils::IsRemote(m_strPath);
}
bool CFileItem::IsSmb() const
{
return URIUtils::IsSmb(m_strPath);
}
bool CFileItem::IsURL() const
{
return URIUtils::IsURL(m_strPath);
}
bool CFileItem::IsPVR() const
{
return CUtil::IsPVR(m_strPath);
}
bool CFileItem::IsLiveTV() const
{
return URIUtils::IsLiveTV(m_strPath);
}
bool CFileItem::IsHD() const
{
return URIUtils::IsHD(m_strPath);
}
bool CFileItem::IsMusicDb() const
{
return URIUtils::IsMusicDb(m_strPath);
}
bool CFileItem::IsVideoDb() const
{
return URIUtils::IsVideoDb(m_strPath);
}
bool CFileItem::IsVirtualDirectoryRoot() const
{
return (m_bIsFolder && m_strPath.empty());
}
bool CFileItem::IsRemovable() const
{
return IsOnDVD() || IsCDDA() || m_iDriveType == CMediaSource::SOURCE_TYPE_REMOVABLE;
}
bool CFileItem::IsReadOnly() const
{
if (IsParentFolder())
return true;
if (m_bIsShareOrDrive)
return true;
return !CUtil::SupportsWriteFileOperations(m_strPath);
}
void CFileItem::FillInDefaultIcon()
{
//CLog::Log(LOGINFO, "FillInDefaultIcon(%s)", pItem->GetLabel().c_str());
// find the default icon for a file or folder item
// for files this can be the (depending on the file type)
// default picture for photo's
// default picture for songs
// default picture for videos
// default picture for shortcuts
// default picture for playlists
// or the icon embedded in an .xbe
//
// for folders
// for .. folders the default picture for parent folder
// for other folders the defaultFolder.png
if (GetIconImage().empty())
{
if (!m_bIsFolder)
{
/* To reduce the average runtime of this code, this list should
* be ordered with most frequently seen types first. Also bear
* in mind the complexity of the code behind the check in the
* case of IsWhatater() returns false.
*/
if (IsPVRChannel())
{
if (GetPVRChannelInfoTag()->IsRadio())
SetIconImage("DefaultAudio.png");
else
SetIconImage("DefaultVideo.png");
}
else if ( IsLiveTV() )
{
// Live TV Channel
SetIconImage("DefaultVideo.png");
}
else if ( URIUtils::IsArchive(m_strPath) )
{ // archive
SetIconImage("DefaultFile.png");
}
else if ( IsUsablePVRRecording() )
{
// PVR recording
SetIconImage("DefaultVideo.png");
}
else if ( IsDeletedPVRRecording() )
{
// PVR deleted recording
SetIconImage("DefaultVideoDeleted.png");
}
else if ( IsAudio() )
{
// audio
SetIconImage("DefaultAudio.png");
}
else if ( IsVideo() )
{
// video
SetIconImage("DefaultVideo.png");
}
else if (IsPVRTimer())
{
SetIconImage("DefaultVideo.png");
}
else if ( IsPicture() )
{
// picture
SetIconImage("DefaultPicture.png");
}
else if ( IsPlayList() )
{
SetIconImage("DefaultPlaylist.png");
}
else if ( IsPythonScript() )
{
SetIconImage("DefaultScript.png");
}
else
{
// default icon for unknown file type
SetIconImage("DefaultFile.png");
}
}
else
{
if ( IsPlayList() )
{
SetIconImage("DefaultPlaylist.png");
}
else if (IsParentFolder())
{
SetIconImage("DefaultFolderBack.png");
}
else
{
SetIconImage("DefaultFolder.png");
}
}
}
// Set the icon overlays (if applicable)
if (!HasOverlay())
{
if (URIUtils::IsInRAR(m_strPath))
SetOverlayImage(CGUIListItem::ICON_OVERLAY_RAR);
else if (URIUtils::IsInZIP(m_strPath))
SetOverlayImage(CGUIListItem::ICON_OVERLAY_ZIP);
}
}
void CFileItem::RemoveExtension()
{
if (m_bIsFolder)
return;
std::string strLabel = GetLabel();
URIUtils::RemoveExtension(strLabel);
SetLabel(strLabel);
}
void CFileItem::CleanString()
{
if (IsLiveTV())
return;
std::string strLabel = GetLabel();
std::string strTitle, strTitleAndYear, strYear;
CUtil::CleanString(strLabel, strTitle, strTitleAndYear, strYear, true);
SetLabel(strTitleAndYear);
}
void CFileItem::SetLabel(const std::string &strLabel)
{
if (strLabel == "..")
{
m_bIsParentFolder = true;
m_bIsFolder = true;
m_specialSort = SortSpecialOnTop;
SetLabelPreformated(true);
}
CGUIListItem::SetLabel(strLabel);
}
void CFileItem::SetFileSizeLabel()
{
if(m_bIsFolder && m_dwSize == 0)
SetLabel2("");
else
SetLabel2(StringUtils::SizeToString(m_dwSize));
}
bool CFileItem::CanQueue() const
{
return m_bCanQueue;
}
void CFileItem::SetCanQueue(bool bYesNo)
{
m_bCanQueue = bYesNo;
}
bool CFileItem::IsParentFolder() const
{
return m_bIsParentFolder;
}
void CFileItem::FillInMimeType(bool lookup /*= true*/)
{
// TODO: adapt this to use CMime::GetMimeType()
if (m_mimetype.empty())
{
if( m_bIsFolder )
m_mimetype = "x-directory/normal";
else if( m_pvrChannelInfoTag )
m_mimetype = m_pvrChannelInfoTag->InputFormat();
else if( StringUtils::StartsWithNoCase(m_strPath, "shout://")
|| StringUtils::StartsWithNoCase(m_strPath, "http://")
|| StringUtils::StartsWithNoCase(m_strPath, "https://"))
{
// If lookup is false, bail out early to leave mime type empty
if (!lookup)
return;
CCurlFile::GetMimeType(GetURL(), m_mimetype);
// try to get mime-type again but with an NSPlayer User-Agent
// in order for server to provide correct mime-type. Allows us
// to properly detect an MMS stream
if (StringUtils::StartsWithNoCase(m_mimetype, "video/x-ms-"))
CCurlFile::GetMimeType(GetURL(), m_mimetype, "NSPlayer/11.00.6001.7000");
// make sure there are no options set in mime-type
// mime-type can look like "video/x-ms-asf ; charset=utf8"
size_t i = m_mimetype.find(';');
if(i != std::string::npos)
m_mimetype.erase(i, m_mimetype.length() - i);
StringUtils::Trim(m_mimetype);
}
else
m_mimetype = CMime::GetMimeType(*this);
// if it's still empty set to an unknown type
if (m_mimetype.empty())
m_mimetype = "application/octet-stream";
}
// change protocol to mms for the following mime-type. Allows us to create proper FileMMS.
if( StringUtils::StartsWithNoCase(m_mimetype, "application/vnd.ms.wms-hdr.asfv1") || StringUtils::StartsWithNoCase(m_mimetype, "application/x-mms-framed") )
StringUtils::Replace(m_strPath, "http:", "mms:");
}
bool CFileItem::IsSamePath(const CFileItem *item) const
{
if (!item)
return false;
if (item->GetPath() == m_strPath)
{
if (item->HasProperty("item_start") || HasProperty("item_start"))
return (item->GetProperty("item_start") == GetProperty("item_start"));
return true;
}
if (HasVideoInfoTag() && item->HasVideoInfoTag())
{
if (m_videoInfoTag->m_iDbId != -1 && item->m_videoInfoTag->m_iDbId != -1)
return ((m_videoInfoTag->m_iDbId == item->m_videoInfoTag->m_iDbId) &&
(m_videoInfoTag->m_type == item->m_videoInfoTag->m_type));
}
if (IsMusicDb() && HasMusicInfoTag())
{
CFileItem dbItem(m_musicInfoTag->GetURL(), false);
if (HasProperty("item_start"))
dbItem.SetProperty("item_start", GetProperty("item_start"));
return dbItem.IsSamePath(item);
}
if (IsVideoDb() && HasVideoInfoTag())
{
CFileItem dbItem(m_videoInfoTag->m_strFileNameAndPath, false);
if (HasProperty("item_start"))
dbItem.SetProperty("item_start", GetProperty("item_start"));
return dbItem.IsSamePath(item);
}
if (item->IsMusicDb() && item->HasMusicInfoTag())
{
CFileItem dbItem(item->m_musicInfoTag->GetURL(), false);
if (item->HasProperty("item_start"))
dbItem.SetProperty("item_start", item->GetProperty("item_start"));
return IsSamePath(&dbItem);
}
if (item->IsVideoDb() && item->HasVideoInfoTag())
{
CFileItem dbItem(item->m_videoInfoTag->m_strFileNameAndPath, false);
if (item->HasProperty("item_start"))
dbItem.SetProperty("item_start", item->GetProperty("item_start"));
return IsSamePath(&dbItem);
}
if (HasProperty("original_listitem_url"))
return (GetProperty("original_listitem_url") == item->GetPath());
return false;
}
bool CFileItem::IsAlbum() const
{
return m_bIsAlbum;
}
void CFileItem::UpdateInfo(const CFileItem &item, bool replaceLabels /*=true*/)
{
if (item.HasVideoInfoTag())
{ // copy info across (TODO: premiered info is normally stored in m_dateTime by the db)
*GetVideoInfoTag() = *item.GetVideoInfoTag();
// preferably use some information from PVR info tag if available
if (m_pvrRecordingInfoTag)
m_pvrRecordingInfoTag->CopyClientInfo(GetVideoInfoTag());
SetOverlayImage(ICON_OVERLAY_UNWATCHED, GetVideoInfoTag()->m_playCount > 0);
SetInvalid();
}
if (item.HasMusicInfoTag())
{
*GetMusicInfoTag() = *item.GetMusicInfoTag();
SetInvalid();
}
if (item.HasPVRRadioRDSInfoTag())
{
m_pvrRadioRDSInfoTag = item.m_pvrRadioRDSInfoTag;
SetInvalid();
}
if (item.HasPictureInfoTag())
{
*GetPictureInfoTag() = *item.GetPictureInfoTag();
SetInvalid();
}
if (replaceLabels && !item.GetLabel().empty())
SetLabel(item.GetLabel());
if (replaceLabels && !item.GetLabel2().empty())
SetLabel2(item.GetLabel2());
if (!item.GetArt("thumb").empty())
SetArt("thumb", item.GetArt("thumb"));
if (!item.GetIconImage().empty())
SetIconImage(item.GetIconImage());
AppendProperties(item);
}
void CFileItem::SetFromVideoInfoTag(const CVideoInfoTag &video)
{
if (!video.m_strTitle.empty())
SetLabel(video.m_strTitle);
if (video.m_strFileNameAndPath.empty())
{
m_strPath = video.m_strPath;
URIUtils::AddSlashAtEnd(m_strPath);
m_bIsFolder = true;
}
else
{
m_strPath = video.m_strFileNameAndPath;
m_bIsFolder = false;
}
*GetVideoInfoTag() = video;
if (video.m_iSeason == 0)
SetProperty("isspecial", "true");
FillInDefaultIcon();
FillInMimeType(false);
}
void CFileItem::SetFromAlbum(const CAlbum &album)
{
if (!album.strAlbum.empty())
SetLabel(album.strAlbum);
m_bIsFolder = true;
m_strLabel2 = album.GetAlbumArtistString();
GetMusicInfoTag()->SetAlbum(album);
SetArt(album.art);
m_bIsAlbum = true;
CMusicDatabase::SetPropertiesFromAlbum(*this,album);
FillInMimeType(false);
}
void CFileItem::SetFromSong(const CSong &song)
{
if (!song.strTitle.empty())
SetLabel(song.strTitle);
if (!song.strFileName.empty())
m_strPath = song.strFileName;
GetMusicInfoTag()->SetSong(song);
m_lStartOffset = song.iStartOffset;
m_lStartPartNumber = 1;
SetProperty("item_start", song.iStartOffset);
m_lEndOffset = song.iEndOffset;
if (!song.strThumb.empty())
SetArt("thumb", song.strThumb);
FillInMimeType(false);
}
std::string CFileItem::GetOpticalMediaPath() const
{
std::string path;
std::string dvdPath;
path = URIUtils::AddFileToFolder(GetPath(), "VIDEO_TS.IFO");
if (CFile::Exists(path))
dvdPath = path;
else
{
dvdPath = URIUtils::AddFileToFolder(GetPath(), "VIDEO_TS");
path = URIUtils::AddFileToFolder(dvdPath, "VIDEO_TS.IFO");
dvdPath.clear();
if (CFile::Exists(path))
dvdPath = path;
}
#ifdef HAVE_LIBBLURAY
if (dvdPath.empty())
{
path = URIUtils::AddFileToFolder(GetPath(), "index.bdmv");
if (CFile::Exists(path))
dvdPath = path;
else
{
dvdPath = URIUtils::AddFileToFolder(GetPath(), "BDMV");
path = URIUtils::AddFileToFolder(dvdPath, "index.bdmv");
dvdPath.clear();
if (CFile::Exists(path))
dvdPath = path;
}
}
#endif
return dvdPath;
}
/*
TODO: Ideally this (and SetPath) would not be available outside of construction
for CFileItem objects, or at least restricted to essentially be equivalent
to construction. This would require re-formulating a bunch of CFileItem
construction, and also allowing CFileItemList to have it's own (public)
SetURL() function, so for now we give direct access.
*/
void CFileItem::SetURL(const CURL& url)
{
m_strPath = url.Get();
}
const CURL CFileItem::GetURL() const
{
CURL url(m_strPath);
return url;
}
bool CFileItem::IsURL(const CURL& url) const
{
return IsPath(url.Get());
}
bool CFileItem::IsPath(const std::string& path) const
{
return URIUtils::PathEquals(m_strPath, path);
}
void CFileItem::SetCueDocument(const CCueDocumentPtr& cuePtr)
{
m_cueDocument = cuePtr;
}
void CFileItem::LoadEmbeddedCue()
{
CMusicInfoTag& tag = *GetMusicInfoTag();
if (!tag.Loaded())
return;
const std::string embeddedCue = tag.GetCueSheet();
if (!embeddedCue.empty())
{
CCueDocumentPtr cuesheet(new CCueDocument);
if (cuesheet->ParseTag(embeddedCue))
{
std::vector<std::string> MediaFileVec;
cuesheet->GetMediaFiles(MediaFileVec);
for (std::vector<std::string>::iterator itMedia = MediaFileVec.begin(); itMedia != MediaFileVec.end(); itMedia++)
cuesheet->UpdateMediaFile(*itMedia, GetPath());
SetCueDocument(cuesheet);
}
}
}
bool CFileItem::HasCueDocument() const
{
return (m_cueDocument.get() != nullptr);
}
bool CFileItem::LoadTracksFromCueDocument(CFileItemList& scannedItems)
{
if (!m_cueDocument)
return false;
CMusicInfoTag& tag = *GetMusicInfoTag();
VECSONGS tracks;
m_cueDocument->GetSongs(tracks);
bool oneFilePerTrack = m_cueDocument->IsOneFilePerTrack();
m_cueDocument.reset();
int tracksFound = 0;
for (VECSONGS::iterator it = tracks.begin(); it != tracks.end(); ++it)
{
CSong& song = *it;
if (song.strFileName == GetPath())
{
if (tag.Loaded())
{
if (song.strAlbum.empty() && !tag.GetAlbum().empty())
song.strAlbum = tag.GetAlbum();
//Pass album artist to final MusicInfoTag object via setting song album artist vector.
if (song.GetAlbumArtist().empty() && !tag.GetAlbumArtist().empty())
song.SetAlbumArtist(tag.GetAlbumArtist());
if (song.genre.empty() && !tag.GetGenre().empty())
song.genre = tag.GetGenre();
//Pass artist to final MusicInfoTag object via setting song artist description string only.
//Artist credits not used during loading from cue sheet.
if (song.strArtistDesc.empty() && !tag.GetArtistString().empty())
song.strArtistDesc = tag.GetArtistString();
if (tag.GetDiscNumber())
song.iTrack |= (tag.GetDiscNumber() << 16); // see CMusicInfoTag::GetDiscNumber()
if (!tag.GetCueSheet().empty())
song.strCueSheet = tag.GetCueSheet();
SYSTEMTIME dateTime;
tag.GetReleaseDate(dateTime);
if (dateTime.wYear)
song.iYear = dateTime.wYear;
if (song.embeddedArt.empty() && !tag.GetCoverArtInfo().empty())
song.embeddedArt = tag.GetCoverArtInfo();
}
if (!song.iDuration && tag.GetDuration() > 0)
{ // must be the last song
song.iDuration = (tag.GetDuration() * 75 - song.iStartOffset + 37) / 75;
}
if ( tag.Loaded() && oneFilePerTrack && ! ( tag.GetAlbum().empty() || tag.GetArtist().empty() || tag.GetTitle().empty() ) )
{
// If there are multiple files in a cue file, the tags from the files should be prefered if they exist.
scannedItems.Add(CFileItemPtr(new CFileItem(song, tag)));
}
else
{
scannedItems.Add(CFileItemPtr(new CFileItem(song)));
}
++tracksFound;
}
}
return tracksFound != 0;
}
/////////////////////////////////////////////////////////////////////////////////
/////
///// CFileItemList
/////
//////////////////////////////////////////////////////////////////////////////////
CFileItemList::CFileItemList()
: CFileItem("", true),
m_fastLookup(false),
m_sortIgnoreFolders(false),
m_cacheToDisc(CACHE_IF_SLOW),
m_replaceListing(false)
{
}
CFileItemList::CFileItemList(const std::string& strPath)
: CFileItem(strPath, true),
m_fastLookup(false),
m_sortIgnoreFolders(false),
m_cacheToDisc(CACHE_IF_SLOW),
m_replaceListing(false)
{
}
CFileItemList::~CFileItemList()
{
Clear();
}
CFileItemPtr CFileItemList::operator[] (int iItem)
{
return Get(iItem);
}
const CFileItemPtr CFileItemList::operator[] (int iItem) const
{
return Get(iItem);
}
CFileItemPtr CFileItemList::operator[] (const std::string& strPath)
{
return Get(strPath);
}
const CFileItemPtr CFileItemList::operator[] (const std::string& strPath) const
{
return Get(strPath);
}
void CFileItemList::SetFastLookup(bool fastLookup)
{
CSingleLock lock(m_lock);
if (fastLookup && !m_fastLookup)
{ // generate the map
m_map.clear();
for (unsigned int i=0; i < m_items.size(); i++)
{
CFileItemPtr pItem = m_items[i];
m_map.insert(MAPFILEITEMSPAIR(pItem->GetPath(), pItem));
}
}
if (!fastLookup && m_fastLookup)
m_map.clear();
m_fastLookup = fastLookup;
}
bool CFileItemList::Contains(const std::string& fileName) const
{
CSingleLock lock(m_lock);
if (m_fastLookup)
return m_map.find(fileName) != m_map.end();
// slow method...
for (unsigned int i = 0; i < m_items.size(); i++)
{
const CFileItemPtr pItem = m_items[i];
if (pItem->IsPath(fileName))
return true;
}
return false;
}
void CFileItemList::Clear()
{
CSingleLock lock(m_lock);
ClearItems();
m_sortDescription.sortBy = SortByNone;
m_sortDescription.sortOrder = SortOrderNone;
m_sortDescription.sortAttributes = SortAttributeNone;
m_sortIgnoreFolders = false;
m_cacheToDisc = CACHE_IF_SLOW;
m_sortDetails.clear();
m_replaceListing = false;
m_content.clear();
}
void CFileItemList::ClearItems()
{
CSingleLock lock(m_lock);
// make sure we free the memory of the items (these are GUIControls which may have allocated resources)
FreeMemory();
for (unsigned int i = 0; i < m_items.size(); i++)
{
CFileItemPtr item = m_items[i];
item->FreeMemory();
}
m_items.clear();
m_map.clear();
}
void CFileItemList::Add(const CFileItemPtr &pItem)
{
CSingleLock lock(m_lock);
m_items.push_back(pItem);
if (m_fastLookup)
{
m_map.insert(MAPFILEITEMSPAIR(pItem->GetPath(), pItem));
}
}
void CFileItemList::AddFront(const CFileItemPtr &pItem, int itemPosition)
{
CSingleLock lock(m_lock);
if (itemPosition >= 0)
{
m_items.insert(m_items.begin()+itemPosition, pItem);
}
else
{
m_items.insert(m_items.begin()+(m_items.size()+itemPosition), pItem);
}
if (m_fastLookup)
{
m_map.insert(MAPFILEITEMSPAIR(pItem->GetPath(), pItem));
}
}
void CFileItemList::Remove(CFileItem* pItem)
{
CSingleLock lock(m_lock);
for (IVECFILEITEMS it = m_items.begin(); it != m_items.end(); ++it)
{
if (pItem == it->get())
{
m_items.erase(it);
if (m_fastLookup)
{
m_map.erase(pItem->GetPath());
}
break;
}
}
}
void CFileItemList::Remove(int iItem)
{
CSingleLock lock(m_lock);
if (iItem >= 0 && iItem < (int)Size())
{
CFileItemPtr pItem = *(m_items.begin() + iItem);
if (m_fastLookup)
{
m_map.erase(pItem->GetPath());
}
m_items.erase(m_items.begin() + iItem);
}
}
void CFileItemList::Append(const CFileItemList& itemlist)
{
CSingleLock lock(m_lock);
for (int i = 0; i < itemlist.Size(); ++i)
Add(itemlist[i]);
}
void CFileItemList::Assign(const CFileItemList& itemlist, bool append)
{
CSingleLock lock(m_lock);
if (!append)
Clear();
Append(itemlist);
SetPath(itemlist.GetPath());
SetLabel(itemlist.GetLabel());
m_sortDetails = itemlist.m_sortDetails;
m_sortDescription = itemlist.m_sortDescription;
m_replaceListing = itemlist.m_replaceListing;
m_content = itemlist.m_content;
m_mapProperties = itemlist.m_mapProperties;
m_cacheToDisc = itemlist.m_cacheToDisc;
}
bool CFileItemList::Copy(const CFileItemList& items, bool copyItems /* = true */)
{
// assign all CFileItem parts
*(CFileItem*)this = *(CFileItem*)&items;
// assign the rest of the CFileItemList properties
m_replaceListing = items.m_replaceListing;
m_content = items.m_content;
m_mapProperties = items.m_mapProperties;
m_cacheToDisc = items.m_cacheToDisc;
m_sortDetails = items.m_sortDetails;
m_sortDescription = items.m_sortDescription;
m_sortIgnoreFolders = items.m_sortIgnoreFolders;
if (copyItems)
{
// make a copy of each item
for (int i = 0; i < items.Size(); i++)
{
CFileItemPtr newItem(new CFileItem(*items[i]));
Add(newItem);
}
}
return true;
}
CFileItemPtr CFileItemList::Get(int iItem)
{
CSingleLock lock(m_lock);
if (iItem > -1 && iItem < (int)m_items.size())
return m_items[iItem];
return CFileItemPtr();
}
const CFileItemPtr CFileItemList::Get(int iItem) const
{
CSingleLock lock(m_lock);
if (iItem > -1 && iItem < (int)m_items.size())
return m_items[iItem];
return CFileItemPtr();
}
CFileItemPtr CFileItemList::Get(const std::string& strPath)
{
CSingleLock lock(m_lock);
if (m_fastLookup)
{
IMAPFILEITEMS it=m_map.find(strPath);
if (it != m_map.end())
return it->second;
return CFileItemPtr();
}
// slow method...
for (unsigned int i = 0; i < m_items.size(); i++)
{
CFileItemPtr pItem = m_items[i];
if (pItem->IsPath(strPath))
return pItem;
}
return CFileItemPtr();
}
const CFileItemPtr CFileItemList::Get(const std::string& strPath) const
{
CSingleLock lock(m_lock);
if (m_fastLookup)
{
std::map<std::string, CFileItemPtr>::const_iterator it=m_map.find(strPath);
if (it != m_map.end())
return it->second;
return CFileItemPtr();
}
// slow method...
for (unsigned int i = 0; i < m_items.size(); i++)
{
CFileItemPtr pItem = m_items[i];
if (pItem->IsPath(strPath))
return pItem;
}
return CFileItemPtr();
}
int CFileItemList::Size() const
{
CSingleLock lock(m_lock);
return (int)m_items.size();
}
bool CFileItemList::IsEmpty() const
{
CSingleLock lock(m_lock);
return m_items.empty();
}
void CFileItemList::Reserve(int iCount)
{
CSingleLock lock(m_lock);
m_items.reserve(iCount);
}
void CFileItemList::Sort(FILEITEMLISTCOMPARISONFUNC func)
{
CSingleLock lock(m_lock);
std::stable_sort(m_items.begin(), m_items.end(), func);
}
void CFileItemList::FillSortFields(FILEITEMFILLFUNC func)
{
CSingleLock lock(m_lock);
std::for_each(m_items.begin(), m_items.end(), func);
}
void CFileItemList::Sort(SortBy sortBy, SortOrder sortOrder, SortAttribute sortAttributes /* = SortAttributeNone */)
{
if (sortBy == SortByNone ||
(m_sortDescription.sortBy == sortBy && m_sortDescription.sortOrder == sortOrder &&
m_sortDescription.sortAttributes == sortAttributes))
return;
SortDescription sorting;
sorting.sortBy = sortBy;
sorting.sortOrder = sortOrder;
sorting.sortAttributes = sortAttributes;
Sort(sorting);
m_sortDescription = sorting;
}
void CFileItemList::Sort(SortDescription sortDescription)
{
if (sortDescription.sortBy == SortByFile ||
sortDescription.sortBy == SortBySortTitle ||
sortDescription.sortBy == SortByDateAdded ||
sortDescription.sortBy == SortByRating ||
sortDescription.sortBy == SortByYear ||
sortDescription.sortBy == SortByPlaylistOrder ||
sortDescription.sortBy == SortByLastPlayed ||
sortDescription.sortBy == SortByPlaycount)
sortDescription.sortAttributes = (SortAttribute)((int)sortDescription.sortAttributes | SortAttributeIgnoreFolders);
if (sortDescription.sortBy == SortByNone ||
(m_sortDescription.sortBy == sortDescription.sortBy && m_sortDescription.sortOrder == sortDescription.sortOrder &&
m_sortDescription.sortAttributes == sortDescription.sortAttributes))
return;
if (m_sortIgnoreFolders)
sortDescription.sortAttributes = (SortAttribute)((int)sortDescription.sortAttributes | SortAttributeIgnoreFolders);
const Fields fields = SortUtils::GetFieldsForSorting(sortDescription.sortBy);
SortItems sortItems((size_t)Size());
for (int index = 0; index < Size(); index++)
{
sortItems[index] = std::shared_ptr<SortItem>(new SortItem);
m_items[index]->ToSortable(*sortItems[index], fields);
(*sortItems[index])[FieldId] = index;
}
// do the sorting
SortUtils::Sort(sortDescription, sortItems);
// apply the new order to the existing CFileItems
VECFILEITEMS sortedFileItems;
sortedFileItems.reserve(Size());
for (SortItems::const_iterator it = sortItems.begin(); it != sortItems.end(); it++)
{
CFileItemPtr item = m_items[(int)(*it)->at(FieldId).asInteger()];
// Set the sort label in the CFileItem
item->SetSortLabel((*it)->at(FieldSort).asWideString());
sortedFileItems.push_back(item);
}
// replace the current list with the re-ordered one
m_items.assign(sortedFileItems.begin(), sortedFileItems.end());
}
void CFileItemList::Randomize()
{
CSingleLock lock(m_lock);
std::random_shuffle(m_items.begin(), m_items.end());
}
void CFileItemList::Archive(CArchive& ar)
{
CSingleLock lock(m_lock);
if (ar.IsStoring())
{
CFileItem::Archive(ar);
int i = 0;
if (m_items.size() > 0 && m_items[0]->IsParentFolder())
i = 1;
ar << (int)(m_items.size() - i);
ar << m_fastLookup;
ar << (int)m_sortDescription.sortBy;
ar << (int)m_sortDescription.sortOrder;
ar << (int)m_sortDescription.sortAttributes;
ar << m_sortIgnoreFolders;
ar << (int)m_cacheToDisc;
ar << (int)m_sortDetails.size();
for (unsigned int j = 0; j < m_sortDetails.size(); ++j)
{
const GUIViewSortDetails &details = m_sortDetails[j];
ar << (int)details.m_sortDescription.sortBy;
ar << (int)details.m_sortDescription.sortOrder;
ar << (int)details.m_sortDescription.sortAttributes;
ar << details.m_buttonLabel;
ar << details.m_labelMasks.m_strLabelFile;
ar << details.m_labelMasks.m_strLabelFolder;
ar << details.m_labelMasks.m_strLabel2File;
ar << details.m_labelMasks.m_strLabel2Folder;
}
ar << m_content;
for (; i < (int)m_items.size(); ++i)
{
CFileItemPtr pItem = m_items[i];
ar << *pItem;
}
}
else
{
CFileItemPtr pParent;
if (!IsEmpty())
{
CFileItemPtr pItem=m_items[0];
if (pItem->IsParentFolder())
pParent.reset(new CFileItem(*pItem));
}
SetFastLookup(false);
Clear();
CFileItem::Archive(ar);
int iSize = 0;
ar >> iSize;
if (iSize <= 0)
return ;
if (pParent)
{
m_items.reserve(iSize + 1);
m_items.push_back(pParent);
}
else
m_items.reserve(iSize);
bool fastLookup=false;
ar >> fastLookup;
int tempint;
ar >> (int&)tempint;
m_sortDescription.sortBy = (SortBy)tempint;
ar >> (int&)tempint;
m_sortDescription.sortOrder = (SortOrder)tempint;
ar >> (int&)tempint;
m_sortDescription.sortAttributes = (SortAttribute)tempint;
ar >> m_sortIgnoreFolders;
ar >> (int&)tempint;
m_cacheToDisc = CACHE_TYPE(tempint);
unsigned int detailSize = 0;
ar >> detailSize;
for (unsigned int j = 0; j < detailSize; ++j)
{
GUIViewSortDetails details;
ar >> (int&)tempint;
details.m_sortDescription.sortBy = (SortBy)tempint;
ar >> (int&)tempint;
details.m_sortDescription.sortOrder = (SortOrder)tempint;
ar >> (int&)tempint;
details.m_sortDescription.sortAttributes = (SortAttribute)tempint;
ar >> details.m_buttonLabel;
ar >> details.m_labelMasks.m_strLabelFile;
ar >> details.m_labelMasks.m_strLabelFolder;
ar >> details.m_labelMasks.m_strLabel2File;
ar >> details.m_labelMasks.m_strLabel2Folder;
m_sortDetails.push_back(details);
}
ar >> m_content;
for (int i = 0; i < iSize; ++i)
{
CFileItemPtr pItem(new CFileItem);
ar >> *pItem;
Add(pItem);
}
SetFastLookup(fastLookup);
}
}
void CFileItemList::FillInDefaultIcons()
{
CSingleLock lock(m_lock);
for (int i = 0; i < (int)m_items.size(); ++i)
{
CFileItemPtr pItem = m_items[i];
pItem->FillInDefaultIcon();
}
}
int CFileItemList::GetFolderCount() const
{
CSingleLock lock(m_lock);
int nFolderCount = 0;
for (int i = 0; i < (int)m_items.size(); i++)
{
CFileItemPtr pItem = m_items[i];
if (pItem->m_bIsFolder)
nFolderCount++;
}
return nFolderCount;
}
int CFileItemList::GetObjectCount() const
{
CSingleLock lock(m_lock);
int numObjects = (int)m_items.size();
if (numObjects && m_items[0]->IsParentFolder())
numObjects--;
return numObjects;
}
int CFileItemList::GetFileCount() const
{
CSingleLock lock(m_lock);
int nFileCount = 0;
for (int i = 0; i < (int)m_items.size(); i++)
{
CFileItemPtr pItem = m_items[i];
if (!pItem->m_bIsFolder)
nFileCount++;
}
return nFileCount;
}
int CFileItemList::GetSelectedCount() const
{
CSingleLock lock(m_lock);
int count = 0;
for (int i = 0; i < (int)m_items.size(); i++)
{
CFileItemPtr pItem = m_items[i];
if (pItem->IsSelected())
count++;
}
return count;
}
void CFileItemList::FilterCueItems()
{
CSingleLock lock(m_lock);
// Handle .CUE sheet files...
std::vector<std::string> itemstodelete;
for (int i = 0; i < (int)m_items.size(); i++)
{
CFileItemPtr pItem = m_items[i];
if (!pItem->m_bIsFolder)
{ // see if it's a .CUE sheet
if (pItem->IsCUESheet())
{
CCueDocumentPtr cuesheet(new CCueDocument);
if (cuesheet->ParseFile(pItem->GetPath()))
{
std::vector<std::string> MediaFileVec;
cuesheet->GetMediaFiles(MediaFileVec);
// queue the cue sheet and the underlying media file for deletion
for(std::vector<std::string>::iterator itMedia = MediaFileVec.begin(); itMedia != MediaFileVec.end(); itMedia++)
{
std::string strMediaFile = *itMedia;
std::string fileFromCue = strMediaFile; // save the file from the cue we're matching against,
// as we're going to search for others here...
bool bFoundMediaFile = CFile::Exists(strMediaFile);
if (!bFoundMediaFile)
{
// try file in same dir, not matching case...
if (Contains(strMediaFile))
{
bFoundMediaFile = true;
}
else
{
// try removing the .cue extension...
strMediaFile = pItem->GetPath();
URIUtils::RemoveExtension(strMediaFile);
CFileItem item(strMediaFile, false);
if (item.IsAudio() && Contains(strMediaFile))
{
bFoundMediaFile = true;
}
else
{ // try replacing the extension with one of our allowed ones.
std::vector<std::string> extensions = StringUtils::Split(g_advancedSettings.GetMusicExtensions(), "|");
for (std::vector<std::string>::const_iterator i = extensions.begin(); i != extensions.end(); ++i)
{
strMediaFile = URIUtils::ReplaceExtension(pItem->GetPath(), *i);
CFileItem item(strMediaFile, false);
if (!item.IsCUESheet() && !item.IsPlayList() && Contains(strMediaFile))
{
bFoundMediaFile = true;
break;
}
}
}
}
}
if (bFoundMediaFile)
{
cuesheet->UpdateMediaFile(fileFromCue, strMediaFile);
// apply CUE for later processing
for (int j = 0; j < (int)m_items.size(); j++)
{
CFileItemPtr pItem = m_items[j];
if (stricmp(pItem->GetPath().c_str(), strMediaFile.c_str()) == 0)
pItem->SetCueDocument(cuesheet);
}
}
}
}
itemstodelete.push_back(pItem->GetPath());
}
}
}
// now delete the .CUE files.
for (int i = 0; i < (int)itemstodelete.size(); i++)
{
for (int j = 0; j < (int)m_items.size(); j++)
{
CFileItemPtr pItem = m_items[j];
if (stricmp(pItem->GetPath().c_str(), itemstodelete[i].c_str()) == 0)
{ // delete this item
m_items.erase(m_items.begin() + j);
break;
}
}
}
}
// Remove the extensions from the filenames
void CFileItemList::RemoveExtensions()
{
CSingleLock lock(m_lock);
for (int i = 0; i < Size(); ++i)
m_items[i]->RemoveExtension();
}
void CFileItemList::Stack(bool stackFiles /* = true */)
{
CSingleLock lock(m_lock);
// not allowed here
if (IsVirtualDirectoryRoot() ||
IsLiveTV() ||
IsSourcesPath() ||
IsLibraryFolder())
return;
SetProperty("isstacked", true);
// items needs to be sorted for stuff below to work properly
Sort(SortByLabel, SortOrderAscending);
StackFolders();
if (stackFiles)
StackFiles();
}
void CFileItemList::StackFolders()
{
// Precompile our REs
VECCREGEXP folderRegExps;
CRegExp folderRegExp(true, CRegExp::autoUtf8);
const std::vector<std::string>& strFolderRegExps = g_advancedSettings.m_folderStackRegExps;
std::vector<std::string>::const_iterator strExpression = strFolderRegExps.begin();
while (strExpression != strFolderRegExps.end())
{
if (!folderRegExp.RegComp(*strExpression))
CLog::Log(LOGERROR, "%s: Invalid folder stack RegExp:'%s'", __FUNCTION__, strExpression->c_str());
else
folderRegExps.push_back(folderRegExp);
strExpression++;
}
if (!folderRegExp.IsCompiled())
{
CLog::Log(LOGDEBUG, "%s: No stack expressions available. Skipping folder stacking", __FUNCTION__);
return;
}
// stack folders
for (int i = 0; i < Size(); i++)
{
CFileItemPtr item = Get(i);
// combined the folder checks
if (item->m_bIsFolder)
{
// only check known fast sources?
// NOTES:
// 1. rars and zips may be on slow sources? is this supposed to be allowed?
if( !item->IsRemote()
|| item->IsSmb()
|| item->IsNfs()
|| URIUtils::IsInRAR(item->GetPath())
|| URIUtils::IsInZIP(item->GetPath())
|| URIUtils::IsOnLAN(item->GetPath())
)
{
// stack cd# folders if contains only a single video file
bool bMatch(false);
VECCREGEXP::iterator expr = folderRegExps.begin();
while (!bMatch && expr != folderRegExps.end())
{
//CLog::Log(LOGDEBUG,"%s: Running expression %s on %s", __FUNCTION__, expr->GetPattern().c_str(), item->GetLabel().c_str());
bMatch = (expr->RegFind(item->GetLabel().c_str()) != -1);
if (bMatch)
{
CFileItemList items;
CDirectory::GetDirectory(item->GetPath(),items,g_advancedSettings.m_videoExtensions);
// optimized to only traverse listing once by checking for filecount
// and recording last file item for later use
int nFiles = 0;
int index = -1;
for (int j = 0; j < items.Size(); j++)
{
if (!items[j]->m_bIsFolder)
{
nFiles++;
index = j;
}
if (nFiles > 1)
break;
}
if (nFiles == 1)
*item = *items[index];
}
expr++;
}
// check for dvd folders
if (!bMatch)
{
std::string dvdPath = item->GetOpticalMediaPath();
if (!dvdPath.empty())
{
// NOTE: should this be done for the CD# folders too?
item->m_bIsFolder = false;
item->SetPath(dvdPath);
item->SetLabel2("");
item->SetLabelPreformated(true);
m_sortDescription.sortBy = SortByNone; /* sorting is now broken */
}
}
}
}
}
}
void CFileItemList::StackFiles()
{
// Precompile our REs
VECCREGEXP stackRegExps;
CRegExp tmpRegExp(true, CRegExp::autoUtf8);
const std::vector<std::string>& strStackRegExps = g_advancedSettings.m_videoStackRegExps;
std::vector<std::string>::const_iterator strRegExp = strStackRegExps.begin();
while (strRegExp != strStackRegExps.end())
{
if (tmpRegExp.RegComp(*strRegExp))
{
if (tmpRegExp.GetCaptureTotal() == 4)
stackRegExps.push_back(tmpRegExp);
else
CLog::Log(LOGERROR, "Invalid video stack RE (%s). Must have 4 captures.", strRegExp->c_str());
}
strRegExp++;
}
// now stack the files, some of which may be from the previous stack iteration
int i = 0;
while (i < Size())
{
CFileItemPtr item1 = Get(i);
// skip folders, nfo files, playlists
if (item1->m_bIsFolder
|| item1->IsParentFolder()
|| item1->IsNFO()
|| item1->IsPlayList()
)
{
// increment index
i++;
continue;
}
int64_t size = 0;
size_t offset = 0;
std::string stackName;
std::string file1;
std::string filePath;
std::vector<int> stack;
VECCREGEXP::iterator expr = stackRegExps.begin();
URIUtils::Split(item1->GetPath(), filePath, file1);
if (URIUtils::HasEncodedFilename(CURL(filePath)))
file1 = CURL::Decode(file1);
int j;
while (expr != stackRegExps.end())
{
if (expr->RegFind(file1, offset) != -1)
{
std::string Title1 = expr->GetMatch(1),
Volume1 = expr->GetMatch(2),
Ignore1 = expr->GetMatch(3),
Extension1 = expr->GetMatch(4);
if (offset)
Title1 = file1.substr(0, expr->GetSubStart(2));
j = i + 1;
while (j < Size())
{
CFileItemPtr item2 = Get(j);
// skip folders, nfo files, playlists
if (item2->m_bIsFolder
|| item2->IsParentFolder()
|| item2->IsNFO()
|| item2->IsPlayList()
)
{
// increment index
j++;
continue;
}
std::string file2, filePath2;
URIUtils::Split(item2->GetPath(), filePath2, file2);
if (URIUtils::HasEncodedFilename(CURL(filePath2)) )
file2 = CURL::Decode(file2);
if (expr->RegFind(file2, offset) != -1)
{
std::string Title2 = expr->GetMatch(1),
Volume2 = expr->GetMatch(2),
Ignore2 = expr->GetMatch(3),
Extension2 = expr->GetMatch(4);
if (offset)
Title2 = file2.substr(0, expr->GetSubStart(2));
if (StringUtils::EqualsNoCase(Title1, Title2))
{
if (!StringUtils::EqualsNoCase(Volume1, Volume2))
{
if (StringUtils::EqualsNoCase(Ignore1, Ignore2) &&
StringUtils::EqualsNoCase(Extension1, Extension2))
{
if (stack.size() == 0)
{
stackName = Title1 + Ignore1 + Extension1;
stack.push_back(i);
size += item1->m_dwSize;
}
stack.push_back(j);
size += item2->m_dwSize;
}
else // Sequel
{
offset = 0;
expr++;
break;
}
}
else if (!StringUtils::EqualsNoCase(Ignore1, Ignore2)) // False positive, try again with offset
{
offset = expr->GetSubStart(3);
break;
}
else // Extension mismatch
{
offset = 0;
expr++;
break;
}
}
else // Title mismatch
{
offset = 0;
expr++;
break;
}
}
else // No match 2, next expression
{
offset = 0;
expr++;
break;
}
j++;
}
if (j == Size())
expr = stackRegExps.end();
}
else // No match 1
{
offset = 0;
expr++;
}
if (stack.size() > 1)
{
// have a stack, remove the items and add the stacked item
// dont actually stack a multipart rar set, just remove all items but the first
std::string stackPath;
if (Get(stack[0])->IsRAR())
stackPath = Get(stack[0])->GetPath();
else
{
CStackDirectory dir;
stackPath = dir.ConstructStackPath(*this, stack);
}
item1->SetPath(stackPath);
// clean up list
for (unsigned k = 1; k < stack.size(); k++)
Remove(i+1);
// item->m_bIsFolder = true; // don't treat stacked files as folders
// the label may be in a different char set from the filename (eg over smb
// the label is converted from utf8, but the filename is not)
if (!CSettings::GetInstance().GetBool(CSettings::SETTING_FILELISTS_SHOWEXTENSIONS))
URIUtils::RemoveExtension(stackName);
item1->SetLabel(stackName);
item1->m_dwSize = size;
break;
}
}
i++;
}
}
bool CFileItemList::Load(int windowID)
{
CFile file;
if (file.Open(GetDiscFileCache(windowID)))
{
CArchive ar(&file, CArchive::load);
ar >> *this;
CLog::Log(LOGDEBUG,"Loading items: %i, directory: %s sort method: %i, ascending: %s", Size(), CURL::GetRedacted(GetPath()).c_str(), m_sortDescription.sortBy,
m_sortDescription.sortOrder == SortOrderAscending ? "true" : "false");
ar.Close();
file.Close();
return true;
}
return false;
}
bool CFileItemList::Save(int windowID)
{
int iSize = Size();
if (iSize <= 0)
return false;
CLog::Log(LOGDEBUG,"Saving fileitems [%s]", CURL::GetRedacted(GetPath()).c_str());
CFile file;
if (file.OpenForWrite(GetDiscFileCache(windowID), true)) // overwrite always
{
CArchive ar(&file, CArchive::store);
ar << *this;
CLog::Log(LOGDEBUG," -- items: %i, sort method: %i, ascending: %s", iSize, m_sortDescription.sortBy, m_sortDescription.sortOrder == SortOrderAscending ? "true" : "false");
ar.Close();
file.Close();
return true;
}
return false;
}
void CFileItemList::RemoveDiscCache(int windowID) const
{
std::string cacheFile(GetDiscFileCache(windowID));
if (CFile::Exists(cacheFile))
{
CLog::Log(LOGDEBUG,"Clearing cached fileitems [%s]",GetPath().c_str());
CFile::Delete(cacheFile);
}
}
std::string CFileItemList::GetDiscFileCache(int windowID) const
{
std::string strPath(GetPath());
URIUtils::RemoveSlashAtEnd(strPath);
Crc32 crc;
crc.ComputeFromLowerCase(strPath);
std::string cacheFile;
if (IsCDDA() || IsOnDVD())
cacheFile = StringUtils::Format("special://temp/r-%08x.fi", (unsigned __int32)crc);
else if (IsMusicDb())
cacheFile = StringUtils::Format("special://temp/mdb-%08x.fi", (unsigned __int32)crc);
else if (IsVideoDb())
cacheFile = StringUtils::Format("special://temp/vdb-%08x.fi", (unsigned __int32)crc);
else if (IsSmartPlayList())
cacheFile = StringUtils::Format("special://temp/sp-%08x.fi", (unsigned __int32)crc);
else if (windowID)
cacheFile = StringUtils::Format("special://temp/%i-%08x.fi", windowID, (unsigned __int32)crc);
else
cacheFile = StringUtils::Format("special://temp/%08x.fi", (unsigned __int32)crc);
return cacheFile;
}
bool CFileItemList::AlwaysCache() const
{
// some database folders are always cached
if (IsMusicDb())
return CMusicDatabaseDirectory::CanCache(GetPath());
if (IsVideoDb())
return CVideoDatabaseDirectory::CanCache(GetPath());
if (IsEPG())
return true; // always cache
return false;
}
std::string CFileItem::GetUserMusicThumb(bool alwaysCheckRemote /* = false */, bool fallbackToFolder /* = false */) const
{
if (m_strPath.empty()
|| StringUtils::StartsWithNoCase(m_strPath, "newsmartplaylist://")
|| StringUtils::StartsWithNoCase(m_strPath, "newplaylist://")
|| m_bIsShareOrDrive
|| IsInternetStream()
|| URIUtils::IsUPnP(m_strPath)
|| (URIUtils::IsFTP(m_strPath) && !g_advancedSettings.m_bFTPThumbs)
|| IsPlugin()
|| IsAddonsPath()
|| IsLibraryFolder()
|| IsParentFolder()
|| IsMusicDb())
return "";
// we first check for <filename>.tbn or <foldername>.tbn
std::string fileThumb(GetTBNFile());
if (CFile::Exists(fileThumb))
return fileThumb;
// Fall back to folder thumb, if requested
if (!m_bIsFolder && fallbackToFolder)
{
CFileItem item(URIUtils::GetDirectory(m_strPath), true);
return item.GetUserMusicThumb(alwaysCheckRemote);
}
// if a folder, check for folder.jpg
if (m_bIsFolder && !IsFileFolder() && (!IsRemote() || alwaysCheckRemote || CSettings::GetInstance().GetBool(CSettings::SETTING_MUSICFILES_FINDREMOTETHUMBS)))
{
std::vector<std::string> thumbs = StringUtils::Split(g_advancedSettings.m_musicThumbs, "|");
for (std::vector<std::string>::const_iterator i = thumbs.begin(); i != thumbs.end(); ++i)
{
std::string folderThumb(GetFolderThumb(*i));
if (CFile::Exists(folderThumb))
{
return folderThumb;
}
}
}
// No thumb found
return "";
}
// Gets the .tbn filename from a file or folder name.
// <filename>.ext -> <filename>.tbn
// <foldername>/ -> <foldername>.tbn
std::string CFileItem::GetTBNFile() const
{
std::string thumbFile;
std::string strFile = m_strPath;
if (IsStack())
{
std::string strPath, strReturn;
URIUtils::GetParentPath(m_strPath,strPath);
CFileItem item(CStackDirectory::GetFirstStackedFile(strFile),false);
std::string strTBNFile = item.GetTBNFile();
strReturn = URIUtils::AddFileToFolder(strPath, URIUtils::GetFileName(strTBNFile));
if (CFile::Exists(strReturn))
return strReturn;
strFile = URIUtils::AddFileToFolder(strPath,URIUtils::GetFileName(CStackDirectory::GetStackedTitlePath(strFile)));
}
if (URIUtils::IsInRAR(strFile) || URIUtils::IsInZIP(strFile))
{
std::string strPath = URIUtils::GetDirectory(strFile);
std::string strParent;
URIUtils::GetParentPath(strPath,strParent);
strFile = URIUtils::AddFileToFolder(strParent, URIUtils::GetFileName(m_strPath));
}
CURL url(strFile);
strFile = url.GetFileName();
if (m_bIsFolder && !IsFileFolder())
URIUtils::RemoveSlashAtEnd(strFile);
if (!strFile.empty())
{
if (m_bIsFolder && !IsFileFolder())
thumbFile = strFile + ".tbn"; // folder, so just add ".tbn"
else
thumbFile = URIUtils::ReplaceExtension(strFile, ".tbn");
url.SetFileName(thumbFile);
thumbFile = url.Get();
}
return thumbFile;
}
bool CFileItem::SkipLocalArt() const
{
return (m_strPath.empty()
|| StringUtils::StartsWithNoCase(m_strPath, "newsmartplaylist://")
|| StringUtils::StartsWithNoCase(m_strPath, "newplaylist://")
|| m_bIsShareOrDrive
|| IsInternetStream()
|| URIUtils::IsUPnP(m_strPath)
|| (URIUtils::IsFTP(m_strPath) && !g_advancedSettings.m_bFTPThumbs)
|| IsPlugin()
|| IsAddonsPath()
|| IsLibraryFolder()
|| IsParentFolder()
|| IsLiveTV()
|| IsDVD());
}
std::string CFileItem::FindLocalArt(const std::string &artFile, bool useFolder) const
{
if (SkipLocalArt())
return "";
std::string thumb;
if (!m_bIsFolder)
{
thumb = GetLocalArt(artFile, false);
if (!thumb.empty() && CFile::Exists(thumb))
return thumb;
}
if ((useFolder || (m_bIsFolder && !IsFileFolder())) && !artFile.empty())
{
std::string thumb2 = GetLocalArt(artFile, true);
if (!thumb2.empty() && thumb2 != thumb && CFile::Exists(thumb2))
return thumb2;
}
return "";
}
std::string CFileItem::GetLocalArt(const std::string &artFile, bool useFolder) const
{
// no retrieving of empty art files from folders
if (useFolder && artFile.empty())
return "";
std::string strFile = m_strPath;
if (IsStack())
{
/* CFileItem item(CStackDirectory::GetFirstStackedFile(strFile),false);
std::string localArt = item.GetLocalArt(artFile);
return localArt;
*/
std::string strPath;
URIUtils::GetParentPath(m_strPath,strPath);
strFile = URIUtils::AddFileToFolder(strPath, URIUtils::GetFileName(CStackDirectory::GetStackedTitlePath(strFile)));
}
if (URIUtils::IsInRAR(strFile) || URIUtils::IsInZIP(strFile))
{
std::string strPath = URIUtils::GetDirectory(strFile);
std::string strParent;
URIUtils::GetParentPath(strPath,strParent);
strFile = URIUtils::AddFileToFolder(strParent, URIUtils::GetFileName(strFile));
}
if (IsMultiPath())
strFile = CMultiPathDirectory::GetFirstPath(m_strPath);
if (IsOpticalMediaFile())
{ // optical media files should be treated like folders
useFolder = true;
strFile = GetLocalMetadataPath();
}
else if (useFolder && !(m_bIsFolder && !IsFileFolder()))
strFile = URIUtils::GetDirectory(strFile);
if (strFile.empty()) // empty filepath -> nothing to find
return "";
if (useFolder)
{
if (!artFile.empty())
return URIUtils::AddFileToFolder(strFile, artFile);
}
else
{
if (artFile.empty()) // old thumbnail matching
return URIUtils::ReplaceExtension(strFile, ".tbn");
else
return URIUtils::ReplaceExtension(strFile, "-" + artFile);
}
return "";
}
std::string CFileItem::GetFolderThumb(const std::string &folderJPG /* = "folder.jpg" */) const
{
std::string strFolder = m_strPath;
if (IsStack() ||
URIUtils::IsInRAR(strFolder) ||
URIUtils::IsInZIP(strFolder))
{
URIUtils::GetParentPath(m_strPath,strFolder);
}
if (IsMultiPath())
strFolder = CMultiPathDirectory::GetFirstPath(m_strPath);
return URIUtils::AddFileToFolder(strFolder, folderJPG);
}
std::string CFileItem::GetMovieName(bool bUseFolderNames /* = false */) const
{
if (IsLabelPreformated())
return GetLabel();
if (m_pvrRecordingInfoTag)
return m_pvrRecordingInfoTag->m_strTitle;
else if (CUtil::IsTVRecording(m_strPath))
{
std::string title = CPVRRecording::GetTitleFromURL(m_strPath);
if (!title.empty())
return title;
}
std::string strMovieName = GetBaseMoviePath(bUseFolderNames);
if (URIUtils::IsStack(strMovieName))
strMovieName = CStackDirectory::GetStackedTitlePath(strMovieName);
URIUtils::RemoveSlashAtEnd(strMovieName);
return CURL::Decode(URIUtils::GetFileName(strMovieName));
}
std::string CFileItem::GetBaseMoviePath(bool bUseFolderNames) const
{
std::string strMovieName = m_strPath;
if (IsMultiPath())
strMovieName = CMultiPathDirectory::GetFirstPath(m_strPath);
if (IsOpticalMediaFile())
return GetLocalMetadataPath();
if (bUseFolderNames &&
(!m_bIsFolder || URIUtils::IsInArchive(m_strPath) ||
(HasVideoInfoTag() && GetVideoInfoTag()->m_iDbId > 0 && !MediaTypes::IsContainer(GetVideoInfoTag()->m_type))))
{
std::string name2(strMovieName);
URIUtils::GetParentPath(name2,strMovieName);
if (URIUtils::IsInArchive(m_strPath))
{
std::string strArchivePath;
URIUtils::GetParentPath(strMovieName, strArchivePath);
strMovieName = strArchivePath;
}
}
return strMovieName;
}
std::string CFileItem::GetLocalFanart() const
{
if (IsVideoDb())
{
if (!HasVideoInfoTag())
return ""; // nothing can be done
CFileItem dbItem(m_bIsFolder ? GetVideoInfoTag()->m_strPath : GetVideoInfoTag()->m_strFileNameAndPath, m_bIsFolder);
return dbItem.GetLocalFanart();
}
std::string strFile2;
std::string strFile = m_strPath;
if (IsStack())
{
std::string strPath;
URIUtils::GetParentPath(m_strPath,strPath);
CStackDirectory dir;
std::string strPath2;
strPath2 = dir.GetStackedTitlePath(strFile);
strFile = URIUtils::AddFileToFolder(strPath, URIUtils::GetFileName(strPath2));
CFileItem item(dir.GetFirstStackedFile(m_strPath),false);
std::string strTBNFile(URIUtils::ReplaceExtension(item.GetTBNFile(), "-fanart"));
strFile2 = URIUtils::AddFileToFolder(strPath, URIUtils::GetFileName(strTBNFile));
}
if (URIUtils::IsInRAR(strFile) || URIUtils::IsInZIP(strFile))
{
std::string strPath = URIUtils::GetDirectory(strFile);
std::string strParent;
URIUtils::GetParentPath(strPath,strParent);
strFile = URIUtils::AddFileToFolder(strParent, URIUtils::GetFileName(m_strPath));
}
// no local fanart available for these
if (IsInternetStream()
|| URIUtils::IsUPnP(strFile)
|| URIUtils::IsBluray(strFile)
|| IsLiveTV()
|| IsPlugin()
|| IsAddonsPath()
|| IsDVD()
|| (URIUtils::IsFTP(strFile) && !g_advancedSettings.m_bFTPThumbs)
|| m_strPath.empty())
return "";
std::string strDir = URIUtils::GetDirectory(strFile);
if (strDir.empty())
return "";
CFileItemList items;
CDirectory::GetDirectory(strDir, items, g_advancedSettings.m_pictureExtensions, DIR_FLAG_NO_FILE_DIRS | DIR_FLAG_READ_CACHE | DIR_FLAG_NO_FILE_INFO);
if (IsOpticalMediaFile())
{ // grab from the optical media parent folder as well
CFileItemList moreItems;
CDirectory::GetDirectory(GetLocalMetadataPath(), moreItems, g_advancedSettings.m_pictureExtensions, DIR_FLAG_NO_FILE_DIRS | DIR_FLAG_READ_CACHE | DIR_FLAG_NO_FILE_INFO);
items.Append(moreItems);
}
std::vector<std::string> fanarts = StringUtils::Split(g_advancedSettings.m_fanartImages, "|");
strFile = URIUtils::ReplaceExtension(strFile, "-fanart");
fanarts.insert(m_bIsFolder ? fanarts.end() : fanarts.begin(), URIUtils::GetFileName(strFile));
if (!strFile2.empty())
fanarts.insert(m_bIsFolder ? fanarts.end() : fanarts.begin(), URIUtils::GetFileName(strFile2));
for (std::vector<std::string>::const_iterator i = fanarts.begin(); i != fanarts.end(); ++i)
{
for (int j = 0; j < items.Size(); j++)
{
std::string strCandidate = URIUtils::GetFileName(items[j]->m_strPath);
URIUtils::RemoveExtension(strCandidate);
std::string strFanart = *i;
URIUtils::RemoveExtension(strFanart);
if (StringUtils::EqualsNoCase(strCandidate, strFanart))
return items[j]->m_strPath;
}
}
return "";
}
std::string CFileItem::GetLocalMetadataPath() const
{
if (m_bIsFolder && !IsFileFolder())
return m_strPath;
std::string parent(URIUtils::GetParentPath(m_strPath));
std::string parentFolder(parent);
URIUtils::RemoveSlashAtEnd(parentFolder);
parentFolder = URIUtils::GetFileName(parentFolder);
if (StringUtils::EqualsNoCase(parentFolder, "VIDEO_TS") || StringUtils::EqualsNoCase(parentFolder, "BDMV"))
{ // go back up another one
parent = URIUtils::GetParentPath(parent);
}
return parent;
}
bool CFileItem::LoadMusicTag()
{
// not audio
if (!IsAudio())
return false;
// already loaded?
if (HasMusicInfoTag() && m_musicInfoTag->Loaded())
return true;
// check db
CMusicDatabase musicDatabase;
if (musicDatabase.Open())
{
CSong song;
if (musicDatabase.GetSongByFileName(m_strPath, song))
{
GetMusicInfoTag()->SetSong(song);
SetArt("thumb", song.strThumb);
return true;
}
musicDatabase.Close();
}
// load tag from file
CLog::Log(LOGDEBUG, "%s: loading tag information for file: %s", __FUNCTION__, m_strPath.c_str());
CMusicInfoTagLoaderFactory factory;
std::unique_ptr<IMusicInfoTagLoader> pLoader (factory.CreateLoader(*this));
if (pLoader.get() != NULL)
{
if (pLoader->Load(m_strPath, *GetMusicInfoTag()))
return true;
}
// no tag - try some other things
if (IsCDDA())
{
// we have the tracknumber...
int iTrack = GetMusicInfoTag()->GetTrackNumber();
if (iTrack >= 1)
{
std::string strText = g_localizeStrings.Get(554); // "Track"
if (!strText.empty() && strText[strText.size() - 1] != ' ')
strText += " ";
std::string strTrack = StringUtils::Format((strText + "%i").c_str(), iTrack);
GetMusicInfoTag()->SetTitle(strTrack);
GetMusicInfoTag()->SetLoaded(true);
return true;
}
}
else
{
std::string fileName = URIUtils::GetFileName(m_strPath);
URIUtils::RemoveExtension(fileName);
for (unsigned int i = 0; i < g_advancedSettings.m_musicTagsFromFileFilters.size(); i++)
{
CLabelFormatter formatter(g_advancedSettings.m_musicTagsFromFileFilters[i], "");
if (formatter.FillMusicTag(fileName, GetMusicInfoTag()))
{
GetMusicInfoTag()->SetLoaded(true);
return true;
}
}
}
return false;
}
void CFileItemList::Swap(unsigned int item1, unsigned int item2)
{
if (item1 != item2 && item1 < m_items.size() && item2 < m_items.size())
std::swap(m_items[item1], m_items[item2]);
}
bool CFileItemList::UpdateItem(const CFileItem *item)
{
if (!item)
return false;
CSingleLock lock(m_lock);
for (unsigned int i = 0; i < m_items.size(); i++)
{
CFileItemPtr pItem = m_items[i];
if (pItem->IsSamePath(item))
{
pItem->UpdateInfo(*item);
return true;
}
}
return false;
}
void CFileItemList::AddSortMethod(SortBy sortBy, int buttonLabel, const LABEL_MASKS &labelMasks, SortAttribute sortAttributes /* = SortAttributeNone */)
{
AddSortMethod(sortBy, sortAttributes, buttonLabel, labelMasks);
}
void CFileItemList::AddSortMethod(SortBy sortBy, SortAttribute sortAttributes, int buttonLabel, const LABEL_MASKS &labelMasks)
{
SortDescription sorting;
sorting.sortBy = sortBy;
sorting.sortAttributes = sortAttributes;
AddSortMethod(sorting, buttonLabel, labelMasks);
}
void CFileItemList::AddSortMethod(SortDescription sortDescription, int buttonLabel, const LABEL_MASKS &labelMasks)
{
GUIViewSortDetails sort;
sort.m_sortDescription = sortDescription;
sort.m_buttonLabel = buttonLabel;
sort.m_labelMasks = labelMasks;
m_sortDetails.push_back(sort);
}
void CFileItemList::SetReplaceListing(bool replace)
{
m_replaceListing = replace;
}
void CFileItemList::ClearSortState()
{
m_sortDescription.sortBy = SortByNone;
m_sortDescription.sortOrder = SortOrderNone;
m_sortDescription.sortAttributes = SortAttributeNone;
}
CVideoInfoTag* CFileItem::GetVideoInfoTag()
{
if (!m_videoInfoTag)
m_videoInfoTag = new CVideoInfoTag;
return m_videoInfoTag;
}
CPictureInfoTag* CFileItem::GetPictureInfoTag()
{
if (!m_pictureInfoTag)
m_pictureInfoTag = new CPictureInfoTag;
return m_pictureInfoTag;
}
MUSIC_INFO::CMusicInfoTag* CFileItem::GetMusicInfoTag()
{
if (!m_musicInfoTag)
m_musicInfoTag = new MUSIC_INFO::CMusicInfoTag;
return m_musicInfoTag;
}
std::string CFileItem::FindTrailer() const
{
std::string strFile2;
std::string strFile = m_strPath;
if (IsStack())
{
std::string strPath;
URIUtils::GetParentPath(m_strPath,strPath);
CStackDirectory dir;
std::string strPath2;
strPath2 = dir.GetStackedTitlePath(strFile);
strFile = URIUtils::AddFileToFolder(strPath,URIUtils::GetFileName(strPath2));
CFileItem item(dir.GetFirstStackedFile(m_strPath),false);
std::string strTBNFile(URIUtils::ReplaceExtension(item.GetTBNFile(), "-trailer"));
strFile2 = URIUtils::AddFileToFolder(strPath,URIUtils::GetFileName(strTBNFile));
}
if (URIUtils::IsInRAR(strFile) || URIUtils::IsInZIP(strFile))
{
std::string strPath = URIUtils::GetDirectory(strFile);
std::string strParent;
URIUtils::GetParentPath(strPath,strParent);
strFile = URIUtils::AddFileToFolder(strParent,URIUtils::GetFileName(m_strPath));
}
// no local trailer available for these
if (IsInternetStream()
|| URIUtils::IsUPnP(strFile)
|| URIUtils::IsBluray(strFile)
|| IsLiveTV()
|| IsPlugin()
|| IsDVD())
return "";
std::string strDir = URIUtils::GetDirectory(strFile);
CFileItemList items;
CDirectory::GetDirectory(strDir, items, g_advancedSettings.m_videoExtensions, DIR_FLAG_READ_CACHE | DIR_FLAG_NO_FILE_INFO | DIR_FLAG_NO_FILE_DIRS);
URIUtils::RemoveExtension(strFile);
strFile += "-trailer";
std::string strFile3 = URIUtils::AddFileToFolder(strDir, "movie-trailer");
// Precompile our REs
VECCREGEXP matchRegExps;
CRegExp tmpRegExp(true, CRegExp::autoUtf8);
const std::vector<std::string>& strMatchRegExps = g_advancedSettings.m_trailerMatchRegExps;
std::vector<std::string>::const_iterator strRegExp = strMatchRegExps.begin();
while (strRegExp != strMatchRegExps.end())
{
if (tmpRegExp.RegComp(*strRegExp))
{
matchRegExps.push_back(tmpRegExp);
}
strRegExp++;
}
std::string strTrailer;
for (int i = 0; i < items.Size(); i++)
{
std::string strCandidate = items[i]->m_strPath;
URIUtils::RemoveExtension(strCandidate);
if (StringUtils::EqualsNoCase(strCandidate, strFile) ||
StringUtils::EqualsNoCase(strCandidate, strFile2) ||
StringUtils::EqualsNoCase(strCandidate, strFile3))
{
strTrailer = items[i]->m_strPath;
break;
}
else
{
VECCREGEXP::iterator expr = matchRegExps.begin();
while (expr != matchRegExps.end())
{
if (expr->RegFind(strCandidate) != -1)
{
strTrailer = items[i]->m_strPath;
i = items.Size();
break;
}
expr++;
}
}
}
return strTrailer;
}
int CFileItem::GetVideoContentType() const
{
VIDEODB_CONTENT_TYPE type = VIDEODB_CONTENT_MOVIES;
if (HasVideoInfoTag() && GetVideoInfoTag()->m_type == MediaTypeTvShow)
type = VIDEODB_CONTENT_TVSHOWS;
if (HasVideoInfoTag() && GetVideoInfoTag()->m_type == MediaTypeEpisode)
return VIDEODB_CONTENT_EPISODES;
if (HasVideoInfoTag() && GetVideoInfoTag()->m_type == MediaTypeMusicVideo)
return VIDEODB_CONTENT_MUSICVIDEOS;
CVideoDatabaseDirectory dir;
VIDEODATABASEDIRECTORY::CQueryParams params;
dir.GetQueryParams(m_strPath, params);
if (params.GetSetId() != -1 && params.GetMovieId() == -1) // movie set
return VIDEODB_CONTENT_MOVIE_SETS;
return type;
}
bool CFileItem::IsResumePointSet() const
{
return (HasVideoInfoTag() && GetVideoInfoTag()->m_resumePoint.IsSet()) ||
(m_pvrRecordingInfoTag && m_pvrRecordingInfoTag->GetLastPlayedPosition() > 0);
}
double CFileItem::GetCurrentResumeTime() const
{
if (m_pvrRecordingInfoTag)
{
// This will retrieve 'fresh' resume information from the PVR server
int rc = m_pvrRecordingInfoTag->GetLastPlayedPosition();
if (rc > 0)
return rc;
// Fall through to default value
}
if (HasVideoInfoTag() && GetVideoInfoTag()->m_resumePoint.IsSet())
{
return GetVideoInfoTag()->m_resumePoint.timeInSeconds;
}
// Resume from start when resume points are invalid or the PVR server returns an error
return 0;
}
| gpl-2.0 |
adamopoulosg/zagori_site | administrator/components/com_k2/models/model.php | 793 | <?php
/**
* @version 2.8.x
* @package K2
* @author JoomlaWorks http://www.joomlaworks.net
* @copyright Copyright (c) 2006 - 2017 JoomlaWorks Ltd. All rights reserved.
* @license GNU/GPL license: http://www.gnu.org/copyleft/gpl.html
*/
defined('_JEXEC') or die;
jimport('joomla.application.component.model');
if (version_compare(JVERSION, '2.5', 'ge'))
{
class K2Model extends JModelLegacy
{
public static function addIncludePath($path = '', $prefix = 'K2Model')
{
return parent::addIncludePath($path, $prefix);
}
}
}
else
{
class K2Model extends JModel
{
public function addIncludePath($path = '', $prefix = 'K2Model')
{
return parent::addIncludePath($path);
}
}
}
| gpl-2.0 |
oluabbeys/drupzod | cake/rd_cake/Model/PermanentUser.php | 13199 | <?php
App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component');
/**
* PermanentUser Model
*
*/
class PermanentUser extends AppModel {
public $actsAs = array('Containable');
public $validate = array(
'username' => array(
'required' => array(
'rule' => array('notBlank'),
'message' => 'Value is required'
),
'unique' => array(
'rule' => 'isUnique',
'message' => 'This name is already taken'
)
),
'password' => array(
'notBlank' => array(
'rule' => array('notBlank')
),
),
'realm_id' => array(
'numeric' => array(
'rule' => array('numeric')
),
),
'profile_id' => array(
'numeric' => array(
'rule' => array('numeric')
),
),
'country_id' => array(
'numeric' => array(
'rule' => array('numeric')
),
),
'language_id' => array(
'numeric' => array(
'rule' => array('numeric')
),
),
'user_id' => array(
'numeric' => array(
'rule' => array('numeric')
),
),
);
public $belongsTo = array(
'Country' => array(
'className' => 'Country',
'foreignKey' => 'country_id'
),
'Language' => array(
'className' => 'Language',
'foreignKey' => 'language_id'
),
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
'Profile' => array(
'className' => 'Profile',
'foreignKey' => 'profile_id'
),
'Realm' => array(
'className' => 'Realm',
'foreignKey' => 'realm_id'
)
);
public $hasMany = array(
'PermanentUserNote' => array(
'dependent' => true
),
'PermanentUserSetting' => array(
'dependent' => true
),
'Radcheck' => array(
'className' => 'Radcheck',
'foreignKey' => false,
'finderQuery' => 'SELECT Radcheck.* FROM radcheck AS Radcheck, permanent_users WHERE permanent_users.username=Radcheck.username AND permanent_users.id={$__cakeID__$}',
'dependent' => true
),
'Radreply' => array(
'className' => 'Radreply',
'foreignKey' => false,
'finderQuery' => 'SELECT Radreply.* FROM radreply AS Radreply, permanent_users WHERE permanent_users.username=Radreply.username AND permanent_users.id={$__cakeID__$}',
'dependent' => true
),
'Device' => array(
'dependent' => true
),
);
public function beforeSave($options = array()) {
if((isset($this->data['PermanentUser']['token']))&&($this->data['PermanentUser']['token']=='')){
App::uses('String', 'Utility');
$this->data['PermanentUser']['token'] = String::uuid();
}
if(isset($this->data['PermanentUser']['password'])){
$this->clearPwd = $this->data['PermanentUser']['password']; //Keep a copy of the original one
$this->data['PermanentUser']['password'] = AuthComponent::password($this->data['PermanentUser']['password']);
}
return true;
}
public function afterSave($created){
if($created){
$this->_add_radius_user();
}else{
$this->_update_radius_user();
}
}
private function _update_radius_user(){
$user_id = $this->data['PermanentUser']['id']; //The user's ID should always be present!
//Get the username
$q_r = $this->findById($user_id);
$username = $q_r['PermanentUser']['username'];
//enabled or disabled (Rd-Account-Disabled)
if(array_key_exists('active',$this->data['PermanentUser'])){ //It may be missing; you never know...
if($this->data['PermanentUser']['active'] == 1){ //Reverse the logic...
$dis = 0;
}else{
$dis = 1;
}
$this->_replace_radcheck_item($username,'Rd-Account-Disabled',$dis);
}
//Password (Cleartext-Password)
if(array_key_exists('password',$this->data['PermanentUser'])){ //Usually used to change the password
$this->_replace_radcheck_item($username,'Cleartext-Password',$this->clearPwd);
}
}
private function _add_radius_user(){
//The username with it's password (Cleartext-Password)
$username = $this->data['PermanentUser']['username'];
$this->_add_radcheck_item($username,'Cleartext-Password',$this->clearPwd);
$this->_add_radcheck_item($username,'Rd-User-Type','user');
//Realm (Rd-Realm)
if(array_key_exists('realm_id',$this->data['PermanentUser'])){ //It may be missing; you never know...
if($this->data['PermanentUser']['realm_id'] != ''){
$q_r = ClassRegistry::init('Realm')->findById($this->data['PermanentUser']['realm_id']);
$realm_name = $q_r['Realm']['name'];
$this->_add_radcheck_item($username,'Rd-Realm',$realm_name);
}
}
//Profile name (User-Profile)
if(array_key_exists('profile_id',$this->data['PermanentUser'])){ //It may be missing; you never know...
if($this->data['PermanentUser']['profile_id'] != ''){
$q_r = ClassRegistry::init('Profile')->findById($this->data['PermanentUser']['profile_id']);
$profile_name = $q_r['Profile']['name'];
$this->_add_radcheck_item($username,'User-Profile',$profile_name);
}
}
//cap type (Rd-Cap-Type-Time this will dertermine if we enforce a counter or not)
if(array_key_exists('cap_time',$this->data['PermanentUser'])){ //It may be missing; you never know...
if($this->data['PermanentUser']['cap_time'] != ''){
$this->_add_radcheck_item($username,'Rd-Cap-Type-Time',$this->data['PermanentUser']['cap_time']);
}
}
//cap type (Rd-Cap-Type-Data this will dertermine if we enforce a counter or not)
if(array_key_exists('cap_data',$this->data['PermanentUser'])){ //It may be missing; you never know...
if($this->data['PermanentUser']['cap_data'] != ''){
$this->_add_radcheck_item($username,'Rd-Cap-Type-Data',$this->data['PermanentUser']['cap_data']);
}
}
//enabled or disabled (Rd-Account-Disabled)
if(array_key_exists('active',$this->data['PermanentUser'])){ //It may be missing; you never know...
if($this->data['PermanentUser']['active'] != ''){
if($this->data['PermanentUser']['active'] == 1){ //Reverse the logic...
$dis = 0;
}else{
$dis = 1;
}
$this->_add_radcheck_item($username,'Rd-Account-Disabled',$dis);
}
}
//Activation date (Rd-Account-Activation-Time)
if(array_key_exists('from_date',$this->data['PermanentUser'])){ //It may be missing; you never know...
if($this->data['PermanentUser']['from_date'] != ''){
$expiration = $this->_radius_format_date($this->data['PermanentUser']['from_date']);
$this->_add_radcheck_item($username,'Rd-Account-Activation-Time',$expiration);
}
}
//Expiration date (Expiration)
if(array_key_exists('to_date',$this->data['PermanentUser'])){ //It may be missing; you never know...
if($this->data['PermanentUser']['to_date'] != ''){
$expiration = $this->_radius_format_date($this->data['PermanentUser']['to_date']);
$this->_add_radcheck_item($username,'Expiration',$expiration);
}
}
//Not Track auth (Rd-Not-Track-Auth) *By default we will (in post-auth)
if(!array_key_exists('track_auth',$this->data['PermanentUser'])){ //It may be missing; you never know...
$this->_add_radcheck_item($username,'Rd-Not-Track-Auth',1);
}
//Not Track acct (Rd-Not-Track-Acct) *By default we will (in pre-acct)
if(!array_key_exists('track_acct',$this->data['PermanentUser'])){ //It may be missing; you never know...
$this->_add_radcheck_item($username,'Rd-Not-Track-Acct',1);
}
//Static IP
if(array_key_exists('static_ip',$this->data['PermanentUser'])){ //It may be missing; you never know...
if($this->data['PermanentUser']['static_ip'] != ''){
$static_ip = $this->data['PermanentUser']['static_ip'];
$this->_add_radreply_item($username,'Service-Type','Framed-User');
$this->_add_radreply_item($username,'Framed-IP-Address',$static_ip);
}
}
//Auto add MAC
if(array_key_exists('auto_add',$this->data['PermanentUser'])){
$this->_add_radcheck_item($username,'Rd-Auto-Mac',1);
}
//If this is an LDAP user
if(array_key_exists('auth_type',$this->data['PermanentUser'])){
if($this->data['PermanentUser']['auth_type'] != 'sql'){ //SQL is the default so we do not need to add the default
$this->_add_radcheck_item($username,'Rd-Auth-Type',$this->data['PermanentUser']['auth_type']);
}
}
//If this is restriction for SSID ....
if(array_key_exists('ssid_only',$this->data['PermanentUser'])){ //It may be missing; you never know...
if($this->data['PermanentUser']['ssid_only'] != ''){
$this->_add_radcheck_item($username,'Rd-Ssid-Check','1');
}
}
//_____ New addition where we can supply SSID ids _____
$count = 0;
$ssid_list = array();
if (
(array_key_exists('ssid_only', $this->data['PermanentUser']))&&
(array_key_exists('ssid_list', $this->data['PermanentUser']))
) {
//--We force checking--
$this->_add_radcheck_item($username,'Rd-Ssid-Check','1');
$ssid_list = array();
foreach($this->data['PermanentUser']['ssid_list'] as $s){
if($this->data['PermanentUser']['ssid_list'][$count] == 0){
$empty_flag = true;
break;
}else{
array_push($ssid_list,$this->data['PermanentUser']['ssid_list'][$count]);
}
$count++;
}
$this->_replace_user_ssids($username,$ssid_list);
}
}
private function _radius_format_date($d){
//Format will be month/date/year eg 03/06/2013 we need it to be 6 Mar 2013
$arr_date = explode('/',$d);
$month = intval($arr_date[0]);
$m_arr = array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
$day = intval($arr_date[1]);
$year = intval($arr_date[2]);
return "$day ".$m_arr[($month-1)]." $year";
}
private function _add_radcheck_item($username,$item,$value,$op = ":="){
$this->Radcheck = ClassRegistry::init('Radcheck');
$this->Radcheck->create();
$d['Radcheck']['username'] = $username;
$d['Radcheck']['op'] = $op;
$d['Radcheck']['attribute'] = $item;
$d['Radcheck']['value'] = $value;
$this->Radcheck->save($d);
$this->Radcheck->id = null;
}
private function _add_radreply_item($username,$item,$value,$op = ":="){
$this->Radreply = ClassRegistry::init('Radreply');
$this->Radreply->create();
$d['Radreply']['username'] = $username;
$d['Radreply']['op'] = $op;
$d['Radreply']['attribute'] = $item;
$d['Radreply']['value'] = $value;
$this->Radreply->save($d);
$this->Radreply->id = null;
}
private function _replace_radcheck_item($username,$item,$value,$op = ":="){
$this->Radcheck = ClassRegistry::init('Radcheck');
$this->Radcheck->deleteAll(
array('Radcheck.username' => $username,'Radcheck.attribute' => $item), false
);
$this->Radcheck->create();
$d['Radcheck']['username'] = $username;
$d['Radcheck']['op'] = $op;
$d['Radcheck']['attribute'] = $item;
$d['Radcheck']['value'] = $value;
$this->Radcheck->save($d);
$this->Radcheck->id = null;
}
private function _replace_user_ssids($username,$ssid_list){
$u = ClassRegistry::init('UserSsid');
//Clean up previous ones
$u->deleteAll(
array('UserSsid.username' => $username), false
);
//Get all the SSID names from the $ssid_list
$s = ClassRegistry::init('Ssid');
$s->contain();
$id_list = array();
foreach($ssid_list as $i){
array_push($id_list, array('Ssid.id' => strval($i)));
}
$q_r = $s->find('all', array('conditions' => array('OR' =>$id_list)));
foreach($q_r as $j){
$name = $j['Ssid']['name'];
$data = array();
$data['username'] = $username;
$data['ssidname'] = $name;
$u->create();
$u->save($data);
$u->id = null;
}
}
}
| gpl-2.0 |
asif-mahmud/Pyramid-Apps | pethouse/pethouse/tests/__init__.py | 1723 | import unittest
import transaction
from pyramid import testing
def dummy_request(dbsession):
return testing.DummyRequest(dbsession=dbsession)
class BaseTest(unittest.TestCase):
def setUp(self):
self.config = testing.setUp(settings={
'sqlalchemy.url': 'sqlite:///:memory:'
})
self.config.include('.models')
settings = self.config.get_settings()
from ..models import (
get_engine,
get_session_factory,
get_tm_session,
)
self.engine = get_engine(settings)
session_factory = get_session_factory(self.engine)
self.session = get_tm_session(session_factory, transaction.manager)
def init_database(self):
from ..models.meta import Base
Base.metadata.create_all(self.engine)
def tearDown(self):
from ..models.meta import Base
testing.tearDown()
transaction.abort()
Base.metadata.drop_all(self.engine)
"""
class TestMyViewSuccessCondition(BaseTest):
def setUp(self):
super(TestMyViewSuccessCondition, self).setUp()
self.init_database()
from .models import MyModel
model = MyModel(name='one', value=55)
self.session.add(model)
def test_passing_view(self):
from .views.default import my_view
info = my_view(dummy_request(self.session))
self.assertEqual(info['one'].name, 'one')
self.assertEqual(info['project'], 'searchbox')
class TestMyViewFailureCondition(BaseTest):
def test_failing_view(self):
from .views.default import my_view
info = my_view(dummy_request(self.session))
self.assertEqual(info.status_int, 500)
"""
| gpl-2.0 |
universsky/openjdk | jdk/src/java.base/share/classes/jdk/internal/jimage/decompressor/CompressedResourceHeader.java | 4319 | /*
* Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.internal.jimage.decompressor;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Objects;
import jdk.internal.jimage.decompressor.ResourceDecompressor.StringsProvider;
/**
*
* A resource header for compressed resource. This class is handled internally,
* you don't have to add header to the resource, headers are added automatically
* for compressed resources.
*/
public final class CompressedResourceHeader {
private static final int SIZE = 21;
public static final int MAGIC = 0xCAFEFAFA;
private final int uncompressedSize;
private final int compressedSize;
private final int decompressorNameOffset;
private final int contentOffset;
private final boolean isTerminal;
public CompressedResourceHeader(int compressedSize,
int uncompressedSize, int decompressorNameOffset, int contentOffset,
boolean isTerminal) {
this.compressedSize = compressedSize;
this.uncompressedSize = uncompressedSize;
this.decompressorNameOffset = decompressorNameOffset;
this.contentOffset = contentOffset;
this.isTerminal = isTerminal;
}
public boolean isTerminal() {
return isTerminal;
}
public int getDecompressorNameOffset() {
return decompressorNameOffset;
}
public int getContentOffset() {
return contentOffset;
}
public String getStoredContent(StringsProvider provider) {
Objects.nonNull(provider);
if(contentOffset == -1) {
return null;
}
return provider.getString(contentOffset);
}
public int getUncompressedSize() {
return uncompressedSize;
}
public int getResourceSize() {
return compressedSize;
}
public byte[] getBytes(ByteOrder order) {
Objects.requireNonNull(order);
ByteBuffer buffer = ByteBuffer.allocate(SIZE);
buffer.order(order);
buffer.putInt(MAGIC);
buffer.putInt(compressedSize);
buffer.putInt(uncompressedSize);
buffer.putInt(decompressorNameOffset);
buffer.putInt(contentOffset);
buffer.put(isTerminal ? (byte)1 : (byte)0);
return buffer.array();
}
public static int getSize() {
return SIZE;
}
public static CompressedResourceHeader readFromResource(ByteOrder order,
byte[] resource) {
Objects.requireNonNull(order);
Objects.requireNonNull(resource);
if (resource.length < getSize()) {
return null;
}
ByteBuffer buffer = ByteBuffer.wrap(resource, 0, SIZE);
buffer.order(order);
int magic = buffer.getInt();
if(magic != MAGIC) {
return null;
}
int size = buffer.getInt();
int uncompressedSize = buffer.getInt();
int decompressorNameOffset = buffer.getInt();
int contentIndex = buffer.getInt();
byte isTerminal = buffer.get();
return new CompressedResourceHeader(size, uncompressedSize,
decompressorNameOffset, contentIndex, isTerminal == 1);
}
}
| gpl-2.0 |
d6bmg/BitsB1.1 | include/geshi/geshi/tsql.php | 24150 | <?php
/*
+------------------------------------------------
| BitsB PHP based BitTorrent Tracker
| =============================================
| by d6bmg
| Copyright (C) 2010-2011 BitsB v1.0
| =============================================
| svn: http:// coming soon.. :)
| Licence Info: GPL
+------------------------------------------------
*/
/*************************************************************************************
* tsql.php
* --------
* Author: Duncan Lock (dunc@dflock.co.uk)
* Copyright: (c) 2006 Duncan Lock (http://dflock.co.uk/), Nigel McNie (http://qbnz.com/highlighter)
* Release Version: 1.0.8.3
* Date Started: 2005/11/22
*
* T-SQL language file for GeSHi.
*
* CHANGES
* -------
* 2004/01/23 (1.0.0)
* - First Release
*
* TODO (updated 2006/01/23)
* -------------------------
*
*************************************************************************************
*
* This file is part of GeSHi.
*
* GeSHi is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GeSHi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GeSHi; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
************************************************************************************/
$language_data = array (
'LANG_NAME' => 'T-SQL',
'COMMENT_SINGLE' => array(1 => '--'),
'COMMENT_MULTI' => array('/*' => '*/'),
'CASE_KEYWORDS' => GESHI_CAPS_UPPER,
'QUOTEMARKS' => array("'", '"'),
'ESCAPE_CHAR' => '\\',
'KEYWORDS' => array(
1 => array(
// Datatypes
'bigint', 'int', 'smallint', 'tinyint', 'bit', 'decimal', 'numeric', 'money',
'smallmoney', 'float', 'real', 'datetime', 'smalldatetime', 'char', 'varchar',
'text', 'nchar', 'nvarchar', 'ntext', 'binary', 'varbinary', 'image', 'cursor',
'sql_variant', 'table', 'timestamp', 'uniqueidentifier',
// Keywords
'ABSOLUTE', 'ACTION', 'ADD', 'ADMIN', 'AFTER', 'AGGREGATE', 'ALIAS', 'ALLOCATE', 'ALTER', 'ARE', 'ARRAY', 'AS',
'ASC', 'ASSERTION', 'AT', 'AUTHORIZATION', 'BACKUP', 'BEFORE', 'BEGIN', 'BINARY', 'BIT', 'BLOB', 'BOOLEAN', 'BOTH', 'BREADTH',
'BREAK', 'BROWSE', 'BULK', 'BY', 'CALL', 'CASCADE', 'CASCADED', 'CASE', 'CAST', 'CATALOG', 'CHAR', 'CHARACTER', 'CHECK', 'CHECKPOINT',
'CLASS', 'CLOB', 'CLOSE', 'CLUSTERED', 'COALESCE', 'COLLATE', 'COLLATION', 'COLUMN', 'COMMIT', 'COMPLETION', 'COMPUTE', 'CONNECT',
'CONNECTION', 'CONSTRAINT', 'CONSTRAINTS', 'CONSTRUCTOR', 'CONTAINS', 'CONTAINSTABLE', 'CONTINUE', 'CONVERT', 'CORRESPONDING', 'CREATE',
'CUBE', 'CURRENT', 'CURRENT_DATE', 'CURRENT_PATH', 'CURRENT_ROLE', 'CURRENT_TIME', 'CURRENT_TIMESTAMP', 'CURRENT_USER',
'CURSOR', 'CYCLE', 'DATA', 'DATABASE', 'DATE', 'DAY', 'DBCC', 'DEALLOCATE', 'DEC', 'DECIMAL', 'DECLARE', 'DEFAULT', 'DEFERRABLE',
'DEFERRED', 'DELETE', 'DENY', 'DEPTH', 'DEREF', 'DESC', 'DESCRIBE', 'DESCRIPTOR', 'DESTROY', 'DESTRUCTOR', 'DETERMINISTIC',
'DIAGNOSTICS', 'DICTIONARY', 'DISCONNECT', 'DISK', 'DISTINCT', 'DISTRIBUTED', 'DOMAIN', 'DOUBLE', 'DROP', 'DUMMY', 'DUMP', 'DYNAMIC',
'EACH', 'ELSE', 'END', 'END-EXEC', 'EQUALS', 'ERRLVL', 'ESCAPE', 'EVERY', 'EXCEPT', 'EXCEPTION', 'EXEC', 'EXECUTE', 'EXIT',
'EXTERNAL', 'FALSE', 'FETCH', 'FILE', 'FILLFACTOR', 'FIRST', 'FLOAT', 'FOR', 'FOREIGN', 'FOUND', 'FREE', 'FREETEXT', 'FREETEXTTABLE',
'FROM', 'FULL', 'FUNCTION', 'GENERAL', 'GET', 'GLOBAL', 'GOTO', 'GRANT', 'GROUP', 'GROUPING', 'HAVING', 'HOLDLOCK', 'HOST', 'HOUR',
'IDENTITY', 'IDENTITY_INSERT', 'IDENTITYCOL', 'IF', 'IGNORE', 'IMMEDIATE', 'INDEX', 'INDICATOR', 'INITIALIZE', 'INITIALLY',
'INNER', 'INOUT', 'INPUT', 'INSERT', 'INT', 'INTEGER', 'INTERSECT', 'INTERVAL', 'INTO', 'IS', 'ISOLATION', 'ITERATE', 'KEY',
'KILL', 'LANGUAGE', 'LARGE', 'LAST', 'LATERAL', 'LEADING', 'LEFT', 'LESS', 'LEVEL', 'LIMIT', 'LINENO', 'LOAD', 'LOCAL',
'LOCALTIME', 'LOCALTIMESTAMP', 'LOCATOR', 'MAP', 'MATCH', 'MINUTE', 'MODIFIES', 'MODIFY', 'MODULE', 'MONTH', 'NAMES', 'NATIONAL',
'NATURAL', 'NCHAR', 'NCLOB', 'NEW', 'NEXT', 'NO', 'NOCHECK', 'NONCLUSTERED', 'NONE', 'NULLIF', 'NUMERIC', 'OBJECT', 'OF',
'OFF', 'OFFSETS', 'OLD', 'ON', 'ONLY', 'OPEN', 'OPENDATASOURCE', 'OPENQUERY', 'OPENROWSET', 'OPENXML', 'OPERATION', 'OPTION',
'ORDER', 'ORDINALITY', 'OUT', 'OUTPUT', 'OVER', 'PAD', 'PARAMETER', 'PARAMETERS', 'PARTIAL', 'PATH', 'PERCENT', 'PLAN',
'POSTFIX', 'PRECISION', 'PREFIX', 'PREORDER', 'PREPARE', 'PRESERVE', 'PRIMARY', 'PRINT', 'PRIOR', 'PRIVILEGES', 'PROC', 'PROCEDURE',
'PUBLIC', 'RAISERROR', 'READ', 'READS', 'READTEXT', 'REAL', 'RECONFIGURE', 'RECURSIVE', 'REF', 'REFERENCES', 'REFERENCING', 'RELATIVE',
'REPLICATION', 'RESTORE', 'RESTRICT', 'RESULT', 'RETURN', 'RETURNS', 'REVOKE', 'RIGHT', 'ROLE', 'ROLLBACK', 'ROLLUP', 'ROUTINE', 'ROW',
'ROWGUIDCOL', 'ROWS', 'RULE', 'SAVE', 'SAVEPOINT', 'SCHEMA', 'SCOPE', 'SCROLL', 'SEARCH', 'SECOND', 'SECTION', 'SELECT',
'SEQUENCE', 'SESSION', 'SESSION_USER', 'SET', 'SETS', 'SETUSER', 'SHUTDOWN', 'SIZE', 'SMALLINT', 'SPACE', 'SPECIFIC',
'SPECIFICTYPE', 'SQL', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNING', 'START', 'STATE', 'STATEMENT', 'STATIC', 'STATISTICS', 'STRUCTURE',
'SYSTEM_USER', 'TABLE', 'TEMPORARY', 'TERMINATE', 'TEXTSIZE', 'THAN', 'THEN', 'TIME', 'TIMESTAMP', 'TIMEZONE_HOUR', 'TIMEZONE_MINUTE',
'TO', 'TOP', 'TRAILING', 'TRAN', 'TRANSACTION', 'TRANSLATION', 'TREAT', 'TRIGGER', 'TRUE', 'TRUNCATE', 'TSEQUAL', 'UNDER', 'UNION',
'UNIQUE', 'UNKNOWN', 'UNNEST', 'UPDATE', 'UPDATETEXT', 'USAGE', 'USE', 'USER', 'USING', 'VALUE', 'VALUES', 'VARCHAR', 'VARIABLE',
'VARYING', 'VIEW', 'WAITFOR', 'WHEN', 'WHENEVER', 'WHERE', 'WHILE', 'WITH', 'WITHOUT', 'WORK', 'WRITE', 'WRITETEXT', 'YEAR', 'ZONE',
'UNCOMMITTED', 'NOCOUNT',
),
2 => array(
/*
Built-in functions
Highlighted in pink.
*/
//Configuration Functions
'@@DATEFIRST','@@OPTIONS','@@DBTS','@@REMSERVER','@@LANGID','@@SERVERNAME',
'@@LANGUAGE','@@SERVICENAME','@@LOCK_TIMEOUT','@@SPID','@@MAX_CONNECTIONS','@@TEXTSIZE',
'@@MAX_PRECISION','@@VERSION','@@NESTLEVEL',
//Cursor Functions
'@@CURSOR_ROWS','@@FETCH_STATUS',
//Date and Time Functions
'DATEADD','DATEDIFF','DATENAME','DATEPART','DAY','GETDATE','GETUTCDATE','MONTH','YEAR',
//Mathematical Functions
'ABS','DEGREES','RAND','ACOS','EXP','ROUND','ASIN','FLOOR','SIGN',
'ATAN','LOG','SIN','ATN2','LOG10','SQUARE','CEILING','PI','SQRT','COS',
'POWER','TAN','COT','RADIANS',
//Meta Data Functions
'COL_LENGTH','fn_listextendedproperty','COL_NAME','FULLTEXTCATALOGPROPERTY',
'COLUMNPROPERTY','FULLTEXTSERVICEPROPERTY','DATABASEPROPERTY','INDEX_COL',
'DATABASEPROPERTYEX','INDEXKEY_PROPERTY','DB_ID','INDEXPROPERTY','DB_NAME',
'OBJECT_ID','FILE_ID','OBJECT_NAME','FILE_NAME','OBJECTPROPERTY','FILEGROUP_ID',
'@@PROCID','FILEGROUP_NAME','SQL_VARIANT_PROPERTY','FILEGROUPPROPERTY',
'TYPEPROPERTY','FILEPROPERTY',
//Security Functions
'fn_trace_geteventinfo','IS_SRVROLEMEMBER','fn_trace_getfilterinfo','SUSER_SID',
'fn_trace_getinfo','SUSER_SNAME','fn_trace_gettable','USER_ID','HAS_DBACCESS',
'IS_MEMBER',
//String Functions
'ASCII','NCHAR','SOUNDEX','CHAR','PATINDEX','SPACE','CHARINDEX',
'REPLACE','STR','DIFFERENCE','QUOTENAME','STUFF','LEFT','REPLICATE',
'SUBSTRING','LEN','REVERSE','UNICODE','LOWER','RIGHT','UPPER','LTRIM',
'RTRIM',
//System Functions
'APP_NAME','COLLATIONPROPERTY','@@ERROR','fn_helpcollations',
'fn_servershareddrives','fn_virtualfilestats','FORMATMESSAGE',
'GETANSINULL','HOST_ID','HOST_NAME','IDENT_CURRENT','IDENT_INCR',
'IDENT_SEED','@@IDENTITY','ISDATE','ISNUMERIC','PARSENAME','PERMISSIONS',
'@@ROWCOUNT','ROWCOUNT_BIG','SCOPE_IDENTITY','SERVERPROPERTY','SESSIONPROPERTY',
'STATS_DATE','@@TRANCOUNT','USER_NAME',
//System Statistical Functions
'@@CONNECTIONS','@@PACK_RECEIVED','@@CPU_BUSY','@@PACK_SENT',
'@@TIMETICKS','@@IDLE','@@TOTAL_ERRORS','@@IO_BUSY',
'@@TOTAL_READ','@@PACKET_ERRORS','@@TOTAL_WRITE',
//Text and Image Functions
'TEXTPTR','TEXTVALID',
//Aggregate functions
'AVG', 'MAX', 'BINARY_CHECKSUM', 'MIN', 'CHECKSUM', 'SUM', 'CHECKSUM_AGG',
'STDEV', 'COUNT', 'STDEVP', 'COUNT_BIG', 'VAR', 'GROUPING', 'VARP'
),
3 => array(
/*
System stored procedures
Higlighted dark brown
*/
//Active Directory Procedures
'sp_ActiveDirectory_Obj', 'sp_ActiveDirectory_SCP',
//Catalog Procedures
'sp_column_privileges', 'sp_special_columns', 'sp_columns', 'sp_sproc_columns',
'sp_databases', 'sp_statistics', 'sp_fkeys', 'sp_stored_procedures', 'sp_pkeys',
'sp_table_privileges', 'sp_server_info', 'sp_tables',
//Cursor Procedures
'sp_cursor_list', 'sp_describe_cursor_columns', 'sp_describe_cursor', 'sp_describe_cursor_tables',
//Database Maintenance Plan Procedures
'sp_add_maintenance_plan', 'sp_delete_maintenance_plan_db', 'sp_add_maintenance_plan_db',
'sp_delete_maintenance_plan_job', 'sp_add_maintenance_plan_job', 'sp_help_maintenance_plan',
'sp_delete_maintenance_plan',
//Distributed Queries Procedures
'sp_addlinkedserver', 'sp_indexes', 'sp_addlinkedsrvlogin', 'sp_linkedservers', 'sp_catalogs',
'sp_primarykeys', 'sp_column_privileges_ex', 'sp_columns_ex',
'sp_table_privileges_ex', 'sp_tables_ex', 'sp_foreignkeys',
//Full-Text Search Procedures
'sp_fulltext_catalog', 'sp_help_fulltext_catalogs_cursor', 'sp_fulltext_column',
'sp_help_fulltext_columns', 'sp_fulltext_database', 'sp_help_fulltext_columns_cursor',
'sp_fulltext_service', 'sp_help_fulltext_tables', 'sp_fulltext_table',
'sp_help_fulltext_tables_cursor', 'sp_help_fulltext_catalogs',
//Log Shipping Procedures
'sp_add_log_shipping_database', 'sp_delete_log_shipping_database', 'sp_add_log_shipping_plan',
'sp_delete_log_shipping_plan', 'sp_add_log_shipping_plan_database',
'sp_delete_log_shipping_plan_database', 'sp_add_log_shipping_primary',
'sp_delete_log_shipping_primary', 'sp_add_log_shipping_secondary',
'sp_delete_log_shipping_secondary', 'sp_can_tlog_be_applied', 'sp_get_log_shipping_monitor_info',
'sp_change_monitor_role', 'sp_remove_log_shipping_monitor', 'sp_change_primary_role',
'sp_resolve_logins', 'sp_change_secondary_role', 'sp_update_log_shipping_monitor_info',
'sp_create_log_shipping_monitor_account', 'sp_update_log_shipping_plan',
'sp_define_log_shipping_monitor', 'sp_update_log_shipping_plan_database',
//OLE Automation Extended Stored Procedures
'sp_OACreate', 'sp_OAMethod', 'sp_OADestroy', 'sp_OASetProperty', 'sp_OAGetErrorInfo',
'sp_OAStop', 'sp_OAGetProperty',
//Replication Procedures
'sp_add_agent_parameter', 'sp_enableagentoffload', 'sp_add_agent_profile',
'sp_enumcustomresolvers', 'sp_addarticle', 'sp_enumdsn', 'sp_adddistpublisher',
'sp_enumfullsubscribers', 'sp_adddistributiondb', 'sp_expired_subscription_cleanup',
'sp_adddistributor', 'sp_generatefilters', 'sp_addmergealternatepublisher',
'sp_getagentoffloadinfo', 'sp_addmergearticle', 'sp_getmergedeletetype', 'sp_addmergefilter',
'sp_get_distributor', 'sp_addmergepublication', 'sp_getqueuedrows', 'sp_addmergepullsubscription',
'sp_getsubscriptiondtspackagename', 'sp_addmergepullsubscription_agent', 'sp_grant_publication_access',
'sp_addmergesubscription', 'sp_help_agent_default', 'sp_addpublication', 'sp_help_agent_parameter',
'sp_addpublication_snapshot', 'sp_help_agent_profile', 'sp_addpublisher70', 'sp_helparticle',
'sp_addpullsubscription', 'sp_helparticlecolumns', 'sp_addpullsubscription_agent', 'sp_helparticledts',
'sp_addscriptexec', 'sp_helpdistpublisher', 'sp_addsubscriber', 'sp_helpdistributiondb',
'sp_addsubscriber_schedule', 'sp_helpdistributor', 'sp_addsubscription', 'sp_helpmergealternatepublisher',
'sp_addsynctriggers', 'sp_helpmergearticle', 'sp_addtabletocontents', 'sp_helpmergearticlecolumn',
'sp_adjustpublisheridentityrange', 'sp_helpmergearticleconflicts', 'sp_article_validation',
'sp_helpmergeconflictrows', 'sp_articlecolumn', 'sp_helpmergedeleteconflictrows', 'sp_articlefilter',
'sp_helpmergefilter', 'sp_articlesynctranprocs', 'sp_helpmergepublication', 'sp_articleview',
'sp_helpmergepullsubscription', 'sp_attachsubscription', 'sp_helpmergesubscription', 'sp_browsesnapshotfolder',
'sp_helppublication', 'sp_browsemergesnapshotfolder', 'sp_help_publication_access', 'sp_browsereplcmds',
'sp_helppullsubscription', 'sp_change_agent_parameter', 'sp_helpreplfailovermode', 'sp_change_agent_profile',
'sp_helpreplicationdboption', 'sp_changearticle', 'sp_helpreplicationoption', 'sp_changedistpublisher',
'sp_helpsubscriberinfo', 'sp_changedistributiondb', 'sp_helpsubscription', 'sp_changedistributor_password',
'sp_ivindexhasnullcols', 'sp_changedistributor_property', 'sp_helpsubscription_properties', 'sp_changemergearticle',
'sp_link_publication', 'sp_changemergefilter', 'sp_marksubscriptionvalidation', 'sp_changemergepublication',
'sp_mergearticlecolumn', 'sp_changemergepullsubscription', 'sp_mergecleanupmetadata', 'sp_changemergesubscription',
'sp_mergedummyupdate', 'sp_changepublication', 'sp_mergesubscription_cleanup', 'sp_changesubscriber',
'sp_publication_validation', 'sp_changesubscriber_schedule', 'sp_refreshsubscriptions', 'sp_changesubscriptiondtsinfo',
'sp_reinitmergepullsubscription', 'sp_changesubstatus', 'sp_reinitmergesubscription', 'sp_change_subscription_properties',
'sp_reinitpullsubscription', 'sp_check_for_sync_trigger', 'sp_reinitsubscription', 'sp_copymergesnapshot',
'sp_removedbreplication', 'sp_copysnapshot', 'sp_repladdcolumn', 'sp_copysubscription', 'sp_replcmds',
'sp_deletemergeconflictrow', 'sp_replcounters', 'sp_disableagentoffload', 'sp_repldone', 'sp_drop_agent_parameter',
'sp_repldropcolumn', 'sp_drop_agent_profile', 'sp_replflush', 'sp_droparticle', 'sp_replicationdboption',
'sp_dropanonymouseagent', 'sp_replication_agent_checkup', 'sp_dropdistpublisher', 'sp_replqueuemonitor',
'sp_dropdistributiondb', 'sp_replsetoriginator', 'sp_dropmergealternatepublisher', 'sp_replshowcmds',
'sp_dropdistributor', 'sp_repltrans', 'sp_dropmergearticle', 'sp_restoredbreplication', 'sp_dropmergefilter',
'sp_revoke_publication_access', 'sp_scriptsubconflicttable', 'sp_dropmergepublication', 'sp_script_synctran_commands',
'sp_dropmergepullsubscription', 'sp_setreplfailovermode', 'sp_showrowreplicainfo', 'sp_dropmergesubscription',
'sp_subscription_cleanup', 'sp_droppublication', 'sp_table_validation', 'sp_droppullsubscription',
'sp_update_agent_profile', 'sp_dropsubscriber', 'sp_validatemergepublication', 'sp_dropsubscription',
'sp_validatemergesubscription', 'sp_dsninfo', 'sp_vupgrade_replication', 'sp_dumpparamcmd',
//Security Procedures
'sp_addalias', 'sp_droprolemember', 'sp_addapprole', 'sp_dropserver', 'sp_addgroup', 'sp_dropsrvrolemember',
'sp_dropuser', 'sp_addlogin', 'sp_grantdbaccess', 'sp_addremotelogin',
'sp_grantlogin', 'sp_addrole', 'sp_helpdbfixedrole', 'sp_addrolemember', 'sp_helpgroup',
'sp_addserver', 'sp_helplinkedsrvlogin', 'sp_addsrvrolemember', 'sp_helplogins', 'sp_adduser',
'sp_helpntgroup', 'sp_approlepassword', 'sp_helpremotelogin', 'sp_changedbowner', 'sp_helprole',
'sp_changegroup', 'sp_helprolemember', 'sp_changeobjectowner', 'sp_helprotect', 'sp_change_users_login',
'sp_helpsrvrole', 'sp_dbfixedrolepermission', 'sp_helpsrvrolemember', 'sp_defaultdb', 'sp_helpuser',
'sp_defaultlanguage', 'sp_MShasdbaccess', 'sp_denylogin', 'sp_password', 'sp_dropalias', 'sp_remoteoption',
'sp_dropapprole', 'sp_revokedbaccess', 'sp_dropgroup', 'sp_revokelogin', 'sp_droplinkedsrvlogin',
'sp_setapprole', 'sp_droplogin', 'sp_srvrolepermission', 'sp_dropremotelogin', 'sp_validatelogins', 'sp_droprole',
//SQL Mail Procedures
'sp_processmail', 'xp_sendmail', 'xp_deletemail', 'xp_startmail', 'xp_findnextmsg', 'xp_stopmail', 'xp_readmail',
//SQL Profiler Procedures
'sp_trace_create', 'sp_trace_setfilter', 'sp_trace_generateevent', 'sp_trace_setstatus', 'sp_trace_setevent',
//SQL Server Agent Procedures
'sp_add_alert', 'sp_help_jobhistory', 'sp_add_category', 'sp_help_jobschedule', 'sp_add_job',
'sp_help_jobserver', 'sp_add_jobschedule', 'sp_help_jobstep', 'sp_add_jobserver', 'sp_help_notification',
'sp_add_jobstep', 'sp_help_operator', 'sp_add_notification', 'sp_help_targetserver',
'sp_add_operator', 'sp_help_targetservergroup', 'sp_add_targetservergroup', 'sp_helptask',
'sp_add_targetsvrgrp_member', 'sp_manage_jobs_by_login', 'sp_addtask', 'sp_msx_defect',
'sp_apply_job_to_targets', 'sp_msx_enlist', 'sp_delete_alert', 'sp_post_msx_operation',
'sp_delete_category', 'sp_purgehistory', 'sp_delete_job', 'sp_purge_jobhistory', 'sp_delete_jobschedule',
'sp_reassigntask', 'sp_delete_jobserver', 'sp_remove_job_from_targets', 'sp_delete_jobstep',
'sp_resync_targetserver', 'sp_delete_notification', 'sp_start_job', 'sp_delete_operator',
'sp_stop_job', 'sp_delete_targetserver', 'sp_update_alert', 'sp_delete_targetservergroup',
'sp_update_category', 'sp_delete_targetsvrgrp_member', 'sp_update_job', 'sp_droptask',
'sp_update_jobschedule', 'sp_help_alert', 'sp_update_jobstep', 'sp_help_category',
'sp_update_notification', 'sp_help_downloadlist', 'sp_update_operator', 'sp_helphistory',
'sp_update_targetservergroup', 'sp_help_job', 'sp_updatetask', 'xp_sqlagent_proxy_account',
//System Procedures
'sp_add_data_file_recover_suspect_db', 'sp_helpconstraint', 'sp_addextendedproc',
'sp_helpdb', 'sp_addextendedproperty', 'sp_helpdevice', 'sp_add_log_file_recover_suspect_db',
'sp_helpextendedproc', 'sp_addmessage', 'sp_helpfile', 'sp_addtype', 'sp_helpfilegroup',
'sp_addumpdevice', 'sp_helpindex', 'sp_altermessage', 'sp_helplanguage', 'sp_autostats',
'sp_helpserver', 'sp_attach_db', 'sp_helpsort', 'sp_attach_single_file_db', 'sp_helpstats',
'sp_bindefault', 'sp_helptext', 'sp_bindrule', 'sp_helptrigger', 'sp_bindsession',
'sp_indexoption', 'sp_certify_removable', 'sp_invalidate_textptr', 'sp_configure',
'sp_lock', 'sp_create_removable', 'sp_monitor', 'sp_createstats', 'sp_procoption',
'sp_cycle_errorlog', 'sp_recompile', 'sp_datatype_info', 'sp_refreshview', 'sp_dbcmptlevel',
'sp_releaseapplock', 'sp_dboption', 'sp_rename', 'sp_dbremove', 'sp_renamedb',
'sp_delete_backuphistory', 'sp_resetstatus', 'sp_depends', 'sp_serveroption', 'sp_detach_db',
'sp_setnetname', 'sp_dropdevice', 'sp_settriggerorder', 'sp_dropextendedproc', 'sp_spaceused',
'sp_dropextendedproperty', 'sp_tableoption', 'sp_dropmessage', 'sp_unbindefault', 'sp_droptype',
'sp_unbindrule', 'sp_executesql', 'sp_updateextendedproperty', 'sp_getapplock', 'sp_updatestats',
'sp_getbindtoken', 'sp_validname', 'sp_help', 'sp_who',
//Web Assistant Procedures
'sp_dropwebtask', 'sp_makewebtask', 'sp_enumcodepages', 'sp_runwebtask',
//XML Procedures
'sp_xml_preparedocument', 'sp_xml_removedocument',
//General Extended Procedures
'xp_cmdshellxp_logininfo', 'xp_enumgroups', 'xp_msver', 'xp_findnextmsgxp_revokelogin',
'xp_grantlogin', 'xp_sprintf', 'xp_logevent', 'xp_sqlmaint', 'xp_loginconfig', 'xp_sscanf',
//API System Stored Procedures
'sp_cursor', 'sp_cursorclose', 'sp_cursorexecute', 'sp_cursorfetch', 'sp_cursoropen',
'sp_cursoroption', 'sp_cursorprepare', 'sp_cursorunprepare', 'sp_execute', 'sp_prepare', 'sp_unprepare',
//Misc
'sp_createorphan', 'sp_droporphans', 'sp_reset_connection', 'sp_sdidebug'
),
4 => array(
//Function/sp's higlighted brown.
'fn_helpcollations', 'fn_listextendedproperty ', 'fn_servershareddrives',
'fn_trace_geteventinfo', 'fn_trace_getfilterinfo', 'fn_trace_getinfo',
'fn_trace_gettable', 'fn_virtualfilestats',
),
),
'SYMBOLS' => array(
'!', '!=', '%', '&', '&&', '(', ')', '*', '+', '-', '/', '<', '<<', '<=',
'<=>', '<>', '=', '>', '>=', '>>', '^', 'ALL', 'AND', 'ANY', 'BETWEEN', 'CROSS',
'EXISTS', 'IN', 'JOIN', 'LIKE', 'NOT', 'NULL', 'OR', 'OUTER', 'SOME', '|', '||', '~'
),
'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false,
1 => false,
2 => false,
3 => false,
4 => false,
),
'STYLES' => array(
'KEYWORDS' => array(
1 => 'color: #0000FF;',
2 => 'color: #FF00FF;',
3 => 'color: #AF0000;',
4 => 'color: #AF0000;'
),
'COMMENTS' => array(
1 => 'color: #008080;',
'MULTI' => 'color: #008080;'
),
'ESCAPE_CHAR' => array(
0 => 'color: #000099; font-weight: bold;'
),
'BRACKETS' => array(
0 => 'color: #808080;'
),
'STRINGS' => array(
0 => 'color: #FF0000;'
),
'NUMBERS' => array(
0 => 'color: #000;'
),
'METHODS' => array(
1 => 'color: #202020;',
2 => 'color: #202020;'
),
'SYMBOLS' => array(
0 => 'color: #808080;'
),
'REGEXPS' => array(
),
'SCRIPT' => array(
)
),
'URLS' => array(
1 => '',
2 => '',
3 => '',
4 => ''
),
'OOLANG' => true,
'OBJECT_SPLITTERS' => array(
1 => '.'
),
'REGEXPS' => array(
),
'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array(
),
'HIGHLIGHT_STRICT_BLOCK' => array(
)
);
?>
| gpl-2.0 |
asiersarasua/QGIS | tests/src/python/test_provider_ogr.py | 25422 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for the non-shapefile, non-tabfile datasources handled by OGR provider.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Even Rouault'
__date__ = '2016-04-11'
__copyright__ = 'Copyright 2016, Even Rouault'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
import shutil
import sys
import tempfile
import hashlib
from osgeo import gdal, ogr # NOQA
from qgis.PyQt.QtCore import QVariant, QByteArray
from qgis.core import (NULL,
QgsApplication,
QgsRectangle,
QgsProviderRegistry,
QgsFeature, QgsFeatureRequest, QgsField, QgsSettings, QgsDataProvider,
QgsVectorDataProvider, QgsVectorLayer, QgsWkbTypes, QgsNetworkAccessManager)
from qgis.testing import start_app, unittest
from utilities import unitTestDataPath
start_app()
TEST_DATA_DIR = unitTestDataPath()
def GDAL_COMPUTE_VERSION(maj, min, rev):
return ((maj) * 1000000 + (min) * 10000 + (rev) * 100)
# Note - doesn't implement ProviderTestCase as most OGR provider is tested by the shapefile provider test
def count_opened_filedescriptors(filename_to_test):
count = -1
if sys.platform.startswith('linux'):
count = 0
open_files_dirname = '/proc/%d/fd' % os.getpid()
filenames = os.listdir(open_files_dirname)
for filename in filenames:
full_filename = open_files_dirname + '/' + filename
if os.path.exists(full_filename):
link = os.readlink(full_filename)
if os.path.basename(link) == os.path.basename(filename_to_test):
count += 1
return count
class PyQgsOGRProvider(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""Run before all tests"""
# Create test layer
cls.basetestpath = tempfile.mkdtemp()
cls.datasource = os.path.join(cls.basetestpath, 'test.csv')
with open(cls.datasource, 'wt') as f:
f.write('id,WKT\n')
f.write('1,POINT(2 49)\n')
cls.dirs_to_cleanup = [cls.basetestpath]
@classmethod
def tearDownClass(cls):
"""Run after all tests"""
for dirname in cls.dirs_to_cleanup:
shutil.rmtree(dirname, True)
def testCapabilities(self):
self.assertTrue(QgsProviderRegistry.instance().providerCapabilities("ogr") & QgsDataProvider.File)
self.assertTrue(QgsProviderRegistry.instance().providerCapabilities("ogr") & QgsDataProvider.Dir)
def testUpdateMode(self):
vl = QgsVectorLayer('{}|layerid=0'.format(self.datasource), 'test', 'ogr')
self.assertTrue(vl.isValid())
caps = vl.dataProvider().capabilities()
self.assertTrue(caps & QgsVectorDataProvider.AddFeatures)
self.assertEqual(vl.dataProvider().property("_debug_open_mode"), "read-write")
# No-op
self.assertTrue(vl.dataProvider().enterUpdateMode())
self.assertEqual(vl.dataProvider().property("_debug_open_mode"), "read-write")
# No-op
self.assertTrue(vl.dataProvider().leaveUpdateMode())
self.assertEqual(vl.dataProvider().property("_debug_open_mode"), "read-write")
def testGeometryTypeKnownAtSecondFeature(self):
datasource = os.path.join(self.basetestpath, 'testGeometryTypeKnownAtSecondFeature.csv')
with open(datasource, 'wt') as f:
f.write('id,WKT\n')
f.write('1,\n')
f.write('2,POINT(2 49)\n')
vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr')
self.assertTrue(vl.isValid())
self.assertEqual(vl.wkbType(), QgsWkbTypes.Point)
def testMixOfPolygonCurvePolygon(self):
datasource = os.path.join(self.basetestpath, 'testMixOfPolygonCurvePolygon.csv')
with open(datasource, 'wt') as f:
f.write('id,WKT\n')
f.write('1,"POLYGON((0 0,0 1,1 1,0 0))"\n')
f.write('2,"CURVEPOLYGON((0 0,0 1,1 1,0 0))"\n')
f.write('3,"MULTIPOLYGON(((0 0,0 1,1 1,0 0)))"\n')
f.write('4,"MULTISURFACE(((0 0,0 1,1 1,0 0)))"\n')
vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr')
self.assertTrue(vl.isValid())
self.assertEqual(len(vl.dataProvider().subLayers()), 1)
self.assertEqual(vl.dataProvider().subLayers()[0], QgsDataProvider.SUBLAYER_SEPARATOR.join(['0', 'testMixOfPolygonCurvePolygon', '4', 'CurvePolygon', '']))
def testMixOfLineStringCompoundCurve(self):
datasource = os.path.join(self.basetestpath, 'testMixOfLineStringCompoundCurve.csv')
with open(datasource, 'wt') as f:
f.write('id,WKT\n')
f.write('1,"LINESTRING(0 0,0 1)"\n')
f.write('2,"COMPOUNDCURVE((0 0,0 1))"\n')
f.write('3,"MULTILINESTRING((0 0,0 1))"\n')
f.write('4,"MULTICURVE((0 0,0 1))"\n')
f.write('5,"CIRCULARSTRING(0 0,1 1,2 0)"\n')
vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr')
self.assertTrue(vl.isValid())
self.assertEqual(len(vl.dataProvider().subLayers()), 1)
self.assertEqual(vl.dataProvider().subLayers()[0], QgsDataProvider.SUBLAYER_SEPARATOR.join(['0', 'testMixOfLineStringCompoundCurve', '5', 'CompoundCurve', '']))
def testGpxElevation(self):
# GPX without elevation data
datasource = os.path.join(TEST_DATA_DIR, 'noelev.gpx')
vl = QgsVectorLayer('{}|layername=routes'.format(datasource), 'test', 'ogr')
self.assertTrue(vl.isValid())
f = next(vl.getFeatures())
self.assertEqual(f.geometry().wkbType(), QgsWkbTypes.LineString)
# GPX with elevation data
datasource = os.path.join(TEST_DATA_DIR, 'elev.gpx')
vl = QgsVectorLayer('{}|layername=routes'.format(datasource), 'test', 'ogr')
self.assertTrue(vl.isValid())
f = next(vl.getFeatures())
self.assertEqual(f.geometry().wkbType(), QgsWkbTypes.LineString25D)
self.assertEqual(f.geometry().constGet().pointN(0).z(), 1)
self.assertEqual(f.geometry().constGet().pointN(1).z(), 2)
self.assertEqual(f.geometry().constGet().pointN(2).z(), 3)
def testNoDanglingFileDescriptorAfterCloseVariant1(self):
''' Test that when closing the provider all file handles are released '''
datasource = os.path.join(self.basetestpath, 'testNoDanglingFileDescriptorAfterCloseVariant1.csv')
with open(datasource, 'wt') as f:
f.write('id,WKT\n')
f.write('1,\n')
f.write('2,POINT(2 49)\n')
vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr')
self.assertTrue(vl.isValid())
# The iterator will take one extra connection
myiter = vl.getFeatures()
# Consume one feature but the iterator is still opened
f = next(myiter)
self.assertTrue(f.isValid())
if sys.platform.startswith('linux'):
self.assertEqual(count_opened_filedescriptors(datasource), 2)
# Should release one file descriptor
del vl
# Non portable, but Windows testing is done with trying to unlink
if sys.platform.startswith('linux'):
self.assertEqual(count_opened_filedescriptors(datasource), 1)
f = next(myiter)
self.assertTrue(f.isValid())
# Should release one file descriptor
del myiter
# Non portable, but Windows testing is done with trying to unlink
if sys.platform.startswith('linux'):
self.assertEqual(count_opened_filedescriptors(datasource), 0)
# Check that deletion works well (can only fail on Windows)
os.unlink(datasource)
self.assertFalse(os.path.exists(datasource))
def testNoDanglingFileDescriptorAfterCloseVariant2(self):
''' Test that when closing the provider all file handles are released '''
datasource = os.path.join(self.basetestpath, 'testNoDanglingFileDescriptorAfterCloseVariant2.csv')
with open(datasource, 'wt') as f:
f.write('id,WKT\n')
f.write('1,\n')
f.write('2,POINT(2 49)\n')
vl = QgsVectorLayer('{}|layerid=0'.format(datasource), 'test', 'ogr')
self.assertTrue(vl.isValid())
# Consume all features.
myiter = vl.getFeatures()
for feature in myiter:
pass
# The iterator is closed, but the corresponding connection still not closed
if sys.platform.startswith('linux'):
self.assertEqual(count_opened_filedescriptors(datasource), 2)
# Should release one file descriptor
del vl
# Non portable, but Windows testing is done with trying to unlink
if sys.platform.startswith('linux'):
self.assertEqual(count_opened_filedescriptors(datasource), 0)
# Check that deletion works well (can only fail on Windows)
os.unlink(datasource)
self.assertFalse(os.path.exists(datasource))
def testGeometryCollection(self):
''' Test that we can at least retrieves attribute of features with geometry collection '''
datasource = os.path.join(self.basetestpath, 'testGeometryCollection.csv')
with open(datasource, 'wt') as f:
f.write('id,WKT\n')
f.write('1,POINT Z(2 49 0)\n')
f.write('2,GEOMETRYCOLLECTION Z (POINT Z (2 49 0))\n')
vl = QgsVectorLayer('{}|layerid=0|geometrytype=GeometryCollection'.format(datasource), 'test', 'ogr')
self.assertTrue(vl.isValid())
self.assertTrue(vl.featureCount(), 1)
values = [f['id'] for f in vl.getFeatures()]
self.assertEqual(values, ['2'])
del vl
os.unlink(datasource)
self.assertFalse(os.path.exists(datasource))
def testGdb(self):
""" Test opening a GDB database layer"""
gdb_path = os.path.join(unitTestDataPath(), 'test_gdb.gdb')
for i in range(3):
l = QgsVectorLayer(gdb_path + '|layerid=' + str(i), 'test', 'ogr')
self.assertTrue(l.isValid())
def testGdbFilter(self):
""" Test opening a GDB database layer with filter"""
gdb_path = os.path.join(unitTestDataPath(), 'test_gdb.gdb')
l = QgsVectorLayer(gdb_path + '|layerid=1|subset="text" = \'shape 2\'', 'test', 'ogr')
self.assertTrue(l.isValid())
it = l.getFeatures()
f = QgsFeature()
while it.nextFeature(f):
self.assertTrue(f.attribute("text") == "shape 2")
def testTriangleTINPolyhedralSurface(self):
""" Test support for Triangles (mapped to Polygons) """
testsets = (
("Triangle((0 0, 0 1, 1 1, 0 0))", QgsWkbTypes.Triangle, "Triangle ((0 0, 0 1, 1 1, 0 0))"),
("Triangle Z((0 0 1, 0 1 2, 1 1 3, 0 0 1))", QgsWkbTypes.TriangleZ, "TriangleZ ((0 0 1, 0 1 2, 1 1 3, 0 0 1))"),
("Triangle M((0 0 4, 0 1 5, 1 1 6, 0 0 4))", QgsWkbTypes.TriangleM, "TriangleM ((0 0 4, 0 1 5, 1 1 6, 0 0 4))"),
("Triangle ZM((0 0 0 1, 0 1 2 3, 1 1 4 5, 0 0 0 1))", QgsWkbTypes.TriangleZM, "TriangleZM ((0 0 0 1, 0 1 2 3, 1 1 4 5, 0 0 0 1))"),
("TIN (((0 0, 0 1, 1 1, 0 0)),((0 0, 1 0, 1 1, 0 0)))", QgsWkbTypes.MultiPolygon, "MultiPolygon (((0 0, 0 1, 1 1, 0 0)),((0 0, 1 0, 1 1, 0 0)))"),
("TIN Z(((0 0 0, 0 1 1, 1 1 1, 0 0 0)),((0 0 0, 1 0 0, 1 1 1, 0 0 0)))", QgsWkbTypes.MultiPolygonZ, "MultiPolygonZ (((0 0 0, 0 1 1, 1 1 1, 0 0 0)),((0 0 0, 1 0 0, 1 1 1, 0 0 0)))"),
("TIN M(((0 0 0, 0 1 2, 1 1 3, 0 0 0)),((0 0 0, 1 0 4, 1 1 3, 0 0 0)))", QgsWkbTypes.MultiPolygonM, "MultiPolygonM (((0 0 0, 0 1 2, 1 1 3, 0 0 0)),((0 0 0, 1 0 4, 1 1 3, 0 0 0)))"),
("TIN ZM(((0 0 0 0, 0 1 1 2, 1 1 1 3, 0 0 0 0)),((0 0 0 0, 1 0 0 4, 1 1 1 3, 0 0 0 0)))", QgsWkbTypes.MultiPolygonZM, "MultiPolygonZM (((0 0 0 0, 0 1 1 2, 1 1 1 3, 0 0 0 0)),((0 0 0 0, 1 0 0 4, 1 1 1 3, 0 0 0 0)))"),
("PolyhedralSurface (((0 0, 0 1, 1 1, 0 0)),((0 0, 1 0, 1 1, 0 0)))", QgsWkbTypes.MultiPolygon, "MultiPolygon (((0 0, 0 1, 1 1, 0 0)),((0 0, 1 0, 1 1, 0 0)))"),
("PolyhedralSurface Z(((0 0 0, 0 1 1, 1 1 1, 0 0 0)),((0 0 0, 1 0 0, 1 1 1, 0 0 0)))", QgsWkbTypes.MultiPolygonZ, "MultiPolygonZ (((0 0 0, 0 1 1, 1 1 1, 0 0 0)),((0 0 0, 1 0 0, 1 1 1, 0 0 0)))"),
("PolyhedralSurface M(((0 0 0, 0 1 2, 1 1 3, 0 0 0)),((0 0 0, 1 0 4, 1 1 3, 0 0 0)))", QgsWkbTypes.MultiPolygonM, "MultiPolygonM (((0 0 0, 0 1 2, 1 1 3, 0 0 0)),((0 0 0, 1 0 4, 1 1 3, 0 0 0)))"),
("PolyhedralSurface ZM(((0 0 0 0, 0 1 1 2, 1 1 1 3, 0 0 0 0)),((0 0 0 0, 1 0 0 4, 1 1 1 3, 0 0 0 0)))", QgsWkbTypes.MultiPolygonZM, "MultiPolygonZM (((0 0 0 0, 0 1 1 2, 1 1 1 3, 0 0 0 0)),((0 0 0 0, 1 0 0 4, 1 1 1 3, 0 0 0 0)))")
)
for row in testsets:
datasource = os.path.join(self.basetestpath, 'test.csv')
with open(datasource, 'wt') as f:
f.write('id,WKT\n')
f.write('1,"%s"' % row[0])
vl = QgsVectorLayer(datasource, 'test', 'ogr')
self.assertTrue(vl.isValid())
self.assertEqual(vl.wkbType(), row[1])
f = QgsFeature()
self.assertTrue(vl.getFeatures(QgsFeatureRequest(1)).nextFeature(f))
self.assertTrue(f.geometry())
self.assertEqual(f.geometry().constGet().asWkt(), row[2])
"""PolyhedralSurface, Tin => mapped to MultiPolygon
Triangle => mapped to Polygon
"""
def testSetupProxy(self):
"""Test proxy setup"""
settings = QgsSettings()
settings.setValue("proxy/proxyEnabled", True)
settings.setValue("proxy/proxyPort", '1234')
settings.setValue("proxy/proxyHost", 'myproxyhostname.com')
settings.setValue("proxy/proxyUser", 'username')
settings.setValue("proxy/proxyPassword", 'password')
settings.setValue("proxy/proxyExcludedUrls", "http://www.myhost.com|http://www.myotherhost.com")
QgsNetworkAccessManager.instance().setupDefaultProxyAndCache()
vl = QgsVectorLayer(TEST_DATA_DIR + '/' + 'lines.shp', 'proxy_test', 'ogr')
self.assertTrue(vl.isValid())
self.assertEqual(gdal.GetConfigOption("GDAL_HTTP_PROXY"), "myproxyhostname.com:1234")
self.assertEqual(gdal.GetConfigOption("GDAL_HTTP_PROXYUSERPWD"), "username:password")
settings.setValue("proxy/proxyEnabled", True)
settings.remove("proxy/proxyPort")
settings.setValue("proxy/proxyHost", 'myproxyhostname.com')
settings.setValue("proxy/proxyUser", 'username')
settings.remove("proxy/proxyPassword")
settings.setValue("proxy/proxyExcludedUrls", "http://www.myhost.com|http://www.myotherhost.com")
QgsNetworkAccessManager.instance().setupDefaultProxyAndCache()
vl = QgsVectorLayer(TEST_DATA_DIR + '/' + 'lines.shp', 'proxy_test', 'ogr')
self.assertTrue(vl.isValid())
self.assertEqual(gdal.GetConfigOption("GDAL_HTTP_PROXY"), "myproxyhostname.com")
self.assertEqual(gdal.GetConfigOption("GDAL_HTTP_PROXYUSERPWD"), "username")
def testEditGeoJsonRemoveField(self):
""" Test bugfix of https://issues.qgis.org/issues/18596 (deleting an existing field)"""
datasource = os.path.join(self.basetestpath, 'testEditGeoJsonRemoveField.json')
with open(datasource, 'wt') as f:
f.write("""{
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "x": 1, "y": 2, "z": 3, "w": 4 }, "geometry": { "type": "Point", "coordinates": [ 0, 0 ] } } ] }""")
vl = QgsVectorLayer(datasource, 'test', 'ogr')
self.assertTrue(vl.isValid())
self.assertTrue(vl.startEditing())
self.assertTrue(vl.deleteAttribute(1))
self.assertTrue(vl.commitChanges())
self.assertEqual(len(vl.dataProvider().fields()), 4 - 1)
f = QgsFeature()
self.assertTrue(vl.getFeatures(QgsFeatureRequest()).nextFeature(f))
self.assertEqual(f['x'], 1)
self.assertEqual(f['z'], 3)
self.assertEqual(f['w'], 4)
def testEditGeoJsonAddField(self):
""" Test bugfix of https://issues.qgis.org/issues/18596 (adding a new field)"""
datasource = os.path.join(self.basetestpath, 'testEditGeoJsonAddField.json')
with open(datasource, 'wt') as f:
f.write("""{
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "x": 1 }, "geometry": { "type": "Point", "coordinates": [ 0, 0 ] } } ] }""")
vl = QgsVectorLayer(datasource, 'test', 'ogr')
self.assertTrue(vl.isValid())
self.assertTrue(vl.startEditing())
self.assertTrue(vl.addAttribute(QgsField('strfield', QVariant.String)))
self.assertTrue(vl.commitChanges())
self.assertEqual(len(vl.dataProvider().fields()), 1 + 1)
f = QgsFeature()
self.assertTrue(vl.getFeatures(QgsFeatureRequest()).nextFeature(f))
self.assertIsNone(f['strfield'])
# Completely reload file
vl = QgsVectorLayer(datasource, 'test', 'ogr')
# As we didn't set any value to the new field, it is not written at
# all in the GeoJSON file, so it has disappeared
self.assertEqual(len(vl.fields()), 1)
def testEditGeoJsonAddFieldAndThenAddFeatures(self):
""" Test bugfix of https://issues.qgis.org/issues/18596 (adding a new field)"""
datasource = os.path.join(self.basetestpath, 'testEditGeoJsonAddField.json')
with open(datasource, 'wt') as f:
f.write("""{
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": { "x": 1 }, "geometry": { "type": "Point", "coordinates": [ 0, 0 ] } } ] }""")
vl = QgsVectorLayer(datasource, 'test', 'ogr')
self.assertTrue(vl.isValid())
self.assertTrue(vl.startEditing())
self.assertTrue(vl.addAttribute(QgsField('strfield', QVariant.String)))
self.assertTrue(vl.commitChanges())
self.assertEqual(len(vl.dataProvider().fields()), 1 + 1)
self.assertEqual([f.name() for f in vl.dataProvider().fields()], ['x', 'strfield'])
f = QgsFeature()
self.assertTrue(vl.getFeatures(QgsFeatureRequest()).nextFeature(f))
self.assertIsNone(f['strfield'])
self.assertEqual([field.name() for field in f.fields()], ['x', 'strfield'])
self.assertTrue(vl.startEditing())
vl.changeAttributeValue(f.id(), 1, 'x')
self.assertTrue(vl.commitChanges())
f = QgsFeature()
self.assertTrue(vl.getFeatures(QgsFeatureRequest()).nextFeature(f))
self.assertEqual(f['strfield'], 'x')
self.assertEqual([field.name() for field in f.fields()], ['x', 'strfield'])
# Completely reload file
vl = QgsVectorLayer(datasource, 'test', 'ogr')
self.assertEqual(len(vl.fields()), 2)
def testDataItems(self):
registry = QgsApplication.dataItemProviderRegistry()
ogrprovider = next(provider for provider in registry.providers() if provider.name() == 'OGR')
# Single layer
item = ogrprovider.createDataItem(os.path.join(TEST_DATA_DIR, 'lines.shp'), None)
self.assertTrue(item.uri().endswith('lines.shp'))
# Multiple layer
item = ogrprovider.createDataItem(os.path.join(TEST_DATA_DIR, 'multilayer.kml'), None)
children = item.createChildren()
self.assertEqual(len(children), 2)
self.assertIn('multilayer.kml|layername=Layer1', children[0].uri())
self.assertIn('multilayer.kml|layername=Layer2', children[1].uri())
# Multiple layer (geopackage)
tmpfile = os.path.join(self.basetestpath, 'testDataItems.gpkg')
ds = ogr.GetDriverByName('GPKG').CreateDataSource(tmpfile)
lyr = ds.CreateLayer('Layer1', geom_type=ogr.wkbPoint)
lyr = ds.CreateLayer('Layer2', geom_type=ogr.wkbPoint)
ds = None
item = ogrprovider.createDataItem(tmpfile, None)
children = item.createChildren()
self.assertEqual(len(children), 2)
self.assertIn('testDataItems.gpkg|layername=Layer1', children[0].uri())
self.assertIn('testDataItems.gpkg|layername=Layer2', children[1].uri())
def testOSM(self):
""" Test that opening several layers of the same OSM datasource works properly """
datasource = os.path.join(TEST_DATA_DIR, 'test.osm')
vl_points = QgsVectorLayer(datasource + "|layername=points", 'test', 'ogr')
vl_multipolygons = QgsVectorLayer(datasource + "|layername=multipolygons", 'test', 'ogr')
f = QgsFeature()
# When sharing the same dataset handle, the spatial filter of test
# points layer would apply to the other layers
iter_points = vl_points.getFeatures(QgsFeatureRequest().setFilterRect(QgsRectangle(-200, -200, -200, -200)))
self.assertFalse(iter_points.nextFeature(f))
iter_multipolygons = vl_multipolygons.getFeatures(QgsFeatureRequest())
self.assertTrue(iter_multipolygons.nextFeature(f))
self.assertTrue(iter_multipolygons.nextFeature(f))
self.assertTrue(iter_multipolygons.nextFeature(f))
self.assertFalse(iter_multipolygons.nextFeature(f))
# Re-start an iterator (tests #20098)
iter_multipolygons = vl_multipolygons.getFeatures(QgsFeatureRequest())
self.assertTrue(iter_multipolygons.nextFeature(f))
# Test filter by id (#20308)
f = next(vl_multipolygons.getFeatures(QgsFeatureRequest().setFilterFid(8)))
self.assertTrue(f.isValid())
self.assertEqual(f.id(), 8)
f = next(vl_multipolygons.getFeatures(QgsFeatureRequest().setFilterFid(1)))
self.assertTrue(f.isValid())
self.assertEqual(f.id(), 1)
f = next(vl_multipolygons.getFeatures(QgsFeatureRequest().setFilterFid(5)))
self.assertTrue(f.isValid())
self.assertEqual(f.id(), 5)
# 6 doesn't exist
it = vl_multipolygons.getFeatures(QgsFeatureRequest().setFilterFids([1, 5, 6, 8]))
f = next(it)
self.assertTrue(f.isValid())
self.assertEqual(f.id(), 1)
f = next(it)
self.assertTrue(f.isValid())
self.assertEqual(f.id(), 5)
f = next(it)
self.assertTrue(f.isValid())
self.assertEqual(f.id(), 8)
del it
def testBinaryField(self):
source = os.path.join(TEST_DATA_DIR, 'attachments.gdb')
vl = QgsVectorLayer(source + "|layername=points__ATTACH")
self.assertTrue(vl.isValid())
fields = vl.fields()
data_field = fields[fields.lookupField('DATA')]
self.assertEqual(data_field.type(), QVariant.ByteArray)
self.assertEqual(data_field.typeName(), 'Binary')
features = {f['ATTACHMENTID']: f for f in vl.getFeatures()}
self.assertEqual(len(features), 2)
self.assertIsInstance(features[1]['DATA'], QByteArray)
self.assertEqual(hashlib.md5(features[1]['DATA'].data()).hexdigest(), 'ef3dbc530cc39a545832a6c82aac57b6')
self.assertIsInstance(features[2]['DATA'], QByteArray)
self.assertEqual(hashlib.md5(features[2]['DATA'].data()).hexdigest(), '4b952b80e4288ca5111be2f6dd5d6809')
def testBlobCreation(self):
"""
Test creating binary blob field in existing table
"""
tmpfile = os.path.join(self.basetestpath, 'newbinaryfield.sqlite')
ds = ogr.GetDriverByName('SQLite').CreateDataSource(tmpfile)
lyr = ds.CreateLayer('test', geom_type=ogr.wkbPoint, options=['FID=fid'])
lyr.CreateField(ogr.FieldDefn('strfield', ogr.OFTString))
lyr.CreateField(ogr.FieldDefn('intfield', ogr.OFTInteger))
f = None
ds = None
vl = QgsVectorLayer(tmpfile)
self.assertTrue(vl.isValid())
dp = vl.dataProvider()
f = QgsFeature(dp.fields())
f.setAttributes([1, 'str', 100])
self.assertTrue(dp.addFeature(f))
# add binary field
self.assertTrue(dp.addAttributes([QgsField('binfield', QVariant.ByteArray)]))
fields = dp.fields()
bin1_field = fields[fields.lookupField('binfield')]
self.assertEqual(bin1_field.type(), QVariant.ByteArray)
self.assertEqual(bin1_field.typeName(), 'Binary')
f = QgsFeature(fields)
bin_1 = b'xxx'
bin_val1 = QByteArray(bin_1)
f.setAttributes([2, 'str2', 200, bin_val1])
self.assertTrue(dp.addFeature(f))
f2 = [f for f in dp.getFeatures()][1]
self.assertEqual(f2.attributes(), [2, 'str2', 200, QByteArray(bin_1)])
def testBoolFieldEvaluation(self):
datasource = os.path.join(unitTestDataPath(), 'bool_geojson.json')
vl = QgsVectorLayer(datasource, 'test', 'ogr')
self.assertTrue(vl.isValid())
self.assertEqual(vl.fields().at(0).name(), 'bool')
self.assertEqual(vl.fields().at(0).type(), QVariant.Bool)
self.assertEqual([f[0] for f in vl.getFeatures()], [True, False, NULL])
self.assertEqual([f[0].__class__.__name__ for f in vl.getFeatures()], ['bool', 'bool', 'QVariant'])
if __name__ == '__main__':
unittest.main()
| gpl-2.0 |
YelaSeamless/infinidb | dbcon/ddlpackage/columndef.cpp | 3526 | /* Copyright (C) 2014 InfiniDB, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2 of
the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */
/***********************************************************************
* $Id: columndef.cpp 9210 2013-01-21 14:10:42Z rdempsey $
*
*
***********************************************************************/
#include <iostream>
#include <iomanip>
#define DDLPKG_DLLEXPORT
#include "ddlpkg.h"
#undef DDLPKG_DLLEXPORT
namespace ddlpackage {
using namespace std;
ColumnDef::~ColumnDef()
{
delete fType;
delete fDefaultValue;
ColumnConstraintList::iterator itr;
for(itr=fConstraints.begin(); itr != fConstraints.end(); ++itr) {
delete *itr;
}
}
ColumnDef::ColumnDef(const char *name, ColumnType* columnType, ColumnConstraintList *constraints,
ColumnDefaultValue *defaultValue, const char * comment ) :
SchemaObject(name),
fType(columnType),
fDefaultValue(defaultValue)
{
if(constraints) {
fConstraints = *constraints;
delete constraints;
}
if ( comment )
fComment = comment;
}
ostream &operator<<(ostream& os, const ColumnType& columnType)
{
os << setw(12) << left << DDLDatatypeString[columnType.fType]
<< "["
<< "L=" << setw(2) << columnType.fLength << ","
<< "P=" << setw(2) << columnType.fPrecision << ","
<< "S=" << setw(2) << columnType.fScale << ","
<< "T=" << setw(2) << columnType.fWithTimezone
<< "]";
return os;
}
ostream &operator<<(ostream& os, const ColumnDef &column)
{
os << "Column: " << column.fName << " " << *column.fType;
if(column.fDefaultValue) {
os << " def=";
if (column.fDefaultValue->fNull)
os << "NULL";
else
os << column.fDefaultValue->fValue;
}
os << endl << " " << column.fConstraints.size()
<< " constraints ";
ColumnConstraintList::const_iterator itr;
for(itr = column.fConstraints.begin();
itr != column.fConstraints.end();
++itr) {
ColumnConstraintDef *con = *itr;
os << *con;
}
return os;
}
ostream &operator<<(ostream& os, const ColumnConstraintDef &con)
{
os << " Constraint: "
<< con.fName << " "
<< ConstraintString[con.fConstraintType] << " "
<< "defer=" << con.fDeferrable << " "
<< ConstraintAttrStrings[con.fCheckTime] << " ";
if(!con.fCheck.empty())
os << "check=" << "\"" << con.fCheck << "\"";
return os;
}
std::ostream &operator<<(std::ostream& os, const ColumnDefList &clist)
{
ColumnDefList::const_iterator itr;
for(itr = clist.begin(); itr != clist.end(); ++itr){
os << **itr;
}
return os;
}
ColumnDefaultValue::ColumnDefaultValue(const char *value) :
fNull(false)
{
if(0 == value)
fNull = true;
else
fValue = value;
}
std::ostream &operator<<(std::ostream& os, const ColumnDefaultValue &defaultValue)
{
os << " def=";
if (defaultValue.fNull)
os << "NULL";
else
os << defaultValue.fValue;
return os;
}
}
| gpl-2.0 |
dailycavalier/brighterchildren | wp-content/plugins/landing-pages/templates/three-column-lander/index.php | 6250 | <?php
/*****************************************/
// Template Title: Three Column Landing Page
// Plugin: Landing Pages - Inboundnow.com
/*****************************************/
/* Declare Template Key */
$key = lp_get_parent_directory(dirname(__FILE__)); // unique ID associated with this template
$path = LANDINGPAGES_URLPATH.'templates/'.$key.'/'; // path to template folder
$url = plugins_url();
/* Define Landing Pages's custom pre-load do_action('lp_init'); hook for 3rd party plugin integration */
do_action('lp_init');
/* Start WordPress Loop and Load $post data */
if (have_posts()) : while (have_posts()) : the_post();
/* Pre-load meta data into variables. These are defined in the templates config.php file */
$conversion_area_placement = lp_get_value($post, $key, 'conversion_area' );
$left_content_bg_color = lp_get_value($post, $key, 'left-content-bg-color' );
$left_content_text_color = lp_get_value($post, $key, 'left-content-text-color' );
$left_content_area = lp_get_value($post, $key, 'left-content-area' );
$middle_content_bg_color = lp_get_value($post, $key, 'middle-content-bg-color' );
$middle_content_text_color = lp_get_value($post, $key, 'middle-content-text-color' );
$right_content_bg_color = lp_get_value($post, $key, 'right-content-bg-color' );
$right_content_text_color = lp_get_value($post, $key, 'right-content-text-color' );
$right_content_area = lp_get_value($post, $key, 'right-content-area' );
$submit_button_color = lp_get_value($post, $key, 'submit-button-color' );
$content = lp_get_value($post, $key, 'main-content');
$conversion_area = lp_get_value($post, $key, 'conversion-area-content');
?>
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>
<?php wp_title(); // Load Normal WordPress Page Title ?>
</title>
<link rel="stylesheet" href="<?php echo $path; ?>assets/css/normalize.css">
<link rel="stylesheet" href="<?php echo $path; ?>assets/css/style.css">
<script src="<?php echo $path; ?>assets/js/modernizr-2.6.2.min.js"></script>
<style type="text/css">
body { font-family: "Open Sans",sans-serif;}
#lp_container_form {text-align: center;}
/* Inline Styling for Template Changes based off user input */
input[type=submit], button[type=submit] {
background: #33B96B;
padding: 10px;
width: 100%;
margin: 0 auto 20px auto;
font-size: 30px;
color: #fff;
border: none;
}
<?php
if ($left_content_bg_color != "") {
echo ".sidebar.left { background: #$left_content_bg_color;} "; // change sidebar color
}
if ($left_content_text_color != "") {
echo ".sidebar.left { color: #$left_content_text_color;} "; // change sidebar color
}
if ($right_content_bg_color != "") {
echo ".sidebar.right { background: #$right_content_bg_color;} "; // change sidebar color
}
if ($right_content_text_color != "") {
echo ".sidebar.right { color: #$right_content_text_color;} "; // change sidebar color
}
if ($middle_content_bg_color != "") {
echo ".main {background: #$middle_content_bg_color;}"; // change content background color
}
if ($middle_content_text_color != "") {
echo ".main, .btn {color: #$middle_content_text_color;}"; // change content background color
}
if ($submit_button_color !=""){
echo ".input[type=submit], button[type=submit] {background: #$submit_button_color;}"; // change content background color
}
?>
#inbound-form-wrapper input[type=text], #inbound-form-wrapper input[type=url], #inbound-form-wrapper input[type=email], #inbound-form-wrapper input[type=tel], #inbound-form-wrapper input[type=number], #inbound-form-wrapper input[type=password] {
width: 100% !important;
}
.main .inbound-now-form {
width: 50%;
margin: auto;
}
</style>
<?php wp_head(); // Load Regular WP Head ?>
<?php do_action('lp_head'); // Load Landing Page Specific Header Items ?>
</head>
<body <?php body_class(); ?>>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please
<a href="http://browsehappy.com/">upgrade your browser</a>or
<a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a>to improve your experience.</p>
<![endif]-->
<div class="wrapper">
<div class="main">
<a href="#" class="btn left"><span class="entypo-left-open"></span>More</a> </a>
<a href="#" class="btn right"><span class="entypo-right-open"></span>More</a> </a>
<h2><?php the_title();?></h2>
<?php echo do_shortcode( $content ); ?>
<?php if ($conversion_area_placement === "middle"){ echo do_shortcode($conversion_area); } ?>
</div>
<div class="sidebar left">
<?php echo do_shortcode( $left_content_area ); ?>
<?php if ($conversion_area_placement === "left"){ echo do_shortcode($conversion_area); } ?>
</div>
<div class="sidebar right">
<?php echo do_shortcode( $right_content_area ); ?>
<?php if ($conversion_area_placement === "right"){ echo do_shortcode($conversion_area); } ?>
</div>
</div> <!-- end .wrapper -->
<?php break; endwhile; endif; // end WordPress Loop
do_action('lp_footer'); // load landing pages footer hook
wp_footer(); // load normal wordpress footer
?>
<script type="text/javascript">
jQuery(function($){
$('.btn.left').click(function(event){
event.preventDefault();
$('body').toggleClass('left');
});
$('.btn.right').click(function(event){
event.preventDefault();
$('body').toggleClass('right');
});
});
</script>
</body>
</html> | gpl-2.0 |
ontoprise/HaloSMWExtension | extensions/ARCLibrary/libs/arc/ARC2_Reader.php | 15779 | <?php
/**
* ARC2 Web Client
*
* @author Benjamin Nowack
* @license <http://arc.semsol.org/license>
* @homepage <http://arc.semsol.org/>
* @package ARC2
* @version 2010-07-06
*/
ARC2::inc('Class');
class ARC2_Reader extends ARC2_Class {
function __construct($a = '', &$caller) {
parent::__construct($a, $caller);
}
function __init() {/* inc_path, proxy_host, proxy_port, proxy_skip, http_accept_header, http_user_agent_header, max_redirects */
parent::__init();
$this->http_method = $this->v('http_method', 'GET', $this->a);
$this->message_body = $this->v('message_body', '', $this->a);;
$this->http_accept_header = $this->v('http_accept_header', 'Accept: application/rdf+xml; q=0.9, */*; q=0.1', $this->a);
$this->http_user_agent_header = $this->v('http_user_agent_header', 'User-Agent: ARC Reader (http://arc.semsol.org/)', $this->a);
$this->http_custom_headers = $this->v('http_custom_headers', '', $this->a);
$this->max_redirects = $this->v('max_redirects', 3, $this->a);
$this->format = $this->v('format', false, $this->a);
$this->redirects = array();
$this->stream_id = '';
$this->timeout = $this->v('reader_timeout', 30, $this->a);
$this->response_headers = array();
$this->digest_auth = 0;
$this->auth_infos = $this->v('reader_auth_infos', array(), $this->a);
}
/* */
function setHTTPMethod($v) {
$this->http_method = $v;
}
function setMessageBody($v) {
$this->message_body = $v;
}
function setAcceptHeader($v) {
$this->http_accept_header = $v;
}
function setCustomHeaders($v) {
$this->http_custom_headers = $v;
}
function addCustomHeaders($v) {
if ($this->http_custom_headers) $this->http_custom_headers .= "\r\n";
$this->http_custom_headers .= $v;
}
/* */
function activate($path, $data = '', $ping_only = 0, $timeout = 0) {
$this->setCredentials($path);
$this->ping_only = $ping_only;
if ($timeout) $this->timeout = $timeout;
$id = md5($path . ' ' . $data);
if ($this->stream_id != $id) {
$this->stream_id = $id;
/* data uri? */
if (!$data && preg_match('/^data\:([^\,]+)\,(.*)$/', $path, $m)) {
$path = '';
$data = preg_match('/base64/', $m[1]) ? base64_decode($m[2]) : rawurldecode($m[2]);
}
$this->base = $this->calcBase($path);
$this->uri = $this->calcURI($path, $this->base);
$this->stream = ($data) ? $this->getDataStream($data) : $this->getSocketStream($this->base, $ping_only);
if ($this->stream && !$this->ping_only) {
$this->getFormat();
}
}
}
/*
* HTTP Basic/Digest + Proxy authorization can be defined in the
* arc_reader_credentials config setting:
'arc_reader_credentials' => array(
'http://basic.example.com/' => 'user:pass', // shortcut for type=basic
'http://digest.example.com/' => 'user::pass', // shortcut for type=digest
'http://proxy.example.com/' => array('type' => 'basic', 'proxy', 'user' => 'user', 'pass' => 'pass'),
),
*/
function setCredentials($url) {
if (!$creds = $this->v('arc_reader_credentials', array(), $this->a)) return 0;
foreach ($creds as $pattern => $creds) {
/* digest shortcut (user::pass) */
if (!is_array($creds) && preg_match('/^(.+)\:\:(.+)$/', $creds, $m)) {
$creds = array('type' => 'digest', 'user' => $m[1], 'pass' => $m[2]);
}
/* basic shortcut (user:pass) */
if (!is_array($creds) && preg_match('/^(.+)\:(.+)$/', $creds, $m)) {
$creds = array('type' => 'basic', 'user' => $m[1], 'pass' => $m[2]);
}
if (!is_array($creds)) return 0;
$regex = '/' . preg_replace('/([\:\/\.\?])/', '\\\\\1', $pattern) . '/';
if (!preg_match($regex, $url)) continue;
$mthd = 'set' . $this->camelCase($creds['type']) . 'AuthCredentials';
if (method_exists($this, $mthd)) $this->$mthd($creds, $url);
}
}
function setBasicAuthCredentials($creds) {
$auth = 'Basic ' . base64_encode($creds['user'] . ':' . $creds['pass']);
$h = in_array('proxy', $creds) ? 'Proxy-Authorization' : 'Authorization';
$this->addCustomHeaders($h . ': ' . $auth);
//echo $h . ': ' . $auth . print_r($creds, 1);
}
function setDigestAuthCredentials($creds, $url) {
$path = $this->v1('path', '/', parse_url($url));
$auth = '';
$hs = $this->getResponseHeaders();
/* initial 401 */
$h = $this->v('www-authenticate', '', $hs);
if ($h && preg_match('/Digest/i', $h)) {
$auth = 'Digest ';
/* Digest realm="$realm", nonce="$nonce", qop="auth", opaque="$opaque" */
$ks = array('realm', 'nonce', 'opaque');/* skipping qop, assuming "auth" */
foreach ($ks as $i => $k) {
$$k = preg_match('/' . $k . '=\"?([^\"]+)\"?/i', $h, $m) ? $m[1] : '';
$auth .= ($i ? ', ' : '') . $k . '="' . $$k . '"';
$this->auth_infos[$k] = $$k;
}
$this->auth_infos['auth'] = $auth;
$this->auth_infos['request_count'] = 1;
}
/* initial 401 or repeated request */
if ($this->v('auth', 0, $this->auth_infos)) {
$qop = 'auth';
$auth = $this->auth_infos['auth'];
$rc = $this->auth_infos['request_count'];
$realm = $this->auth_infos['realm'];
$nonce = $this->auth_infos['nonce'];
$ha1 = md5($creds['user'] . ':' . $realm . ':' . $creds['pass']);
$ha2 = md5($this->http_method . ':' . $path);
$nc = dechex($rc);
$cnonce = dechex($rc * 2);
$resp = md5($ha1 . ':' . $nonce . ':' . $nc . ':' . $cnonce . ':' . $qop . ':' . $ha2);
$auth .= ', username="' . $creds['user'] . '"' .
', uri="' . $path . '"' .
', qop=' . $qop . '' .
', nc=' . $nc .
', cnonce="' . $cnonce . '"' .
', uri="' . $path . '"' .
', response="' . $resp . '"' .
'';
$this->auth_infos['request_count'] = $rc + 1;
}
if (!$auth) return 0;
$h = in_array('proxy', $creds) ? 'Proxy-Authorization' : 'Authorization';
$this->addCustomHeaders($h . ': ' . $auth);
}
/* */
function useProxy($url) {
if (!$this->v1('proxy_host', 0, $this->a)) {
return false;
}
$skips = $this->v1('proxy_skip', array(), $this->a);
foreach ($skips as $skip) {
if (strpos($url, $skip) !== false) {
return false;
}
}
return true;
}
/* */
function createStream($path, $data = '') {
$this->base = $this->calcBase($path);
$this->stream = ($data) ? $this->getDataStream($data) : $this->getSocketStream($this->base);
}
function getDataStream($data) {
return array('type' => 'data', 'pos' => 0, 'headers' => array(), 'size' => strlen($data), 'data' => $data, 'buffer' => '');
}
function getSocketStream($url) {
if ($url == 'file://') {
return $this->addError('Error: file does not exists or is not accessible');
}
$parts = parse_url($url);
$mappings = array('file' => 'File', 'http' => 'HTTP', 'https' => 'HTTP');
if ($scheme = $this->v(strtolower($parts['scheme']), '', $mappings)) {
return $this->m('get' . $scheme . 'Socket', $url, $this->getDataStream(''));
}
}
function getFileSocket($url) {
$parts = parse_url($url);
$s = file_exists($parts['path']) ? @fopen($parts['path'], 'rb') : false;
if (!$s) {
return $this->addError('Socket error: Could not open "' . $parts['path'] . '"');
}
return array('type' => 'socket', 'socket' =>& $s, 'headers' => array(), 'pos' => 0, 'size' => filesize($parts['path']), 'buffer' => '');
}
function getHTTPSocket($url, $redirs = 0, $prev_parts = '') {
$parts = parse_url($url);
/* relative redirect */
if (!isset($parts['scheme']) && $prev_parts) $parts['scheme'] = $prev_parts['scheme'];
if (!isset($parts['host']) && $prev_parts) $parts['host'] = $prev_parts['host'];
/* no scheme */
if (!$this->v('scheme', '', $parts)) return $this->addError('Socket error: Missing URI scheme.');
/* port tweaks */
$parts['port'] = ($parts['scheme'] == 'https') ? $this->v1('port', 443, $parts) : $this->v1('port', 80, $parts);
$nl = "\r\n";
$http_mthd = strtoupper($this->http_method);
if ($this->v1('user', 0, $parts) || $this->useProxy($url)) {
$h_code = $http_mthd . ' ' . $url;
}
else {
$h_code = $http_mthd . ' ' . $this->v1('path', '/', $parts) . (($v = $this->v1('query', 0, $parts)) ? '?' . $v : '') . (($v = $this->v1('fragment', 0, $parts)) ? '#' . $v : '');
}
$port_code = ($parts['port'] != 80) ? ':' . $parts['port'] : '';
$h_code .= ' HTTP/1.0' . $nl.
'Host: ' . $parts['host'] . $port_code . $nl .
(($v = $this->http_accept_header) ? $v . $nl : '') .
(($v = $this->http_user_agent_header) && !preg_match('/User\-Agent\:/', $this->http_custom_headers) ? $v . $nl : '') .
(($http_mthd == 'POST') ? 'Content-Length: ' . strlen($this->message_body) . $nl : '') .
($this->http_custom_headers ? trim($this->http_custom_headers) . $nl : '') .
$nl .
'';
/* post body */
if ($http_mthd == 'POST') {
$h_code .= $this->message_body . $nl;
}
/* connect */
if ($this->useProxy($url)) {
$s = @fsockopen($this->a['proxy_host'], $this->a['proxy_port'], $errno, $errstr, $this->timeout);
}
elseif (($parts['scheme'] == 'https') && function_exists('stream_socket_client')) {
// SSL options via config array, code by Hannes Muehleisen (muehleis@informatik.hu-berlin.de)
$context = stream_context_create();
foreach ($this->a as $k => $v) {
if (preg_match('/^arc_reader_ssl_(.+)$/', $k, $m)) {
stream_context_set_option($context, 'ssl', $m[1], $v);
}
}
$s = stream_socket_client('ssl://' . $parts['host'] . $port_code, $errno, $errstr, $this->timeout, STREAM_CLIENT_CONNECT, $context);
}
elseif ($parts['scheme'] == 'https') {
$s = @fsockopen('ssl://' . $parts['host'], $parts['port'], $errno, $errstr, $this->timeout);
}
elseif ($parts['scheme'] == 'http') {
$s = @fsockopen($parts['host'], $parts['port'], $errno, $errstr, $this->timeout);
}
if (!$s) {
return $this->addError('Socket error: Could not connect to "' . $url . '" (proxy: ' . ($this->useProxy($url) ? '1' : '0') . '): ' . $errstr);
}
/* request */
fwrite($s, $h_code);
/* timeout */
if ($this->timeout) {
//stream_set_blocking($s, false);
stream_set_timeout($s, $this->timeout);
}
/* response headers */
$h = array();
$this->response_headers = $h;
if (!$this->ping_only) {
do {
$line = trim(fgets($s, 4096));
$info = stream_get_meta_data($s);
if (preg_match("/^HTTP[^\s]+\s+([0-9]{1})([0-9]{2})(.*)$/i", $line, $m)) {/* response code */
$error = in_array($m[1], array('4', '5')) ? $m[1] . $m[2] . ' ' . $m[3] : '';
$error = ($m[1].$m[2] == '304') ? '304 '.$m[3] : $error;
$h['response-code'] = $m[1] . $m[2];
$h['error'] = $error;
$h['redirect'] = ($m[1] == '3') ? true : false;
}
elseif (preg_match('/^([^\:]+)\:\s*(.*)$/', $line, $m)) {/* header */
$h_name = strtolower($m[1]);
if (!isset($h[$h_name])) {/* 1st value */
$h[$h_name] = trim($m[2]);
}
elseif (!is_array($h[$h_name])) {/* 2nd value */
$h[$h_name] = array($h[$h_name], trim($m[2]));
}
else {/* more values */
$h[$h_name][] = trim($m[2]);
}
}
} while(!$info['timed_out'] && !feof($s) && $line);
$h['format'] = strtolower(preg_replace('/^([^\s]+).*$/', '\\1', $this->v('content-type', '', $h)));
$h['encoding'] = preg_match('/(utf\-8|iso\-8859\-1|us\-ascii)/', $this->v('content-type', '', $h), $m) ? strtoupper($m[1]) : '';
$h['encoding'] = preg_match('/charset=\s*([^\s]+)/si', $this->v('content-type', '', $h), $m) ? strtoupper($m[1]) : $h['encoding'];
$this->response_headers = $h;
/* result */
if ($info['timed_out']) {
return $this->addError('Connection timed out after ' . $this->timeout . ' seconds');
}
/* error */
if ($v = $this->v('error', 0, $h)) {
/* digest auth */
/* 401 received */
if (preg_match('/Digest/i', $this->v('www-authenticate', '', $h)) && !$this->digest_auth) {
$this->setCredentials($url);
$this->digest_auth = 1;
return $this->getHTTPSocket($url);
}
return $this->addError($error . ' "' . (!feof($s) ? trim(strip_tags(fread($s, 128))) . '..."' : ''));
}
/* redirect */
if ($this->v('redirect', 0, $h) && ($new_url = $this->v1('location', 0, $h))) {
fclose($s);
$this->redirects[$url] = $new_url;
$this->base = $new_url;
if ($redirs > $this->max_redirects) {
return $this->addError('Max numbers of redirects exceeded.');
}
return $this->getHTTPSocket($new_url, $redirs+1, $parts);
}
}
if ($this->timeout) {
stream_set_blocking($s, true);
}
return array('type' => 'socket', 'url' => $url, 'socket' =>& $s, 'headers' => $h, 'pos' => 0, 'size' => $this->v('content-length', 0, $h), 'buffer' => '');
}
function readStream($buffer_xml = true, $d_size = 1024) {
//if (!$s = $this->v('stream')) return '';
if (!$s = $this->v('stream')) return $this->addError('missing stream in "readStream" ' . $this->uri);
$s_type = $this->v('type', '', $s);
$r = $s['buffer'];
$s['buffer'] = '';
if ($s['size']) $d_size = min($d_size, $s['size'] - $s['pos']);
/* data */
if ($s_type == 'data') {
$d = ($d_size > 0) ? substr($s['data'], $s['pos'], $d_size) : '';
}
/* socket */
elseif ($s_type == 'socket') {
$d = ($d_size > 0) && !feof($s['socket']) ? fread($s['socket'], $d_size) : '';
}
$eof = $d ? false : true;
/* chunked despite HTTP 1.0 request */
if (isset($s['headers']) && isset($s['headers']['transfer-encoding']) && ($s['headers']['transfer-encoding'] == 'chunked')) {
$d = preg_replace('/(^|[\r\n]+)[0-9a-f]{1,4}[\r\n]+/', '', $d);
}
$s['pos'] += strlen($d);
if ($buffer_xml) {/* stop after last closing xml tag (if available) */
if (preg_match('/^(.*\>)([^\>]*)$/s', $d, $m)) {
$d = $m[1];
$s['buffer'] = $m[2];
}
elseif (!$eof) {
$s['buffer'] = $r . $d;
$this->stream = $s;
return $this->readStream(true, $d_size);
}
}
$this->stream = $s;
return $r . $d;
}
function closeStream() {
if (isset($this->stream)) {
if ($this->v('type', 0, $this->stream) == 'socket') {
@fclose($this->stream['socket']);
}
unset($this->stream);
}
}
/* */
function getFormat() {
if (!$this->format) {
if (!$this->v('stream')) {
return $this->addError('missing stream in "getFormat"');
}
$v = $this->readStream(false);
$mtype = $this->v('format', '', $this->stream['headers']);
$this->stream['buffer'] = $v . $this->stream['buffer'];
$ext = preg_match('/\.([^\.]+)$/', $this->uri, $m) ? $m[1] : '';
$this->format = ARC2::getFormat($v, $mtype, $ext);
}
return $this->format;
}
/* */
function getResponseHeaders() {
if (isset($this->stream) && isset($this->stream['headers'])) {
return $this->stream['headers'];
}
return $this->response_headers;
}
function getEncoding($default = 'UTF-8') {
return $this->v1('encoding', $default, $this->stream['headers']);
}
function getRedirects() {
return $this->redirects;
}
function getAuthInfos() {
return $this->auth_infos;
}
/* */
}
| gpl-2.0 |
seyekuyinu/highlifer | wp-content/plugins/myMail/classes/libs/phpmailer/class.smtp.php | 39913 | <?php
/**
* PHPMailer RFC821 SMTP email transport class.
* PHP Version 5
* @package PHPMailer
* @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
* @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
* @author Jim Jagielski (jimjag) <jimjag@gmail.com>
* @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
* @author Brent R. Matzelle (original founder)
* @copyright 2014 Marcus Bointon
* @copyright 2010 - 2012 Jim Jagielski
* @copyright 2004 - 2009 Andy Prevost
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
* @note This program is distributed in the hope that it will be useful - WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*/
/**
* PHPMailer RFC821 SMTP email transport class.
* Implements RFC 821 SMTP commands and provides some utility methods for sending mail to an SMTP server.
* @package PHPMailer
* @author Chris Ryan
* @author Marcus Bointon <phpmailer@synchromedia.co.uk>
*/
class SMTP_mymail
{
/**
* The PHPMailer SMTP version number.
* @var string
*/
const VERSION = '5.2.14';
/**
* SMTP line break constant.
* @var string
*/
const CRLF = "\r\n";
/**
* The SMTP port to use if one is not specified.
* @var integer
*/
const DEFAULT_SMTP_PORT = 25;
/**
* The maximum line length allowed by RFC 2822 section 2.1.1
* @var integer
*/
const MAX_LINE_LENGTH = 998;
/**
* Debug level for no output
*/
const DEBUG_OFF = 0;
/**
* Debug level to show client -> server messages
*/
const DEBUG_CLIENT = 1;
/**
* Debug level to show client -> server and server -> client messages
*/
const DEBUG_SERVER = 2;
/**
* Debug level to show connection status, client -> server and server -> client messages
*/
const DEBUG_CONNECTION = 3;
/**
* Debug level to show all messages
*/
const DEBUG_LOWLEVEL = 4;
/**
* The PHPMailer SMTP Version number.
* @var string
* @deprecated Use the `VERSION` constant instead
* @see SMTP::VERSION
*/
public $Version = '5.2.14';
/**
* SMTP server port number.
* @var integer
* @deprecated This is only ever used as a default value, so use the `DEFAULT_SMTP_PORT` constant instead
* @see SMTP::DEFAULT_SMTP_PORT
*/
public $SMTP_PORT = 25;
/**
* SMTP reply line ending.
* @var string
* @deprecated Use the `CRLF` constant instead
* @see SMTP::CRLF
*/
public $CRLF = "\r\n";
/**
* Debug output level.
* Options:
* * self::DEBUG_OFF (`0`) No debug output, default
* * self::DEBUG_CLIENT (`1`) Client commands
* * self::DEBUG_SERVER (`2`) Client commands and server responses
* * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status
* * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages
* @var integer
*/
public $do_debug = self::DEBUG_OFF;
/**
* How to handle debug output.
* Options:
* * `echo` Output plain-text as-is, appropriate for CLI
* * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
* * `error_log` Output to error log as configured in php.ini
*
* Alternatively, you can provide a callable expecting two params: a message string and the debug level:
* <code>
* $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
* </code>
* @var string|callable
*/
public $Debugoutput = 'echo';
/**
* Whether to use VERP.
* @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
* @link http://www.postfix.org/VERP_README.html Info on VERP
* @var boolean
*/
public $do_verp = false;
/**
* The timeout value for connection, in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
* This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
* @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2
* @var integer
*/
public $Timeout = 300;
/**
* How long to wait for commands to complete, in seconds.
* Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
* @var integer
*/
public $Timelimit = 300;
/**
* The socket for the server connection.
* @var resource
*/
protected $smtp_conn;
/**
* Error information, if any, for the last SMTP command.
* @var array
*/
protected $error = array(
'error' => '',
'detail' => '',
'smtp_code' => '',
'smtp_code_ex' => ''
);
/**
* The reply the server sent to us for HELO.
* If null, no HELO string has yet been received.
* @var string|null
*/
protected $helo_rply = null;
/**
* The set of SMTP extensions sent in reply to EHLO command.
* Indexes of the array are extension names.
* Value at index 'HELO' or 'EHLO' (according to command that was sent)
* represents the server name. In case of HELO it is the only element of the array.
* Other values can be boolean TRUE or an array containing extension options.
* If null, no HELO/EHLO string has yet been received.
* @var array|null
*/
protected $server_caps = null;
/**
* The most recent reply received from the server.
* @var string
*/
protected $last_reply = '';
/**
* Output debugging info via a user-selected method.
* @see SMTP::$Debugoutput
* @see SMTP::$do_debug
* @param string $str Debug string to output
* @param integer $level The debug level of this message; see DEBUG_* constants
* @return void
*/
protected function edebug($str, $level = 0)
{
if ($level > $this->do_debug) {
return;
}
//Avoid clash with built-in function names
if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
call_user_func($this->Debugoutput, $str, $this->do_debug);
return;
}
switch ($this->Debugoutput) {
case 'error_log':
//Don't output, just log
error_log($str);
break;
case 'html':
//Cleans up output a bit for a better looking, HTML-safe output
echo htmlentities(
preg_replace('/[\r\n]+/', '', $str),
ENT_QUOTES,
'UTF-8'
)
. "<br>\n";
break;
case 'echo':
default:
//Normalize line breaks
$str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
"\n",
"\n \t ",
trim($str)
)."\n";
}
}
/**
* Connect to an SMTP server.
* @param string $host SMTP server IP or host name
* @param integer $port The port number to connect to
* @param integer $timeout How long to wait for the connection to open
* @param array $options An array of options for stream_context_create()
* @access public
* @return boolean
*/
public function connect($host, $port = null, $timeout = 30, $options = array())
{
static $streamok;
//This is enabled by default since 5.0.0 but some providers disable it
//Check this once and cache the result
if (is_null($streamok)) {
$streamok = function_exists('stream_socket_client');
}
// Clear errors to avoid confusion
$this->setError('');
// Make sure we are __not__ connected
if ($this->connected()) {
// Already connected, generate error
$this->setError('Already connected to a server');
return false;
}
if (empty($port)) {
$port = self::DEFAULT_SMTP_PORT;
}
// Connect to the SMTP server
$this->edebug(
"Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true),
self::DEBUG_CONNECTION
);
$errno = 0;
$errstr = '';
if ($streamok) {
$socket_context = stream_context_create($options);
//Suppress errors; connection failures are handled at a higher level
$this->smtp_conn = @stream_socket_client(
$host . ":" . $port,
$errno,
$errstr,
$timeout,
STREAM_CLIENT_CONNECT,
$socket_context
);
} else {
//Fall back to fsockopen which should work in more places, but is missing some features
$this->edebug(
"Connection: stream_socket_client not available, falling back to fsockopen",
self::DEBUG_CONNECTION
);
$this->smtp_conn = fsockopen(
$host,
$port,
$errno,
$errstr,
$timeout
);
}
// Verify we connected properly
if (!is_resource($this->smtp_conn)) {
$this->setError(
'Failed to connect to server',
$errno,
$errstr
);
$this->edebug(
'SMTP ERROR: ' . $this->error['error']
. ": $errstr ($errno)",
self::DEBUG_CLIENT
);
return false;
}
$this->edebug('Connection: opened', self::DEBUG_CONNECTION);
// SMTP server can take longer to respond, give longer timeout for first read
// Windows does not have support for this timeout function
if (substr(PHP_OS, 0, 3) != 'WIN') {
$max = ini_get('max_execution_time');
// Don't bother if unlimited
if ($max != 0 && $timeout > $max) {
@set_time_limit($timeout);
}
stream_set_timeout($this->smtp_conn, $timeout, 0);
}
// Get any announcement
$announce = $this->get_lines();
$this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
return true;
}
/**
* Initiate a TLS (encrypted) session.
* @access public
* @return boolean
*/
public function startTLS()
{
if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
return false;
}
// Begin encrypted connection
if (!stream_socket_enable_crypto(
$this->smtp_conn,
true,
STREAM_CRYPTO_METHOD_TLS_CLIENT
)) {
return false;
}
return true;
}
/**
* Perform SMTP authentication.
* Must be run after hello().
* @see hello()
* @param string $username The user name
* @param string $password The password
* @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5, XOAUTH2)
* @param string $realm The auth realm for NTLM
* @param string $workstation The auth workstation for NTLM
* @param null|OAuth $OAuth An optional OAuth instance (@see PHPMailerOAuth)
* @return bool True if successfully authenticated.* @access public
*/
public function authenticate(
$username,
$password,
$authtype = null,
$realm = '',
$workstation = '',
$OAuth = null
) {
if (!$this->server_caps) {
$this->setError('Authentication is not allowed before HELO/EHLO');
return false;
}
if (array_key_exists('EHLO', $this->server_caps)) {
// SMTP extensions are available. Let's try to find a proper authentication method
if (!array_key_exists('AUTH', $this->server_caps)) {
$this->setError('Authentication is not allowed at this stage');
// 'at this stage' means that auth may be allowed after the stage changes
// e.g. after STARTTLS
return false;
}
self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL);
self::edebug(
'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
self::DEBUG_LOWLEVEL
);
if (empty($authtype)) {
foreach (array('LOGIN', 'CRAM-MD5', 'NTLM', 'PLAIN', 'XOAUTH2') as $method) {
if (in_array($method, $this->server_caps['AUTH'])) {
$authtype = $method;
break;
}
}
if (empty($authtype)) {
$this->setError('No supported authentication methods found');
return false;
}
self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL);
}
if (!in_array($authtype, $this->server_caps['AUTH'])) {
$this->setError("The requested authentication method \"$authtype\" is not supported by the server");
return false;
}
} elseif (empty($authtype)) {
$authtype = 'LOGIN';
}
switch ($authtype) {
case 'PLAIN':
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
return false;
}
// Send encoded username and password
if (!$this->sendCommand(
'User & Password',
base64_encode("\0" . $username . "\0" . $password),
235
)
) {
return false;
}
break;
case 'LOGIN':
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
return false;
}
if (!$this->sendCommand("Username", base64_encode($username), 334)) {
return false;
}
if (!$this->sendCommand("Password", base64_encode($password), 235)) {
return false;
}
break;
case 'XOAUTH2':
//If the OAuth Instance is not set. Can be a case when PHPMailer is used
//instead of PHPMailerOAuth
if (is_null($OAuth)) {
return false;
}
$oauth = $OAuth->getOauth64();
// Start authentication
if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) {
return false;
}
break;
case 'NTLM':
/*
* ntlm_sasl_client.php
* Bundled with Permission
*
* How to telnet in windows:
* http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
* PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
*/
require_once 'extras/ntlm_sasl_client.php';
$temp = new stdClass;
$ntlm_client = new ntlm_sasl_client_class;
//Check that functions are available
if (!$ntlm_client->Initialize($temp)) {
$this->setError($temp->error);
$this->edebug(
'You need to enable some modules in your php.ini file: '
. $this->error['error'],
self::DEBUG_CLIENT
);
return false;
}
//msg1
$msg1 = $ntlm_client->TypeMsg1($realm, $workstation); //msg1
if (!$this->sendCommand(
'AUTH NTLM',
'AUTH NTLM ' . base64_encode($msg1),
334
)
) {
return false;
}
//Though 0 based, there is a white space after the 3 digit number
//msg2
$challenge = substr($this->last_reply, 3);
$challenge = base64_decode($challenge);
$ntlm_res = $ntlm_client->NTLMResponse(
substr($challenge, 24, 8),
$password
);
//msg3
$msg3 = $ntlm_client->TypeMsg3(
$ntlm_res,
$username,
$realm,
$workstation
);
// send encoded username
return $this->sendCommand('Username', base64_encode($msg3), 235);
case 'CRAM-MD5':
// Start authentication
if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
return false;
}
// Get the challenge
$challenge = base64_decode(substr($this->last_reply, 4));
// Build the response
$response = $username . ' ' . $this->hmac($challenge, $password);
// send encoded credentials
return $this->sendCommand('Username', base64_encode($response), 235);
default:
$this->setError("Authentication method \"$authtype\" is not supported");
return false;
}
return true;
}
/**
* Calculate an MD5 HMAC hash.
* Works like hash_hmac('md5', $data, $key)
* in case that function is not available
* @param string $data The data to hash
* @param string $key The key to hash with
* @access protected
* @return string
*/
protected function hmac($data, $key)
{
if (function_exists('hash_hmac')) {
return hash_hmac('md5', $data, $key);
}
// The following borrowed from
// http://php.net/manual/en/function.mhash.php#27225
// RFC 2104 HMAC implementation for php.
// Creates an md5 HMAC.
// Eliminates the need to install mhash to compute a HMAC
// by Lance Rushing
$bytelen = 64; // byte length for md5
if (strlen($key) > $bytelen) {
$key = pack('H*', md5($key));
}
$key = str_pad($key, $bytelen, chr(0x00));
$ipad = str_pad('', $bytelen, chr(0x36));
$opad = str_pad('', $bytelen, chr(0x5c));
$k_ipad = $key ^ $ipad;
$k_opad = $key ^ $opad;
return md5($k_opad . pack('H*', md5($k_ipad . $data)));
}
/**
* Check connection state.
* @access public
* @return boolean True if connected.
*/
public function connected()
{
if (is_resource($this->smtp_conn)) {
$sock_status = stream_get_meta_data($this->smtp_conn);
if ($sock_status['eof']) {
// The socket is valid but we are not connected
$this->edebug(
'SMTP NOTICE: EOF caught while checking if connected',
self::DEBUG_CLIENT
);
$this->close();
return false;
}
return true; // everything looks good
}
return false;
}
/**
* Close the socket and clean up the state of the class.
* Don't use this function without first trying to use QUIT.
* @see quit()
* @access public
* @return void
*/
public function close()
{
$this->setError('');
$this->server_caps = null;
$this->helo_rply = null;
if (is_resource($this->smtp_conn)) {
// close the connection and cleanup
fclose($this->smtp_conn);
$this->smtp_conn = null; //Makes for cleaner serialization
$this->edebug('Connection: closed', self::DEBUG_CONNECTION);
}
}
/**
* Send an SMTP DATA command.
* Issues a data command and sends the msg_data to the server,
* finializing the mail transaction. $msg_data is the message
* that is to be send with the headers. Each header needs to be
* on a single line followed by a <CRLF> with the message headers
* and the message body being separated by and additional <CRLF>.
* Implements rfc 821: DATA <CRLF>
* @param string $msg_data Message data to send
* @access public
* @return boolean
*/
public function data($msg_data)
{
//This will use the standard timelimit
if (!$this->sendCommand('DATA', 'DATA', 354)) {
return false;
}
/* The server is ready to accept data!
* According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
* so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
* smaller lines to fit within the limit.
* We will also look for lines that start with a '.' and prepend an additional '.'.
* NOTE: this does not count towards line-length limit.
*/
// Normalize line breaks before exploding
$lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
/* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
* of the first line (':' separated) does not contain a space then it _should_ be a header and we will
* process all lines before a blank line as headers.
*/
$field = substr($lines[0], 0, strpos($lines[0], ':'));
$in_headers = false;
if (!empty($field) && strpos($field, ' ') === false) {
$in_headers = true;
}
foreach ($lines as $line) {
$lines_out = array();
if ($in_headers and $line == '') {
$in_headers = false;
}
//Break this line up into several smaller lines if it's too long
//Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
while (isset($line[self::MAX_LINE_LENGTH])) {
//Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
//so as to avoid breaking in the middle of a word
$pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
//Deliberately matches both false and 0
if (!$pos) {
//No nice break found, add a hard break
$pos = self::MAX_LINE_LENGTH - 1;
$lines_out[] = substr($line, 0, $pos);
$line = substr($line, $pos);
} else {
//Break at the found point
$lines_out[] = substr($line, 0, $pos);
//Move along by the amount we dealt with
$line = substr($line, $pos + 1);
}
//If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
if ($in_headers) {
$line = "\t" . $line;
}
}
$lines_out[] = $line;
//Send the lines to the server
foreach ($lines_out as $line_out) {
//RFC2821 section 4.5.2
if (!empty($line_out) and $line_out[0] == '.') {
$line_out = '.' . $line_out;
}
$this->client_send($line_out . self::CRLF);
}
}
//Message data has been sent, complete the command
//Increase timelimit for end of DATA command
$savetimelimit = $this->Timelimit;
$this->Timelimit = $this->Timelimit * 2;
$result = $this->sendCommand('DATA END', '.', 250);
//Restore timelimit
$this->Timelimit = $savetimelimit;
return $result;
}
/**
* Send an SMTP HELO or EHLO command.
* Used to identify the sending server to the receiving server.
* This makes sure that client and server are in a known state.
* Implements RFC 821: HELO <SP> <domain> <CRLF>
* and RFC 2821 EHLO.
* @param string $host The host name or IP to connect to
* @access public
* @return boolean
*/
public function hello($host = '')
{
//Try extended hello first (RFC 2821)
return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
}
/**
* Send an SMTP HELO or EHLO command.
* Low-level implementation used by hello()
* @see hello()
* @param string $hello The HELO string
* @param string $host The hostname to say we are
* @access protected
* @return boolean
*/
protected function sendHello($hello, $host)
{
$noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
$this->helo_rply = $this->last_reply;
if ($noerror) {
$this->parseHelloFields($hello);
} else {
$this->server_caps = null;
}
return $noerror;
}
/**
* Parse a reply to HELO/EHLO command to discover server extensions.
* In case of HELO, the only parameter that can be discovered is a server name.
* @access protected
* @param string $type - 'HELO' or 'EHLO'
*/
protected function parseHelloFields($type)
{
$this->server_caps = array();
$lines = explode("\n", $this->last_reply);
foreach ($lines as $n => $s) {
//First 4 chars contain response code followed by - or space
$s = trim(substr($s, 4));
if (empty($s)) {
continue;
}
$fields = explode(' ', $s);
if (!empty($fields)) {
if (!$n) {
$name = $type;
$fields = $fields[0];
} else {
$name = array_shift($fields);
switch ($name) {
case 'SIZE':
$fields = ($fields ? $fields[0] : 0);
break;
case 'AUTH':
if (!is_array($fields)) {
$fields = array();
}
break;
default:
$fields = true;
}
}
$this->server_caps[$name] = $fields;
}
}
}
/**
* Send an SMTP MAIL command.
* Starts a mail transaction from the email address specified in
* $from. Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command.
* Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
* @param string $from Source address of this message
* @access public
* @return boolean
*/
public function mail($from)
{
$useVerp = ($this->do_verp ? ' XVERP' : '');
return $this->sendCommand(
'MAIL FROM',
'MAIL FROM:<' . $from . '>' . $useVerp,
250
);
}
/**
* Send an SMTP QUIT command.
* Closes the socket if there is no error or the $close_on_error argument is true.
* Implements from rfc 821: QUIT <CRLF>
* @param boolean $close_on_error Should the connection close if an error occurs?
* @access public
* @return boolean
*/
public function quit($close_on_error = true)
{
$noerror = $this->sendCommand('QUIT', 'QUIT', 221);
$err = $this->error; //Save any error
if ($noerror or $close_on_error) {
$this->close();
$this->error = $err; //Restore any error from the quit command
}
return $noerror;
}
/**
* Send an SMTP RCPT command.
* Sets the TO argument to $toaddr.
* Returns true if the recipient was accepted false if it was rejected.
* Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
* @param string $address The address the message is being sent to
* @access public
* @return boolean
*/
public function recipient($address)
{
return $this->sendCommand(
'RCPT TO',
'RCPT TO:<' . $address . '>',
array(250, 251)
);
}
/**
* Send an SMTP RSET command.
* Abort any transaction that is currently in progress.
* Implements rfc 821: RSET <CRLF>
* @access public
* @return boolean True on success.
*/
public function reset()
{
return $this->sendCommand('RSET', 'RSET', 250);
}
/**
* Send a command to an SMTP server and check its return code.
* @param string $command The command name - not sent to the server
* @param string $commandstring The actual command to send
* @param integer|array $expect One or more expected integer success codes
* @access protected
* @return boolean True on success.
*/
protected function sendCommand($command, $commandstring, $expect)
{
if (!$this->connected()) {
$this->setError("Called $command without being connected");
return false;
}
//Reject line breaks in all commands
if (strpos($commandstring, "\n") !== false or strpos($commandstring, "\r") !== false) {
$this->setError("Command '$command' contained line breaks");
return false;
}
$this->client_send($commandstring . self::CRLF);
$this->last_reply = $this->get_lines();
// Fetch SMTP code and possible error code explanation
$matches = array();
if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) {
$code = $matches[1];
$code_ex = (count($matches) > 2 ? $matches[2] : null);
// Cut off error code from each response line
$detail = preg_replace(
"/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m",
'',
$this->last_reply
);
} else {
// Fall back to simple parsing if regex fails
$code = substr($this->last_reply, 0, 3);
$code_ex = null;
$detail = substr($this->last_reply, 4);
}
$this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
if (!in_array($code, (array)$expect)) {
$this->setError(
"$command command failed",
$detail,
$code,
$code_ex
);
$this->edebug(
'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
self::DEBUG_CLIENT
);
return false;
}
$this->setError('');
return true;
}
/**
* Send an SMTP SAML command.
* Starts a mail transaction from the email address specified in $from.
* Returns true if successful or false otherwise. If True
* the mail transaction is started and then one or more recipient
* commands may be called followed by a data command. This command
* will send the message to the users terminal if they are logged
* in and send them an email.
* Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
* @param string $from The address the message is from
* @access public
* @return boolean
*/
public function sendAndMail($from)
{
return $this->sendCommand('SAML', "SAML FROM:$from", 250);
}
/**
* Send an SMTP VRFY command.
* @param string $name The name to verify
* @access public
* @return boolean
*/
public function verify($name)
{
return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
}
/**
* Send an SMTP NOOP command.
* Used to keep keep-alives alive, doesn't actually do anything
* @access public
* @return boolean
*/
public function noop()
{
return $this->sendCommand('NOOP', 'NOOP', 250);
}
/**
* Send an SMTP TURN command.
* This is an optional command for SMTP that this class does not support.
* This method is here to make the RFC821 Definition complete for this class
* and _may_ be implemented in future
* Implements from rfc 821: TURN <CRLF>
* @access public
* @return boolean
*/
public function turn()
{
$this->setError('The SMTP TURN command is not implemented');
$this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
return false;
}
/**
* Send raw data to the server.
* @param string $data The data to send
* @access public
* @return integer|boolean The number of bytes sent to the server or false on error
*/
public function client_send($data)
{
$this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
return fwrite($this->smtp_conn, $data);
}
/**
* Get the latest error.
* @access public
* @return array
*/
public function getError()
{
return $this->error;
}
/**
* Get SMTP extensions available on the server
* @access public
* @return array|null
*/
public function getServerExtList()
{
return $this->server_caps;
}
/**
* A multipurpose method
* The method works in three ways, dependent on argument value and current state
* 1. HELO/EHLO was not sent - returns null and set up $this->error
* 2. HELO was sent
* $name = 'HELO': returns server name
* $name = 'EHLO': returns boolean false
* $name = any string: returns null and set up $this->error
* 3. EHLO was sent
* $name = 'HELO'|'EHLO': returns server name
* $name = any string: if extension $name exists, returns boolean True
* or its options. Otherwise returns boolean False
* In other words, one can use this method to detect 3 conditions:
* - null returned: handshake was not or we don't know about ext (refer to $this->error)
* - false returned: the requested feature exactly not exists
* - positive value returned: the requested feature exists
* @param string $name Name of SMTP extension or 'HELO'|'EHLO'
* @return mixed
*/
public function getServerExt($name)
{
if (!$this->server_caps) {
$this->setError('No HELO/EHLO was sent');
return null;
}
// the tight logic knot ;)
if (!array_key_exists($name, $this->server_caps)) {
if ($name == 'HELO') {
return $this->server_caps['EHLO'];
}
if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) {
return false;
}
$this->setError('HELO handshake was used. Client knows nothing about server extensions');
return null;
}
return $this->server_caps[$name];
}
/**
* Get the last reply from the server.
* @access public
* @return string
*/
public function getLastReply()
{
return $this->last_reply;
}
/**
* Read the SMTP server's response.
* Either before eof or socket timeout occurs on the operation.
* With SMTP we can tell if we have more lines to read if the
* 4th character is '-' symbol. If it is a space then we don't
* need to read anything else.
* @access protected
* @return string
*/
protected function get_lines()
{
// If the connection is bad, give up straight away
if (!is_resource($this->smtp_conn)) {
return '';
}
$data = '';
$endtime = 0;
stream_set_timeout($this->smtp_conn, $this->Timeout);
if ($this->Timelimit > 0) {
$endtime = time() + $this->Timelimit;
}
while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
$str = @fgets($this->smtp_conn, 515);
$this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
$this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
$data .= $str;
// If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen
if ((isset($str[3]) and $str[3] == ' ')) {
break;
}
// Timed-out? Log and break
$info = stream_get_meta_data($this->smtp_conn);
if ($info['timed_out']) {
$this->edebug(
'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
self::DEBUG_LOWLEVEL
);
break;
}
// Now check if reads took too long
if ($endtime and time() > $endtime) {
$this->edebug(
'SMTP -> get_lines(): timelimit reached ('.
$this->Timelimit . ' sec)',
self::DEBUG_LOWLEVEL
);
break;
}
}
return $data;
}
/**
* Enable or disable VERP address generation.
* @param boolean $enabled
*/
public function setVerp($enabled = false)
{
$this->do_verp = $enabled;
}
/**
* Get VERP address generation mode.
* @return boolean
*/
public function getVerp()
{
return $this->do_verp;
}
/**
* Set error messages and codes.
* @param string $message The error message
* @param string $detail Further detail on the error
* @param string $smtp_code An associated SMTP error code
* @param string $smtp_code_ex Extended SMTP code
*/
protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
{
$this->error = array(
'error' => $message,
'detail' => $detail,
'smtp_code' => $smtp_code,
'smtp_code_ex' => $smtp_code_ex
);
}
/**
* Set debug output method.
* @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it.
*/
public function setDebugOutput($method = 'echo')
{
$this->Debugoutput = $method;
}
/**
* Get debug output method.
* @return string
*/
public function getDebugOutput()
{
return $this->Debugoutput;
}
/**
* Set debug output level.
* @param integer $level
*/
public function setDebugLevel($level = 0)
{
$this->do_debug = $level;
}
/**
* Get debug output level.
* @return integer
*/
public function getDebugLevel()
{
return $this->do_debug;
}
/**
* Set SMTP timeout.
* @param integer $timeout
*/
public function setTimeout($timeout = 0)
{
$this->Timeout = $timeout;
}
/**
* Get SMTP timeout.
* @return integer
*/
public function getTimeout()
{
return $this->Timeout;
}
}
| gpl-2.0 |
mssnaveensharma/mjejaneriver-jaqui | administrator/components/com_jhotelreservation/models/extraoptions.php | 6834 | <?php
/**
* @package JHotelReservation
* @subpackage com_jhotelreservation
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
require_once "hoteltranslations.php";
/**
* List Model.
*
* @package JHotelReservation
* @subpackage com_jhotelreservation
*/
class JHotelReservationModelExtraOptions extends JModelList
{
/**
* Constructor.
*
* @param array An optional associative array of configuration settings.
*
* @see JController
* @since 1.6
*/
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'id', 'eo.id',
'title', 'eo.name',
'oredering', 'eo.ordering'
);
}
parent::__construct($config);
}
/**
* Overrides the getItems method to attach additional metrics to the list.
*
* @return mixed An array of data items on success, false on failure.
*
* @since 1.6.1
*/
public function getItems()
{
// Get a storage key.
$store = $this->getStoreId('getItems');
// Try to load the data from internal storage.
if (!empty($this->cache[$store]))
{
return $this->cache[$store];
}
// Load the list items.
$items = parent::getItems();
// If emtpy or an error, just return.
if (empty($items))
{
return array();
}
// Add the items to the internal cache.
$this->cache[$store] = $items;
return $this->cache[$store];
}
/**
* Method to build an SQL query to load the list data.
*
* @return string An SQL query
*
* @since 1.6
*/
protected function getListQuery()
{
// Create a new query objeeo.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select all fields from the table.
$query->select($this->getState('list.select', 'eo.*'));
$query->from($db->quoteName('#__hotelreservation_extra_options').' AS eo');
// Filter on the published state.
$published = $this->getState('filter.status_id');
if (is_numeric($published)) {
$query->where('eo.status = '.(int) $published);
} elseif ($published === '') {
$query->where('(eo.status IN (0, 1))');
}
// Filter the items over the menu id if set.
$hotelId = $this->getState('filter.hotel_id');
if (!empty($hotelId)) {
$query->where('eo.hotel_id = '.$db->quote($hotelId));
}else{
$query->where('eo.hotel_id = -2');
}
$query->group('eo.id');
// Add the list ordering clause.
$query->order($db->escape($this->getState('list.ordering', 'eo.id')).' '.$db->escape($this->getState('list.direction', 'ASC')));
return $query;
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* @param string $ordering An optional ordering field.
* @param string $direction An optional direction (asc|desc).
*
* @return void
*
* @since 1.6
*/
protected function populateState($ordering = null, $direction = null)
{
$app = JFactory::getApplication('administrator');
// Check if the ordering field is in the white list, otherwise use the incoming value.
$value = $app->getUserStateFromRequest($this->context.'.ordercol', 'filter_order', $ordering);
$this->setState('list.ordering', $value);
// Check if the ordering direction is valid, otherwise use the incoming value.
$value = $app->getUserStateFromRequest($this->context.'.orderdirn', 'filter_order_Dir', $direction);
$this->setState('list.direction', $value);
//dmp($this->context);
$hotel_id = JRequest::getVar('hotel_id', null);
if($hotel_id == 0 ){
$hotel_id = $app->getUserState($this->context.'.filter.hotel_id');
if (!$hotel_id) {
$hotel_id = 0;
}
}
$layout = JRequest::getVar('layout', null);
if(!isset($layout)){
$app->setUserState($this->context.'.filter.hotel_id', $hotel_id);
}
$this->setState('filter.hotel_id', $hotel_id);
$status_id = JRequest::getVar('status_id', null);
$this->setState('filter.status_id', $status_id);
// List state information.
parent::populateState('eo.id', 'desc');
}
/**
* Method to adjust the ordering of a row.
*
* @param int The ID of the primary key to move.
* @param integer Increment, usually +1 or -1
* @return boolean False on failure or error, true otherwise.
*/
public function reorder($pk, $direction = 0)
{
// Sanitize the id and adjustment.
$pk = (!empty($pk)) ? $pk : (int) $this->getState('extraoption.id');
$user = JFactory::getUser();
// Get an instance of the record's table.
$table = JTable::getInstance('ExtraOption');
// Load the row.
if (!$table->load($pk)) {
$this->setError($table->getError());
return false;
}
// Access checks.
$allow = true; //$user->authorise('core.edit.state', 'com_users');
if (!$allow)
{
$this->setError(JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED',true));
return false;
}
// Move the row.
// TODO: Where clause to restrict category.
$table->move($pk);
return true;
}
/**
* Saves the manually set order of records.
*
* @param array An array of primary key ids.
* @param int +/-1
*/
function saveorder($pks, $order)
{
// Initialise variables.
$table = JTable::getInstance('ExtraOption');
$user = JFactory::getUser();
$conditions = array();
if (empty($pks)) {
return JError::raiseWarning(500, JText::_('COM_USERS_ERROR_LEVELS_NOLEVELS_SELECTED',true));
}
// update ordering values
foreach ($pks as $i => $pk)
{
$table->load((int) $pk);
// Access checks.
$allow = true;//$user->authorise('core.edit.state', 'com_users');
if (!$allow)
{
// Prune items that you can't change.
unset($pks[$i]);
JError::raiseWarning(403, JText::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED',true));
}
elseif ($table->ordering != $order[$i])
{
$table->ordering = $order[$i];
if (!$table->store())
{
$this->setError($table->getError());
return false;
}
}
}
// Execute reorder for each category.
foreach ($conditions as $cond)
{
$table->load($cond[0]);
$table->reorder($cond[1]);
}
return true;
}
function &getHotels()
{
// Load the data
if (empty( $this->_hotels ))
{
$query = ' SELECT
h.*,
c.country_name
FROM #__hotelreservation_hotels h
LEFT JOIN #__hotelreservation_countries c USING ( country_id)
ORDER BY hotel_name, country_name ';
//$this->_db->setQuery( $query );
$this->_hotels = $this->_getList( $query );
}
return $this->_hotels;
}
}
| gpl-2.0 |
quannt/WordPress-WindowsPhone | WordPress/EulaControl.xaml.cs | 1231 | using System.Windows;
using System.Windows.Controls;
using System.IO;
using WordPress.Localization;
using WordPress.Settings;
namespace WordPress
{
public partial class EulaControl : UserControl
{
#region constructors
public EulaControl()
{
// Required to initialize variables
InitializeComponent();
acceptButton.Click += OnAcceptButtonClick;
declineButton.Click += OnDeclineButtonClick;
Loaded += OnControlLoaded;
}
#endregion
#region methods
private void OnAcceptButtonClick(object sender, RoutedEventArgs args)
{
UserSettings settings = new UserSettings();
settings.AcceptedEula = true;
settings.Save();
Visibility = Visibility.Collapsed;
}
private void OnDeclineButtonClick(object sender, RoutedEventArgs args)
{
throw new ApplicationShouldEndException();
}
private void OnControlLoaded(object sender, RoutedEventArgs args)
{
browser.NavigateToString(LocalizedResources.Eula);
}
#endregion
}
} | gpl-2.0 |
tuliolages/OpenRedu | spec/helpers/lectures_helper_spec.rb | 345 | # -*- encoding : utf-8 -*-
require 'spec_helper'
describe LecturesHelper do
#Delete this example and add some real ones or delete this file
it "should be included in the object returned by #helper" do
included_modules = (class << helper; self; end).send :included_modules
included_modules.should include(LecturesHelper)
end
end
| gpl-2.0 |
titilambert/nagvis | share/server/core/classes/WuiViewManageShapes.php | 2031 | <?php
/*****************************************************************************
*
* WuiViewManageShapes.php - Class to manage shapes
*
* Copyright (c) 2004-2011 NagVis Project (Contact: info@nagvis.org)
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
/**
* @author Lars Michelsen <lars@vertical-visions.de>
*/
class WuiViewManageShapes {
/**
* Parses the information in html format
*
* @return String String with Html Code
* @author Lars Michelsen <lars@vertical-visions.de>
*/
public function parse() {
global $CORE;
// Initialize template system
$TMPL = New CoreTemplateSystem($CORE);
$TMPLSYS = $TMPL->getTmplSys();
$aData = Array(
'htmlBase' => cfg('paths', 'htmlbase'),
'langUploadShape' => l('uploadShape'),
'langChoosePngImage' => l('chooseImage'),
'langUpload' => l('upload'),
'langDeleteShape' => l('deleteShape'),
'langDelete' => l('delete'),
'shapes' => $CORE->getAvailableShapes(),
'lang' => $CORE->getJsLang(),
);
// Build page based on the template file and the data array
return $TMPLSYS->get($TMPL->getTmplFile('default', 'wuiManageShapes'), $aData);
}
}
?>
| gpl-2.0 |
prunkdump/gepi | mod_discipline/stats2/apps/vues/bilans.php | 20519 | <?php
/*
*
* Copyright 2001, 2010 Thomas Belliard, Laurent Delineau, Edouard Hue, Eric Lebrun, Gabriel Fischer, Didier Blanqui
*
* This file is part of GEPI.
*
* GEPI is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GEPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GEPI; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// On empêche l'accès direct au fichier
if (basename($_SERVER["SCRIPT_NAME"])==basename(__File__)){
die();
};
?>
<div id="result">
<div id="wrap" >
<h3><font class="red">Bilans des incidents pour la période du: <?php echo $_SESSION['stats_periodes']['du'];?> au <?php echo $_SESSION['stats_periodes']['au'];?> </font> </h3>
<?php ClassVue::afficheVue('parametres.php',$vars) ?>
</div>
<div id="tableaux">
<div id="banner">
<ul class="css-tabs" id="menutabs">
<?php $i=0;
foreach ($incidents as $titre=>$incidents_titre) :?>
<?php if($titre=='L\'Etablissement') {
if($affichage_etab) : ?>
<li><a href="#tab<?php echo $i;?>" title="Bilan des incidents" name="Etablissement-onglet-01"><?php echo $titre;?></a></li>
<li><a href="#tab<?php echo $i+1;?>" name="Etablissement-onglet-02"><img src="apps/img/user.png" alt="Synthèse individuelle" title="Synthèse individuelle"/></a> </li>
<?php $i=$i+2;
endif;
} else if ($titre=='Tous les élèves' ||$titre=='Tous les personnels' ) { ?>
<li><a href="#tab<?php echo $i;?>" title="Bilan des incidents" name="<?php echo $titre;?>-onglet-01"><?php echo $titre;?></a></li>
<li><a href="#tab<?php echo $i+1;?>" name="<?php echo $titre;?>-onglet-02"><img src="apps/img/user.png" alt="Synthèse individuelle" title="Synthèse individuelle"/></a> </li>
<?php $i=$i+2;
} else { ?>
<li><a href="#tab<?php echo $i;?>" name="<?php echo $titre;?>-onglet-01" title="Bilan des incidents">
<?php if (isset($infos_individus[$titre])) {
echo mb_substr($infos_individus[$titre]['prenom'],0,1).'.'.$infos_individus[$titre]['nom'];
if (isset($infos_individus[$titre]['classe'])) echo'('.$infos_individus[$titre]['classe'].')';
}
else echo $titre;?></a>
</li>
<?php if (isset($infos_individus[$titre]['classe'])|| !isset($infos_individus[$titre])) { ?>
<li><a href="#tab<?php echo $i+1;?>" name="<?php echo $titre;?>-onglet-02"><img src="apps/img/user.png" alt="Synthèse par élève" title="Synthèse par élève"/></a> </li>
<?php
$i=$i+2;
}
else {
$i=$i+1;
}
}
endforeach ?>
</ul>
</div>
<div class="css-panes" id="containDiv">
<?php
$i=0;
foreach ($incidents as $titre=>$incidents_titre) {
if ($titre!=='L\'Etablissement' || ($titre=='L\'Etablissement' && !is_null($affichage_etab) ) ) {?>
<div class="panel" id="tab<?php echo $i;?>">
<?php
if (isset($incidents_titre['error'])) {?>
<table class="boireaus">
<tr ><td class="nouveau"><font class='titre'>Bilan des incidents concernant :</font>
<?php if (isset($infos_individus[$titre])) {
echo $infos_individus[$titre]['prenom'].' '.$infos_individus[$titre]['nom'];
if (isset($infos_individus[$titre]['classe'])) echo'('.$infos_individus[$titre]['classe'].')';
}
else echo $titre;?>
</td></tr>
<tr><td class='nouveau'>Pas d'incidents avec les critères sélectionnés...</td></tr>
</table><br /><br />
<?php echo'</div>';?>
<?php if ($titre!=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels') {?>
<div class="panel" id="tab<?php echo $i+1;?>">
<table class="boireaus">
<tr><td class="nouveau"><strong>Bilan individuel</strong> </td></tr>
<tr><td class="nouveau">Pas d'incidents avec les critères sélectionnés...</td></tr>
</table>
</div>
<?php
$i=$i+2;
}
} else { ?>
<table class="boireaus">
<tr >
<td rowspan="6" colspan="5" class='nouveau'>
<p><font class='titre'>Bilan des incidents concernant : </font>
<?php if (isset($infos_individus[$titre])) {
echo $infos_individus[$titre]['prenom'].' '.$infos_individus[$titre]['nom'];
if (isset($infos_individus[$titre]['classe'])) echo'('.$infos_individus[$titre]['classe'].')';
}
else echo $titre;?>
</p>
<?php if($filtres_categories||$filtres_mesures||$filtres_roles||$filtres_sanctions) { ?><p>avec les filtres selectionnés</p><?php }?>
</td>
<td <?php if ($titre=='L\'Etablissement' ) {?> colspan="3" <?php }?> class='nouveau'><font class='titre'>Nombres d'incidents sur la période:</font> <?php echo $totaux[$titre]['incidents']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php echo round((100*($totaux[$titre]['incidents']/$totaux['L\'Etablissement']['incidents'])),2);?></td><?php } ?></tr>
<tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de mesures prises pour ces incidents :</font> <?php echo $totaux[$titre]['mesures_prises']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['mesures_prises']) echo round((100*($totaux[$titre]['mesures_prises']/$totaux['L\'Etablissement']['mesures_prises'])),2); else echo'0';?></td><?php } ?></tr>
<tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de mesures demandées pour ces incidents :</font> <?php echo $totaux[$titre]['mesures_demandees']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['mesures_demandees']) echo round((100*($totaux[$titre]['mesures_demandees']/$totaux['L\'Etablissement']['mesures_demandees'])),2); else echo'0';?></td><?php } ?></tr>
<tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de sanctions prises pour ces incidents:</font> <?php echo $totaux[$titre]['sanctions']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['sanctions']) echo round((100*($totaux[$titre]['sanctions']/$totaux['L\'Etablissement']['sanctions'])),2); else echo'0';?></td><?php } ?></tr>
<tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total d'heures de retenues pour ces incidents:</font> <?php echo $totaux[$titre]['heures_retenues']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['heures_retenues']) echo round((100*($totaux[$titre]['heures_retenues']/$totaux['L\'Etablissement']['heures_retenues'])),2); else echo '0'; ?></td><?php } ?></tr>
<tr><td <?php if ($titre=='L\'Etablissement' ) {?> colspan="2" <?php }?> class='nouveau'><font class='titre'>Nombre total de jours d'exclusions pour ces incidents:</font> <?php echo $totaux[$titre]['jours_exclusions']; ?></td><?php if ($titre!=='L\'Etablissement' ) {?> <td class='nouveau' > <font class='titre'>% sur la période/Etab: </font> <?php if($totaux['L\'Etablissement']['jours_exclusions']) echo round((100*($totaux[$titre]['jours_exclusions']/$totaux['L\'Etablissement']['jours_exclusions'])),2); else echo '0'; ?></td><?php } ?></tr>
</table>
<?php if($mode_detaille) { ?>
<table class="sortable resizable boireaus" id="table<?php echo $i;?>">
<thead>
<tr><th><font class='titre'>Date</font></th><th class="text"><font class='titre'>Déclarant</font></th><th><font class='titre'>Heure</font></th><th class="text"><font class='titre'>Nature</font></th>
<th><font class='titre' title="Catégories">Cat.</font></th><th class="text" ><font class='titre'>Description</font></th><th width="50%" class="nosort"><font class='titre'>Suivi</font></th></tr>
</thead>
<?php $alt_b=1;
foreach($incidents_titre as $incident) {
$alt_b=$alt_b*(-1);?>
<tr class='lig<?php echo $alt_b;?>'><td><?php echo $incident->date; ?></td><td><?php echo $incident->declarant; ?></td><td><?php echo $incident->heure; ?></td>
<td><?php echo $incident->nature; ?></td><td><?php if(!is_null($incident->id_categorie))echo $incident->sigle_categorie;else echo'-'; ?></td><td><?php echo $incident->description; ?></td>
<td class="nouveau"><?php if(!isset($protagonistes[$incident->id_incident]))echo'<h3 class="red">Aucun protagoniste défini pour cet incident</h3>';
else { ?>
<table class="boireaus" width="100%" >
<?php foreach($protagonistes[$incident->id_incident] as $protagoniste) {?>
<tr><td>
<?php echo $protagoniste->prenom.' '.$protagoniste->nom.' <br/> ';
echo $protagoniste->statut.' ';
if($protagoniste->classe) echo $protagoniste->classe .' - '; else echo ' - ' ;
if($protagoniste->qualite=="") echo'<font class="red">Aucun rôle affecté.</font><br />';
else echo $protagoniste->qualite.'<br />';
?></td><td ><?php
if (isset($mesures[$incident->id_incident][$protagoniste->login])) { ?>
<p><strong>Mesures :</strong></p>
<table class="boireaus" >
<tr><th><font class='titre'>Nature</font></th><th><font class='titre'>Mesure</font></th></tr>
<?php
$alt_c=1;
foreach ($mesures[$incident->id_incident][$protagoniste->login] as $mesure) {
$alt_c=$alt_c*(-1); ?>
<tr class="lig<?php echo $alt_c;?>"><td><?php echo $mesure->mesure; ?></td>
<td><?php echo $mesure->type.' par '.$mesure->login_u; ?></td></tr> <?php } ?>
</table>
<?php }
if (isset($sanctions[$incident->id_incident][$protagoniste->login])) { ?>
<p><strong>Sanctions :</strong></p>
<table class="boireaus" width="100%">
<tr><th><font class='titre'>Nature</font></th><th><font class='titre'>Effectuée</font></th><th><font class='titre'>Date</font></th>
<th><font class='titre'>Durée</font></th>
</tr>
<?php
$alt_d=1;
foreach ($sanctions[$incident->id_incident][$protagoniste->login] as $sanction) {
$alt_d=$alt_d*(-1); ?>
<tr class="lig<?php echo $alt_d;?>"><td><?php echo $sanction->nature; ?></td>
<td><?php echo $sanction->effectuee; ?></td>
<td><?php if($sanction->nature=='retenue')echo $sanction->ret_date;
if($sanction->nature=='exclusion')echo 'Du '.$sanction->exc_date_debut.' au '.$sanction->exc_date_fin;
if($sanction->nature=='travail')echo 'Pour le '.$sanction->trv_date_retour;?>
</td>
<td><?php if($sanction->nature=='retenue') {
echo $sanction->ret_duree.' heure';
if ($sanction->ret_duree >1) echo 's';
}else if($sanction->nature=='exclusion') {
echo $sanction->exc_duree.' jour';
if ($sanction->exc_duree >1) echo 's';
}else{
echo'-';
}
?>
</td>
</tr>
<?php } ?>
</table>
<?php } ?>
</td></tr>
<?php } ?></table>
<?php } ?></td></tr>
<?php }
}?>
</table>
<br /><br /><a href="#wrap"><img src="apps/img/retour_haut.png" alt="simple" title="simplifié"/>Retour aux selections </a>
</div>
<?php if (isset($liste_eleves[$titre])): ?>
<div class="panel" id="tab<?php echo $i+1;?>">
<table class="boireaus"> <tr><td class="nouveau" colspan="11"><strong>Bilan individuel</strong></td><td><a href="#" class="export_csv" name="<?php echo $temp_dir.'/separateur/'.$titre;?>"><img src="../../images/notes_app_csv.png" alt="export_csv"/></a></td></tr></table>
<table class="sortable resizable ">
<thead>
<tr>
<?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?>
<th colspan="3"
<?php } else { ?>
<th colspan="2"
<?php } ?>
<?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Individu</th>
<th >Incidents</th><th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Mesures prises</th>
<th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Sanctions prises</th>
<th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Heures de retenues</th>
<th colspan="2" <?php if (!isset($totaux_indiv[$titre])) {?> <?php }?>>Jours d'exclusion</th>
</tr>
<tr>
<th>Nom</th><th>Prénom</th>
<?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?>
<th class="text">Classe</th>
<?php } ?>
<th>Nombre</th><th>Nombre</th><th>%/Etab</th><th>Nombre</th><th>%/Etab</th><th>Nombre</th><th>%/Etab</th><th>Nombre</th><th>%/Etab</th>
</tr>
</thead>
<tbody>
<?php
$alt_b=1;
foreach ($liste_eleves[$titre] as $eleve) {
$alt_b=$alt_b*(-1);?>
<tr <?php if ($alt_b==1) echo"class='alt'";?>><td><a href="index.php?ctrl=Bilans&action=add_selection&login=<?php echo $eleve?>"><?php echo $totaux_indiv[$eleve]['nom']; ?></a></td><td><?php echo $totaux_indiv[$eleve]['prenom']; ?></td>
<?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?>
<td><?php echo $totaux_indiv[$eleve]['classe']; ?></td>
<?php } ?>
<td><?php echo $totaux_indiv[$eleve]['incidents']; ?></td><td><?php if(isset($totaux_indiv[$eleve]['mesures'])) echo $totaux_indiv[$eleve]['mesures'];else echo'0'; ?></td><td><?php if($totaux['L\'Etablissement']['mesures_prises'])echo str_replace(",",".",round(100*($totaux_indiv[$eleve]['mesures']/$totaux['L\'Etablissement']['mesures_prises']),2)); else echo'0';?></td>
<td><?php if(isset($totaux_indiv[$eleve]['sanctions'])) echo $totaux_indiv[$eleve]['sanctions']; else echo '0';?></td><td><?php if($totaux['L\'Etablissement']['sanctions']) echo str_replace(",",".",round(100* ($totaux_indiv[$eleve]['sanctions']/$totaux['L\'Etablissement']['sanctions']),2)); else echo'0';?></td>
<td><?php if(isset($totaux_indiv[$eleve]['heures_retenues'])) echo $totaux_indiv[$eleve]['heures_retenues'];else echo '0'; ?></td><td><?php if($totaux['L\'Etablissement']['heures_retenues'])echo str_replace(",",".",round(100*($totaux_indiv[$eleve]['heures_retenues']/$totaux['L\'Etablissement']['heures_retenues']),2));else echo'0';?></td>
<td><?php if(isset($totaux_indiv[$eleve]['jours_exclusions'])) echo $totaux_indiv[$eleve]['jours_exclusions'];else echo '0'; ?></td><td><?php if($totaux['L\'Etablissement']['jours_exclusions'])echo str_replace(",",".",round(100*($totaux_indiv[$eleve]['jours_exclusions']/$totaux['L\'Etablissement']['jours_exclusions']),2));else echo'0';?></td></tr>
<?php }?>
</tbody>
<?php if (!isset($totaux_indiv[$titre])) { ?>
<tfoot>
<tr>
<?php if($titre=='L\'Etablissement' || $titre=='Tous les élèves' ||$titre=='Tous les personnels' ){?>
<td colspan="3">
<?php } else{ ?>
<td colspan="2">
<?php } ?>
Total</td>
<td><?php if(isset($totaux_par_classe[$titre]['incidents']))echo $totaux_par_classe[$titre]['incidents']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['mesures_prises'])) echo $totaux_par_classe[$titre]['mesures']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['mesures_prises']) && $totaux['L\'Etablissement']['mesures_prises']>0) echo round(100*($totaux_par_classe[$titre]['mesures']/$totaux['L\'Etablissement']['mesures_prises']),2); else echo'0';?></td>
<td><?php if(isset($totaux_par_classe[$titre]['sanctions'])) echo $totaux_par_classe[$titre]['sanctions']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['sanctions']) && $totaux['L\'Etablissement']['sanctions']>0) echo round(100*($totaux_par_classe[$titre]['sanctions']/$totaux['L\'Etablissement']['sanctions']),2); else echo'0';?></td>
<td><?php if(isset($totaux_par_classe[$titre]['heures_retenues'])) echo $totaux_par_classe[$titre]['heures_retenues']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['heures_retenues']) && $totaux['L\'Etablissement']['heures_retenues']>0) echo round(100*($totaux_par_classe[$titre]['heures_retenues']/$totaux['L\'Etablissement']['heures_retenues']),2); else echo'0';?></td>
<td><?php if(isset($totaux_par_classe[$titre]['jours_exclusions'])) echo $totaux_par_classe[$titre]['jours_exclusions']; else echo'0';?></td><td><?php if(isset($totaux['L\'Etablissement']['jours_exclusions']) && $totaux['L\'Etablissement']['jours_exclusions']>0) echo round(100*($totaux_par_classe[$titre]['jours_exclusions']/$totaux['L\'Etablissement']['jours_exclusions']),2);else echo'0';?></td>
</tr>
</tfoot>
<?php }?>
</table>
</div>
<?php $i=$i+2;
else :
$i=$i+1;
endif;
}
}
}?>
</div>
</div>
</div>
| gpl-2.0 |
sojo/d8_friendsofsilence | core/modules/menu_ui/src/Tests/MenuCacheTagsTest.php | 3845 | <?php
/**
* @file
* Contains \Drupal\menu_ui\Tests\MenuCacheTagsTest.
*/
namespace Drupal\menu_ui\Tests;
use Drupal\Core\Url;
use Drupal\menu_link_content\Entity\MenuLinkContent;
use Drupal\system\Tests\Cache\PageCacheTagsTestBase;
use Drupal\system\Entity\Menu;
/**
* Tests the Menu and Menu Link entities' cache tags.
*
* @group menu_ui
*/
class MenuCacheTagsTest extends PageCacheTagsTestBase {
/**
* {@inheritdoc}
*/
public static $modules = array('menu_ui', 'block', 'test_page_test');
/**
* Tests cache tags presence and invalidation of the Menu entity.
*
* Tests the following cache tags:
* - "menu:<menu ID>"
*/
public function testMenuBlock() {
$url = Url::fromRoute('test_page_test.test_page');
// Create a Llama menu, add a link to it and place the corresponding block.
$menu = Menu::create(array(
'id' => 'llama',
'label' => 'Llama',
'description' => 'Description text',
));
$menu->save();
/** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
$menu_link_manager = \Drupal::service('plugin.manager.menu.link');
// Move a link into the new menu.
$menu_link = $menu_link_manager->updateDefinition('test_page_test.test_page', array('menu_name' => 'llama', 'parent' => ''));
$block = $this->drupalPlaceBlock('system_menu_block:llama', array('label' => 'Llama', 'provider' => 'system', 'region' => 'footer'));
// Prime the page cache.
$this->verifyPageCache($url, 'MISS');
// Verify a cache hit, but also the presence of the correct cache tags.
$expected_tags = array(
'rendered',
'block_view',
'config:block_list',
'config:block.block.' . $block->id(),
'config:system.menu.llama',
// The cache contexts associated with the (in)accessible menu links are
// bubbled.
'config:user.role.anonymous',
);
$this->verifyPageCache($url, 'HIT', $expected_tags);
// Verify that after modifying the menu, there is a cache miss.
$this->pass('Test modification of menu.', 'Debug');
$menu->set('label', 'Awesome llama');
$menu->save();
$this->verifyPageCache($url, 'MISS');
// Verify a cache hit.
$this->verifyPageCache($url, 'HIT');
// Verify that after modifying the menu link weight, there is a cache miss.
$menu_link_manager->updateDefinition('test_page_test.test_page', array('weight' => -10));
$this->pass('Test modification of menu link.', 'Debug');
$this->verifyPageCache($url, 'MISS');
// Verify a cache hit.
$this->verifyPageCache($url, 'HIT');
// Verify that after adding a menu link, there is a cache miss.
$this->pass('Test addition of menu link.', 'Debug');
$menu_link_2 = MenuLinkContent::create(array(
'id' => '',
'parent' => '',
'title' => 'Alpaca',
'menu_name' => 'llama',
'link' => [[
'uri' => 'internal:/',
]],
'bundle' => 'menu_name',
));
$menu_link_2->save();
$this->verifyPageCache($url, 'MISS');
// Verify a cache hit.
$this->verifyPageCache($url, 'HIT');
// Verify that after resetting the first menu link, there is a cache miss.
$this->pass('Test reset of menu link.', 'Debug');
$this->assertTrue($menu_link->isResettable(), 'First link can be reset');
$menu_link = $menu_link_manager->resetLink($menu_link->getPluginId());
$this->verifyPageCache($url, 'MISS');
// Verify a cache hit.
$this->verifyPageCache($url, 'HIT', $expected_tags);
// Verify that after deleting the menu, there is a cache miss.
$this->pass('Test deletion of menu.', 'Debug');
$menu->delete();
$this->verifyPageCache($url, 'MISS');
// Verify a cache hit.
$this->verifyPageCache($url, 'HIT', ['config:block_list', 'config:user.role.anonymous', 'rendered']);
}
}
| gpl-2.0 |
groundhogxc/XCSoar | src/Lua/Logger.cpp | 5928 | /*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "Logger.hpp"
#include "Util.hpp"
#include "Interface.hpp"
extern "C" {
#include <lauxlib.h>
}
static int
l_logger_index(lua_State *L)
{
const ComputerSettings &settings_computer = CommonInterface::GetComputerSettings();
const LoggerSettings &logger = settings_computer.logger;
const char *name = lua_tostring(L, 2);
if (name == nullptr)
return 0;
else if (StringIsEqual(name, "pilot_name")) {
Lua::Push(L, logger.pilot_name);
} else if (StringIsEqual(name, "time_step_cruise")) {
// The time interval between logged points when not circling.
Lua::Push(L, logger.time_step_cruise);
} else if (StringIsEqual(name, "time_step_circling")) {
// The time interval between logged points when circling.
Lua::Push(L, logger.time_step_circling);
} else if (StringIsEqual(name, "auto_logger")) {
Lua::Push(L, (int)logger.auto_logger);
} else if (StringIsEqual(name, "nmea_logger")) {
Lua::Push(L, logger.enable_nmea_logger);
} else if (StringIsEqual(name, "log_book")) {
Lua::Push(L, logger.enable_flight_logger);
} else if (StringIsEqual(name, "logger_id")) {
Lua::Push(L, logger.logger_id);
} else
return 0;
return 1;
}
static int
l_logger_setpilotname(lua_State *L)
{
if (lua_gettop(L) != 1)
return luaL_error(L, "Invalid parameters");
ComputerSettings &settings_computer = CommonInterface::SetComputerSettings();
LoggerSettings &logger = settings_computer.logger;
logger.pilot_name.SetUTF8(luaL_checkstring(L, 1));
return 0;
}
static int
l_logger_settimestepcruise(lua_State *L)
{
if (lua_gettop(L) != 1)
return luaL_error(L, "Invalid parameters");
ComputerSettings &settings_computer = CommonInterface::SetComputerSettings();
LoggerSettings &logger = settings_computer.logger;
float time = luaL_checknumber(L, 1);
logger.time_step_cruise = time;
return 0;
}
static int
l_logger_settimestepcicrling(lua_State *L)
{
if (lua_gettop(L) != 1)
return luaL_error(L, "Invalid parameters");
ComputerSettings &settings_computer = CommonInterface::SetComputerSettings();
LoggerSettings &logger = settings_computer.logger;
float time = luaL_checknumber(L, 1);
logger.time_step_circling = time;
return 0;
}
static int
l_logger_setautologger(lua_State *L)
{
if (lua_gettop(L) != 1)
return luaL_error(L, "Invalid parameters");
ComputerSettings &settings_computer = CommonInterface::SetComputerSettings();
LoggerSettings &logger = settings_computer.logger;
int mode = luaL_checknumber(L, 1);
if((mode>=0) && (mode<=2))
logger.auto_logger = (LoggerSettings::AutoLogger)mode;
return 0;
}
static int
l_logger_enablenmea(lua_State *L)
{
if (lua_gettop(L) != 0)
return luaL_error(L, "Invalid parameters");
ComputerSettings &settings_computer = CommonInterface::SetComputerSettings();
LoggerSettings &logger = settings_computer.logger;
logger.enable_nmea_logger = true;
return 0;
}
static int
l_logger_disablenmea(lua_State *L)
{
if (lua_gettop(L) != 0)
return luaL_error(L, "Invalid parameters");
ComputerSettings &settings_computer = CommonInterface::SetComputerSettings();
LoggerSettings &logger = settings_computer.logger;
logger.enable_nmea_logger = false;
return 0;
}
static int
l_logger_enablelogbook(lua_State *L)
{
if (lua_gettop(L) != 0)
return luaL_error(L, "Invalid parameters");
ComputerSettings &settings_computer = CommonInterface::SetComputerSettings();
LoggerSettings &logger = settings_computer.logger;
logger.enable_flight_logger = true;
return 0;
}
static int
l_logger_disablelogbook(lua_State *L)
{
if (lua_gettop(L) != 0)
return luaL_error(L, "Invalid parameters");
ComputerSettings &settings_computer = CommonInterface::SetComputerSettings();
LoggerSettings &logger = settings_computer.logger;
logger.enable_flight_logger = false;
return 0;
}
static int
l_logger_setloggerid(lua_State *L)
{
if (lua_gettop(L) != 1)
return luaL_error(L, "Invalid parameters");
ComputerSettings &settings_computer = CommonInterface::SetComputerSettings();
LoggerSettings &logger = settings_computer.logger;
logger.logger_id.SetUTF8(luaL_checkstring(L, 1));
return 0;
}
static constexpr struct luaL_Reg settings_funcs[] = {
{"set_pilot_name", l_logger_setpilotname},
{"set_time_step_cruise", l_logger_settimestepcruise},
{"set_time_step_circling", l_logger_settimestepcicrling},
{"set_autologger", l_logger_setautologger},
{"enable_nmea", l_logger_enablenmea},
{"disable_nmea", l_logger_disablenmea},
{"enable_logbook", l_logger_enablelogbook},
{"disable_logbook", l_logger_disablelogbook},
{"set_logger_id", l_logger_setloggerid},
{nullptr, nullptr}
};
void
Lua::InitLogger(lua_State *L)
{
lua_getglobal(L, "xcsoar");
lua_newtable(L);
lua_newtable(L);
SetField(L, -2, "__index", l_logger_index);
lua_setmetatable(L, -2);
luaL_setfuncs(L, settings_funcs, 0);
lua_setfield(L, -2, "logger");
lua_pop(L, 1);
}
| gpl-2.0 |
glazzara/olena | scribo/src/text_in_doc_preprocess.cc | 2957 | // Copyright (C) 2010, 2011, 2013 EPITA Research and Development
// Laboratory (LRDE)
//
// This file is part of Olena.
//
// Olena is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free
// Software Foundation, version 2 of the License.
//
// Olena is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Olena. If not, see <http://www.gnu.org/licenses/>.
//
// As a special exception, you may use this file as part of a free
// software project without restriction. Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to produce
// an executable, this file does not by itself cause the resulting
// executable to be covered by the GNU General Public License. This
// exception does not however invalidate any other reasons why the
// executable file might be covered by the GNU General Public License.
#include <libgen.h>
#include <iostream>
#include <mln/core/image/image2d.hh>
#include <mln/io/magick/load.hh>
#include <mln/io/pbm/save.hh>
#include <mln/value/rgb8.hh>
#include <scribo/debug/option_parser.hh>
#include <scribo/toolchain/text_in_doc_preprocess.hh>
static const scribo::debug::arg_data arg_desc[] =
{
{ "input.*", "An image." },
{ "output.pbm", "Binary preprocess image." },
{0, 0}
};
// --enable/disable-<name>
static const scribo::debug::toggle_data toggle_desc[] =
{
// name, description, default value
{ "fg-extraction", "Detect and slit foreground/background components. (default: disabled)", false },
{0, 0, false}
};
// --<name> <args>
static const scribo::debug::opt_data opt_desc[] =
{
// name, description, arguments, check args function, number of args, default arg
{ "lambda", "Set the maximum area of the background objects. It is only useful if fg-extraction is enabled.", "<size>",
0, 1, "0" },
{ "verbose", "Enable verbose mode", 0, 0, 0, 0 },
{0, 0, 0, 0, 0, 0}
};
int main(int argc, char* argv[])
{
using namespace scribo;
using namespace mln;
scribo::debug::option_parser options(arg_desc, toggle_desc, opt_desc);
if (!options.parse(argc, argv))
return 1;
image2d<value::rgb8> input_rgb;
io::magick::load(input_rgb, options.arg("input.*"));
unsigned lambda = atoi(options.opt_value("lambda").c_str());
bool fg_extraction = options.is_enabled("fg-extraction");
bool verbose = options.is_set("verbose");
image2d<bool> output;
output = toolchain::text_in_doc_preprocess(input_rgb, fg_extraction,
lambda, 0.34, false, verbose);
mln::io::pbm::save(output, options.arg("output.pbm"));
}
| gpl-2.0 |
netgrams/netgram | TMessagesProj/src/main/java/com/finalsoft/messenger/query/BotQuery.java | 8593 | /*
* This is the source code of Telegram for Android v. 3.x.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2016.
*/
package org.pouyadr.messenger.query;
import org.pouyadr.SQLite.SQLiteCursor;
import org.pouyadr.SQLite.SQLitePreparedStatement;
import org.pouyadr.messenger.AndroidUtilities;
import org.pouyadr.messenger.MessagesStorage;
import org.pouyadr.messenger.NotificationCenter;
import org.pouyadr.messenger.FileLog;
import org.pouyadr.tgnet.NativeByteBuffer;
import org.pouyadr.tgnet.TLRPC;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
public class BotQuery {
private static HashMap<Integer, TLRPC.BotInfo> botInfos = new HashMap<>();
private static HashMap<Long, TLRPC.Message> botKeyboards = new HashMap<>();
private static HashMap<Integer, Long> botKeyboardsByMids = new HashMap<>();
public static void cleanup() {
botInfos.clear();
botKeyboards.clear();
botKeyboardsByMids.clear();
}
public static void clearBotKeyboard(final long did, final ArrayList<Integer> messages) {
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
if (messages != null) {
for (int a = 0; a < messages.size(); a++) {
Long did = botKeyboardsByMids.get(messages.get(a));
if (did != null) {
botKeyboards.remove(did);
botKeyboardsByMids.remove(messages.get(a));
NotificationCenter.getInstance().postNotificationName(NotificationCenter.botKeyboardDidLoaded, null, did);
}
}
} else {
botKeyboards.remove(did);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.botKeyboardDidLoaded, null, did);
}
}
});
}
public static void loadBotKeyboard(final long did) {
TLRPC.Message keyboard = botKeyboards.get(did);
if (keyboard != null) {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.botKeyboardDidLoaded, keyboard, did);
return;
}
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
try {
TLRPC.Message botKeyboard = null;
SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT info FROM bot_keyboard WHERE uid = %d", did));
if (cursor.next()) {
NativeByteBuffer data;
if (!cursor.isNull(0)) {
data = cursor.byteBufferValue(0);
if (data != null) {
botKeyboard = TLRPC.Message.TLdeserialize(data, data.readInt32(false), false);
data.reuse();
}
}
}
cursor.dispose();
if (botKeyboard != null) {
final TLRPC.Message botKeyboardFinal = botKeyboard;
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.botKeyboardDidLoaded, botKeyboardFinal, did);
}
});
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
public static void loadBotInfo(final int uid, boolean cache, final int classGuid) {
if (cache) {
TLRPC.BotInfo botInfo = botInfos.get(uid);
if (botInfo != null) {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.botInfoDidLoaded, botInfo, classGuid);
return;
}
}
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
try {
TLRPC.BotInfo botInfo = null;
SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT info FROM bot_info WHERE uid = %d", uid));
if (cursor.next()) {
NativeByteBuffer data;
if (!cursor.isNull(0)) {
data = cursor.byteBufferValue(0);
if (data != null) {
botInfo = TLRPC.BotInfo.TLdeserialize(data, data.readInt32(false), false);
data.reuse();
}
}
}
cursor.dispose();
if (botInfo != null) {
final TLRPC.BotInfo botInfoFinal = botInfo;
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.botInfoDidLoaded, botInfoFinal, classGuid);
}
});
}
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
public static void putBotKeyboard(final long did, final TLRPC.Message message) {
if (message == null) {
return;
}
try {
int mid = 0;
SQLiteCursor cursor = MessagesStorage.getInstance().getDatabase().queryFinalized(String.format(Locale.US, "SELECT mid FROM bot_keyboard WHERE uid = %d", did));
if (cursor.next()) {
mid = cursor.intValue(0);
}
cursor.dispose();
if (mid >= message.id) {
return;
}
SQLitePreparedStatement state = MessagesStorage.getInstance().getDatabase().executeFast("REPLACE INTO bot_keyboard VALUES(?, ?, ?)");
state.requery();
NativeByteBuffer data = new NativeByteBuffer(message.getObjectSize());
message.serializeToStream(data);
state.bindLong(1, did);
state.bindInteger(2, message.id);
state.bindByteBuffer(3, data);
state.step();
data.reuse();
state.dispose();
AndroidUtilities.runOnUIThread(new Runnable() {
@Override
public void run() {
TLRPC.Message old = botKeyboards.put(did, message);
if (old != null) {
botKeyboardsByMids.remove(old.id);
}
botKeyboardsByMids.put(message.id, did);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.botKeyboardDidLoaded, message, did);
}
});
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
public static void putBotInfo(final TLRPC.BotInfo botInfo) {
if (botInfo == null) {
return;
}
botInfos.put(botInfo.user_id, botInfo);
MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
@Override
public void run() {
try {
SQLitePreparedStatement state = MessagesStorage.getInstance().getDatabase().executeFast("REPLACE INTO bot_info(uid, info) VALUES(?, ?)");
state.requery();
NativeByteBuffer data = new NativeByteBuffer(botInfo.getObjectSize());
botInfo.serializeToStream(data);
state.bindInteger(1, botInfo.user_id);
state.bindByteBuffer(2, data);
state.step();
data.reuse();
state.dispose();
} catch (Exception e) {
FileLog.e("tmessages", e);
}
}
});
}
}
| gpl-2.0 |