void UtrnetDemoGameInstance::FindSessions(TSharedPtr<const FUniqueNetId> UserId, FName SessionName, bool bIsLAN, bool bIsPresence)
{
    isLoading_ = true;
    
    // Get the SessionInterface from our OnlineSubsystem
    IOnlineSessionPtr Sessions = GetSession();

    if (Sessions.IsValid() && Sessions.IsValid() && UserId.IsValid())
    {
        /*
        Fill in all the SearchSettings, like if we are searching for a LAN game and how many results we want to have!
        */
        SessionSearch = MakeShareable(new FOnlineSessionSearch());

        SessionSearch->bIsLanQuery = bIsLAN;
        SessionSearch->MaxSearchResults = 20;
        SessionSearch->PingBucketSize = 50;

        // We only want to set this Query Setting if "bIsPresence" is true
        if (bIsPresence)
        {
            SessionSearch->QuerySettings.Set(SEARCH_PRESENCE, bIsPresence, EOnlineComparisonOp::Equals);
        }

        TSharedRef<FOnlineSessionSearch> SearchSettingsRef = SessionSearch.ToSharedRef();

        // Set the Delegate to the Delegate Handle of the FindSession function
        OnFindSessionsCompleteDelegateHandle = Sessions->AddOnFindSessionsCompleteDelegate_Handle(OnFindSessionsCompleteDelegate);

        // Finally call the SessionInterface function. The Delegate gets called once this is finished
        if(!Sessions->FindSessions(*UserId, SearchSettingsRef)) {
            OnFindSessionsComplete(false);
        }
    } else {
        // If something goes wrong, just call the Delegate Function directly with "false".
        OnFindSessionsComplete(false);        
    }
}
Example #2
0
HXBOOL CHXDirectory::MakeCurrentDir()
{
    HXBOOL bRetVal = FALSE;

    HX_ASSERT("MakeCurrentDir Not Working As Expected" == NULL);

    if (GetSession() && (!m_strPath.IsEmpty()))
    {
	OS_STRING_TYPE osFileName(m_strPath);
	TPtrC symbNameDesc((TText*) ((OS_TEXT_PTR) osFileName));
	
	bRetVal = (m_symbSession.SetSessionPath(symbNameDesc) == KErrNone);
	if (bRetVal)
	{
#ifndef HELIX_CONFIG_SYMBIAN_PLATFORM_SECURITY
        // SetDefaultPath is depricated in Symbian 9
	    bRetVal = (m_symbSession.SetDefaultPath(symbNameDesc) == KErrNone);
#endif 
	}
    }

    return bRetVal;
}
void Player::SendLevelupInfo(uint32 level, uint32 Hp, uint32 Mana, uint32 Stat0, uint32 Stat1, uint32 Stat2, uint32 Stat3, uint32 Stat4)
{
    packet_SMSG_LEVELUP_INFO packet;
    packet.level = level;
    packet.Hp = Hp;
    packet.Mana = Mana;

    // grep: these are probably the other powers :)
    packet.unk0 = 0;
    packet.unk1 = 0;
    packet.unk2 = 0;
    packet.unk3 = 0;
	packet.unk4 = 0;
    packet.unk5 = 0;

    // Append stat differences
    packet.Stat0 = Stat0;
    packet.Stat1 = Stat1;
    packet.Stat2 = Stat2;
    packet.Stat3 = Stat3;
    packet.Stat4 = Stat4;
    GetSession()->OutPacket(SMSG_LEVELUP_INFO, sizeof(packet_SMSG_LEVELUP_INFO),(const char*)&packet);
}
Example #4
0
void Transporter::TeleportTransport(uint32 newMapid, uint32 oldmap, float x, float y, float z)
{
    //sEventMgr.RemoveEvents(this, EVENT_TRANSPORTER_NEXT_WAYPOINT);

    RemoveFromWorld(false);
    SetMapId(newMapid);
    SetPosition(x, y, z, m_position.o, false);
    AddToWorld();

    WorldPacket packet(SMSG_TRANSFER_PENDING, 12);
    packet << newMapid;
    packet << getEntry();
    packet << oldmap;

    for (auto passengerGuid : m_passengers)
    {
        auto passenger = objmgr.GetPlayer(passengerGuid);
        if (passenger == nullptr)
            continue;

        passenger->GetSession()->SendPacket(&packet);
        bool teleport_successful = passenger->Teleport(LocationVector(x, y, z, passenger->GetOrientation()), this->GetMapMgr());
        if (!teleport_successful)
        {
            passenger->RepopAtGraveyard(passenger->GetPositionX(), passenger->GetPositionY(), passenger->GetPositionZ(), passenger->GetMapId());
        }
        else
        {
            if (!passenger->HasUnitMovementFlag(MOVEFLAG_TRANSPORT))
            {
                passenger->AddUnitMovementFlag(MOVEFLAG_TRANSPORT);
            }
        }
    }

    this->RespawnCreaturePassengers();
}
Example #5
0
  void RoundIdService::Handle(QSharedPointer<WebRequest> wrp)
  {
    QSharedPointer<Session> session = GetSession();
    QVariantMap map;

    bool session_active = !session.isNull();
    map["active"] = false;
    map["id"] = "";

    if(session_active) {
      QSharedPointer<Dissent::Anonymity::Round> round =
        session->GetCurrentRound();

      if(!round.isNull()) {
        map["active"] = true;
        map["id"] = round->GetRoundId().ToString();
      } 
    } 

    wrp->GetOutputData().setValue(map);
    wrp->SetStatus(HttpResponse::STATUS_OK);
    emit FinishedWebRequest(wrp, true);
    return;
  }
Example #6
0
HXBOOL CHXDirectory::SetCurrentDir()
{
    HXBOOL bRetVal = FALSE;

    if (GetSession())
    {
	TFileName* psymbCurrentDir = new TFileName;

	if (psymbCurrentDir)
	{
	    bRetVal = (m_symbSession.SessionPath(*psymbCurrentDir) == KErrNone);

	    if (bRetVal)
	    {
		m_strPath = (const char *) OS_STRING2((OS_TEXT_PTR) psymbCurrentDir->Ptr(), 
						      psymbCurrentDir->Length());
	    }

	    delete psymbCurrentDir;
	}
    }

    return bRetVal;
}
// -----------------------------------------------------------------------------
// CUpnpHttpServer::SendMessageL
// Send HTTP message
// -----------------------------------------------------------------------------
//
TInt CUpnpHttpServer::SendMessageL( CUpnpHttpMessage* aMessage )
    {
    LOG_FUNC_NAME;

    if (!aMessage)
		{
		LOGS("CUpnpHttpServer::SendMessageL - Tried to send Null");
		return KErrNotFound;
		}

    TInt trapError( KErrNone );
    TInt sessId( KErrNone );

    TRAP(trapError, sessId = TrapSendMessageL( aMessage ) );

    if( trapError < KErrNone )
        {
        LOGS1( "HTTP *** Sending of message failed. Error: %i", trapError );
        // HttpSession errors that cannot be forwarded to upper layers
        if( -trapError >= EHttpBadRequest && -trapError <= EHttpExpectationFailed )
            {
            CUpnpHttpMessage* notify = NULL;
            notify = RUpnpHttpMessageFactory::HttpResponseErrorL( aMessage, -trapError );
            CUpnpHttpSession* sess = GetSession( aMessage->SessionId() );
            sess->DeleteThisSessionL( sess );

            ToReceiveStackD( notify ); //Upper layer takes care about cleanup
            }
        else
            {
            User::Leave(trapError);
            }
        }
    // nobody use the value
    return sessId;
    }
Example #8
0
OGRSpatialReference *OGROCIDataSource::FetchSRS( int nId )

{
    if( nId < 0 )
        return NULL;

/* -------------------------------------------------------------------- */
/*      First, we look through our SRID cache, is it there?             */
/* -------------------------------------------------------------------- */
    int  i;

    for( i = 0; i < nKnownSRID; i++ )
    {
        if( panSRID[i] == nId )
            return papoSRS[i];
    }

/* -------------------------------------------------------------------- */
/*      Try looking up in MDSYS.CS_SRS table.                           */
/* -------------------------------------------------------------------- */
    OGROCIStatement oStatement( GetSession() );
    char            szSelect[200], **papszResult;

    snprintf( szSelect, sizeof(szSelect),
             "SELECT WKTEXT, AUTH_SRID, AUTH_NAME FROM MDSYS.CS_SRS "
             "WHERE SRID = %d AND WKTEXT IS NOT NULL", nId );

    if( oStatement.Execute( szSelect ) != CE_None )
        return NULL;

    papszResult = oStatement.SimpleFetchRow();
    if( CSLCount(papszResult) < 1 )
        return NULL;

/* -------------------------------------------------------------------- */
/*      Turn into a spatial reference.                                  */
/* -------------------------------------------------------------------- */
    char *pszWKT = papszResult[0];
    OGRSpatialReference *poSRS = NULL;

    poSRS = new OGRSpatialReference();
    if( poSRS->importFromWkt( &pszWKT ) != OGRERR_NONE )
    {
        delete poSRS;
        poSRS = NULL;
    }

/* -------------------------------------------------------------------- */
/*      If we have a corresponding EPSG code for this SRID, use that    */
/*      authority.                                                      */
/* -------------------------------------------------------------------- */
    int bGotEPSGMapping = FALSE;
    for( i = 0; anEPSGOracleMapping[i] != 0; i += 2 )
    {
        if( anEPSGOracleMapping[i] == nId )
        {
            poSRS->SetAuthority( poSRS->GetRoot()->GetValue(), "EPSG",
                                 anEPSGOracleMapping[i+1] );
            bGotEPSGMapping = TRUE;
            break;
        }
    }

/* -------------------------------------------------------------------- */
/*      Insert authority information, if it is available.               */
/* -------------------------------------------------------------------- */
    if( papszResult[1] != NULL && atoi(papszResult[1]) != 0
        && papszResult[2] != NULL && strlen(papszResult[1]) != 0
        && poSRS->GetRoot() != NULL
        && !bGotEPSGMapping )
    {
        poSRS->SetAuthority( poSRS->GetRoot()->GetValue(),
                             papszResult[2], atoi(papszResult[1]) );
    }

/* -------------------------------------------------------------------- */
/*      Add to the cache.                                               */
/* -------------------------------------------------------------------- */
    panSRID = (int *) CPLRealloc(panSRID,sizeof(int) * (nKnownSRID+1) );
    papoSRS = (OGRSpatialReference **)
        CPLRealloc(papoSRS, sizeof(void*) * (nKnownSRID + 1) );
    panSRID[nKnownSRID] = nId;
    papoSRS[nKnownSRID] = poSRS;

    nKnownSRID++;

    return poSRS;
}
Example #9
0
void OGROCIDataSource::ValidateLayer( const char *pszLayerName )

{
    int iLayer;

/* -------------------------------------------------------------------- */
/*      Try to find layer.                                              */
/* -------------------------------------------------------------------- */
    for( iLayer = 0; iLayer < nLayers; iLayer++ )
    {
        if( EQUAL(pszLayerName,papoLayers[iLayer]->GetLayerDefn()->GetName()) )
            break;
    }

    if( iLayer == nLayers )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "ValidateLayer(): %s is not a recognised layer.",
                  pszLayerName );
        return;
    }

/* -------------------------------------------------------------------- */
/*      Verify we have an FID and geometry column for this table.       */
/* -------------------------------------------------------------------- */
    OGROCITableLayer *poLayer = (OGROCITableLayer *) papoLayers[iLayer];

    if( strlen(poLayer->GetFIDColumn()) == 0 )
    {
        CPLError( CE_Failure, CPLE_AppDefined,
                  "ValidateLayer(): %s lacks a fid column.",
                  pszLayerName );

        return;
    }

/* -------------------------------------------------------------------- */
/*      Prepare and execute the geometry validation.                    */
/* -------------------------------------------------------------------- */

    if( strlen(poLayer->GetGeometryColumn()) != 0 )
    {
        OGROCIStringBuf oValidateCmd;
        OGROCIStatement oValidateStmt( GetSession() );

        oValidateCmd.Append( "SELECT c." );
        oValidateCmd.Append( poLayer->GetFIDColumn() );
        oValidateCmd.Append( ", SDO_GEOM.VALIDATE_GEOMETRY(c." );
        oValidateCmd.Append( poLayer->GetGeometryColumn() );
        oValidateCmd.Append( ", m.diminfo) from " );
        oValidateCmd.Append( poLayer->GetLayerDefn()->GetName() );
        oValidateCmd.Append( " c, user_sdo_geom_metadata m WHERE m.table_name= '");
        oValidateCmd.Append( poLayer->GetLayerDefn()->GetName() );
        oValidateCmd.Append( "' AND m.column_name = '" );
        oValidateCmd.Append( poLayer->GetGeometryColumn() );
        oValidateCmd.Append( "' AND SDO_GEOM.VALIDATE_GEOMETRY(c." );
        oValidateCmd.Append( poLayer->GetGeometryColumn() );
        oValidateCmd.Append( ", m.diminfo ) <> 'TRUE'" );

        oValidateStmt.Execute( oValidateCmd.GetString() );

/* -------------------------------------------------------------------- */
/*      Report results to debug stream.                                 */
/* -------------------------------------------------------------------- */
        char **papszRow;

        while( (papszRow = oValidateStmt.SimpleFetchRow()) != NULL )
        {
            const char *pszReason = papszRow[1];

            if( EQUAL(pszReason,"13011") )
                pszReason = "13011: value is out of range";
            else if( EQUAL(pszReason,"13050") )
                pszReason = "13050: unable to construct spatial object";
            else if( EQUAL(pszReason,"13349") )
                pszReason = "13349: polygon boundary crosses itself";

            CPLDebug( "OCI", "Validation failure for FID=%s: %s",
                  papszRow[0], pszReason );
        }
    }
}
Example #10
0
void show_chains(int *mapp, int *map) {
  char szBuffer[ 255 ];

  GetSession()->bout.Color(0);
  GetSession()->bout.ClearScreen();
  GetSession()->bout.NewLine();
  bool abort = false;
  bool next = false;
  if (GetApplication()->HasConfigFlag(OP_FLAGS_CHAIN_REG) && chains_reg) {
    sprintf(szBuffer, "|#5  Num |#1%-42.42s|#2%-22.22s|#1%-5.5s", "Description", "Sponsored by", "Usage");
    pla(szBuffer, &abort);

    if (okansi()) {
      sprintf(szBuffer, "|#%d %s", FRAME_COLOR,
              "\xDA\xC4\xC4\xC4\xC2\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC2\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC2\xC4\xC4\xC4\xC4\xC4\xBF");
    } else {
      sprintf(szBuffer, " +---+-----------------------------------------+---------------------+-----+");
    }
    pla(szBuffer, &abort);
    for (int i = 0; i < *mapp && !abort && !hangup; i++) {
      WUser user;
      strcat(szBuffer, ". ");
      if (okansi()) {
        GetApplication()->GetUserManager()->ReadUser(&user, chains_reg[map[i]].regby[0]);
        sprintf(szBuffer, " |#%d\xB3|#5%3d|#%d\xB3|#1%-41s|#%d\xB3|%2.2d%-21s|#%d\xB3|#1%5d|#%d\xB3",
                FRAME_COLOR,
                i + 1,
                FRAME_COLOR,
                chains[map[i]].description,
                FRAME_COLOR,
                (chains_reg[map[i]].regby[0]) ? 14 : 13,
                (chains_reg[map[i]].regby[0]) ? user.GetName() : "Available",
                FRAME_COLOR,
                chains_reg[map[i]].usage,
                FRAME_COLOR);
        pla(szBuffer, &abort);
        if (chains_reg[map[i]].regby[0] != 0) {
          for (int i1 = 1; i1 < 5 && !abort; i1++) {
            if (chains_reg[map[i]].regby[i1] != 0) {
              GetApplication()->GetUserManager()->ReadUser(&user, chains_reg[map[i]].regby[i1]);
              sprintf(szBuffer, " |#%d\xB3   \xBA%-41s\xB3|#2%-21s|#%d\xB3%5.5s\xB3",
                      FRAME_COLOR, " ", user.GetName(), FRAME_COLOR, " ");
              pla(szBuffer, &abort);
            }
          }
        }
      } else {
        GetApplication()->GetUserManager()->ReadUser(&user, chains_reg[map[i]].regby[0]);
        sprintf(szBuffer, " |%3d|%-41.41s|%-21.21s|%5d|",
                i + 1, chains[map[i]].description,
                (chains_reg[map[i]].regby[0]) ? user.GetName() : "Available",
                chains_reg[map[i]].usage);
        pla(szBuffer, &abort);
        if (chains_reg[map[i]].regby[0] != 0) {
          for (int i1 = 1; i1 < 5; i1++) {
            if (chains_reg[map[i]].regby[i1] != 0) {
              GetApplication()->GetUserManager()->ReadUser(&user, chains_reg[map[i]].regby[i1]);
              sprintf(szBuffer, " |   |                                         |%-21.21s|     |",
                      (chains_reg[map[i]].regby[i1]) ? user.GetName() : "Available");
              pla(szBuffer, &abort);
            }
          }
        }
      }
    }
    if (okansi()) {
      sprintf(szBuffer, "|#%d %s", FRAME_COLOR,
              "\xC0\xC4\xC4\xC4\xC1\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC1\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC1\xC4\xC4\xC4\xC4\xC4\xD9");
    } else {
      sprintf(szBuffer, " +---+-----------------------------------------+---------------------+-----+");
    }
    pla(szBuffer, &abort);

  } else {
    GetSession()->bout.DisplayLiteBar(" [ %s Online Programs ] ", syscfg.systemname);
    GetSession()->bout <<
                       "|#7\xDA\xC4\xC4\xC2\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC2\xC4\xC4\xC2\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xBF\r\n";
    for (int i = 0; i < *mapp && !abort && !hangup; i++) {
      sprintf(szBuffer, "|#7\xB3|#2%2d|#7\xB3 |#1%-33.33s|#7\xB3", i + 1, chains[map[i]].description);
      osan(szBuffer, &abort, &next);
      i++;
      if (!abort && !hangup) {
        char szBuffer[ 255 ];
        if (i >= *mapp) {
          sprintf(szBuffer, "  |#7\xB3                                  |#7\xB3");
        } else {
          sprintf(szBuffer, "|#2%2d|#7\xB3 |#1%-33.33s|#7\xB3", i + 1, chains[map[i]].description);
        }
        pla(szBuffer, &abort);
      }
    }
    GetSession()->bout <<
                       "|#7\xC0\xC4\xC4\xC1\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC1\xC4\xC4\xC1\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xC4\xD9\r\n";
  }
}
Example #11
0
void InterpretCommand(MenuInstanceData * pMenuData, const char *pszScript) {
  char szCmd[31], szParam1[51], szParam2[51];
  char szTempScript[ 255 ];
  memset(szTempScript, 0, sizeof(szTempScript));
  strncpy(szTempScript, pszScript, 250);

  if (pszScript[0] == 0) {
    return;
  }

  char* pszScriptPointer = szTempScript;
  while (pszScriptPointer && !hangup) {
    pszScriptPointer = MenuParseLine(pszScriptPointer, szCmd, szParam1, szParam2);

    if (szCmd[0] == 0) {    // || !pszScriptPointer || !*pszScriptPointer
      break;
    }

    // -------------------------
    // Run a new menu instance

    int nCmdID = GetMenuIndex(szCmd);
    switch (nCmdID) {
    case 0: {
      // "MENU"
      // Spawn a new menu
      MenuInstanceData *pNewMenuData = static_cast<MenuInstanceData *>(malloc(sizeof(MenuInstanceData)));

      memset(pNewMenuData, 0, sizeof(MenuInstanceData));
      pNewMenuData->nFinished = 0;
      pNewMenuData->nReload = 0;

      Menus(pNewMenuData, pMenuData->szPath, szParam1);
      free(pNewMenuData);
    }
    break;
    case 1: {
      // -------------------------
      // Exit out of this instance
      // of the menu
      // -------------------------
      // "ReturnFromMenu"
      InterpretCommand(pMenuData, pMenuData->header.szExitScript);
      pMenuData->nFinished = 1;
    }
    break;
    case 2: {
      // "EditMenuSet"
      EditMenus();           // flag if we are editing this menu
      pMenuData->nFinished = 1;
      pMenuData->nReload = 1;
    }
    break;
    case 3: {
      // "DLFreeFile"
      align(szParam2);
      MenuDownload(szParam1, szParam2, true, true);
    }
    break;
    case 4: {
      // "DLFile"
      align(szParam2);
      MenuDownload(szParam1, szParam2, false, true);
    }
    break;
    case 5: {
      // "RunDoor"
      MenuRunDoorName(szParam1, false);
    }
    break;
    case 6: {
      // "RunDoorFree"
      MenuRunDoorName(szParam1, true);
    }
    break;
    case 7: {
      // "RunDoorNumber"
      int nTemp = atoi(szParam1);
      MenuRunDoorNumber(nTemp, false);
    }
    break;
    case 8: {
      // "RunDoorNumberFree"
      int nTemp = atoi(szParam1);
      MenuRunDoorNumber(nTemp, true);
    }
    break;
    case 9: {
      // "PrintFile"
      printfile(szParam1, true);
    }
    break;
    case 10: {
      // "PrintFileNA"
      printfile(szParam1, false);
    }
    break;
    case 11: {
      // "SetSubNumber"
      SetSubNumber(szParam1);
    }
    break;
    case 12: {
      // "SetDirNumber"
      SetDirNumber(szParam1);
    }
    break;
    case 13: {
      // "SetMsgConf"
      SetMsgConf(szParam1[0]);
    }
    break;
    case 14: {
      // "SetDirConf"
      SetDirConf(szParam1[0]);
    }
    break;
    case 15: {
      // "EnableConf"
      EnableConf();
    }
    break;
    case 16: {
      // "DisableConf"
      DisableConf();
    }
    break;
    case 17: {
      // "Pause"
      pausescr();
    }
    break;
    case 18: {
      // "ConfigUserMenuSet"
      ConfigUserMenuSet();
      pMenuData->nFinished = 1;
      pMenuData->nReload = 1;
    }
    break;
    case 19: {
      // "DisplayHelp"
      if (GetSession()->GetCurrentUser()->IsExpert()) {
        AMDisplayHelp(pMenuData);
      }
    }
    break;
    case 20: {
      // "SelectSub"
      ChangeSubNumber();
    }
    break;
    case 21: {
      // "SelectDir"
      ChangeDirNumber();
    }
    break;
    case 22: {
      // "SubList"
      SubList();
    }
    break;
    case 23: {
      // "UpSubConf"
      UpSubConf();
    }
    break;
    case 24: {
      // "DownSubConf"
      DownSubConf();
    }
    break;
    case 25: {
      // "UpSub"
      UpSub();
    }
    break;
    case 26: {
      // "DownSub"
      DownSub();
    }
    break;
    case 27: {
      // "ValidateUser"
      ValidateUser();
    }
    break;
    case 28: {
      // "Doors"
      Chains();
    }
    break;
    case 29: {
      // "TimeBank"
      TimeBank();
    }
    break;
    case 30: {
      // "AutoMessage"
      AutoMessage();
    }
    break;
    case 31: {
      // "BBSList"
      BBSList();
    }
    break;
    case 32: {
      // "RequestChat"
      RequestChat();
    }
    break;
    case 33: {
      // "Defaults"
      Defaults(pMenuData);
    }
    break;
    case 34: {
      // "SendEMail"
      SendEMail();
    }
    break;
    case 35: {
      // "Feedback"
      FeedBack();
    }
    break;
    case 36: {
      // "Bulletins"
      Bulletins();
    }
    break;
    case 37: {
      // "HopSub"
      HopSub();
    }
    break;
    case 38: {
      // "SystemInfo"
      SystemInfo();
    }
    break;
    case 39: {
      // "JumpSubConf"
      JumpSubConf();
    }
    break;
    case 40: {
      // "KillEMail"
      KillEMail();
    }
    break;
    case 41: {
      // "LastCallers"
      LastCallers();
    }
    break;
    case 42: {
      // "ReadEMail"
      ReadEMail();
    }
    break;
    case 43: {
      // "NewMessageScan"
      NewMessageScan();
    }
    break;
    case 44: {
      // "Goodbye"
      GoodBye();
    }
    break;
    case 45: {
      // "PostMessage"
      WWIV_PostMessage();
    }
    break;
    case 46: {
      // "NewMsgScanCurSub"
      ScanSub();
    }
    break;
    case 47: {
      // "RemovePost"
      RemovePost();
    }
    break;
    case 48: {
      // "TitleScan"
      TitleScan();
    }
    break;
    case 49: {
      // "ListUsers"
      ListUsers();
    }
    break;
    case 50: {
      // "Vote"
      Vote();
    }
    break;
    case 51: {
      // "ToggleExpert"
      ToggleExpert();
    }
    break;
    case 52: {
      // "YourInfo"
      YourInfo();
    }
    break;
    case 53: {
      // "ExpressScan"
      ExpressScan();
    }
    break;
    case 54: {
      // "WWIVVer"
      WWIVVersion();
    }
    break;
    case 55: {
      // "InstanceEdit"
      InstanceEdit();
    }
    break;
    case 56: {
      // "ConferenceEdit"
      JumpEdit();
    }
    break;
    case 57: {
      // "SubEdit"
      BoardEdit();
    }
    break;
    case 58: {
      // "ChainEdit"
      ChainEdit();
    }
    break;
    case 59: {
      // "ToggleAvailable"
      ToggleChat();
    }
    break;
    case 60: {
      // "ChangeUser"
      ChangeUser();
    }
    break;
    case 61: {
      // "CLOUT"
      CallOut();
    }
    break;
    case 62: {
      // "Debug"
      Debug();
    }
    break;
    case 63: {
      // "DirEdit"
      DirEdit();
    }
    break;
    case 65: {
      // "Edit"
      EditText();
    }
    break;
    case 66: {
      // "BulletinEdit"
      EditBulletins();
    }
    break;
    case 67: {
      // "LoadText"
      // LoadText and LoadTextFile are the same, so they are now merged.
      LoadTextFile();
    }
    break;
    case 68: {
      // "ReadAllMail"
      ReadAllMail();
    }
    break;
    case 69: {
      // "Reboot"
      RebootComputer();
    }
    break;
    case 70: {
      // "ReloadMenus"
      ReloadMenus();
    }
    break;
    case 71: {
      // "ResetUserIndex"
      ResetFiles();
    }
    break;
    case 72: {
      // "ResetQScan"
      ResetQscan();
    }
    break;
    case 73: {
      // "MemStat"
      MemoryStatus();
    }
    break;
    case 74: {
      // "PackMsgs"
      PackMessages();
    }
    break;
    case 75: {
      // "VoteEdit"
      InitVotes();
    }
    break;
    case 76: {
      // "Log"
      ReadLog();
    }
    break;
    case 77: {
      // "NetLog"
      ReadNetLog();
    }
    break;
    case 78: {
      // "Pending"
      PrintPending();
    }
    break;
    case 79: {
      // "Status"
      PrintStatus();
    }
    break;
    case 80: {
      // "TextEdit"
      TextEdit();
    }
    break;
    case 81: {
      // "UserEdit"
      UserEdit();
    }
    break;
    case 82: {
      // "VotePrint"
      VotePrint();
    }
    break;
    case 83: {
      // "YLog"
      YesturdaysLog();
    }
    break;
    case 84: {
      // "ZLog"
      ZLog();
    }
    break;
    case 85: {
      // "ViewNetDataLog"
      ViewNetDataLog();
    }
    break;
    case 86: {
      // "UploadPost"
      UploadPost();
    }
    break;
    case 87: {
      // "ClearScreen"
      GetSession()->bout.ClearScreen();
    }
    break;
    case 88: {
      // "NetListing"
      NetListing();
    }
    break;
    case 89: {
      // "WHO"
      WhoIsOnline();
    }
    break;
    case 90: {
      // /A "NewMsgsAllConfs"
      NewMsgsAllConfs();
    }
    break;
    case 91: {
      // /E "MultiEMail"
      MultiEmail();
    }
    break;
    case 92: {
      // "NewMsgScanFromHere"
      NewMsgScanFromHere();
    }
    break;
    case 93: {
      // "ValidatePosts"
      ValidateScan();
    }
    break;
    case 94: {
      // "ChatRoom"
      ChatRoom();
    }
    break;
    case 95: {
      // "DownloadPosts"
      DownloadPosts();
    }
    break;
    case 96: {
      // "DownloadFileList"
      DownloadFileList();
    }
    break;
    case 97: {
      // "ClearQScan"
      ClearQScan();
    }
    break;
    case 98: {
      // "FastGoodBye"
      FastGoodBye();
    }
    break;
    case 99: {
      // "NewFilesAllConfs"
      NewFilesAllConfs();
    }
    break;
    case 100: {
      // "ReadIDZ"
      ReadIDZ();
    }
    break;
    case 101: {
      // "UploadAllDirs"
      UploadAllDirs();
    }
    break;
    case 102: {
      // "UploadCurDir"
      UploadCurDir();
    }
    break;
    case 103: {
      // "RenameFiles"
      RenameFiles();
    }
    break;
    case 104: {
      // "MoveFiles"
      MoveFiles();
    }
    break;
    case 105: {
      // "SortDirs"
      SortDirs();
    }
    break;
    case 106: {
      // "ReverseSortDirs"
      ReverseSort();
    }
    break;
    case 107: {
      // "AllowEdit"
      AllowEdit();
    }
    break;
    case 109: {
      // "UploadFilesBBS"
      UploadFilesBBS();
    }
    break;
    case 110: {
      // "DirList"
      DirList();
    }
    break;
    case 111: {
      // "UpDirConf"
      UpDirConf();
    }
    break;
    case 112: {
      // "UpDir"
      UpDir();
    }
    break;
    case 113: {
      // "DownDirConf"
      DownDirConf();
    }
    break;
    case 114: {
      // "DownDir"
      DownDir();
    }
    break;
    case 115: {
      // "ListUsersDL"
      ListUsersDL();
    }
    break;
    case 116: {
      // "PrintDSZLog"
      PrintDSZLog();
    }
    break;
    case 117: {
      // "PrintDevices"
      PrintDevices();
    }
    break;
    case 118: {
      // "ViewArchive"
      ViewArchive();
    }
    break;
    case 119: {
      // "BatchMenu"
      BatchMenu();
    }
    break;
    case 120: {
      // "Download"
      Download();
    }
    break;
    case 121: {
      // "TempExtract"
      TempExtract();
    }
    break;
    case 122: {
      // "FindDescription"
      FindDescription();
    }
    break;
    case 123: {
      // "ArchiveMenu"
      TemporaryStuff();
    }
    break;
    case 124: {
      // "HopDir"
      HopDir();
    }
    break;
    case 125: {
      // "JumpDirConf"
      JumpDirConf();
    }
    break;
    case 126: {
      // "ListFiles"
      ListFiles();
    }
    break;
    case 127: {
      // "NewFileScan"
      NewFileScan();
    }
    break;
    case 128: {
      // "SetNewFileScanDate"
      SetNewFileScanDate();
    }
    break;
    case 129: {
      // "RemoveFiles"
      RemoveFiles();
    }
    break;
    case 130: {
      // "SearchAllFiles"
      SearchAllFiles();
    }
    break;
    case 131: {
      // "XferDefaults"
      XferDefaults();
    }
    break;
    case 132: {
      // "Upload"
      Upload();
    }
    break;
    case 133: {
      // "YourInfoDL"
      YourInfoDL();
    }
    break;
    case 134: {
      // "UploadToSysop"
      UploadToSysop();
    }
    break;
    case 135: {
      // "ReadAutoMessage"
      ReadAutoMessage();
    }
    break;
    case 136: {
      // "SetNewScanMsg"
      SetNewScanMsg();
    }
    break;
    case 137: {
      // "ReadMessages"
      ReadMessages();
    }
    break;
    /*
    case 138:
    { // "RUN"
    ExecuteBasic(szParam1);
    } break;
    */
    case 139: {
      // "EventEdit"
      EventEdit();
    }
    break;
    case 140: {
      // "LoadTextFile"
      LoadTextFile();
    }
    break;
    case 141: {
      // "GuestApply"
      GuestApply();
    }
    break;
    case 142: {
      // "ConfigFileList"
      ConfigFileList();
    }
    break;
    case 143: {
      // "ListAllColors"
      ListAllColors();
    }
    break;
#ifdef QUESTIONS
    case 144: {
      // "EditQuestions"
      EditQuestions();
    }
    break;
    case 145: {
      // "Questions"
      Questions();
    }
    break;
#endif
    case 146: {
      // "RemoveNotThere"
      RemoveNotThere();
    }
    break;
    case 147: {
      // "AttachFile"
      AttachFile();
    }
    break;
    case 148: {
      // "InternetEmail"
      InternetEmail();
    }
    break;
    case 149: {
      // "UnQScan"
      UnQScan();
    }
    break;
    // ppMenuStringsIndex[150] thru ppMenuStringsIndex[153] not used.....
    case 154: {
      // "Packers"
      Packers();
    }
    break;
    case 155: {
      // Color_Config
      color_config();
    }
    break;
    //------------------------------------------------------------------
    //  ppMenuStringsIndex[156] and [157] are reserved for SDS Systems and systems
    //  that distribute modifications.  DO NOT reuse these strings for
    //  other menu options.
    //------------------------------------------------------------------
    //    case 156:
    //    { // ModAccess
    //        ModsAccess();
    //    } break;
    //    case 157:
    //    { // SDSAccess
    //        SDSAccess();
    //      } break;
    //------------------------------------------------------------------
    case 158: {
      // InitVotes
      InitVotes();
    }
    break;
    case 161: {
      // TurnMCIOn
      TurnMCIOn();
    }
    break;
    case 162: {
      // TurnMCIOff
      TurnMCIOff();
    }
    break;
    default: {
      MenuSysopLog("The following command was not recognized");
      MenuSysopLog(szCmd);
    }
    break;
    }
  }
}
Example #12
0
bool ChatHandler::ParseCommands(char const* text)
{
    ASSERT(text);
    ASSERT(*text);

    std::string fullcmd = text;

    /// chat case (.command or !command format)
    if (m_session)
    {
        if (text[0] != '!' && text[0] != '.')
            return false;
    }

    /// ignore single . and ! in line
    if (strlen(text) < 2)
        return false;
    // original `text` can't be used. It content destroyed in command code processing.

    /// ignore messages staring from many dots.
    if ((text[0] == '.' && text[1] == '.') || (text[0] == '!' && text[1] == '!'))
        return false;

    /// skip first . or ! (in console allowed use command with . and ! and without its)
    if (text[0] == '!' || text[0] == '.')
        ++text;

    if (!ExecuteCommandInTable(getCommandTable(), text, fullcmd) && sHookMgr->OnCommand(GetSession() ? GetSession()->GetPlayer() : NULL, text))
    {
        if (m_session && !m_session->HasPermission(rbac::RBAC_PERM_COMMANDS_NOTIFY_COMMAND_NOT_FOUND_ERROR))
            return false;

        SendSysMessage(LANG_NO_CMD);
    }
    return true;
}
Example #13
0
bool WebAppInputLine::OpenInputFile(FILE** ppFile, const PathName& fileName)
{
  const char* lpszFileName = fileName.GetData();

#if defined(MIKTEX_WINDOWS)
  string utf8FileName;
  if (!Utils::IsUTF8(lpszFileName))
  {
    LogWarn("converting ANSI file name");
    utf8FileName = StringUtil::AnsiToUTF8(lpszFileName);
    LogWarn("conversion succeeded: " + utf8FileName);
    lpszFileName = utf8FileName.c_str();
  }
#endif

  shared_ptr<Session> session = GetSession();

  if (pimpl->enablePipes && lpszFileName[0] == '|')
  {
    string command = lpszFileName + 1;
    Session::ExamineCommandLineResult examineResult;
    string examinedCommand;
    string toBeExecuted;
    tie(examineResult, examinedCommand, toBeExecuted) = session->ExamineCommandLine(command);
    if (examineResult == Session::ExamineCommandLineResult::SyntaxError)
    {
      LogError("command line syntax error: " + command);
      return false;
    }
    if (examineResult != Session::ExamineCommandLineResult::ProbablySafe && examineResult != Session::ExamineCommandLineResult::MaybeSafe)
    {
      LogError("command is unsafe: " + command);
      return false;
    }
    switch (pimpl->shellCommandMode)
    {
    case ShellCommandMode::Unrestricted:
      toBeExecuted = command;
      break;
    case ShellCommandMode::Forbidden:
      LogError("command not executed: " + command);
      return false;
    case ShellCommandMode::Query:
      // TODO
    case ShellCommandMode::Restricted:
      if (examineResult != Session::ExamineCommandLineResult::ProbablySafe)
      {
        LogError("command not allowed: " + command);
        return false;
      }
      break;
    default:
      MIKTEX_UNEXPECTED();
    }
    LogInfo("executing input pipe: " + toBeExecuted);
    *ppFile = session->OpenFile(toBeExecuted, FileMode::Command, FileAccess::Read, false);
    pimpl->foundFile.Clear();
    pimpl->foundFileFq.Clear();
  }
  else
  {
#if defined(WITH_OMEGA)
    PathName unmangled;
    if (AmI("omega"))
    {
      unmangled = UnmangleNameOfFile(lpszFileName);
      lpszFileName = unmangled.GetData();
    }
#endif

    if (!session->FindFile(lpszFileName, GetInputFileType(), pimpl->foundFile))
    {
      return false;
    }

    pimpl->foundFileFq = pimpl->foundFile;
    pimpl->foundFileFq.MakeAbsolute();

#if 1 // 2015-01-15
    if (pimpl->foundFile[0] == '.' && PathName::IsDirectoryDelimiter(pimpl->foundFile[1]))
    {
      PathName temp(pimpl->foundFile.GetData() + 2);
      pimpl->foundFile = temp;
    }
#endif

    try
    {
      if (pimpl->foundFile.HasExtension(".gz"))
      {
        CommandLineBuilder cmd("zcat");
        cmd.AppendArgument(pimpl->foundFile);
        *ppFile = session->OpenFile(cmd.ToString(), FileMode::Command, FileAccess::Read, false);
      }
      else if (pimpl->foundFile.HasExtension(".bz2"))
      {
        CommandLineBuilder cmd("bzcat");
        cmd.AppendArgument(pimpl->foundFile);
        *ppFile = session->OpenFile(cmd.ToString(), FileMode::Command, FileAccess::Read, false);
      }
      else if (pimpl->foundFile.HasExtension(".xz") || pimpl->foundFile.HasExtension(".lzma"))
      {
        CommandLineBuilder cmd("xzcat");
        cmd.AppendArgument(pimpl->foundFile);
        *ppFile = session->OpenFile(cmd.ToString(), FileMode::Command, FileAccess::Read, false);
      }
      else
      {
        *ppFile = session->OpenFile(pimpl->foundFile.GetData(), FileMode::Open, FileAccess::Read, false);
      }
    }
#if defined(MIKTEX_WINDOWS)
    catch (const SharingViolationException &)
    {
    }
#endif
    catch (const UnauthorizedAccessException &)
    {
    }
    catch (const FileNotFoundException &)
    {
    }
  }

  if (*ppFile == nullptr)
  {
    return false;
  }

  if (!AmI("xetex"))
  {
    auto openFileInfo = session->TryGetOpenFileInfo(*ppFile);
    if (openFileInfo.first && openFileInfo.second.mode != FileMode::Command)
    {
      int bom = CheckBom(*ppFile);
      switch (bom)
      {
      case Bom::UTF8:
        LogInfo("UTF8 BOM detected: " + openFileInfo.second.fileName);
        break;
      case Bom::UTF16be:
        LogInfo("UTF16be BOM detected: " + openFileInfo.second.fileName);
        break;
      case Bom::UTF16le:
        LogInfo("UTF16le BOM detected: " + openFileInfo.second.fileName);
        break;
      }
    }
  }

  pimpl->lastInputFileName = lpszFileName;

  return true;
}
Example #14
0
bool WebAppInputLine::OpenOutputFile(C4P::FileRoot& f, const PathName& fileName, bool text, PathName& outPath)
{
  const char* lpszPath = fileName.GetData();
#if defined(MIKTEX_WINDOWS)
  string utf8Path;
  if (!Utils::IsUTF8(lpszPath))
  {
    utf8Path = StringUtil::AnsiToUTF8(lpszPath);
    lpszPath = utf8Path.c_str();
  }
#endif
  shared_ptr<Session> session = GetSession();
  FILE* file = nullptr;
  if (pimpl->enablePipes && lpszPath[0] == '|')
  {
    string command = lpszPath + 1;
    Session::ExamineCommandLineResult examineResult;
    string examinedCommand;
    string toBeExecuted;
    tie(examineResult, examinedCommand, toBeExecuted) = session->ExamineCommandLine(command);
    if (examineResult == Session::ExamineCommandLineResult::SyntaxError)
    {
      LogError("command line syntax error: " + command);
      return false;
    }
    if (examineResult != Session::ExamineCommandLineResult::ProbablySafe && examineResult != Session::ExamineCommandLineResult::MaybeSafe)
    {
      LogError("command is unsafe: " + command);
      return false;
    }
    switch (pimpl->shellCommandMode)
    {
    case ShellCommandMode::Unrestricted:
      toBeExecuted = command;
      break;
    case ShellCommandMode::Forbidden:
      LogError("command not executed: " + command);
      return false;
    case ShellCommandMode::Query:
      // TODO
    case ShellCommandMode::Restricted:
      if (examineResult != Session::ExamineCommandLineResult::ProbablySafe)
      {
        LogError("command not allowed: " + command);
        return false;
      }
      break;
    default:
      MIKTEX_UNEXPECTED();
    }
    LogInfo("executing output pipe: " + toBeExecuted);
    file = session->OpenFile(toBeExecuted, FileMode::Command, FileAccess::Write, false);
  }
  else
  {
#if defined(WITH_OMEGA)
    PathName unmangled;
    if (AmI("omega"))
    {
      unmangled = UnmangleNameOfFile(lpszPath);
      lpszPath = unmangled.GetData();
    }
#endif
    bool isAuxFile = !IsOutputFile(lpszPath);
    PathName path;
    if (isAuxFile && !pimpl->auxDirectory.Empty())
    {
      path = pimpl->auxDirectory / lpszPath;
      lpszPath = path.GetData();
    }
    else if (!pimpl->outputDirectory.Empty())
    {
      path = pimpl->outputDirectory / lpszPath;
      lpszPath = path.GetData();
    }
    file = session->TryOpenFile(lpszPath, FileMode::Create, FileAccess::Write, text);
    if (file != nullptr)
    {
      outPath = lpszPath;
    }
  }
  if (file == nullptr)
  {
    return false;
  }
  f.Attach(file, true);
  return true;
}
OGRSpatialReference *OGRMSSQLSpatialDataSource::FetchSRS( int nId )

{
    if( nId <= 0 )
        return NULL;

/* -------------------------------------------------------------------- */
/*      First, we look through our SRID cache, is it there?             */
/* -------------------------------------------------------------------- */
    int  i;

    for( i = 0; i < nKnownSRID; i++ )
    {
        if( panSRID[i] == nId )
            return papoSRS[i];
    }

    OGRSpatialReference *poSRS = NULL;

/* -------------------------------------------------------------------- */
/*      Try looking up in spatial_ref_sys table                         */
/* -------------------------------------------------------------------- */
    if (bUseGeometryColumns)
    {
        CPLODBCStatement oStmt( GetSession() );
        oStmt.Appendf( "SELECT srtext FROM spatial_ref_sys WHERE srid = %d", nId );

        if( oStmt.ExecuteSQL() && oStmt.Fetch() )
        {
            if ( oStmt.GetColData( 0 ) )
            {
                poSRS = new OGRSpatialReference();
                char* pszWKT = (char*)oStmt.GetColData( 0 );
                if( poSRS->importFromWkt( &pszWKT ) != OGRERR_NONE )
                {
                    delete poSRS;
                    poSRS = NULL;
                }    
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      Try looking up the EPSG list                                    */
/* -------------------------------------------------------------------- */
    if (!poSRS)
    {
        poSRS = new OGRSpatialReference();
        if( poSRS->importFromEPSG( nId ) != OGRERR_NONE )
        {
            delete poSRS;
            poSRS = NULL;
        } 
    }

/* -------------------------------------------------------------------- */
/*      Add to the cache.                                               */
/* -------------------------------------------------------------------- */
    if (poSRS)
    {
        panSRID = (int *) CPLRealloc(panSRID,sizeof(int) * (nKnownSRID+1) );
        papoSRS = (OGRSpatialReference **)
            CPLRealloc(papoSRS, sizeof(void*) * (nKnownSRID + 1) );
        panSRID[nKnownSRID] = nId;
        papoSRS[nKnownSRID] = poSRS;
        nKnownSRID++;
    }

    return poSRS;
}
Example #16
0
/**
 * Finds GetSession()->usernum and system number from emailAddress, sets network number as
 * appropriate.
 * @param emailAddress The text of the email address.
 * @param pUserNumber OUT The User Number
 * @param pSystemmNumber OUT The System Number
 */
void parse_email_info(const std::string emailAddress, int *pUserNumber, int *pSystemNumber) {
  char *ss1, onx[20], ch, *mmk;
  unsigned nUserNumber, nSystemNumber;
  int i, nv, on, xx, onxi, odci;
  net_system_list_rec *csne;

  char szEmailAddress[ 255 ];
  strcpy(szEmailAddress, emailAddress.c_str());

  *pUserNumber = 0;
  *pSystemNumber = 0;
  net_email_name[0] = '\0';
  char *ss = strrchr(szEmailAddress, '@');
  if (ss == NULL) {
    nUserNumber = finduser1(szEmailAddress);
    if (nUserNumber > 0) {
      *pUserNumber = static_cast< unsigned short >(nUserNumber);
    } else if (wwiv::strings::IsEquals(szEmailAddress, "SYSOP")) {     // Add 4.31 Build3
      *pUserNumber = 1;
    } else {
      GetSession()->bout << "Unknown user.\r\n";
    }
  } else if (atoi(ss + 1) == 0) {
    for (i = 0; i < GetSession()->GetMaxNetworkNumber(); i++) {
      set_net_num(i);
      if ((WWIV_STRNICMP("internet", GetSession()->GetNetworkName(), 8) == 0) ||
          ((WWIV_STRNICMP("filenet", GetSession()->GetNetworkName(), 7) == 0) && (*pSystemNumber == 32767))) {
        strcpy(net_email_name, szEmailAddress);
        for (ss1 = net_email_name; *ss1; ss1++) {
          if ((*ss1 >= 'A') && (*ss1 <= 'Z')) {
            *ss1 += 'a' - 'A';
          }
        }
        *pSystemNumber = 1;
        break;
      }
    }
    if (i >= GetSession()->GetMaxNetworkNumber()) {
      GetSession()->bout << "Unknown user.\r\n";
    }
  } else {
    ss[0] = '\0';
    ss = &(ss[1]);
    i = strlen(szEmailAddress);
    while (i > 0 && szEmailAddress[i - 1] == ' ') {
      --i;
    }
    szEmailAddress[i] = 0;
    nUserNumber = atoi(szEmailAddress);
    if (nUserNumber == 0 && szEmailAddress[0] == '#') {
      nUserNumber = atoi(szEmailAddress + 1);
    }
    if (strchr(szEmailAddress, '@')) {
      nUserNumber = 0;
    }
    nSystemNumber = atoi(ss);
    ss1 = strchr(ss, '.');
    if (ss1) {
      ss1++;
    }
    if (nUserNumber == 0) {
      strcpy(net_email_name, szEmailAddress);
      i = strlen(net_email_name);
      while (i > 0 && net_email_name[i - 1] == ' ') {
        --i;
      }
      net_email_name[i] = '\0';
      if (net_email_name[0]) {
        *pSystemNumber = static_cast< unsigned short >(nSystemNumber);
      } else {
        GetSession()->bout << "Unknown user.\r\n";
      }
    } else {
      *pUserNumber = static_cast< unsigned short >(nUserNumber);
      *pSystemNumber = static_cast< unsigned short >(nSystemNumber);
    }
    if (*pSystemNumber && ss1) {
      for (i = 0; i < GetSession()->GetMaxNetworkNumber(); i++) {
        set_net_num(i);
        if (wwiv::strings::IsEqualsIgnoreCase(ss1, GetSession()->GetNetworkName())) {
          if (!valid_system(*pSystemNumber)) {
            GetSession()->bout.NewLine();
            GetSession()->bout << "There is no " << ss1 << " @" << *pSystemNumber << ".\r\n\n";
            *pSystemNumber = *pUserNumber = 0;
          } else {
            if (*pSystemNumber == net_sysnum) {
              *pSystemNumber = 0;
              if (*pUserNumber == 0) {
                *pUserNumber = static_cast< unsigned short >(finduser(net_email_name));
              }
              if (*pUserNumber == 0 || *pUserNumber > 32767) {
                *pUserNumber = 0;
                GetSession()->bout << "Unknown user.\r\n";
              }
            }
          }
          break;
        }
      }
      if (i >= GetSession()->GetMaxNetworkNumber()) {
        GetSession()->bout.NewLine();
        GetSession()->bout << "This system isn't connected to " << ss1 << "\r\n";
        *pSystemNumber = *pUserNumber = 0;
      }
    } else if (*pSystemNumber && GetSession()->GetMaxNetworkNumber() > 1) {
      odc[0] = '\0';
      odci = 0;
      onx[0] = 'Q';
      onx[1] = '\0';
      onxi = 1;
      nv = 0;
      on = GetSession()->GetNetworkNumber();
      ss = static_cast<char *>(BbsAllocA(GetSession()->GetMaxNetworkNumber()));
      WWIV_ASSERT(ss != NULL);
      xx = -1;
      for (i = 0; i < GetSession()->GetMaxNetworkNumber(); i++) {
        set_net_num(i);
        if (net_sysnum == *pSystemNumber) {
          xx = i;
        } else if (valid_system(*pSystemNumber)) {
          ss[nv++] = static_cast< char >(i);
        }
      }
      set_net_num(on);
      if (nv == 0) {
        if (xx != -1) {
          set_net_num(xx);
          *pSystemNumber = 0;
          if (*pUserNumber == 0) {
            *pUserNumber = static_cast< unsigned short >(finduser(net_email_name));
            if (*pUserNumber == 0 || *pUserNumber > 32767) {
              *pUserNumber = 0;
              GetSession()->bout << "Unknown user.\r\n";
            }
          }
        } else {
          GetSession()->bout.NewLine();
          GetSession()->bout << "Unknown system\r\n";
          *pSystemNumber = *pUserNumber = 0;
        }
      } else if (nv == 1) {
        set_net_num(ss[0]);
      } else {
        GetSession()->bout.NewLine();
        for (i = 0; i < nv; i++) {
          set_net_num(ss[i]);
          csne = next_system(*pSystemNumber);
          if (csne) {
            if (i < 9) {
              onx[onxi++] = static_cast< char >(i + '1');
              onx[onxi] = 0;
            } else {
              odci = static_cast< char >((i + 1) / 10);
              odc[odci - 1] = static_cast< char >(odci + '0');
              odc[odci] = 0;
            }
            GetSession()->bout << i + 1 << ". " << GetSession()->GetNetworkName() << " (" << csne->name << ")\r\n";
          }
        }
        GetSession()->bout << "Q. Quit\r\n\n";
        GetSession()->bout << "|#2Which network (number): ";
        if (nv < 9) {
          ch = onek(onx);
          if (ch == 'Q') {
            i = -1;
          } else {
            i = ch - '1';
          }
        } else {
          mmk = mmkey(2);
          if (*mmk == 'Q') {
            i = -1;
          } else {
            i = atoi(mmk) - 1;
          }
        }
        if (i >= 0 && i < nv) {
          set_net_num(ss[i]);
        } else {
          GetSession()->bout << "\r\n|#6Aborted.\r\n\n";
          *pUserNumber = *pSystemNumber = 0;
        }
      }
      free(ss);
    } else {
      if (*pSystemNumber == net_sysnum) {
        *pSystemNumber = 0;
        if (*pUserNumber == 0) {
          *pUserNumber = static_cast< unsigned short >(finduser(net_email_name));
        }
        if (*pUserNumber == 0 || *pUserNumber > 32767) {
          *pUserNumber = 0;
          GetSession()->bout << "Unknown user.\r\n";
        }
      } else if (!valid_system(*pSystemNumber)) {
        GetSession()->bout << "\r\nUnknown user.\r\n";
        *pSystemNumber = *pUserNumber = 0;
      }
    }
  }
}
Example #17
0
int OGROCIDataSource::FetchSRSId( OGRSpatialReference * poSRS )

{
    char                *pszWKT = NULL;
    int                 nSRSId;

    if( poSRS == NULL )
        return -1;

    if( !poSRS->IsProjected() && !poSRS->IsGeographic() )
        return -1;

/* ==================================================================== */
/*      The first strategy is to see if we can identify it by           */
/*      authority information within the SRS.  Either using ORACLE      */
/*      authority values directly, or check if there is a known         */
/*      translation for an EPSG authority code.                         */
/* ==================================================================== */
    const char *pszAuthName = NULL, *pszAuthCode = NULL;

    if( poSRS->IsGeographic() )
    {
        pszAuthName = poSRS->GetAuthorityName( "GEOGCS" );
        pszAuthCode = poSRS->GetAuthorityCode( "GEOGCS" );
    }
    else if( poSRS->IsProjected() )
    {
        pszAuthName = poSRS->GetAuthorityName( "PROJCS" );
        pszAuthCode = poSRS->GetAuthorityCode( "PROJCS" );
    }

    if( pszAuthName != NULL && pszAuthCode != NULL )
    {
        if( EQUAL(pszAuthName,"Oracle")
            && atoi(pszAuthCode) != 0 )
            return atoi(pszAuthCode);

        if( EQUAL(pszAuthName,"EPSG") )
        {
            int i, nEPSGCode = atoi(pszAuthCode);

            for( i = 0; anEPSGOracleMapping[i] != 0; i += 2 )
            {
                if( nEPSGCode == anEPSGOracleMapping[i+1] )
                    return anEPSGOracleMapping[i];
            }
        }
    }

/* ==================================================================== */
/*      We need to lookup the SRS in the existing Oracle CS_SRS         */
/*      table.                                                          */
/* ==================================================================== */

/* -------------------------------------------------------------------- */
/*      Convert SRS into old style format (SF-SQL 1.0).                 */
/* -------------------------------------------------------------------- */
    OGRSpatialReference *poSRS2 = poSRS->Clone();

    poSRS2->StripCTParms();

/* -------------------------------------------------------------------- */
/*      Convert any degree type unit names to "Decimal Degree".         */
/* -------------------------------------------------------------------- */
    double dfAngularUnits = poSRS2->GetAngularUnits( NULL );
    if( fabs(dfAngularUnits - 0.0174532925199433) < 0.0000000000000010 )
        poSRS2->SetAngularUnits( "Decimal Degree", 0.0174532925199433 );

/* -------------------------------------------------------------------- */
/*      Translate SRS to WKT.                                           */
/* -------------------------------------------------------------------- */
    if( poSRS2->exportToWkt( &pszWKT ) != OGRERR_NONE )
    {
        delete poSRS2;
        return -1;
    }

    delete poSRS2;

/* -------------------------------------------------------------------- */
/*      Try to find in the existing table.                              */
/* -------------------------------------------------------------------- */
    OGROCIStringBuf     oCmdText;
    OGROCIStatement     oCmdStatement( GetSession() );
    char                **papszResult = NULL;

    oCmdText.Append( "SELECT SRID FROM MDSYS.CS_SRS WHERE WKTEXT = '" );
    oCmdText.Append( pszWKT );
    oCmdText.Append( "'" );

    if( oCmdStatement.Execute( oCmdText.GetString() ) == CE_None )
        papszResult = oCmdStatement.SimpleFetchRow() ;

/* -------------------------------------------------------------------- */
/*      We got it!  Return it.                                          */
/* -------------------------------------------------------------------- */
    if( CSLCount(papszResult) == 1 )
    {
        CPLFree( pszWKT );
        return atoi( papszResult[0] );
    }

/* ==================================================================== */
/*      We didn't find it, so we need to define it as a new SRID at     */
/*      the end of the list of known values.                            */
/* ==================================================================== */

/* -------------------------------------------------------------------- */
/*      Get the current maximum srid in the srs table.                  */
/* -------------------------------------------------------------------- */
    if( oCmdStatement.Execute("SELECT MAX(SRID) FROM MDSYS.CS_SRS") == CE_None )
        papszResult = oCmdStatement.SimpleFetchRow();
    else
        papszResult = NULL;

    if( CSLCount(papszResult) == 1 )
        nSRSId = atoi(papszResult[0]) + 1;
    else
        nSRSId = 1;

/* -------------------------------------------------------------------- */
/*      Try adding the SRS to the SRS table.                            */
/* -------------------------------------------------------------------- */
    oCmdText.Clear();
    oCmdText.Append( "INSERT INTO MDSYS.CS_SRS (SRID, WKTEXT, CS_NAME) " );
    oCmdText.Appendf( 100, " VALUES (%d,'", nSRSId );
    oCmdText.Append( pszWKT );
    oCmdText.Append( "', '" );
    oCmdText.Append( poSRS->GetRoot()->GetChild(0)->GetValue() );
    oCmdText.Append( "' )" );

    CPLFree( pszWKT );

    if( oCmdStatement.Execute( oCmdText.GetString() ) != CE_None )
        return -1;
    else
        return nSRSId;
}
Example #18
0
bool CWebSock::AddModLoop(const CString& sLoopName, CModule& Module) {
	CString sTitle(Module.GetWebMenuTitle());

	if (!sTitle.empty() && (IsLoggedIn() || (!Module.WebRequiresLogin() && !Module.WebRequiresAdmin())) && (GetSession()->IsAdmin() || !Module.WebRequiresAdmin())) {
		CTemplate& Row = m_Template.AddRow(sLoopName);

		Row["ModName"] = Module.GetModName();
		Row["Title"] = sTitle;

		if (m_sModName == Module.GetModName()) {
			Row["Active"] = "true";
		}

		if (Module.GetUser()) {
			Row["Username"] = Module.GetUser()->GetUserName();
		}

		VWebSubPages& vSubPages = Module.GetSubPages();

		for (unsigned int a = 0; a < vSubPages.size(); a++) {
			TWebSubPage& SubPage = vSubPages[a];

			// bActive is whether or not the current url matches this subpage (params will be checked below)
			bool bActive = (m_sModName == Module.GetModName() && m_sPage == SubPage->GetName());

			if (SubPage->RequiresAdmin() && !GetSession()->IsAdmin()) {
				continue;  // Don't add admin-only subpages to requests from non-admin users
			}

			CTemplate& SubRow = Row.AddRow("SubPageLoop");

			SubRow["ModName"] = Module.GetModName();
			SubRow["PageName"] = SubPage->GetName();
			SubRow["Title"] = SubPage->GetTitle().empty() ? SubPage->GetName() : SubPage->GetTitle();

			CString& sParams = SubRow["Params"];

			const VPair& vParams = SubPage->GetParams();
			for (size_t b = 0; b < vParams.size(); b++) {
				pair<CString, CString> ssNV = vParams[b];

				if (!sParams.empty()) {
					sParams += "&";
				}

				if (!ssNV.first.empty()) {
					if (!ssNV.second.empty()) {
						sParams += ssNV.first.Escape_n(CString::EURL);
						sParams += "=";
						sParams += ssNV.second.Escape_n(CString::EURL);
					}

					if (bActive && GetParam(ssNV.first, false) != ssNV.second) {
						bActive = false;
					}
				}
			}

			if (bActive) {
				SubRow["Active"] = "true";
			}
		}

		return true;
	}

	return false;
}
Example #19
0
int OGROCIDataSource::Open( const char * pszNewName,
                            char** papszOpenOptionsIn,
                            int bUpdate,
                            int bTestOpen )

{
    CPLAssert( nLayers == 0 && poSession == NULL );

/* -------------------------------------------------------------------- */
/*      Verify Oracle prefix.                                           */
/* -------------------------------------------------------------------- */
    if( !STARTS_WITH_CI(pszNewName,"OCI:") )
    {
        if( !bTestOpen )
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                      "%s does not conform to Oracle OCI driver naming convention,"
                      " OCI:*\n", pszNewName );
        }
        return FALSE;
    }

/* -------------------------------------------------------------------- */
/*      Try to parse out name, password and database name.              */
/* -------------------------------------------------------------------- */
    char *pszUserid;
    const char *pszPassword = "";
    const char *pszDatabase = "";
    char **papszTableList = NULL;
    const char *pszWorkspace = "";

    int   i;

    if( pszNewName[4] == '\0' )
    {
        pszUserid = CPLStrdup(CSLFetchNameValueDef(papszOpenOptionsIn, "USER", ""));
        pszPassword = CSLFetchNameValueDef(papszOpenOptionsIn, "PASSWORD", "");
        pszDatabase = CSLFetchNameValueDef(papszOpenOptionsIn, "DBNAME", "");
        const char* pszTables = CSLFetchNameValue(papszOpenOptionsIn, "TABLES");
        if( pszTables )
            papszTableList = CSLTokenizeStringComplex(pszTables, ",", TRUE, FALSE );
        pszWorkspace = CSLFetchNameValueDef(papszOpenOptions, "WORKSPACE", "");
    }
    else
    {
        pszUserid = CPLStrdup( pszNewName + 4 );

        // Is there a table list?
        for( i = static_cast<int>(strlen(pszUserid))-1; i > 1; i-- )
        {
            if( pszUserid[i] == ':' )
            {
                papszTableList = CSLTokenizeStringComplex( pszUserid+i+1, ",",
                                                        TRUE, FALSE );
                pszUserid[i] = '\0';
                break;
            }

            if( pszUserid[i] == '/' || pszUserid[i] == '@' )
                break;
        }

        for( i = 0;
            pszUserid[i] != '\0' && pszUserid[i] != '/' && pszUserid[i] != '@';
            i++ ) {}

        if( pszUserid[i] == '/' )
        {
            pszUserid[i++] = '\0';
            pszPassword = pszUserid + i;
            for( ; pszUserid[i] != '\0' && pszUserid[i] != '@'; i++ ) {}
        }

        if( pszUserid[i] == '@' )
        {
            pszUserid[i++] = '\0';
            pszDatabase = pszUserid + i;
        }
    }

/* -------------------------------------------------------------------- */
/*      Try to establish connection.                                    */
/* -------------------------------------------------------------------- */
    CPLDebug( "OCI", "Userid=%s, Password=%s, Database=%s",
              pszUserid, pszPassword, pszDatabase );

    if( EQUAL(pszDatabase, "") &&
        EQUAL(pszPassword, "") &&
        EQUAL(pszUserid, "") )
    {
        /* Use username/password OS Authentication and ORACLE_SID database */

        poSession = OGRGetOCISession( "/", "", "" );
    }
    else
    {
        poSession = OGRGetOCISession( pszUserid, pszPassword, pszDatabase );
    }

    if( poSession == NULL )
    {
        CPLFree(pszUserid);
        CSLDestroy(papszTableList);
        return FALSE;
    }

    if( ! EQUAL(pszWorkspace, "") )
    {
        OGROCIStringBuf oValidateCmd;
        OGROCIStatement oValidateStmt( GetSession() );

        oValidateCmd.Append( "call DBMS_WM.GotoWorkspace('" );
        oValidateCmd.Append( pszWorkspace );
        oValidateCmd.Append( "')" );

        oValidateStmt.Execute( oValidateCmd.GetString() );
    }

    pszName = CPLStrdup( pszNewName );

    bDSUpdate = bUpdate;

/* -------------------------------------------------------------------- */
/*      If no list of target tables was provided, collect a list of     */
/*      spatial tables now.                                             */
/* -------------------------------------------------------------------- */
    if( papszTableList == NULL )
    {
        OGROCIStatement oGetTables( poSession );

        if( oGetTables.Execute(
            "SELECT TABLE_NAME, OWNER FROM ALL_SDO_GEOM_METADATA" )
            == CE_None )
        {
            char **papszRow;

            while( (papszRow = oGetTables.SimpleFetchRow()) != NULL )
            {
                char szFullTableName[100];

                if( EQUAL(papszRow[1],pszUserid) )
                    strcpy( szFullTableName, papszRow[0] );
                else
                    snprintf( szFullTableName, sizeof(szFullTableName), "%s.%s",
                             papszRow[1], papszRow[0] );

                if( CSLFindString( papszTableList, szFullTableName ) == -1 )
                    papszTableList = CSLAddString( papszTableList,
                                                   szFullTableName );
            }
        }
    }
    CPLFree( pszUserid );

/* -------------------------------------------------------------------- */
/*      Open all the selected tables or views.                          */
/* -------------------------------------------------------------------- */
    for( i = 0; papszTableList != NULL && papszTableList[i] != NULL; i++ )
    {
        OpenTable( papszTableList[i], -1, bUpdate, FALSE, papszOpenOptionsIn );
    }

    CSLDestroy( papszTableList );

    return TRUE;
}
Example #20
0
void Player::SendInitialLogonPackets()
{
	// Initial Packets... they seem to be re-sent on port.
	//m_session->OutPacket(SMSG_SET_REST_START_OBSOLETE, 4, &m_timeLogoff); // Seem to be unused by client

    StackWorldPacket<32> data( SMSG_BINDPOINTUPDATE );

    data << float( m_bind_pos_x );
    data << float( m_bind_pos_y );
    data << float( m_bind_pos_z );
    data << uint32( m_bind_mapid );
    data << uint32( m_bind_zoneid );

    m_session->SendPacket( &data );

	//Proficiencies
    SendSetProficiency( 4, armor_proficiency);
    SendSetProficiency( 2, weapon_proficiency);
	
	//Tutorial Flags
	data.Initialize( SMSG_TUTORIAL_FLAGS );
	
    for (int i = 0; i < 8; i++)
		data << uint32( m_Tutorials[i] );

	m_session->SendPacket(&data);

	smsg_TalentsInfo( false );
	smsg_InitialSpells();

	data.Initialize(SMSG_SEND_UNLEARN_SPELLS);
	data << uint32(0); // count, for(count) uint32;
	GetSession()->SendPacket( &data );

	SendInitialActions();
	smsg_InitialFactions();

    /* Some minor documentation about the time field
    // MOVE THIS DOCUMENTATION TO THE WIKI

    minute's = 0x0000003F                  00000000000000000000000000111111
    hour's   = 0x000007C0                  00000000000000000000011111000000
    weekdays = 0x00003800                  00000000000000000011100000000000
    days     = 0x000FC000                  00000000000011111100000000000000
    months   = 0x00F00000                  00000000111100000000000000000000
    years    = 0x1F000000                  00011111000000000000000000000000
    unk	     = 0xE0000000                  11100000000000000000000000000000
    */

	data.Initialize(SMSG_LOGIN_SETTIMESPEED);

	time_t minutes = sWorld.GetGameTime( ) / 60;
	time_t hours = minutes / 60; minutes %= 60;
    time_t gameTime = 0;

    // TODO: Add stuff to handle these variables

	time_t basetime = UNIXTIME;
	uint32 DayOfTheWeek;
	if(localtime(&basetime)->tm_wday == 0)
		DayOfTheWeek = 6;
	else
		   DayOfTheWeek = localtime(&basetime)->tm_wday - 1;
	uint32 DayOfTheMonth = localtime(&basetime)->tm_mday - 1;
	uint32 CurrentMonth = localtime(&basetime)->tm_mon;
	uint32 CurrentYear = localtime(&basetime)->tm_year - 100;

	#define MINUTE_BITMASK      0x0000003F
    #define HOUR_BITMASK        0x000007C0
    #define WEEKDAY_BITMASK     0x00003800
    #define DAY_BITMASK         0x000FC000
    #define MONTH_BITMASK       0x00F00000
    #define YEAR_BITMASK        0x1F000000
    #define UNK_BITMASK         0xE0000000

    #define MINUTE_SHIFTMASK    0
    #define HOUR_SHIFTMASK      6
    #define WEEKDAY_SHIFTMASK   11
    #define DAY_SHIFTMASK       14
    #define MONTH_SHIFTMASK     20
    #define YEAR_SHIFTMASK      24
    #define UNK_SHIFTMASK       29

    gameTime = ((minutes << MINUTE_SHIFTMASK) & MINUTE_BITMASK);
    gameTime|= ((hours << HOUR_SHIFTMASK) & HOUR_BITMASK);
    gameTime|= ((DayOfTheWeek << WEEKDAY_SHIFTMASK) & WEEKDAY_BITMASK);
    gameTime|= ((DayOfTheMonth << DAY_SHIFTMASK) & DAY_BITMASK);
    gameTime|= ((CurrentMonth << MONTH_SHIFTMASK) & MONTH_BITMASK);
    gameTime|= ((CurrentYear << YEAR_SHIFTMASK) & YEAR_BITMASK);

    data << uint32( gameTime );
	data << float( 0.0166666669777748f );  // Normal Game Speed
	data << uint32( 0 ); // 3.1.2
	
    m_session->SendPacket( &data );

	// cebernic for speedhack bug
	m_lastRunSpeed = 0;
	UpdateSpeed();

    WorldPacket ArenaSettings(SMSG_UPDATE_WORLD_STATE, 16);

    ArenaSettings << uint32( 0xC77 );
    ArenaSettings << uint32( sWorld.Arena_Progress );
    ArenaSettings << uint32( 0xF3D );
    ArenaSettings << uint32( sWorld.Arena_Season );

    m_session->SendPacket( &ArenaSettings );

	sLog.outDetail("WORLD: Sent initial logon packets for %s.", GetName());
}
Example #21
0
void WorldSocket::OnRead()
{
    TcpSocket::OnRead();
    if(!ibuf.GetLength())
    {
        this->CloseAndDelete();
        return;
    }
    while(ibuf.GetLength() > 0) // when all packets from the current ibuf are transformed into WorldPackets the remaining len will be zero
    {

        if(_gothdr) // already got header, this packet has to be the data part
        {
            ASSERT(_remaining > 0); // case pktsize==0 is handled below
            if(ibuf.GetLength() < _remaining)
            {
                DEBUG(logdebug("Delaying WorldPacket generation, bufsize is %u but should be >= %u",ibuf.GetLength(),_remaining));
                break;
            }
            _gothdr=false;
            WorldPacket *wp = new WorldPacket(_remaining);
            wp->resize(_remaining);
            ibuf.Read((char*)wp->contents(),_remaining);
            wp->SetOpcode(_opcode);
            GetSession()->AddToPktQueue(wp);
        }
        else // no pending header stored, so this packet must be a header
        {
            if(ibuf.GetLength() < sizeof(ServerPktHeader))
            {
                DEBUG(logdebug("Delaying header reading, bufsize is %u but should be >= %u",ibuf.GetLength(),sizeof(ServerPktHeader)));
                break;
            }

            if(GetSession()->GetInstance()->GetConf()->client > CLIENT_TBC)//Funny, old sources have this in TBC already...
            {
              // read first byte and check if size is 3 or 2 bytes
              uint8 firstSizeByte;
              ibuf.Read((char*)&firstSizeByte, 1);
              (_crypt.*pDecryptRecv)(&firstSizeByte, 1);
              if (firstSizeByte & 0x80) // got large packet
              {
                  ServerPktHeaderBig hdr;
                  ibuf.Read(((char*)&hdr) + 1, sizeof(ServerPktHeaderBig) - 1); // read *big* header, except first byte
                  (_crypt.*pDecryptRecv)(((uint8*)&hdr) + 1, sizeof(ServerPktHeaderBig) - 1); // decrypt 2 of 3 bytes (first one already decrypted above) of size, and cmd
                  hdr.size[0] = firstSizeByte; // assign missing first byte

                  uint32 realsize = ((hdr.size[0]&0x7F) << 16) | (hdr.size[1] << 8) | hdr.size[2];
                  _remaining = realsize - 2;
                  _opcode = hdr.cmd;
              }
              else // "normal" packet
              {
                  ServerPktHeader hdr;
                  ibuf.Read(((char*)&hdr) + 1, sizeof(ServerPktHeader) - 1); // read header, except first byte
                  (_crypt.*pDecryptRecv)(((uint8*)&hdr) + 1, sizeof(ServerPktHeader) - 1); // decrypt all except first
                  hdr.size |= firstSizeByte; // add already decrypted first byte

                  _remaining = ntohs(hdr.size) - 2;
                  _opcode = hdr.cmd;
              }
            }
            else
            {
              ServerPktHeader hdr;
              ibuf.Read(((char*)&hdr), sizeof(ServerPktHeader)); // read header
              (_crypt.*pDecryptRecv)(((uint8*)&hdr), sizeof(ServerPktHeader)); // decrypt all

              _remaining = ntohs(hdr.size) - 2;
              _opcode = hdr.cmd;

            }

            if(_opcode > MAX_OPCODE_ID)
            {
                logcritical("CRYPT ERROR: opcode=%u, remain=%u",_opcode,_remaining); // this should never be the case!
                GetSession()->GetInstance()->SetError(); // no way to recover the crypt, must exit
                // if the crypt gets messy its hardly possible to recover it, especially if we dont know
                // the length of the following data part
                // TODO: invent some way how to recover the crypt (reconnect?)
                return;
            }
            // the header is fine, now check if there are more data
            if(_remaining == 0) // this is a packet with no data (like CMSG_NULL_ACTION)
            {
                WorldPacket *wp = new WorldPacket;
                wp->SetOpcode(_opcode);
                GetSession()->AddToPktQueue(wp);
            }
            else // there is a data part to fetch
            {
                _gothdr=true; // only got the header, next packet will contain the data
            }
        }
    }
}
OGRLayer * OGRMSSQLSpatialDataSource::CreateLayer( const char * pszLayerName,
                                          OGRSpatialReference *poSRS,
                                          OGRwkbGeometryType eType,
                                          char ** papszOptions )

{
    char                *pszTableName = NULL;
    char                *pszSchemaName = NULL;
    const char          *pszGeomType = NULL;
    const char          *pszGeomColumn = NULL;
    int                 nCoordDimension = 3;

    /* determine the dimension */
    if( eType == wkbFlatten(eType) )
        nCoordDimension = 2;

    if( CSLFetchNameValue( papszOptions, "DIM") != NULL )
        nCoordDimension = atoi(CSLFetchNameValue( papszOptions, "DIM"));
        
    /* MSSQL Schema handling:
       Extract schema name from input layer name or passed with -lco SCHEMA.
       Set layer name to "schema.table" or to "table" if schema is not
       specified
    */
    const char* pszDotPos = strstr(pszLayerName,".");
    if ( pszDotPos != NULL )
    {
      int length = pszDotPos - pszLayerName;
      pszSchemaName = (char*)CPLMalloc(length+1);
      strncpy(pszSchemaName, pszLayerName, length);
      pszSchemaName[length] = '\0';
      
      if( CSLFetchBoolean(papszOptions,"LAUNDER", TRUE) )
          pszTableName = LaunderName( pszDotPos + 1 ); //skip "."
      else
          pszTableName = CPLStrdup( pszDotPos + 1 ); //skip "."
    }
    else
    {
      pszSchemaName = NULL;
      if( CSLFetchBoolean(papszOptions,"LAUNDER", TRUE) )
          pszTableName = LaunderName( pszLayerName ); //skip "."
      else
          pszTableName = CPLStrdup( pszLayerName ); //skip "."
    }

    if( CSLFetchNameValue( papszOptions, "SCHEMA" ) != NULL )
    {
        CPLFree(pszSchemaName);
        pszSchemaName = CPLStrdup(CSLFetchNameValue( papszOptions, "SCHEMA" ));
    }

    if (pszSchemaName == NULL)
        pszSchemaName = CPLStrdup("dbo");

/* -------------------------------------------------------------------- */
/*      Do we already have this layer?  If so, should we blow it        */
/*      away?                                                           */
/* -------------------------------------------------------------------- */
    int iLayer;

    for( iLayer = 0; iLayer < nLayers; iLayer++ )
    {
        if( EQUAL(pszLayerName,papoLayers[iLayer]->GetTableName()) )
        {
            if( CSLFetchNameValue( papszOptions, "OVERWRITE" ) != NULL
                && !EQUAL(CSLFetchNameValue(papszOptions,"OVERWRITE"),"NO") )
            {
                if (!pszSchemaName)
                    pszSchemaName = CPLStrdup(papoLayers[iLayer]->GetSchemaName());

                DeleteLayer( iLayer );
            }
            else
            {
                CPLError( CE_Failure, CPLE_AppDefined, 
                          "Layer %s already exists, CreateLayer failed.\n"
                          "Use the layer creation option OVERWRITE=YES to "
                          "replace it.",
                          pszLayerName );

                CPLFree( pszSchemaName );
                CPLFree( pszTableName );
                return NULL;
            }
        }
    }

/* -------------------------------------------------------------------- */
/*      Handle the GEOM_TYPE option.                                    */
/* -------------------------------------------------------------------- */
    pszGeomType = CSLFetchNameValue( papszOptions, "GEOM_TYPE" );

    if( !pszGeomType )
        pszGeomType = "geometry";
    
    if( !EQUAL(pszGeomType, "geometry")
        && !EQUAL(pszGeomType, "geography"))
    {
        CPLError( CE_Failure, CPLE_AppDefined, 
                  "FORMAT=%s not recognised or supported.", 
                  pszGeomType );

        CPLFree( pszSchemaName );
        CPLFree( pszTableName );
        return NULL;
    }

    /* determine the geometry column name */
    pszGeomColumn =  CSLFetchNameValue( papszOptions, "GEOM_NAME");
    if (!pszGeomColumn)
        pszGeomColumn = "ogr_geometry";

/* -------------------------------------------------------------------- */
/*      Initialize the metadata tables                                  */
/* -------------------------------------------------------------------- */

    if (InitializeMetadataTables() != OGRERR_NONE)
    {
        CPLFree( pszSchemaName );
        CPLFree( pszTableName );
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Try to get the SRS Id of this spatial reference system,         */
/*      adding to the srs table if needed.                              */
/* -------------------------------------------------------------------- */
    int nSRSId = 0;

    if( CSLFetchNameValue( papszOptions, "SRID") != NULL )
        nSRSId = atoi(CSLFetchNameValue( papszOptions, "SRID"));

    if( nSRSId == 0 && poSRS != NULL )
        nSRSId = FetchSRSId( poSRS );

/* -------------------------------------------------------------------- */
/*      Create a new table and create a new entry in the geometry,      */
/*      geometry_columns metadata table.                                */
/* -------------------------------------------------------------------- */

    if( eType != wkbNone )
    {
        const char *pszGeometryType = OGRToOGCGeomType(eType);

        CPLODBCStatement oStmt( &oSession );
        
        oStmt.Appendf( "DELETE FROM geometry_columns WHERE f_table_schema = '%s' "
            "AND f_table_name = '%s'\n", pszSchemaName, pszTableName );
        
        oStmt.Appendf("INSERT INTO [geometry_columns] ([f_table_catalog], [f_table_schema] ,[f_table_name], "
            "[f_geometry_column],[coord_dimension],[srid],[geometry_type]) VALUES ('%s', '%s', '%s', '%s', %d, %d, '%s')\n", 
            pszCatalog, pszSchemaName, pszTableName, pszGeomColumn, nCoordDimension, nSRSId, pszGeometryType );

        oStmt.Appendf("CREATE TABLE [%s].[%s] ([ogr_fid] [int] IDENTITY(1,1) NOT NULL, "
            "[%s] [%s] NULL, CONSTRAINT [PK_%s] PRIMARY KEY CLUSTERED ([ogr_fid] ASC))",
            pszSchemaName, pszTableName, pszGeomColumn, pszGeomType, pszTableName);

        oSession.BeginTransaction();
        
        if( !oStmt.ExecuteSQL() )
        {
            CPLError( CE_Failure, CPLE_AppDefined,
                        "Error creating layer: %s", GetSession()->GetLastError() );

            return NULL;
        }

        oSession.CommitTransaction();
    }

    CPLFree( pszSchemaName );
    CPLFree( pszTableName );

/* -------------------------------------------------------------------- */
/*      Create the layer object.                                        */
/* -------------------------------------------------------------------- */
    OGRMSSQLSpatialTableLayer   *poLayer;

    poLayer = new OGRMSSQLSpatialTableLayer( this );

    poLayer->SetLaunderFlag( CSLFetchBoolean(papszOptions,"LAUNDER",TRUE) );
    poLayer->SetPrecisionFlag( CSLFetchBoolean(papszOptions,"PRECISION",TRUE));
    
    if (poLayer->Initialize("dbo", pszLayerName, pszGeomColumn, nCoordDimension, nSRSId, eType) == OGRERR_FAILURE)
    {
        return NULL;
    }

/* -------------------------------------------------------------------- */
/*      Add layer to data source layer list.                            */
/* -------------------------------------------------------------------- */
    papoLayers = (OGRMSSQLSpatialTableLayer **)
        CPLRealloc( papoLayers,  sizeof(OGRMSSQLSpatialTableLayer *) * (nLayers+1) );

    papoLayers[nLayers++] = poLayer;


    return poLayer;
}
Example #23
0
CWebSock::EPageReqResult CWebSock::OnPageRequestInternal(const CString& sURI, CString& sPageRet) {
	if (CZNC::Get().GetProtectWebSessions() && GetSession()->GetIP() != GetRemoteIP()) {
		DEBUG("Expected IP: " << GetSession()->GetIP());
		DEBUG("Remote IP:   " << GetRemoteIP());
		PrintErrorPage(403, "Access denied", "This session does not belong to your IP.");
		return PAGE_DONE;
	}

	// Check that they really POSTed from one our forms by checking if they
	// know the "secret" CSRF check value. Don't do this for login since
	// CSRF against the login form makes no sense and the login form does a
	// cookies-enabled check which would break otherwise.
	if (IsPost() && GetParam("_CSRF_Check") != GetCSRFCheck() && sURI != "/login") {
		DEBUG("Expected _CSRF_Check: " << GetCSRFCheck());
		DEBUG("Actual _CSRF_Check:   " << GetParam("_CSRF_Check"));
		PrintErrorPage(403, "Access denied", "POST requests need to send "
				"a secret token to prevent cross-site request forgery attacks.");
		return PAGE_DONE;
	}

	SendCookie("SessionId", GetSession()->GetId());

	if (GetSession()->IsLoggedIn()) {
		m_sUser = GetSession()->GetUser()->GetUserName();
		m_bLoggedIn = true;
	}

	// Handle the static pages that don't require a login
	if (sURI == "/") {
		if(!m_bLoggedIn && GetParam("cookie_check", false).ToBool() && GetRequestCookie("SessionId").empty()) {
			GetSession()->AddError("Your browser does not have cookies enabled for this site!");
		}
		return PrintTemplate("index", sPageRet);
	} else if (sURI == "/favicon.ico") {
		return PrintStaticFile("/pub/favicon.ico", sPageRet);
	} else if (sURI == "/robots.txt") {
		return PrintStaticFile("/pub/robots.txt", sPageRet);
	} else if (sURI == "/logout") {
		GetSession()->SetUser(NULL);
		SetLoggedIn(false);
		Redirect("/");

		// We already sent a reply
		return PAGE_DONE;
	} else if (sURI == "/login") {
		if (GetParam("submitted").ToBool()) {
			m_sUser = GetParam("user");
			m_sPass = GetParam("pass");
			m_bLoggedIn = OnLogin(m_sUser, m_sPass);

			// AcceptedLogin()/RefusedLogin() will call Redirect()
			return PAGE_DEFERRED;
		}

		Redirect("/"); // the login form is here
		return PAGE_DONE;
	} else if (sURI.Left(5) == "/pub/") {
		return PrintStaticFile(sURI, sPageRet);
	} else if (sURI.Left(11) == "/skinfiles/") {
		CString sSkinName = sURI.substr(11);
		CString::size_type uPathStart = sSkinName.find("/");
		if (uPathStart != CString::npos) {
			CString sFilePath = sSkinName.substr(uPathStart + 1);
			sSkinName.erase(uPathStart);

			m_Template.ClearPaths();
			m_Template.AppendPath(GetSkinPath(sSkinName) + "pub");

			if (PrintFile(m_Template.ExpandFile(sFilePath))) {
				return PAGE_DONE;
			} else {
				return PAGE_NOTFOUND;
			}
		}
		return PAGE_NOTFOUND;
	} else if (sURI.Left(6) == "/mods/" || sURI.Left(10) == "/modfiles/") {
		ParsePath();
		// Make sure modules are treated as directories
		if (sURI.Right(1) != "/" && sURI.find(".") == CString::npos && sURI.TrimLeft_n("/mods/").TrimLeft_n("/").find("/") == CString::npos) {
			Redirect(sURI + "/");
			return PAGE_DONE;
		}

		CModule *pModule = CZNC::Get().GetModules().FindModule(m_sModName);
		if (!pModule) {
			// Check if GetSession()->GetUser() is NULL and display
			// an error in that case
			if (!ForceLogin())
				return PAGE_DONE;

			pModule = GetSession()->GetUser()->GetModules().FindModule(m_sModName);
		}

		if (!pModule) {
			return PAGE_NOTFOUND;
		} else if (pModule->WebRequiresLogin() && !ForceLogin()) {
			return PAGE_PRINT;
		} else if (pModule->WebRequiresAdmin() && !GetSession()->IsAdmin()) {
			PrintErrorPage(403, "Forbidden", "You need to be an admin to access this module");
			return PAGE_DONE;
		} else if (!pModule->IsGlobal() && pModule->GetUser() != GetSession()->GetUser()) {
			PrintErrorPage(403, "Forbidden", "You must login as " + pModule->GetUser()->GetUserName() + " in order to view this page");
			return PAGE_DONE;
		} else if (pModule->OnWebPreRequest(*this, m_sPage)) {
			return PAGE_DEFERRED;
		}

		VWebSubPages& vSubPages = pModule->GetSubPages();

		for (unsigned int a = 0; a < vSubPages.size(); a++) {
			TWebSubPage& SubPage = vSubPages[a];

			bool bActive = (m_sModName == pModule->GetModName() && m_sPage == SubPage->GetName());

			if (bActive && SubPage->RequiresAdmin() && !GetSession()->IsAdmin()) {
				PrintErrorPage(403, "Forbidden", "You need to be an admin to access this page");
				return PAGE_DONE;
			}
		}

		if (pModule && !pModule->IsGlobal() && (!IsLoggedIn() || pModule->GetUser() != GetSession()->GetUser())) {
			AddModLoop("UserModLoop", *pModule);
		}

		if (sURI.Left(10) == "/modfiles/") {
			m_Template.AppendPath(GetSkinPath(GetSkinName()) + "/mods/" + m_sModName + "/files/");
			m_Template.AppendPath(pModule->GetModDataDir() + "/files/");

			if (PrintFile(m_Template.ExpandFile(m_sPage.TrimLeft_n("/")))) {
				return PAGE_PRINT;
			} else {
				return PAGE_NOTFOUND;
			}
		} else {
			SetPaths(pModule, true);

			/* if a module returns false from OnWebRequest, it does not
			   want the template to be printed, usually because it did a redirect. */
			if (pModule->OnWebRequest(*this, m_sPage, m_Template)) {
				// If they already sent a reply, let's assume
				// they did what they wanted to do.
				if (SentHeader()) {
					return PAGE_DONE;
				}
				return PrintTemplate(m_sPage, sPageRet, pModule);
			}

			if (!SentHeader()) {
				PrintErrorPage(404, "Not Implemented", "The requested module does not acknowledge web requests");
			}
			return PAGE_DONE;
		}
	} else {
		CString sPage(sURI.Trim_n("/"));
		if (sPage.length() < 32) {
			for (unsigned int a = 0; a < sPage.length(); a++) {
				unsigned char c = sPage[a];

				if ((c < '0' || c > '9') && (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && c != '_') {
					return PAGE_NOTFOUND;
				}
			}

			return PrintTemplate(sPage, sPageRet);
		}
	}

	return PAGE_NOTFOUND;
}
Example #24
0
void valscan() {
  // Must be local cosysop or better
  if (!lcs()) {
    return;
  }

  int ac = 0;
  int os = GetSession()->GetCurrentMessageArea();

  if (uconfsub[1].confnum != -1 && okconf(GetSession()->GetCurrentUser())) {
    ac = 1;
    tmp_disable_conf(true);
  }
  bool done = false;
  for (int sn = 0; sn < GetSession()->num_subs && !hangup && !done; sn++) {
    if (!iscan(sn)) {
      continue;
    }
    if (GetSession()->GetCurrentReadMessageArea() < 0) {
      return;
    }

    uint32_t sq = qsc_p[sn];

    // Must be sub with validation "on"
    if (!(xsubs[GetSession()->GetCurrentReadMessageArea()].num_nets)
        || !(subboards[GetSession()->GetCurrentReadMessageArea()].anony & anony_val_net)) {
      continue;
    }

    GetSession()->bout.NewLine();
    GetSession()->bout.Color(2);
    GetSession()->bout.ClearEOL();
    GetSession()->bout << "{{ ValScanning " << subboards[GetSession()->GetCurrentReadMessageArea()].name << " }}\r\n";
    lines_listed = 0;
    GetSession()->bout.ClearEOL();
    if (okansi() && !newline) {
      GetSession()->bout << "\r\x1b[2A";
    }

    for (int i = 1; i <= GetSession()->GetNumMessagesInCurrentMessageArea() && !hangup && !done; i++) {    // was i = 0
      if (get_post(i)->status & status_pending_net) {
        CheckForHangup();
        GetSession()->localIO()->tleft(true);
        if (i > 0 && i <= GetSession()->GetNumMessagesInCurrentMessageArea()) {
          bool next;
          int val;
          read_message(i, &next, &val);
          GetSession()->bout << "|#4[|#4Subboard: " << subboards[GetSession()->GetCurrentReadMessageArea()].name << "|#1]\r\n";
          GetSession()->bout <<  "|#1D|#9)elete, |#1R|#9)eread |#1V|#9)alidate, |#1M|#9)ark Validated, |#1Q|#9)uit: |#2";
          char ch = onek("QDVMR");
          switch (ch) {
          case 'Q':
            done = true;
            break;
          case 'R':
            i--;
            continue;
          case 'V': {
            open_sub(true);
            resynch(&i, nullptr);
            postrec *p1 = get_post(i);
            p1->status &= ~status_pending_net;
            write_post(i, p1);
            close_sub();
            send_net_post(p1, subboards[GetSession()->GetCurrentReadMessageArea()].filename,
                          GetSession()->GetCurrentReadMessageArea());
            GetSession()->bout.NewLine();
            GetSession()->bout << "|#7Message sent.\r\n\n";
          }
          break;
          case 'M':
            if (lcs() && i > 0 && i <= GetSession()->GetNumMessagesInCurrentMessageArea() &&
                subboards[GetSession()->GetCurrentReadMessageArea()].anony & anony_val_net &&
                xsubs[GetSession()->GetCurrentReadMessageArea()].num_nets) {
              open_sub(true);
              resynch(&i, nullptr);
              postrec *p1 = get_post(i);
              p1->status &= ~status_pending_net;
              write_post(i, p1);
              close_sub();
              GetSession()->bout.NewLine();
              GetSession()->bout << "|#9Not set for net pending now.\r\n\n";
            }
            break;
          case 'D':
            if (lcs()) {
              if (i > 0) {
                open_sub(true);
                resynch(&i, nullptr);
                postrec p2 = *get_post(i);
                delete_message(i);
                close_sub();
                if (p2.ownersys == 0) {
                  WUser tu;
                  GetApplication()->GetUserManager()->ReadUser(&tu, p2.owneruser);
                  if (!tu.IsUserDeleted()) {
                    if (static_cast<unsigned long>(date_to_daten(tu.GetFirstOn())) < p2.daten) {
                      GetSession()->bout.NewLine();
                      GetSession()->bout << "|#2Remove how many posts credit? ";
                      char szNumCredits[ 11 ];
                      input(szNumCredits, 3, true);
                      int nNumPostCredits = 1;
                      if (szNumCredits[0]) {
                        nNumPostCredits = atoi(szNumCredits);
                      }
                      nNumPostCredits = std::min<int>(tu.GetNumMessagesPosted(), nNumPostCredits);
                      if (nNumPostCredits) {
                        tu.SetNumMessagesPosted(tu.GetNumMessagesPosted() - static_cast<unsigned short>(nNumPostCredits));
                      }
                      GetSession()->bout.NewLine();
                      GetSession()->bout << "|#3Post credit removed = " << nNumPostCredits << wwiv::endl;
                      tu.SetNumDeletedPosts(tu.GetNumDeletedPosts() + 1);
                      GetApplication()->GetUserManager()->WriteUser(&tu, p2.owneruser);
                      GetApplication()->UpdateTopScreen();
                    }
                  }
                }
                resynch(&i, &p2);
              }
            }
            break;
          }
        }
      }
    }
    qsc_p[sn] = sq;
  }

  if (ac) {
    tmp_disable_conf(false);
  }

  GetSession()->SetCurrentMessageArea(os);
  GetSession()->bout.NewLine(2);
}
Example #25
0
void ClusterInterface::HandleTeleportResult(WorldPacket & pck)
{
	uint32 sessionid;
	uint8 result;
	uint32 mapid, instanceid;
	LocationVector vec;
	float o;

	pck >> sessionid;

	WorldSession* s = GetSession(sessionid);

	if (!s)
	{
		//tell the realm-server we have no session
		WorldPacket data(ICMSG_ERROR_HANDLER, 5);
		data << uint8(1); //1 = no session
		data << sessionid;
		sClusterInterface.SendPacket(&data);
		return;
	}

	pck >> result >> mapid >> instanceid >> vec >> o;

	//the destination is on the same server
	if (result == 1)
	{
		if (s->GetPlayer() != NULL)
			sEventMgr.AddEvent(s->GetPlayer(), &Player::EventClusterMapChange, mapid, instanceid, vec, EVENT_UNK, 1, 1, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
	}
	else
	{
		//make this non-async, needs redone to support packing the player
		//since were saving it HAS TO BE HERE so the new server has the correct data
		WorldPacket nw(SMSG_NEW_WORLD);
		nw << mapid << vec << o;
		s->SendPacket(&nw);

		uint32 oldmapid = s->GetPlayer()->GetMapId();
		uint32 oldinstanceid = s->GetPlayer()->GetInstanceID();
		uint32 playerlowguid = s->GetPlayer()->GetLowGUID();
		s->GetPlayer()->SetMapId(mapid);
		s->GetPlayer()->SetInstanceID(instanceid);
		s->GetPlayer()->SetPosition(vec.x, vec.y, vec.z, o);
		s->GetPlayer()->SaveToDB(true);

		//need to shift back to old ones for removing from world :)
		s->GetPlayer()->SetMapId(oldmapid);
		s->GetPlayer()->SetInstanceID(oldinstanceid);

		WorldPacket data(ICMSG_SWITCH_SERVER, 100);
		data << sessionid << playerlowguid << mapid << instanceid << vec << o;
		sClusterInterface.SendPacket(&data);

		RPlayerInfo * pRPlayer = GetPlayer(playerlowguid);
		bool newRplr = false;
		if(pRPlayer == NULL)
		{
			pRPlayer = new RPlayerInfo;
			newRplr = true;
		}
		s->GetPlayer()->UpdateRPlayerInfo(pRPlayer, newRplr);
		pRPlayer->MapId = mapid;
		pRPlayer->InstanceId = instanceid;
		data.Initialize(ICMSG_PLAYER_INFO);
		pRPlayer->Pack(data);
		sClusterInterface.SendPacket(&data);

		sEventMgr.AddEvent(s->GetPlayer(), &Player::HandleClusterRemove, EVENT_UNK, 1, 1, EVENT_FLAG_DO_NOT_EXECUTE_IN_WORLD_CONTEXT);
	}
}
Example #26
0
CString CWebSock::GetCSRFCheck() {
	CSmartPtr<CWebSession> pSession = GetSession();
	return pSession->GetId().MD5();
}
Example #27
0
void do_chains() {
  int *map = static_cast<int*>(BbsAllocA(GetSession()->max_chains * sizeof(int)));
  WWIV_ASSERT(map != NULL);
  if (!map) {
    return;
  }

  GetSession()->localIO()->tleft(true);
  int mapp = 0;
  memset(odc, 0, sizeof(odc));
  for (int i = 0; i < GetSession()->GetNumberOfChains(); i++) {
    bool ok = true;
    chainfilerec c = chains[i];
    if ((c.ansir & ansir_ansi) && !okansi()) {
      ok = false;
    }
    if ((c.ansir & ansir_local_only) && GetSession()->using_modem) {
      ok = false;
    }
    if (c.sl > GetSession()->GetEffectiveSl()) {
      ok = false;
    }
    if (c.ar && !GetSession()->GetCurrentUser()->HasArFlag(c.ar)) {
      ok = false;
    }
    if (GetApplication()->HasConfigFlag(OP_FLAGS_CHAIN_REG) && chains_reg && (GetSession()->GetEffectiveSl() < 255)) {
      chainregrec r = chains_reg[ i ];
      if (r.maxage) {
        if (r.minage > GetSession()->GetCurrentUser()->GetAge() || r.maxage < GetSession()->GetCurrentUser()->GetAge()) {
          ok = false;
        }
      }
    }
    if (ok) {
      map[ mapp++ ] = i;
      if (mapp < 100) {
        if ((mapp % 10) == 0) {
          odc[mapp / 10 - 1] = static_cast< char >('0' + (mapp / 10));
        }
      }
    }
  }
  if (mapp == 0) {
    GetSession()->bout << "\r\n\n|#5Sorry, no external programs available.\r\n";
    free(map);
    GetSession()->SetMMKeyArea(WSession::mmkeyMessageAreas);
    return;
  }
  show_chains(&mapp, map);

  bool done   = false;
  GetSession()->SetMMKeyArea(WSession::mmkeyMessageAreas);
  int start   = 0;
  char *ss    = NULL;

  do {
    GetSession()->SetMMKeyArea(WSession::mmkeyChains);
    GetSession()->localIO()->tleft(true);
    GetSession()->bout.NewLine();
    GetSession()->bout << "|#7Which chain (1-" << mapp << ", Q=Quit, ?=List): ";

    int nChainNumber = -1;
    if (mapp < 100) {
      ss = mmkey(2);
      nChainNumber = atoi(ss);
    } else {
      char szChainNumber[ 11 ];
      input(szChainNumber, 3);
      nChainNumber = atoi(szChainNumber);
    }
    if (nChainNumber > 0 && nChainNumber <= mapp) {
      done = true;
      GetSession()->SetMMKeyArea(WSession::mmkeyChains);
      GetSession()->bout << "\r\n|#6Please wait...\r\n";
      run_chain(map[ nChainNumber - 1 ]);
    } else if (wwiv::strings::IsEquals(ss, "Q")) {
      GetSession()->SetMMKeyArea(WSession::mmkeyMessageAreas);
      done = true;
    } else if (wwiv::strings::IsEquals(ss, "?")) {
      show_chains(&mapp, map);
    } else if (wwiv::strings::IsEquals(ss, "P")) {
      if (start > 0) {
        start -= 14;
      }
      start = std::max<int>(start, 0);
    } else if (wwiv::strings::IsEquals(ss, "N")) {
      if (start + 14 < mapp) {
        start += 14;
      }
    }
  } while (!hangup  && !done);

  free(map);
}
void Player::MakeTalentGlyphLink(std::ostringstream &out)
{
    // |cff4e96f7|Htalent:1396:4|h[Unleashed Fury]|h|r
    // |cff66bbff|Hglyph:23:460|h[Glyph of Fortitude]|h|r

    if (m_specsCount)
        // loop through all specs (only 1 for now)
        for (uint32 specIdx = 0; specIdx < m_specsCount; ++specIdx)
        {
            // find class talent tabs (all players have 3 talent tabs)
            uint32 const* talentTabIds = GetTalentTabPages(getClass());

            out << "\n" << "Active Talents ";

            for (uint32 i = 0; i < 3; ++i)
            {
                uint32 talentTabId = talentTabIds[i];
                for (PlayerTalentMap::iterator iter = m_talents[specIdx].begin(); iter != m_talents[specIdx].end(); ++iter)
                {
                    PlayerTalent talent = (*iter).second;

                    if (talent.state == PLAYERSPELL_REMOVED)
                        continue;

                    // skip another tab talents
                    if (talent.talentEntry->TalentTab != talentTabId)
                        continue;

                    TalentEntry const* talentInfo = sTalentStore.LookupEntry(talent.talentEntry->TalentID);

                    SpellEntry const* spell_entry = sSpellStore.LookupEntry(talentInfo->RankID[talent.currentRank]);

                    out << "|cff4e96f7|Htalent:" << talent.talentEntry->TalentID << ":" << talent.currentRank
                        << " |h[" << spell_entry->SpellName[GetSession()->GetSessionDbcLocale()] << "]|h|r";
                }
            }

            uint32 freepoints = 0;

            out << " Unspent points : ";

            if ((freepoints = GetFreeTalentPoints()) > 0)
                out << "|h|cff00ff00" << freepoints << "|h|r";
            else
                out << "|h|cffff0000" << freepoints << "|h|r";

            out << "\n" << "Active Glyphs ";
            // GlyphProperties.dbc
            for (uint8 i = 0; i < MAX_GLYPH_SLOT_INDEX; ++i)
            {
                GlyphPropertiesEntry const* glyph = sGlyphPropertiesStore.LookupEntry(m_glyphs[specIdx][i].GetId());
                if (!glyph)
                    continue;

                SpellEntry const* spell_entry = sSpellStore.LookupEntry(glyph->SpellId);

                out << "|cff66bbff|Hglyph:" << GetGlyphSlot(i) << ":" << m_glyphs[specIdx][i].GetId()
                    << " |h[" << spell_entry->SpellName[GetSession()->GetSessionDbcLocale()] << "]|h|r";

            }
        }
}
Example #29
0
bool ChatHandler::ExecuteCommandInTable(std::vector<ChatCommand> const& table, const char* text, std::string const& fullcmd)
{
    char const* oldtext = text;
    std::string cmd = "";

    while (*text != ' ' && *text != '\0')
    {
        cmd += *text;
        ++text;
    }

    while (*text == ' ') ++text;

    for (uint32 i = 0; i < table.size(); ++i)
    {
        if (!hasStringAbbr(table[i].Name, cmd.c_str()))
            continue;

        bool match = false;
        if (strlen(table[i].Name) > cmd.length())
        {
            for (uint32 j = 0; j < table.size(); ++j)
            {
                if (!hasStringAbbr(table[j].Name, cmd.c_str()))
                    continue;

                if (strcmp(table[j].Name, cmd.c_str()) == 0)
                {
                    match = true;
                    break;
                }
            }
        }
        if (match)
            continue;

        // select subcommand from child commands list
        if (!table[i].ChildCommands.empty())
        {
            if (!ExecuteCommandInTable(table[i].ChildCommands, text, fullcmd))
            {
#ifdef ELUNA
                if (!sEluna->OnCommand(GetSession() ? GetSession()->GetPlayer() : NULL, oldtext))
                    return true;
#endif

                if (text[0] != '\0')
                    SendSysMessage(LANG_NO_SUBCMD);
                else
                    SendSysMessage(LANG_CMD_SYNTAX);

                ShowHelpForCommand(table[i].ChildCommands, text);
            }

            return true;
        }

        // must be available and have handler
        if (!table[i].Handler || !isAvailable(table[i]))
            continue;

        SetSentErrorMessage(false);
        // table[i].Name == "" is special case: send original command to handler
        if ((table[i].Handler)(this, table[i].Name[0] != '\0' ? text : oldtext))
        {
            if (!m_session) // ignore console
                return true;

            Player* player = m_session->GetPlayer();
            if (!AccountMgr::IsPlayerAccount(m_session->GetSecurity()))
            {
                ObjectGuid guid = player->GetTarget();
                uint32 areaId = player->GetAreaId();
                std::string areaName = "Unknown";
                std::string zoneName = "Unknown";
                if (AreaTableEntry const* area = GetAreaEntryByAreaID(areaId))
                {
                    int locale = GetSessionDbcLocale();
                    areaName = area->area_name[locale];
                    if (AreaTableEntry const* zone = GetAreaEntryByAreaID(area->zone))
                        zoneName = zone->area_name[locale];
                }

                sLog->outCommand(m_session->GetAccountId(), "Command: %s [Player: %s (%s) (Account: %u) X: %f Y: %f Z: %f Map: %u (%s) Area: %u (%s) Zone: %s Selected: %s (%s)]",
                    fullcmd.c_str(), player->GetName().c_str(), player->GetGUID().ToString().c_str(),
                    m_session->GetAccountId(), player->GetPositionX(), player->GetPositionY(),
                    player->GetPositionZ(), player->GetMapId(),
                    player->FindMap() ? player->FindMap()->GetMapName() : "Unknown",
                    areaId, areaName.c_str(), zoneName.c_str(),
                    (player->GetSelectedUnit()) ? player->GetSelectedUnit()->GetName().c_str() : "",
                    guid.ToString().c_str());
            }
        }
        // some commands have custom error messages. Don't send the default one in these cases.
        else if (!HasSentErrorMessage())
        {
            if (!table[i].Help.empty())
                SendSysMessage(table[i].Help.c_str());
            else
                SendSysMessage(LANG_CMD_SYNTAX);
        }

        return true;
    }

    return false;
}
Example #30
0
// Check if an update is required
//
CAutoUpdater::ErrorType CAutoUpdater::CheckForUpdate()
{		
	if (!InternetOkay())
	{
		return InternetConnectFailure;
	}


	bTransferSuccess = false;


	// First we must check the remote configuration file to see if an update is necessary
	CString URL = CString(UPDATE_CHECK_URL) + CString(LOCATION_UPDATE_FILE_CHECK);
	HINTERNET hSession = GetSession(URL);
	if (!hSession)
	{
		return InternetSessionFailure;
	}

	BYTE pBuf[TRANSFER_SIZE];
	memset(pBuf, NULL, sizeof(pBuf));
	bTransferSuccess = DownloadConfig(hSession, pBuf, TRANSFER_SIZE);
	InternetCloseHandle(hSession);
	if (!bTransferSuccess)
	{
		return ConfigDownloadFailure;
	}

	// Get the version number of our executable and compare to see if an update is needed
	CString executable = GetExecutable();
	CString fileVersion = GetFileVersion(executable);\
	if (fileVersion.IsEmpty())
	{
		return NoExecutableVersion;
	}

	CString updateVersion = (char *) pBuf;
	if (CompareVersions(updateVersion, fileVersion) != 1)
	{	
		return UpdateNotRequired;
	}

	// At this stage an update is required	
	TCHAR path[MAX_PATH];
	GetTempPath(MAX_PATH, path);
	CString directory = path;
	
	// Download the updated file
	/*
	TCHAR *pToken = strtok(updateVersion.GetBuffer(256),_T("."));
	while(pToken!=NULL)
	{	
		if(IsDigits(pToken[0]))
			URL.Insert(URL.GetLength(),pToken[0]);
		pToken = strtok(NULL, _T("."));
	}
	*/
	updateVersion.TrimLeft();
	updateVersion.TrimRight();
	updateVersion.TrimRight(_T("."));
	URL = CString(UPDATE_DOWNLOAD_URL) + updateVersion + CString("/") + CString(InstallerName) + CString(".exe");
	updateVersion.ReleaseBuffer();
	DBG_PRINT(URL);
	
	hSession = GetSession(URL);
	if (!hSession)
	{
		return InternetSessionFailure;
	}

	CAutoUpdateDlg autoupdate_dlg;
	int nResult = autoupdate_dlg.DoModal();
	if (nResult==0)
	{
		AppConfig.autoupdate_disable=1;
		return UpdateNotComplete;	
	}
	else if (nResult==2)
	{
		return UpdateNotComplete;
	}

	// Proceed with the update
	CString updateFileLocation = directory+InstallerName+CString(".exe");
	download_update_dlg = new CDownloadUpdateDlg();
	CAutoUpdater_DownloadInfo * Info = new CAutoUpdater_DownloadInfo(hSession, updateFileLocation,download_update_dlg);
	

   	CWinThread * controlThread = AfxBeginThread(DownloadUpdateFile,Info,THREAD_PRIORITY_NORMAL);
	download_update_dlg->DoModal();
	
	//download_update_dlg->OnCancel();
	LPDWORD lpExitCode = new unsigned long;
	*lpExitCode = STILL_ACTIVE;
	//while(*lpExitCode==STILL_ACTIVE)
	//{
	//	GetExitCodeThread(controlThread->m_hThread,lpExitCode);
	//	::Sleep(1000);
	//}
	//bTransferSuccess = (int)(*lpExitCode);
	
	//InternetCloseHandle(hSession);
//	if (!bTransferSuccess)
//	{
//		return FileDownloadFailure;
//	}	

    MessageBox(AfxGetMainWnd()->m_hWnd, LoadString(IDS_INSTALL_UPDATE), LoadString(IDS_PCMAN_CLOSE), MB_ICONINFORMATION|MB_OK);
	if (!::ShellExecute(AfxGetMainWnd()->m_hWnd, "open", updateFileLocation, NULL, NULL,
						   SW_SHOWNORMAL))
	{
		return UpdateNotComplete;
	}
   
	
	ASSERT(AfxGetMainWnd() != NULL);
    SetActiveWindow(AfxGetMainWnd()->m_hWnd);
	

	AfxGetMainWnd()->SendMessage(WM_COMMIT_UPDATE);

	
	return Success;
}