code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
// // Copyright (C) 2010-2014 Codership Oy <info@codership.com> // #include "galera_common.hpp" #include "replicator_smm.hpp" #include "galera_exception.hpp" #include "uuid.hpp" extern "C" { #include "galera_info.h" } #include <sstream> #include <iostream> static void apply_trx_ws(void* recv_ctx, wsrep_apply_cb_t apply_cb, wsrep_commit_cb_t commit_cb, const galera::TrxHandle& trx, const wsrep_trx_meta_t& meta) { using galera::TrxHandle; static const size_t max_apply_attempts(4); size_t attempts(1); do { try { if (trx.is_toi()) { log_debug << "Executing TO isolated action: " << trx; } gu_trace(trx.apply(recv_ctx, apply_cb, meta)); if (trx.is_toi()) { log_debug << "Done executing TO isolated action: " << trx.global_seqno(); } break; } catch (galera::ApplyException& e) { if (trx.is_toi()) { log_warn << "Ignoring error for TO isolated action: " << trx; break; } else { int const err(e.status()); if (err > 0) { wsrep_bool_t unused(false); int const rcode( commit_cb( recv_ctx, TrxHandle::trx_flags_to_wsrep_flags(trx.flags()), &meta, &unused, false)); if (WSREP_OK != rcode) { gu_throw_fatal << "Rollback failed. Trx: " << trx; } ++attempts; if (attempts <= max_apply_attempts) { log_warn << e.what() << "\nRetrying " << attempts << "th time"; } } else { GU_TRACE(e); throw; } } } } while (attempts <= max_apply_attempts); if (gu_unlikely(attempts > max_apply_attempts)) { std::ostringstream msg; msg << "Failed to apply trx " << trx.global_seqno() << " " << max_apply_attempts << " times"; throw galera::ApplyException(msg.str(), WSREP_CB_FAILURE); } return; } std::ostream& galera::operator<<(std::ostream& os, ReplicatorSMM::State state) { switch (state) { case ReplicatorSMM::S_DESTROYED: return (os << "DESTROYED"); case ReplicatorSMM::S_CLOSED: return (os << "CLOSED"); case ReplicatorSMM::S_CLOSING: return (os << "CLOSING"); case ReplicatorSMM::S_CONNECTED: return (os << "CONNECTED"); case ReplicatorSMM::S_JOINING: return (os << "JOINING"); case ReplicatorSMM::S_JOINED: return (os << "JOINED"); case ReplicatorSMM::S_SYNCED: return (os << "SYNCED"); case ReplicatorSMM::S_DONOR: return (os << "DONOR"); } gu_throw_fatal << "invalid state " << static_cast<int>(state); } ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Public ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// galera::ReplicatorSMM::ReplicatorSMM(const struct wsrep_init_args* args) : init_lib_ (reinterpret_cast<gu_log_cb_t>(args->logger_cb)), config_ (), init_config_ (config_, args->node_address), parse_options_ (config_, args->options), str_proto_ver_ (-1), protocol_version_ (-1), proto_max_ (gu::from_string<int>(config_.get(Param::proto_max))), state_ (S_CLOSED), sst_state_ (SST_NONE), co_mode_ (CommitOrder::from_string( config_.get(Param::commit_order))), data_dir_ (args->data_dir ? args->data_dir : ""), state_file_ (data_dir_.length() ? data_dir_+'/'+GALERA_STATE_FILE : GALERA_STATE_FILE), st_ (state_file_), trx_params_ (data_dir_, -1, KeySet::version(config_.get(Param::key_format)), gu::from_string<int>(config_.get( Param::max_write_set_size))), uuid_ (WSREP_UUID_UNDEFINED), state_uuid_ (WSREP_UUID_UNDEFINED), state_uuid_str_ (), cc_seqno_ (WSREP_SEQNO_UNDEFINED), pause_seqno_ (WSREP_SEQNO_UNDEFINED), app_ctx_ (args->app_ctx), view_cb_ (args->view_handler_cb), apply_cb_ (args->apply_cb), commit_cb_ (args->commit_cb), unordered_cb_ (args->unordered_cb), sst_donate_cb_ (args->sst_donate_cb), synced_cb_ (args->synced_cb), sst_donor_ (), sst_uuid_ (WSREP_UUID_UNDEFINED), sst_seqno_ (WSREP_SEQNO_UNDEFINED), sst_mutex_ (), sst_cond_ (), sst_retry_sec_ (1), ist_sst_ (false), gcache_ (config_, data_dir_), gcs_ (config_, gcache_, proto_max_, args->proto_ver, args->node_name, args->node_incoming), service_thd_ (gcs_, gcache_), as_ (0), gcs_as_ (gcs_, *this, gcache_), ist_receiver_ (config_, args->node_address), ist_senders_ (gcs_, gcache_), wsdb_ (), cert_ (config_, service_thd_), local_monitor_ (), apply_monitor_ (), commit_monitor_ (), causal_read_timeout_(config_.get(Param::causal_read_timeout)), receivers_ (), replicated_ (), replicated_bytes_ (), keys_count_ (), keys_bytes_ (), data_bytes_ (), unrd_bytes_ (), local_commits_ (), local_rollbacks_ (), local_cert_failures_(), local_replays_ (), causal_reads_ (), preordered_id_ (), incoming_list_ (""), incoming_mutex_ (), wsrep_stats_ () { // @todo add guards (and perhaps actions) state_.add_transition(Transition(S_CLOSED, S_DESTROYED)); state_.add_transition(Transition(S_CLOSED, S_CONNECTED)); state_.add_transition(Transition(S_CLOSING, S_CLOSED)); state_.add_transition(Transition(S_CONNECTED, S_CLOSING)); state_.add_transition(Transition(S_CONNECTED, S_CONNECTED)); state_.add_transition(Transition(S_CONNECTED, S_JOINING)); // the following is possible only when bootstrapping new cluster // (trivial wsrep_cluster_address) state_.add_transition(Transition(S_CONNECTED, S_JOINED)); // the following are possible on PC remerge state_.add_transition(Transition(S_CONNECTED, S_DONOR)); state_.add_transition(Transition(S_CONNECTED, S_SYNCED)); state_.add_transition(Transition(S_JOINING, S_CLOSING)); // the following is possible if one non-prim conf follows another state_.add_transition(Transition(S_JOINING, S_CONNECTED)); state_.add_transition(Transition(S_JOINING, S_JOINED)); state_.add_transition(Transition(S_JOINED, S_CLOSING)); state_.add_transition(Transition(S_JOINED, S_CONNECTED)); state_.add_transition(Transition(S_JOINED, S_SYNCED)); state_.add_transition(Transition(S_SYNCED, S_CLOSING)); state_.add_transition(Transition(S_SYNCED, S_CONNECTED)); state_.add_transition(Transition(S_SYNCED, S_DONOR)); state_.add_transition(Transition(S_DONOR, S_CLOSING)); state_.add_transition(Transition(S_DONOR, S_CONNECTED)); state_.add_transition(Transition(S_DONOR, S_JOINED)); local_monitor_.set_initial_position(0); wsrep_uuid_t uuid; wsrep_seqno_t seqno; st_.get (uuid, seqno); if (0 != args->state_id && args->state_id->uuid != WSREP_UUID_UNDEFINED && args->state_id->uuid == uuid && seqno == WSREP_SEQNO_UNDEFINED) { /* non-trivial recovery information provided on startup, and db is safe * so use recovered seqno value */ seqno = args->state_id->seqno; } log_debug << "End state: " << uuid << ':' << seqno << " #################"; update_state_uuid (uuid); cc_seqno_ = seqno; // is it needed here? apply_monitor_.set_initial_position(seqno); if (co_mode_ != CommitOrder::BYPASS) commit_monitor_.set_initial_position(seqno); cert_.assign_initial_position(seqno, trx_proto_ver()); build_stats_vars(wsrep_stats_); } galera::ReplicatorSMM::~ReplicatorSMM() { log_info << "dtor state: " << state_(); switch (state_()) { case S_CONNECTED: case S_JOINING: case S_JOINED: case S_SYNCED: case S_DONOR: close(); case S_CLOSING: // @todo wait that all users have left the building case S_CLOSED: ist_senders_.cancel(); break; case S_DESTROYED: break; } } wsrep_status_t galera::ReplicatorSMM::connect(const std::string& cluster_name, const std::string& cluster_url, const std::string& state_donor, bool const bootstrap) { sst_donor_ = state_donor; service_thd_.reset(); ssize_t err; wsrep_status_t ret(WSREP_OK); wsrep_seqno_t const seqno(cert_.position()); wsrep_uuid_t const gcs_uuid(seqno < 0 ? WSREP_UUID_UNDEFINED :state_uuid_); log_info << "Setting initial position to " << gcs_uuid << ':' << seqno; if ((err = gcs_.set_initial_position(gcs_uuid, seqno)) != 0) { log_error << "gcs init failed:" << strerror(-err); ret = WSREP_NODE_FAIL; } gcache_.reset(); if (ret == WSREP_OK && (err = gcs_.connect(cluster_name, cluster_url, bootstrap)) != 0) { log_error << "gcs connect failed: " << strerror(-err); ret = WSREP_NODE_FAIL; } if (ret == WSREP_OK) { state_.shift_to(S_CONNECTED); } return ret; } wsrep_status_t galera::ReplicatorSMM::close() { if (state_() != S_CLOSED) { gcs_.close(); } return WSREP_OK; } wsrep_status_t galera::ReplicatorSMM::async_recv(void* recv_ctx) { assert(recv_ctx != 0); if (state_() == S_CLOSED || state_() == S_CLOSING) { log_error <<"async recv cannot start, provider in closed/closing state"; return WSREP_FATAL; } ++receivers_; as_ = &gcs_as_; bool exit_loop(false); wsrep_status_t retval(WSREP_OK); while (WSREP_OK == retval && state_() != S_CLOSING) { ssize_t rc; while (gu_unlikely((rc = as_->process(recv_ctx, exit_loop)) == -ECANCELED)) { recv_IST(recv_ctx); // hack: prevent fast looping until ist controlling thread // resumes gcs prosessing usleep(10000); } if (gu_unlikely(rc <= 0)) { retval = WSREP_CONN_FAIL; } else if (gu_unlikely(exit_loop == true)) { assert(WSREP_OK == retval); if (receivers_.sub_and_fetch(1) > 0) { log_info << "Slave thread exiting on request."; break; } ++receivers_; log_warn << "Refusing exit for the last slave thread."; } } /* exiting loop already did proper checks */ if (!exit_loop && receivers_.sub_and_fetch(1) == 0) { if (state_() != S_CLOSING) { log_warn << "Broken shutdown sequence, provider state: " << state_() << ", retval: " << retval; assert (0); /* avoid abort in production */ state_.shift_to(S_CLOSING); } state_.shift_to(S_CLOSED); } log_debug << "Slave thread exit. Return code: " << retval; return retval; } void galera::ReplicatorSMM::apply_trx(void* recv_ctx, TrxHandle* trx) { assert(trx != 0); assert(trx->global_seqno() > 0); assert(trx->is_certified() == true); assert(trx->global_seqno() > apply_monitor_.last_left()); assert(trx->is_local() == false); ApplyOrder ao(*trx); CommitOrder co(*trx, co_mode_); gu_trace(apply_monitor_.enter(ao)); trx->set_state(TrxHandle::S_APPLYING); wsrep_trx_meta_t meta = {{state_uuid_, trx->global_seqno() }, trx->depends_seqno()}; gu_trace(apply_trx_ws(recv_ctx, apply_cb_, commit_cb_, *trx, meta)); /* at this point any exception in apply_trx_ws() is fatal, not * catching anything. */ if (gu_likely(co_mode_ != CommitOrder::BYPASS)) { gu_trace(commit_monitor_.enter(co)); } trx->set_state(TrxHandle::S_COMMITTING); wsrep_bool_t exit_loop(false); wsrep_cb_status_t const rcode( commit_cb_( recv_ctx, TrxHandle::trx_flags_to_wsrep_flags(trx->flags()), &meta, &exit_loop, true)); if (gu_unlikely (rcode > 0)) gu_throw_fatal << "Commit failed. Trx: " << trx; if (gu_likely(co_mode_ != CommitOrder::BYPASS)) { commit_monitor_.leave(co); } trx->set_state(TrxHandle::S_COMMITTED); if (trx->local_seqno() != -1) { // trx with local seqno -1 originates from IST (or other source not gcs) report_last_committed(cert_.set_trx_committed(trx)); } /* For now need to keep it inside apply monitor to ensure all processing * ends by the time monitors are drained because of potential gcache * cleanup (and loss of the writeset buffer). Perhaps unordered monitor * is needed here. */ trx->unordered(recv_ctx, unordered_cb_); apply_monitor_.leave(ao); trx->set_exit_loop(exit_loop); } wsrep_status_t galera::ReplicatorSMM::replicate(TrxHandle* trx, wsrep_trx_meta_t* meta) { if (state_() < S_JOINED) return WSREP_TRX_FAIL; assert(trx->state() == TrxHandle::S_EXECUTING || trx->state() == TrxHandle::S_MUST_ABORT); assert(trx->local_seqno() == WSREP_SEQNO_UNDEFINED && trx->global_seqno() == WSREP_SEQNO_UNDEFINED); wsrep_status_t retval(WSREP_TRX_FAIL); if (trx->state() == TrxHandle::S_MUST_ABORT) { must_abort: trx->set_state(TrxHandle::S_ABORTING); return retval; } WriteSetNG::GatherVector actv; gcs_action act; act.type = GCS_ACT_TORDERED; #ifndef NDEBUG act.seqno_g = GCS_SEQNO_ILL; #endif if (trx->new_version()) { act.buf = NULL; act.size = trx->write_set_out().gather(trx->source_id(), trx->conn_id(), trx->trx_id(), actv); } else { trx->set_last_seen_seqno(last_committed()); assert (trx->last_seen_seqno() >= 0); trx->flush(0); const MappedBuffer& wscoll(trx->write_set_collection()); act.buf = &wscoll[0]; act.size = wscoll.size(); assert (act.buf != NULL); assert (act.size > 0); } trx->set_state(TrxHandle::S_REPLICATING); ssize_t rcode(-1); do { assert(act.seqno_g == GCS_SEQNO_ILL); const ssize_t gcs_handle(gcs_.schedule()); if (gu_unlikely(gcs_handle < 0)) { log_debug << "gcs schedule " << strerror(-gcs_handle); trx->set_state(TrxHandle::S_MUST_ABORT); goto must_abort; } trx->set_gcs_handle(gcs_handle); if (trx->new_version()) { trx->set_last_seen_seqno(last_committed()); assert(trx->last_seen_seqno() >= 0); trx->unlock(); assert (act.buf == NULL); // just a sanity check rcode = gcs_.replv(actv, act, true); } else { assert(trx->last_seen_seqno() >= 0); trx->unlock(); assert (act.buf != NULL); rcode = gcs_.repl(act, true); } trx->lock(); } while (rcode == -EAGAIN && trx->state() != TrxHandle::S_MUST_ABORT && (usleep(1000), true)); assert(trx->last_seen_seqno() >= 0); if (rcode < 0) { if (rcode != -EINTR) { log_debug << "gcs_repl() failed with " << strerror(-rcode) << " for trx " << *trx; } assert(rcode != -EINTR || trx->state() == TrxHandle::S_MUST_ABORT); assert(act.seqno_l == GCS_SEQNO_ILL && act.seqno_g == GCS_SEQNO_ILL); assert(NULL == act.buf || !trx->new_version()); if (trx->state() != TrxHandle::S_MUST_ABORT) { trx->set_state(TrxHandle::S_MUST_ABORT); } trx->set_gcs_handle(-1); goto must_abort; } assert(act.buf != NULL); assert(act.size == rcode); assert(act.seqno_l != GCS_SEQNO_ILL); assert(act.seqno_g != GCS_SEQNO_ILL); ++replicated_; replicated_bytes_ += rcode; trx->set_gcs_handle(-1); if (trx->new_version()) { gu_trace(trx->unserialize(static_cast<const gu::byte_t*>(act.buf), act.size, 0)); trx->update_stats(keys_count_, keys_bytes_, data_bytes_, unrd_bytes_); } trx->set_received(act.buf, act.seqno_l, act.seqno_g); if (trx->state() == TrxHandle::S_MUST_ABORT) { retval = cert_for_aborted(trx); if (retval != WSREP_BF_ABORT) { LocalOrder lo(*trx); ApplyOrder ao(*trx); CommitOrder co(*trx, co_mode_); local_monitor_.self_cancel(lo); apply_monitor_.self_cancel(ao); if (co_mode_ !=CommitOrder::BYPASS) commit_monitor_.self_cancel(co); } else if (meta != 0) { meta->gtid.uuid = state_uuid_; meta->gtid.seqno = trx->global_seqno(); meta->depends_on = trx->depends_seqno(); } if (trx->state() == TrxHandle::S_MUST_ABORT) goto must_abort; } else { retval = WSREP_OK; } assert(trx->last_seen_seqno() >= 0); return retval; } void galera::ReplicatorSMM::abort_trx(TrxHandle* trx) { assert(trx != 0); assert(trx->is_local() == true); log_debug << "aborting trx " << *trx << " " << trx; switch (trx->state()) { case TrxHandle::S_MUST_ABORT: case TrxHandle::S_ABORTING: // guess this is here because we can have a race return; case TrxHandle::S_EXECUTING: trx->set_state(TrxHandle::S_MUST_ABORT); break; case TrxHandle::S_REPLICATING: { trx->set_state(TrxHandle::S_MUST_ABORT); // trx is in gcs repl int rc; if (trx->gcs_handle() > 0 && ((rc = gcs_.interrupt(trx->gcs_handle()))) != 0) { log_debug << "gcs_interrupt(): handle " << trx->gcs_handle() << " trx id " << trx->trx_id() << ": " << strerror(-rc); } break; } case TrxHandle::S_CERTIFYING: { trx->set_state(TrxHandle::S_MUST_ABORT); // trx is waiting in local monitor LocalOrder lo(*trx); trx->unlock(); local_monitor_.interrupt(lo); trx->lock(); break; } case TrxHandle::S_APPLYING: { trx->set_state(TrxHandle::S_MUST_ABORT); // trx is waiting in apply monitor ApplyOrder ao(*trx); trx->unlock(); apply_monitor_.interrupt(ao); trx->lock(); break; } case TrxHandle::S_COMMITTING: trx->set_state(TrxHandle::S_MUST_ABORT); if (co_mode_ != CommitOrder::BYPASS) { // trx waiting in commit monitor CommitOrder co(*trx, co_mode_); trx->unlock(); commit_monitor_.interrupt(co); trx->lock(); } break; default: gu_throw_fatal << "invalid state " << trx->state(); } } wsrep_status_t galera::ReplicatorSMM::pre_commit(TrxHandle* trx, wsrep_trx_meta_t* meta) { assert(trx->state() == TrxHandle::S_REPLICATING); assert(trx->local_seqno() > -1); assert(trx->global_seqno() > -1); assert(trx->last_seen_seqno() >= 0); if (meta != 0) { meta->gtid.uuid = state_uuid_; meta->gtid.seqno = trx->global_seqno(); meta->depends_on = trx->depends_seqno(); } // State should not be checked here: If trx has been replicated, // it has to be certified and potentially applied. #528 // if (state_() < S_JOINED) return WSREP_TRX_FAIL; wsrep_status_t retval(cert_and_catch(trx)); if (gu_unlikely(retval != WSREP_OK)) { assert(trx->state() == TrxHandle::S_MUST_ABORT || trx->state() == TrxHandle::S_MUST_REPLAY_AM || trx->state() == TrxHandle::S_MUST_CERT_AND_REPLAY); if (trx->state() == TrxHandle::S_MUST_ABORT) { trx->set_state(TrxHandle::S_ABORTING); } return retval; } assert(trx->state() == TrxHandle::S_CERTIFYING); assert(trx->global_seqno() > apply_monitor_.last_left()); trx->set_state(TrxHandle::S_APPLYING); ApplyOrder ao(*trx); CommitOrder co(*trx, co_mode_); bool interrupted(false); try { gu_trace(apply_monitor_.enter(ao)); } catch (gu::Exception& e) { if (e.get_errno() == EINTR) { interrupted = true; } else throw; } if (gu_unlikely(interrupted) || trx->state() == TrxHandle::S_MUST_ABORT) { assert(trx->state() == TrxHandle::S_MUST_ABORT); if (interrupted) trx->set_state(TrxHandle::S_MUST_REPLAY_AM); else trx->set_state(TrxHandle::S_MUST_REPLAY_CM); retval = WSREP_BF_ABORT; } else if ((trx->flags() & TrxHandle::F_COMMIT) != 0) { trx->set_state(TrxHandle::S_COMMITTING); if (co_mode_ != CommitOrder::BYPASS) { try { gu_trace(commit_monitor_.enter(co)); } catch (gu::Exception& e) { if (e.get_errno() == EINTR) { interrupted = true; } else throw; } if (gu_unlikely(interrupted) || trx->state() == TrxHandle::S_MUST_ABORT) { assert(trx->state() == TrxHandle::S_MUST_ABORT); if (interrupted) trx->set_state(TrxHandle::S_MUST_REPLAY_CM); else trx->set_state(TrxHandle::S_MUST_REPLAY); retval = WSREP_BF_ABORT; } } } else { trx->set_state(TrxHandle::S_EXECUTING); } assert((retval == WSREP_OK && (trx->state() == TrxHandle::S_COMMITTING || trx->state() == TrxHandle::S_EXECUTING)) || (retval == WSREP_TRX_FAIL && trx->state() == TrxHandle::S_ABORTING) || (retval == WSREP_BF_ABORT && ( trx->state() == TrxHandle::S_MUST_REPLAY_AM || trx->state() == TrxHandle::S_MUST_REPLAY_CM || trx->state() == TrxHandle::S_MUST_REPLAY))); return retval; } wsrep_status_t galera::ReplicatorSMM::replay_trx(TrxHandle* trx, void* trx_ctx) { assert(trx->state() == TrxHandle::S_MUST_CERT_AND_REPLAY || trx->state() == TrxHandle::S_MUST_REPLAY_AM || trx->state() == TrxHandle::S_MUST_REPLAY_CM || trx->state() == TrxHandle::S_MUST_REPLAY); assert(trx->trx_id() != static_cast<wsrep_trx_id_t>(-1)); assert(trx->global_seqno() > apply_monitor_.last_left()); wsrep_status_t retval(WSREP_OK); switch (trx->state()) { case TrxHandle::S_MUST_CERT_AND_REPLAY: retval = cert_and_catch(trx); if (retval != WSREP_OK) { // apply monitor is self canceled in cert break; } trx->set_state(TrxHandle::S_MUST_REPLAY_AM); // fall through case TrxHandle::S_MUST_REPLAY_AM: { // safety measure to make sure that all preceding trxs finish before // replaying trx->set_depends_seqno(trx->global_seqno() - 1); ApplyOrder ao(*trx); gu_trace(apply_monitor_.enter(ao)); trx->set_state(TrxHandle::S_MUST_REPLAY_CM); // fall through } case TrxHandle::S_MUST_REPLAY_CM: if (co_mode_ != CommitOrder::BYPASS) { CommitOrder co(*trx, co_mode_); gu_trace(commit_monitor_.enter(co)); } trx->set_state(TrxHandle::S_MUST_REPLAY); // fall through case TrxHandle::S_MUST_REPLAY: ++local_replays_; trx->set_state(TrxHandle::S_REPLAYING); try { wsrep_trx_meta_t meta = {{state_uuid_, trx->global_seqno() }, trx->depends_seqno()}; gu_trace(apply_trx_ws(trx_ctx, apply_cb_, commit_cb_, *trx, meta)); wsrep_bool_t unused(false); wsrep_cb_status_t rcode( commit_cb_( trx_ctx, TrxHandle::trx_flags_to_wsrep_flags(trx->flags()), &meta, &unused, true)); if (gu_unlikely(rcode > 0)) gu_throw_fatal << "Commit failed. Trx: " << trx; } catch (gu::Exception& e) { st_.mark_corrupt(); throw; } // apply, commit monitors are released in post commit return WSREP_OK; default: gu_throw_fatal << "Invalid state in replay for trx " << *trx; } log_debug << "replaying failed for trx " << *trx; trx->set_state(TrxHandle::S_ABORTING); return retval; } wsrep_status_t galera::ReplicatorSMM::post_commit(TrxHandle* trx) { if (trx->state() == TrxHandle::S_MUST_ABORT) { // This is possible in case of ALG: BF applier BF aborts // trx that has already grabbed commit monitor and is committing. // However, this should be acceptable assuming that commit // operation does not reserve any more resources and is able // to release already reserved resources. log_debug << "trx was BF aborted during commit: " << *trx; // manipulate state to avoid crash trx->set_state(TrxHandle::S_MUST_REPLAY); trx->set_state(TrxHandle::S_REPLAYING); } assert(trx->state() == TrxHandle::S_COMMITTING || trx->state() == TrxHandle::S_REPLAYING); assert(trx->local_seqno() > -1 && trx->global_seqno() > -1); CommitOrder co(*trx, co_mode_); if (co_mode_ != CommitOrder::BYPASS) commit_monitor_.leave(co); ApplyOrder ao(*trx); report_last_committed(cert_.set_trx_committed(trx)); apply_monitor_.leave(ao); trx->set_state(TrxHandle::S_COMMITTED); ++local_commits_; return WSREP_OK; } wsrep_status_t galera::ReplicatorSMM::post_rollback(TrxHandle* trx) { if (trx->state() == TrxHandle::S_MUST_ABORT) { trx->set_state(TrxHandle::S_ABORTING); } assert(trx->state() == TrxHandle::S_ABORTING || trx->state() == TrxHandle::S_EXECUTING); trx->set_state(TrxHandle::S_ROLLED_BACK); // Trx was either rolled back by user or via certification failure, // last committed report not needed since cert index state didn't change. // report_last_committed(); ++local_rollbacks_; return WSREP_OK; } wsrep_status_t galera::ReplicatorSMM::causal_read(wsrep_gtid_t* gtid) { wsrep_seqno_t cseq(static_cast<wsrep_seqno_t>(gcs_.caused())); if (cseq < 0) { log_warn << "gcs_caused() returned " << cseq << " (" << strerror(-cseq) << ')'; return WSREP_TRX_FAIL; } try { // @note: Using timed wait for monitor is currently a hack // to avoid deadlock resulting from race between monitor wait // and drain during configuration change. Instead of this, // monitor should have proper mechanism to interrupt waiters // at monitor drain and disallowing further waits until // configuration change related operations (SST etc) have been // finished. gu::datetime::Date wait_until(gu::datetime::Date::calendar() + causal_read_timeout_); if (gu_likely(co_mode_ != CommitOrder::BYPASS)) { commit_monitor_.wait(cseq, wait_until); } else { apply_monitor_.wait(cseq, wait_until); } if (gtid != 0) { gtid->uuid = state_uuid_; gtid->seqno = cseq; } ++causal_reads_; return WSREP_OK; } catch (gu::Exception& e) { log_debug << "monitor wait failed for causal read: " << e.what(); return WSREP_TRX_FAIL; } } wsrep_status_t galera::ReplicatorSMM::to_isolation_begin(TrxHandle* trx, wsrep_trx_meta_t* meta) { if (meta != 0) { meta->gtid.uuid = state_uuid_; meta->gtid.seqno = trx->global_seqno(); meta->depends_on = trx->depends_seqno(); } assert(trx->state() == TrxHandle::S_REPLICATING); assert(trx->trx_id() == static_cast<wsrep_trx_id_t>(-1)); assert(trx->local_seqno() > -1 && trx->global_seqno() > -1); assert(trx->global_seqno() > apply_monitor_.last_left()); wsrep_status_t retval; switch ((retval = cert_and_catch(trx))) { case WSREP_OK: { ApplyOrder ao(*trx); CommitOrder co(*trx, co_mode_); gu_trace(apply_monitor_.enter(ao)); if (co_mode_ != CommitOrder::BYPASS) try { commit_monitor_.enter(co); } catch (...) { gu_throw_fatal << "unable to enter commit monitor: " << *trx; } trx->set_state(TrxHandle::S_APPLYING); log_debug << "Executing TO isolated action: " << *trx; st_.mark_unsafe(); break; } case WSREP_TRX_FAIL: // Apply monitor is released in cert() in case of failure. trx->set_state(TrxHandle::S_ABORTING); break; default: log_error << "unrecognized retval " << retval << " for to isolation certification for " << *trx; retval = WSREP_FATAL; break; } return retval; } wsrep_status_t galera::ReplicatorSMM::to_isolation_end(TrxHandle* trx) { assert(trx->state() == TrxHandle::S_APPLYING); log_debug << "Done executing TO isolated action: " << *trx; CommitOrder co(*trx, co_mode_); if (co_mode_ != CommitOrder::BYPASS) commit_monitor_.leave(co); ApplyOrder ao(*trx); report_last_committed(cert_.set_trx_committed(trx)); apply_monitor_.leave(ao); st_.mark_safe(); return WSREP_OK; } namespace galera { static WriteSetOut* writeset_from_handle (wsrep_po_handle_t& handle, const TrxHandle::Params& trx_params) { WriteSetOut* ret = reinterpret_cast<WriteSetOut*>(handle.opaque); if (NULL == ret) { try { ret = new WriteSetOut( // gu::String<256>(trx_params.working_dir_) << '/' << &handle, trx_params.working_dir_, wsrep_trx_id_t(&handle), /* key format is not essential since we're not adding keys */ KeySet::version(trx_params.key_format_), NULL, 0, 0, WriteSetNG::MAX_VERSION, DataSet::MAX_VERSION, DataSet::MAX_VERSION, trx_params.max_write_set_size_); handle.opaque = ret; } catch (std::bad_alloc& ba) { gu_throw_error(ENOMEM) << "Could not create WriteSetOut"; } } return ret; } } /* namespace galera */ wsrep_status_t galera::ReplicatorSMM::preordered_collect(wsrep_po_handle_t& handle, const struct wsrep_buf* const data, size_t const count, bool const copy) { if (gu_unlikely(trx_params_.version_ < WS_NG_VERSION)) return WSREP_NOT_IMPLEMENTED; WriteSetOut* const ws(writeset_from_handle(handle, trx_params_)); for (size_t i(0); i < count; ++i) { ws->append_data(data[i].ptr, data[i].len, copy); } return WSREP_OK; } wsrep_status_t galera::ReplicatorSMM::preordered_commit(wsrep_po_handle_t& handle, const wsrep_uuid_t& source, uint64_t const flags, int const pa_range, bool const commit) { if (gu_unlikely(trx_params_.version_ < WS_NG_VERSION)) return WSREP_NOT_IMPLEMENTED; WriteSetOut* const ws(writeset_from_handle(handle, trx_params_)); if (gu_likely(true == commit)) { ws->set_flags (WriteSetNG::wsrep_flags_to_ws_flags(flags)); /* by loooking at trx_id we should be able to detect gaps / lost events * (however resending is not implemented yet). Something like * * wsrep_trx_id_t const trx_id(cert_.append_preordered(source, ws)); * * begs to be here. */ wsrep_trx_id_t const trx_id(preordered_id_.add_and_fetch(1)); WriteSetNG::GatherVector actv; size_t const actv_size(ws->gather(source, 0, trx_id, actv)); ws->set_preordered (pa_range); // also adds CRC int rcode; do { rcode = gcs_.sendv(actv, actv_size, GCS_ACT_TORDERED, false); } while (rcode == -EAGAIN && (usleep(1000), true)); if (rcode < 0) gu_throw_error(-rcode) << "Replication of preordered writeset failed."; } delete ws; handle.opaque = NULL; return WSREP_OK; } wsrep_status_t galera::ReplicatorSMM::sst_sent(const wsrep_gtid_t& state_id, int const rcode) { assert (rcode <= 0); assert (rcode == 0 || state_id.seqno == WSREP_SEQNO_UNDEFINED); assert (rcode != 0 || state_id.seqno >= 0); if (state_() != S_DONOR) { log_error << "sst sent called when not SST donor, state " << state_(); return WSREP_CONN_FAIL; } gcs_seqno_t seqno(rcode ? rcode : state_id.seqno); if (state_id.uuid != state_uuid_ && seqno >= 0) { // state we have sent no longer corresponds to the current group state // mark an error seqno = -EREMCHG; } try { // #557 - remove this if() when we return back to joining after SST if (!ist_sst_ || rcode < 0) gcs_.join(seqno); ist_sst_ = false; return WSREP_OK; } catch (gu::Exception& e) { log_error << "failed to recover from DONOR state: " << e.what(); return WSREP_CONN_FAIL; } } void galera::ReplicatorSMM::process_trx(void* recv_ctx, TrxHandle* trx) { assert(recv_ctx != 0); assert(trx != 0); assert(trx->local_seqno() > 0); assert(trx->global_seqno() > 0); assert(trx->last_seen_seqno() >= 0); assert(trx->depends_seqno() == -1); assert(trx->state() == TrxHandle::S_REPLICATING); wsrep_status_t const retval(cert_and_catch(trx)); switch (retval) { case WSREP_OK: try { gu_trace(apply_trx(recv_ctx, trx)); } catch (std::exception& e) { st_.mark_corrupt(); log_fatal << "Failed to apply trx: " << *trx; log_fatal << e.what(); log_fatal << "Node consistency compromized, aborting..."; abort(); } break; case WSREP_TRX_FAIL: // certification failed, apply monitor has been canceled trx->set_state(TrxHandle::S_ABORTING); trx->set_state(TrxHandle::S_ROLLED_BACK); break; default: // this should not happen for remote actions gu_throw_error(EINVAL) << "unrecognized retval for remote trx certification: " << retval << " trx: " << *trx; } } void galera::ReplicatorSMM::process_commit_cut(wsrep_seqno_t seq, wsrep_seqno_t seqno_l) { assert(seq > 0); assert(seqno_l > 0); LocalOrder lo(seqno_l); gu_trace(local_monitor_.enter(lo)); if (seq >= cc_seqno_) /* Refs #782. workaround for * assert(seqno >= seqno_released_) in gcache. */ cert_.purge_trxs_upto(seq, true); local_monitor_.leave(lo); log_debug << "Got commit cut from GCS: " << seq; } void galera::ReplicatorSMM::establish_protocol_versions (int proto_ver) { switch (proto_ver) { case 1: trx_params_.version_ = 1; str_proto_ver_ = 0; break; case 2: trx_params_.version_ = 1; str_proto_ver_ = 1; break; case 3: case 4: trx_params_.version_ = 2; str_proto_ver_ = 1; break; case 5: trx_params_.version_ = 3; str_proto_ver_ = 1; break; default: log_fatal << "Configuration change resulted in an unsupported protocol " "version: " << proto_ver << ". Can't continue."; abort(); }; protocol_version_ = proto_ver; log_info << "REPL Protocols: " << protocol_version_ << " (" << trx_params_.version_ << ", " << str_proto_ver_ << ")"; } static bool app_wants_state_transfer (const void* const req, ssize_t const req_len) { return (req_len != (strlen(WSREP_STATE_TRANSFER_NONE) + 1) || memcmp(req, WSREP_STATE_TRANSFER_NONE, req_len)); } void galera::ReplicatorSMM::update_incoming_list(const wsrep_view_info_t& view) { static char const separator(','); ssize_t new_size(0); if (view.memb_num > 0) { new_size += view.memb_num - 1; // separators for (int i = 0; i < view.memb_num; ++i) { new_size += strlen(view.members[i].incoming); } } gu::Lock lock(incoming_mutex_); incoming_list_.clear(); incoming_list_.resize(new_size); if (new_size <= 0) return; incoming_list_ = view.members[0].incoming; for (int i = 1; i < view.memb_num; ++i) { incoming_list_ += separator; incoming_list_ += view.members[i].incoming; } } void galera::ReplicatorSMM::process_conf_change(void* recv_ctx, const wsrep_view_info_t& view_info, int repl_proto, State next_state, wsrep_seqno_t seqno_l) { assert(seqno_l > -1); update_incoming_list(view_info); LocalOrder lo(seqno_l); gu_trace(local_monitor_.enter(lo)); wsrep_seqno_t const upto(cert_.position()); apply_monitor_.drain(upto); if (co_mode_ != CommitOrder::BYPASS) commit_monitor_.drain(upto); if (view_info.my_idx >= 0) { uuid_ = view_info.members[view_info.my_idx].id; } bool const st_required(state_transfer_required(view_info)); wsrep_seqno_t const group_seqno(view_info.state_id.seqno); const wsrep_uuid_t& group_uuid (view_info.state_id.uuid); if (st_required) { log_info << "State transfer required: " << "\n\tGroup state: " << group_uuid << ":" << group_seqno << "\n\tLocal state: " << state_uuid_<< ":" << apply_monitor_.last_left(); if (S_CONNECTED != state_()) state_.shift_to(S_CONNECTED); } void* app_req(0); size_t app_req_len(0); const_cast<wsrep_view_info_t&>(view_info).state_gap = st_required; wsrep_cb_status_t const rcode( view_cb_(app_ctx_, recv_ctx, &view_info, 0, 0, &app_req, &app_req_len)); if (WSREP_CB_SUCCESS != rcode) { assert(app_req_len <= 0); close(); gu_throw_fatal << "View callback failed. This is unrecoverable, " "restart required."; } else if (st_required && 0 == app_req_len && state_uuid_ != group_uuid) { close(); gu_throw_fatal << "Local state UUID " << state_uuid_ << " is different from group state UUID " << group_uuid << ", and SST request is null: restart required."; } if (view_info.view >= 0) // Primary configuration { establish_protocol_versions (repl_proto); // we have to reset cert initial position here, SST does not contain // cert index yet (see #197). cert_.assign_initial_position(group_seqno, trx_params_.version_); // at this point there is no ongoing master or slave transactions // and no new requests to service thread should be possible service_thd_.flush(); // make sure service thd is idle if (upto > 0) gcache_.seqno_release(upto); // make sure all gcache // buffers are released // record state seqno, needed for IST on DONOR cc_seqno_ = group_seqno; bool const app_wants_st(app_wants_state_transfer(app_req, app_req_len)); if (st_required && app_wants_st) { // GCache::Seqno_reset() happens here request_state_transfer (recv_ctx, group_uuid, group_seqno, app_req, app_req_len); } else { if (view_info.view == 1 || !app_wants_st) { update_state_uuid (group_uuid); apply_monitor_.set_initial_position(group_seqno); if (co_mode_ != CommitOrder::BYPASS) commit_monitor_.set_initial_position(group_seqno); } if (state_() == S_CONNECTED || state_() == S_DONOR) { switch (next_state) { case S_JOINING: state_.shift_to(S_JOINING); break; case S_DONOR: if (state_() == S_CONNECTED) { state_.shift_to(S_DONOR); } break; case S_JOINED: state_.shift_to(S_JOINED); break; case S_SYNCED: state_.shift_to(S_SYNCED); synced_cb_(app_ctx_); break; default: log_debug << "next_state " << next_state; break; } } st_.set(state_uuid_, WSREP_SEQNO_UNDEFINED); } if (state_() == S_JOINING && sst_state_ != SST_NONE) { /* There are two reasons we can be here: * 1) we just got state transfer in request_state_transfer() above; * 2) we failed here previously (probably due to partition). */ try { gcs_.join(sst_seqno_); sst_state_ = SST_NONE; } catch (gu::Exception& e) { log_error << "Failed to JOIN the cluster after SST"; } } } else { // Non-primary configuration if (state_uuid_ != WSREP_UUID_UNDEFINED) { st_.set (state_uuid_, apply_monitor_.last_left()); } if (next_state != S_CONNECTED && next_state != S_CLOSING) { log_fatal << "Internal error: unexpected next state for " << "non-prim: " << next_state << ". Restart required."; abort(); } state_.shift_to(next_state); } local_monitor_.leave(lo); gcs_.resume_recv(); free(app_req); } void galera::ReplicatorSMM::process_join(wsrep_seqno_t seqno_j, wsrep_seqno_t seqno_l) { LocalOrder lo(seqno_l); gu_trace(local_monitor_.enter(lo)); wsrep_seqno_t const upto(cert_.position()); apply_monitor_.drain(upto); if (co_mode_ != CommitOrder::BYPASS) commit_monitor_.drain(upto); if (seqno_j < 0 && S_JOINING == state_()) { // #595, @todo: find a way to re-request state transfer log_fatal << "Failed to receive state transfer: " << seqno_j << " (" << strerror (-seqno_j) << "), need to restart."; abort(); } else { state_.shift_to(S_JOINED); } local_monitor_.leave(lo); } void galera::ReplicatorSMM::process_sync(wsrep_seqno_t seqno_l) { LocalOrder lo(seqno_l); gu_trace(local_monitor_.enter(lo)); wsrep_seqno_t const upto(cert_.position()); apply_monitor_.drain(upto); if (co_mode_ != CommitOrder::BYPASS) commit_monitor_.drain(upto); state_.shift_to(S_SYNCED); synced_cb_(app_ctx_); local_monitor_.leave(lo); } wsrep_seqno_t galera::ReplicatorSMM::pause() { // Grab local seqno for local_monitor_ wsrep_seqno_t const local_seqno( static_cast<wsrep_seqno_t>(gcs_.local_sequence())); LocalOrder lo(local_seqno); local_monitor_.enter(lo); // Local monitor should take care that concurrent // pause requests are enqueued assert(pause_seqno_ == WSREP_SEQNO_UNDEFINED); pause_seqno_ = local_seqno; // Get drain seqno from cert index wsrep_seqno_t const ret(cert_.position()); apply_monitor_.drain(ret); assert (apply_monitor_.last_left() >= ret); if (co_mode_ != CommitOrder::BYPASS) { commit_monitor_.drain(ret); assert (commit_monitor_.last_left() >= ret); } st_.set(state_uuid_, ret); log_info << "Provider paused at " << state_uuid_ << ':' << ret << " (" << pause_seqno_ << ")"; return ret; } void galera::ReplicatorSMM::resume() { assert(pause_seqno_ != WSREP_SEQNO_UNDEFINED); if (pause_seqno_ == WSREP_SEQNO_UNDEFINED) { gu_throw_error(EALREADY) << "tried to resume unpaused provider"; } st_.set(state_uuid_, WSREP_SEQNO_UNDEFINED); log_info << "resuming provider at " << pause_seqno_; LocalOrder lo(pause_seqno_); pause_seqno_ = WSREP_SEQNO_UNDEFINED; local_monitor_.leave(lo); log_info << "Provider resumed."; } void galera::ReplicatorSMM::desync() { wsrep_seqno_t seqno_l; ssize_t const ret(gcs_.desync(&seqno_l)); if (seqno_l > 0) { LocalOrder lo(seqno_l); // need to process it regardless of ret value if (ret == 0) { /* #706 - the check below must be state request-specific. We are not holding any locks here and must be able to wait like any other action. However practice may prove different, leaving it here as a reminder. if (local_monitor_.would_block(seqno_l)) { gu_throw_error (-EDEADLK) << "Ran out of resources waiting to " << "desync the node. " << "The node must be restarted."; } */ local_monitor_.enter(lo); state_.shift_to(S_DONOR); local_monitor_.leave(lo); } else { local_monitor_.self_cancel(lo); } } if (ret) { gu_throw_error (-ret) << "Node desync failed."; } } void galera::ReplicatorSMM::resync() { gcs_.join(commit_monitor_.last_left()); } ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// //// Private ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /* don't use this directly, use cert_and_catch() instead */ inline wsrep_status_t galera::ReplicatorSMM::cert(TrxHandle* trx) { assert(trx->state() == TrxHandle::S_REPLICATING || trx->state() == TrxHandle::S_MUST_CERT_AND_REPLAY); assert(trx->local_seqno() != WSREP_SEQNO_UNDEFINED); assert(trx->global_seqno() != WSREP_SEQNO_UNDEFINED); assert(trx->last_seen_seqno() >= 0); assert(trx->last_seen_seqno() < trx->global_seqno()); trx->set_state(TrxHandle::S_CERTIFYING); LocalOrder lo(*trx); ApplyOrder ao(*trx); CommitOrder co(*trx, co_mode_); bool interrupted(false); try { gu_trace(local_monitor_.enter(lo)); } catch (gu::Exception& e) { if (e.get_errno() == EINTR) { interrupted = true; } else throw; } wsrep_status_t retval(WSREP_OK); bool const applicable(trx->global_seqno() > apply_monitor_.last_left()); if (gu_likely (!interrupted)) { switch (cert_.append_trx(trx)) { case Certification::TEST_OK: if (gu_likely(applicable)) { if (trx->state() == TrxHandle::S_CERTIFYING) { retval = WSREP_OK; } else { assert(trx->state() == TrxHandle::S_MUST_ABORT); trx->set_state(TrxHandle::S_MUST_REPLAY_AM); retval = WSREP_BF_ABORT; } } else { // this can happen after SST position has been submitted // but not all actions preceding SST initial position // have been processed trx->set_state(TrxHandle::S_MUST_ABORT); retval = WSREP_TRX_FAIL; } break; case Certification::TEST_FAILED: if (gu_unlikely(trx->is_toi() && applicable)) // small sanity check { // may happen on configuration change log_warn << "Certification failed for TO isolated action: " << *trx; assert(0); } local_cert_failures_ += trx->is_local(); trx->set_state(TrxHandle::S_MUST_ABORT); retval = WSREP_TRX_FAIL; break; } if (gu_unlikely(WSREP_TRX_FAIL == retval)) { report_last_committed(cert_.set_trx_committed(trx)); } // at this point we are about to leave local_monitor_. Make sure // trx checksum was alright before that. trx->verify_checksum(); // we must do it 'in order' for std::map reasons, so keeping // it inside the monitor gcache_.seqno_assign (trx->action(), trx->global_seqno(), trx->depends_seqno()); local_monitor_.leave(lo); } else { retval = cert_for_aborted(trx); if (WSREP_TRX_FAIL == retval) { local_monitor_.self_cancel(lo); } else { assert(WSREP_BF_ABORT == retval); } } if (gu_unlikely(WSREP_TRX_FAIL == retval && applicable)) { // applicable but failed certification: self-cancel monitors apply_monitor_.self_cancel(ao); if (co_mode_ != CommitOrder::BYPASS) commit_monitor_.self_cancel(co); } return retval; } /* pretty much any exception in cert() is fatal as it blocks local_monitor_ */ wsrep_status_t galera::ReplicatorSMM::cert_and_catch(TrxHandle* trx) { try { return cert(trx); } catch (std::exception& e) { log_fatal << "Certification exception: " << e.what(); } catch (...) { log_fatal << "Unknown certification exception"; } abort(); } /* This must be called BEFORE local_monitor_.self_cancel() due to * gcache_.seqno_assign() */ wsrep_status_t galera::ReplicatorSMM::cert_for_aborted(TrxHandle* trx) { Certification::TestResult const res(cert_.test(trx, false)); switch (res) { case Certification::TEST_OK: trx->set_state(TrxHandle::S_MUST_CERT_AND_REPLAY); return WSREP_BF_ABORT; case Certification::TEST_FAILED: if (trx->state() != TrxHandle::S_MUST_ABORT) { trx->set_state(TrxHandle::S_MUST_ABORT); } // Mext step will be monitors release. Make sure that ws was not // corrupted and cert failure is real before procedeing with that. trx->verify_checksum(); gcache_.seqno_assign (trx->action(), trx->global_seqno(), -1); return WSREP_TRX_FAIL; default: log_fatal << "Unexpected return value from Certification::test(): " << res; abort(); } } void galera::ReplicatorSMM::update_state_uuid (const wsrep_uuid_t& uuid) { if (state_uuid_ != uuid) { *(const_cast<wsrep_uuid_t*>(&state_uuid_)) = uuid; std::ostringstream os; os << state_uuid_; strncpy(const_cast<char*>(state_uuid_str_), os.str().c_str(), sizeof(state_uuid_str_)); } st_.set(uuid, WSREP_SEQNO_UNDEFINED); } void galera::ReplicatorSMM::abort() { gcs_.close(); gu_abort(); }
edf-hpc/galera
galera/src/replicator_smm.cpp
C++
gpl-2.0
54,183
<?php global $contractor_id; $categories_permitted = fv_get_contractor_membership_addon_categories($contractor_id); //Message count if ( $contractor_id ) { $message_count = SF_Message::get_message_ids_sent_to($contractor_id); $project_count = SF_Project::get_project_ids_for_contractor($contractor_id); } $author_link = get_the_permalink($contractor_id); ?> <div class="hero blue-hero contractor edit-profile"> <div class="container"> <?php $featured_thumb = get_the_post_thumbnail($contractor_id, array(130,130), array('class' => 'img-thumbnail')); if ($featured_thumb ) { ?> <div class="featured-img logo"> <a href="#" title="Click to edit logo" data-toggle="modal" data-target="#photoEditModalFeatured"><?php echo $featured_thumb; ?></a> </div> <?php } else { ?> <div class="featured-img logo"> <a href="#" title="Click to upload logo" class="click-upload" data-toggle="modal" data-target="#photoUploadModalFeatured"><span><i class="fa fa-camera"></i>upload logo</span></a> </div> <?php } ?> <div class="title-block"> <a href="<?php echo $author_link; ?>" target="_blank"><h1><?php echo get_the_title($contractor_id); ?></h1></a><small><i>posted by <?php echo get_post_meta($contractor_id, '_name', true); ?></i></small><span class="rating-stars"> <?php $star_rating = fv_get_contractor_star_rating($contractor_id); if ( $star_rating ) { $star_rating_ii = 0; while ( $star_rating_ii < $star_rating ) { $star_rating_ii++; ?> <span class="fa fa-star white-star"></span> <?php } } ?> </span> </div> </div> </div> <div class="profile-nav"> <nav class="container" role="navigation"> <ul class="nav nav-pills"> <li><a href="<?php echo add_query_arg(array('action' => 'profile'), get_permalink()); ?>">edit profile</a></li> <li><a href="<?php echo add_query_arg(array('action' => 'membership'), get_permalink()); ?>">membership</a></li> <li><a href="<?php echo add_query_arg(array('action' => 'jobs'), get_permalink()); ?>"><?php if ( $project_count ) : ?><span class="counter-bubble"><?php echo count($project_count); ?><?php endif; ?></span>jobs</a></li> <li><a href="<?php echo add_query_arg(array('action' => 'endorsements'), get_permalink()); ?>">endorsements/ratings</a></li> <li><a href="<?php echo add_query_arg(array('action' => 'messages'), get_permalink()); ?>"><?php if ( $message_count ) : ?><span class="counter-bubble"><?php echo count($message_count); ?><?php endif; ?></span>messages</a></li> <li><a href="<?php echo add_query_arg(array('action' => 'medialibrary'), get_permalink()); ?>">media library</a></li> <?php if ( empty($_GET['action']) || $_GET['action'] == 'profile' ) : ?><li class="col-lg-3 save-btn-li"><a class="save-btn" href="#">save</a></li><?php endif; ?> </ul> </nav> </div>
icommstudios/AFS
wp-content/themes/AFS-theme/templates/contractors/contractor-profile-header.php
PHP
gpl-2.0
2,944
package AST; public abstract class Blockstatements implements SyntaxNode { private SyntaxNode parent; public Blockstatements getBlockstatements() { throw new ClassCastException("tried to call abstract method"); } public void setBlockstatements(Blockstatements blockstatements) { throw new ClassCastException("tried to call abstract method"); } public Blockstatement getBlockstatement() { throw new ClassCastException("tried to call abstract method"); } public void setBlockstatement(Blockstatement blockstatement) { throw new ClassCastException("tried to call abstract method"); } public SyntaxNode getParent() { return parent; } public void setParent(SyntaxNode parent) { this.parent=parent; } public abstract void accept(Visitor visitor); public abstract void childrenAccept(Visitor visitor); public abstract void traverseTopDown(Visitor visitor); public abstract void traverseBottomUp(Visitor visitor); public String toString() { return toString(""); } public abstract String toString(String tab); }
waqasraz/Compiler-J--
jmm/src/AST/Blockstatements.java
Java
gpl-2.0
1,140
<?php namespace GFPDF\Helper\Fields; use GFPDF\Helper\Helper_QueryPath; use GFPDF_Vendor\QueryPath\Exception; /** * @package Gravity PDF * @copyright Copyright (c) 2021, Blue Liquid Designs * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License */ /* Exit if accessed directly */ if ( ! defined( 'ABSPATH' ) ) { exit; } /** * Controls the display and output of a Gravity Form field * * @since 4.0 */ class Field_V3_Products extends Field_Products { /** * Display the HTML version of this field * * @param string $value * @param bool $label * * @return string * * @throws Exception * @since 4.0 */ public function html( $value = '', $label = true ) { $html = parent::html( $value, $label ); /* Format the order label correctly */ $label = apply_filters( 'gform_order_label', esc_html__( 'Order', 'gravityforms' ), $this->form->id ); $label = apply_filters( 'gform_order_label_' . $this->form->id, $label, $this->form->id ); $heading = '<h2 class="default entry-view-section-break">' . $label . '</h2>'; /* Pull out the .entry-products table from the HTML using querypath */ $qp = new Helper_QueryPath(); $table = $qp->html5( $html, 'div.inner-container' )->innerHTML5(); $html = $heading; $html .= $table; return $html; } }
GravityPDF/gravity-forms-pdf-extended
src/Helper/Fields/Field_V3_Products.php
PHP
gpl-2.0
1,324
using System; using Org.BouncyCastle.Asn1; namespace Org.BouncyCastle.Asn1.X509.Qualified { public abstract class EtsiQCObjectIdentifiers { // // base id // static readonly DerObjectIdentifier IdEtsiQcs = new DerObjectIdentifier("0.4.0.1862.1"); static readonly DerObjectIdentifier IdEtsiQcsQcCompliance = new DerObjectIdentifier(IdEtsiQcs+".1"); static readonly DerObjectIdentifier IdEtsiQcsLimitValue = new DerObjectIdentifier(IdEtsiQcs+".2"); static readonly DerObjectIdentifier IdEtsiQcsRetentionPeriod = new DerObjectIdentifier(IdEtsiQcs+".3"); static readonly DerObjectIdentifier IdEtsiQcsQcSscd = new DerObjectIdentifier(IdEtsiQcs+".4"); } }
hjgode/iTextSharpCF
itextsharp-4.0.1/srcbc/asn1/x509/qualified/ETSIQCObjectIdentifiers.cs
C#
gpl-2.0
759
class AddUserStatusToUser < ActiveRecord::Migration def change add_column :users, :user_status, :string end end
treestoryteam/EnhacedTreeStory2
db/migrate/20160222171154_add_user_status_to_user.rb
Ruby
gpl-2.0
120
from utils import scaleToZoom def jsonScript(layer): json = """ <script src="data/json_{layer}.js\"></script>""".format(layer=layer) return json def scaleDependentLayerScript(layer, layerName): min = layer.minimumScale() max = layer.maximumScale() scaleDependentLayer = """ if (map.getZoom() <= {min} && map.getZoom() >= {max}) {{ feature_group.addLayer(json_{layerName}JSON); console.log("show"); //restackLayers(); }} else if (map.getZoom() > {min} || map.getZoom() < {max}) {{ feature_group.removeLayer(json_{layerName}JSON); console.log("hide"); //restackLayers(); }}""".format(min=scaleToZoom(min), max=scaleToZoom(max), layerName=layerName) return scaleDependentLayer def scaleDependentScript(layers): scaleDependent = """ map.on("zoomend", function(e) {""" scaleDependent += layers scaleDependent += """ });""" scaleDependent += layers return scaleDependent def openScript(): openScript = """ <script>""" return openScript def crsScript(crsAuthId, crsProj4): crs = """ var crs = new L.Proj.CRS('{crsAuthId}', '{crsProj4}', {{ resolutions: [2800, 1400, 700, 350, 175, 84, 42, 21, 11.2, 5.6, 2.8, 1.4, 0.7, 0.35, 0.14, 0.07], }});""".format(crsAuthId=crsAuthId, crsProj4=crsProj4) return crs def mapScript(extent, matchCRS, crsAuthId, measure, maxZoom, minZoom, bounds): map = """ var map = L.map('map', {""" if extent == "Canvas extent" and matchCRS and crsAuthId != 'EPSG:4326': map += """ crs: crs, continuousWorld: false, worldCopyJump: false, """ if measure: map += """ measureControl:true,""" map += """ zoomControl:true, maxZoom:""" + unicode(maxZoom) + """, minZoom:""" + unicode(minZoom) + """ })""" if extent == "Canvas extent": map += """.fitBounds(""" + bounds + """);""" map += """ var hash = new L.Hash(map); var additional_attrib = '<a href="https://github.com/tomchadwin/qgis2web" target ="_blank">qgis2web</a>';""" return map def featureGroupsScript(): featureGroups = """ var feature_group = new L.featureGroup([]); var raster_group = new L.LayerGroup([]);""" return featureGroups def basemapsScript(basemap, attribution): basemaps = """ var basemap = L.tileLayer('{basemap}', {{ attribution: additional_attrib + ' {attribution}' }}); basemap.addTo(map);""".format(basemap=basemap, attribution=attribution) return basemaps def layerOrderScript(): layerOrder = """ var layerOrder=new Array(); function restackLayers() { for (index = 0; index < layerOrder.length; index++) { feature_group.removeLayer(layerOrder[index]); feature_group.addLayer(layerOrder[index]); } } layerControl = L.control.layers({},{},{collapsed:false});""" return layerOrder def popFuncsScript(table): popFuncs = """ var popupContent = {table}; layer.bindPopup(popupContent);""".format(table=table) return popFuncs def popupScript(safeLayerName, popFuncs): popup = """ function pop_{safeLayerName}(feature, layer) {{{popFuncs} }}""".format(safeLayerName=safeLayerName, popFuncs=popFuncs) return popup def pointToLayerScript(radius, borderWidth, borderStyle, colorName, borderColor, borderOpacity, opacity, labeltext): pointToLayer = """ pointToLayer: function (feature, latlng) {{ return L.circleMarker(latlng, {{ radius: {radius}, fillColor: '{colorName}', color: '{borderColor}', weight: {borderWidth}, opacity: {borderOpacity}, dashArray: '{dashArray}', fillOpacity: {opacity} }}){labeltext}""".format(radius=radius, colorName=colorName, borderColor=borderColor, borderWidth=borderWidth * 4, borderOpacity=borderOpacity if borderStyle != 0 else 0, dashArray=getLineStyle(borderStyle, borderWidth), opacity=opacity, labeltext=labeltext) return pointToLayer def pointStyleScript(pointToLayer, popFuncs): pointStyle = """{pointToLayer} }}, onEachFeature: function (feature, layer) {{{popFuncs} }}""".format(pointToLayer=pointToLayer, popFuncs=popFuncs) return pointStyle def wfsScript(scriptTag): wfs = """ <script src='{scriptTag}'></script>""".format(scriptTag=scriptTag) return wfs def jsonPointScript(safeLayerName, pointToLayer, usedFields): if usedFields != 0: jsonPoint = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ onEachFeature: pop_{safeLayerName}, {pointToLayer} }} }}); layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, pointToLayer=pointToLayer) else: jsonPoint = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ {pointToLayer} }} }}); layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, pointToLayer=pointToLayer) return jsonPoint def clusterScript(safeLayerName): cluster = """ var cluster_group{safeLayerName}JSON = new L.MarkerClusterGroup({{showCoverageOnHover: false}}); cluster_group{safeLayerName}JSON.addLayer(json_{safeLayerName}JSON);""".format(safeLayerName=safeLayerName) return cluster def categorizedPointStylesScript(symbol, opacity, borderOpacity): styleValues = """ radius: '{radius}', fillColor: '{fillColor}', color: '{color}', weight: {borderWidth}, opacity: {borderOpacity}, dashArray: '{dashArray}', fillOpacity: '{opacity}', }}; break;""".format(radius=symbol.size() * 2, fillColor=symbol.color().name(), color=symbol.symbolLayer(0).borderColor().name(), borderWidth=symbol.symbolLayer(0).outlineWidth() * 4, borderOpacity=borderOpacity if symbol.symbolLayer(0).outlineStyle() != 0 else 0, dashArray=getLineStyle(symbol.symbolLayer(0).outlineStyle(), symbol.symbolLayer(0).outlineWidth()), opacity=opacity) return styleValues def simpleLineStyleScript(radius, colorName, penStyle, opacity): lineStyle = """ return {{ weight: {radius}, color: '{colorName}', dashArray: '{penStyle}', opacity: {opacity} }};""".format(radius=radius * 4, colorName=colorName, penStyle=penStyle, opacity=opacity) return lineStyle def singlePolyStyleScript(radius, colorName, borderOpacity, fillColor, penStyle, opacity): polyStyle = """ return {{ weight: {radius}, color: '{colorName}', fillColor: '{fillColor}', dashArray: '{penStyle}', opacity: {borderOpacity}, fillOpacity: {opacity} }};""".format(radius=radius, colorName=colorName, fillColor=fillColor, penStyle=penStyle, borderOpacity=borderOpacity, opacity=opacity) return polyStyle def nonPointStylePopupsScript(lineStyle, popFuncs): nonPointStylePopups = """ style: function (feature) {{{lineStyle} }}, onEachFeature: function (feature, layer) {{{popFuncs} }}""".format(lineStyle=lineStyle, popFuncs=popFuncs) return nonPointStylePopups def nonPointStyleFunctionScript(safeLayerName, lineStyle): nonPointStyleFunction = """ function doStyle{safeLayerName}(feature) {{{lineStyle} }}""".format(safeLayerName=safeLayerName, lineStyle=lineStyle) return nonPointStyleFunction def categoryScript(layerName, valueAttr): category = """ function doStyle{layerName}(feature) {{ switch (feature.properties.{valueAttr}) {{""".format(layerName=layerName, valueAttr=valueAttr) return category def defaultCategoryScript(): defaultCategory = """ default: return {""" return defaultCategory def eachCategoryScript(catValue): if isinstance(catValue, basestring): valQuote = "'" else: valQuote = "" eachCategory = """ case """ + valQuote + unicode(catValue) + valQuote + """: return {""" return eachCategory def endCategoryScript(): endCategory = """ } }""" return endCategory def categorizedPointWFSscript(layerName, labeltext, popFuncs): categorizedPointWFS = """ pointToLayer: function (feature, latlng) {{ return L.circleMarker(latlng, doStyle{layerName}(feature)){labeltext} }}, onEachFeature: function (feature, layer) {{{popFuncs} }}""".format(layerName=layerName, labeltext=labeltext, popFuncs=popFuncs) return categorizedPointWFS def categorizedPointJSONscript(safeLayerName, labeltext, usedFields): if usedFields != 0: categorizedPointJSON = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ onEachFeature: pop_{safeLayerName}, pointToLayer: function (feature, latlng) {{ return L.circleMarker(latlng, doStyle{safeLayerName}(feature)){labeltext} }} }}); layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, labeltext=labeltext) else: categorizedPointJSON = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ pointToLayer: function (feature, latlng) {{ return L.circleMarker(latlng, doStyle{safeLayerName}(feature)){labeltext} }} }}); layerOrder[layerOrder.length] = json_{safeLayerName}JSON;""".format(safeLayerName=safeLayerName, labeltext=labeltext) return categorizedPointJSON def categorizedLineStylesScript(symbol, opacity): categorizedLineStyles = """ color: '{color}', weight: '{weight}', dashArray: '{dashArray}', opacity: '{opacity}', }}; break;""".format(color=symbol.color().name(), weight=symbol.width() * 4, dashArray=getLineStyle(symbol.symbolLayer(0).penStyle(), symbol.width()), opacity=opacity) return categorizedLineStyles def categorizedNonPointStyleFunctionScript(layerName, popFuncs): categorizedNonPointStyleFunction = """ style: doStyle{layerName}, onEachFeature: function (feature, layer) {{{popFuncs} }}""".format(layerName=layerName, popFuncs=popFuncs) return categorizedNonPointStyleFunction def categorizedPolygonStylesScript(symbol, opacity, borderOpacity): categorizedPolygonStyles = """ weight: '{weight}', fillColor: '{fillColor}', color: '{color}', dashArray: '{dashArray}', opacity: '{borderOpacity}', fillOpacity: '{opacity}', }}; break;""".format(weight=symbol.symbolLayer(0).borderWidth() * 4, fillColor=symbol.color().name() if symbol.symbolLayer(0).brushStyle() != 0 else "none", color=symbol.symbolLayer(0).borderColor().name() if symbol.symbolLayer(0).borderStyle() != 0 else "none", dashArray=getLineStyle(symbol.symbolLayer(0).borderStyle(), symbol.symbolLayer(0).borderWidth()), borderOpacity=borderOpacity, opacity=opacity) return categorizedPolygonStyles def graduatedStyleScript(layerName): graduatedStyle = """ function doStyle{layerName}(feature) {{""".format(layerName=layerName) return graduatedStyle def rangeStartScript(valueAttr, r): rangeStart = """ if (feature.properties.{valueAttr} >= {lowerValue} && feature.properties.{valueAttr} <= {upperValue}) {{""".format(valueAttr=valueAttr, lowerValue=r.lowerValue(), upperValue=r.upperValue()) return rangeStart def graduatedPointStylesScript(valueAttr, r, symbol, opacity, borderOpacity): graduatedPointStyles = rangeStartScript(valueAttr, r) graduatedPointStyles += """ return {{ radius: '{radius}', fillColor: '{fillColor}', color: '{color}', weight: {lineWeight}, fillOpacity: '{opacity}', opacity: '{borderOpacity}', dashArray: '{dashArray}' }} }}""".format(radius=symbol.size() * 2, fillColor=symbol.color().name(), color=symbol.symbolLayer(0).borderColor().name(), lineWeight=symbol.symbolLayer(0).outlineWidth() * 4, opacity=opacity, borderOpacity=borderOpacity, dashArray=getLineStyle(symbol.symbolLayer(0).outlineStyle(), symbol.symbolLayer(0).outlineWidth())) return graduatedPointStyles def graduatedLineStylesScript(valueAttr, r, categoryStr, symbol, opacity): graduatedLineStyles = rangeStartScript(valueAttr, r) graduatedLineStyles += """ return {{ color: '{color}', weight: '{weight}', dashArray: '{dashArray}', opacity: '{opacity}', }} }}""".format(color=symbol.symbolLayer(0).color().name(), weight=symbol.width() * 4, dashArray=getLineStyle(symbol.symbolLayer(0).penStyle(), symbol.width()), opacity=opacity) return graduatedLineStyles def graduatedPolygonStylesScript(valueAttr, r, symbol, opacity, borderOpacity): graduatedPolygonStyles = rangeStartScript(valueAttr, r) graduatedPolygonStyles += """ return {{ color: '{color}', weight: '{weight}', dashArray: '{dashArray}', fillColor: '{fillColor}', opacity: '{borderOpacity}', fillOpacity: '{opacity}', }} }}""".format(color=symbol.symbolLayer(0).borderColor().name(), weight=symbol.symbolLayer(0).borderWidth() * 4 if symbol.symbolLayer(0).borderStyle() != 0 else "0", dashArray=getLineStyle(symbol.symbolLayer(0).borderStyle(), symbol.symbolLayer(0).borderWidth() if symbol.symbolLayer(0).borderStyle() != 0 else "0"), fillColor=symbol.color().name() if symbol.symbolLayer(0).brushStyle() != 0 else "none", borderOpacity=borderOpacity, opacity=opacity) return graduatedPolygonStyles def endGraduatedStyleScript(): endGraduatedStyle = """ }""" return endGraduatedStyle def customMarkerScript(safeLayerName, labeltext, usedFields): if usedFields != 0: customMarker = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ onEachFeature: pop_{safeLayerName}, pointToLayer: function (feature, latlng) {{ return L.marker(latlng, {{ icon: L.icon({{ iconUrl: feature.properties.icon_exp, iconSize: [24, 24], // size of the icon change this to scale your icon (first coordinate is x, second y from the upper left corner of the icon) iconAnchor: [12, 12], // point of the icon which will correspond to marker's location (first coordinate is x, second y from the upper left corner of the icon) popupAnchor: [0, -14] // point from which the popup should open relative to the iconAnchor (first coordinate is x, second y from the upper left corner of the icon) }}) }}){labeltext} }}}} );""".format(safeLayerName=safeLayerName, labeltext=labeltext) else: customMarker = """ var json_{safeLayerName}JSON = new L.geoJson(json_{safeLayerName}, {{ pointToLayer: function (feature, latlng) {{ return L.marker(latlng, {{ icon: L.icon({{ iconUrl: feature.properties.icon_exp, iconSize: [24, 24], // size of the icon change this to scale your icon (first coordinate is x, second y from the upper left corner of the icon) iconAnchor: [12, 12], // point of the icon which will correspond to marker's location (first coordinate is x, second y from the upper left corner of the icon) popupAnchor: [0, -14] // point from which the popup should open relative to the iconAnchor (first coordinate is x, second y from the upper left corner of the icon) }}) }}){labeltext} }}}} );""".format(safeLayerName=safeLayerName, labeltext=labeltext) return customMarker def wmsScript(safeLayerName, wms_url, wms_layer, wms_format): wms = """ var overlay_{safeLayerName} = L.tileLayer.wms('{wms_url}', {{ layers: '{wms_layer}', format: '{wms_format}', transparent: true, continuousWorld : true, }});""".format(safeLayerName=safeLayerName, wms_url=wms_url, wms_layer=wms_layer, wms_format=wms_format) return wms def rasterScript(safeLayerName, out_raster_name, bounds): raster = """ var img_{safeLayerName} = '{out_raster_name}'; var img_bounds_{safeLayerName} = {bounds}; var overlay_{safeLayerName} = new L.imageOverlay(img_{safeLayerName}, img_bounds_{safeLayerName});""".format(safeLayerName=safeLayerName, out_raster_name=out_raster_name, bounds=bounds) return raster def titleSubScript(webmap_head, webmap_subhead): titleSub = """ var title = new L.Control(); title.onAdd = function (map) { this._div = L.DomUtil.create('div', 'info'); // create a div with a class "info" this.update(); return this._div; }; title.update = function () { this._div.innerHTML = '<h2>""" + webmap_head.encode('utf-8') + """</h2>""" + webmap_subhead.encode('utf-8') + """' }; title.addTo(map);""" return titleSub def addressSearchScript(): addressSearch = """ var osmGeocoder = new L.Control.OSMGeocoder({ collapsed: false, position: 'topright', text: 'Search', }); osmGeocoder.addTo(map);""" return addressSearch def locateScript(): locate = """ map.locate({setView: true, maxZoom: 16}); function onLocationFound(e) { var radius = e.accuracy / 2; L.marker(e.latlng).addTo(map) .bindPopup("You are within " + radius + " meters from this point").openPopup(); L.circle(e.latlng, radius).addTo(map); } map.on('locationfound', onLocationFound); """ return locate def endHTMLscript(wfsLayers): endHTML = """ </script>{wfsLayers} </body> </html>""".format(wfsLayers=wfsLayers) return endHTML def getLineStyle(penType, lineWidth): dash = lineWidth * 10 dot = lineWidth * 1 gap = lineWidth * 5 if penType > 1: if penType == 2: penStyle = [dash, gap] if penType == 3: penStyle = [dot, gap] if penType == 4: penStyle = [dash, gap, dot, gap] if penType == 5: penStyle = [dash, gap, dot, gap, dot, gap] penStyle = ','.join(map(str, penStyle)) else: penStyle = "" return penStyle
radumas/qgis2web
leafletScriptStrings.py
Python
gpl-2.0
20,814
<?php /** * File containing the eZContentOperationCollection class. * * @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version 2012.9 * @package kernel */ /*! \class eZContentOperationCollection ezcontentoperationcollection.php \brief The class eZContentOperationCollection does */ class eZContentOperationCollection { /*! Constructor */ function eZContentOperationCollection() { } static public function readNode( $nodeID ) { } static public function readObject( $nodeID, $userID, $languageCode ) { if ( $languageCode != '' ) { $node = eZContentObjectTreeNode::fetch( $nodeID, $languageCode ); } else { $node = eZContentObjectTreeNode::fetch( $nodeID ); } if ( $node === null ) // return $Module->handleError( eZError::KERNEL_NOT_AVAILABLE, 'kernel' ); return false; $object = $node->attribute( 'object' ); if ( $object === null ) // return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' ); { return false; } /* if ( !$object->attribute( 'can_read' ) ) { // return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' ); return false; } */ return array( 'status' => true, 'object' => $object, 'node' => $node ); } static public function loopNodes( $nodeID ) { return array( 'parameters' => array( array( 'parent_node_id' => 3 ), array( 'parent_node_id' => 5 ), array( 'parent_node_id' => 12 ) ) ); } static public function loopNodeAssignment( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nodeAssignmentList = $version->attribute( 'node_assignments' ); $parameters = array(); foreach ( $nodeAssignmentList as $nodeAssignment ) { if ( $nodeAssignment->attribute( 'parent_node' ) > 0 ) { if ( $nodeAssignment->attribute( 'is_main' ) == 1 ) { $mainNodeID = self::publishNode( $nodeAssignment->attribute( 'parent_node' ), $objectID, $versionNum, false ); } else { $parameters[] = array( 'parent_node_id' => $nodeAssignment->attribute( 'parent_node' ) ); } } } for ( $i = 0; $i < count( $parameters ); $i++ ) { $parameters[$i]['main_node_id'] = $mainNodeID; } return array( 'parameters' => $parameters ); } function publishObjectExtensionHandler( $contentObjectID, $contentObjectVersion ) { eZContentObjectEditHandler::executePublish( $contentObjectID, $contentObjectVersion ); } static public function setVersionStatus( $objectID, $versionNum, $status ) { $object = eZContentObject::fetch( $objectID ); if ( !$versionNum ) { $versionNum = $object->attribute( 'current_version' ); } $version = $object->version( $versionNum ); if ( !$version ) return; $version->setAttribute( 'status', $status ); $version->store(); } static public function setObjectStatusPublished( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $db = eZDB::instance(); $db->begin(); $object->publishContentObjectRelations( $versionNum ); $object->setAttribute( 'status', eZContentObject::STATUS_PUBLISHED ); $version->setAttribute( 'status', eZContentObjectVersion::STATUS_PUBLISHED ); $object->setAttribute( 'current_version', $versionNum ); $objectIsAlwaysAvailable = $object->isAlwaysAvailable(); $object->setAttribute( 'language_mask', eZContentLanguage::maskByLocale( $version->translationList( false, false ), $objectIsAlwaysAvailable ) ); if ( $object->attribute( 'published' ) == 0 ) { $object->setAttribute( 'published', time() ); } $object->setAttribute( 'modified', time() ); $classID = $object->attribute( 'contentclass_id' ); $class = eZContentClass::fetch( $classID ); $objectName = $class->contentObjectName( $object ); $object->setName( $objectName, $versionNum ); $existingTranslations = $version->translations( false ); foreach( $existingTranslations as $translation ) { $translatedName = $class->contentObjectName( $object, $versionNum, $translation ); $object->setName( $translatedName, $versionNum, $translation ); } if ( $objectIsAlwaysAvailable ) { $initialLanguageID = $object->attribute( 'initial_language_id' ); $object->setAlwaysAvailableLanguageID( $initialLanguageID ); } $version->store(); $object->store(); eZContentObjectTreeNode::setVersionByObjectID( $objectID, $versionNum ); $nodes = $object->assignedNodes(); foreach ( $nodes as $node ) { $node->setName( $object->attribute( 'name' ) ); $node->updateSubTreePath(); } $db->commit(); /* Check if current class is the user class, and if so, clean up the user-policy cache */ if ( in_array( $classID, eZUser::contentClassIDs() ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } } static public function attributePublishAction( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $nodes = $object->assignedNodes(); $version = $object->version( $versionNum ); $contentObjectAttributes = $object->contentObjectAttributes( true, $versionNum, $version->initialLanguageCode(), false ); foreach ( $contentObjectAttributes as $contentObjectAttribute ) { $contentObjectAttribute->onPublish( $object, $nodes ); } } /*! \static Generates the related viewcaches (PreGeneration) for the content object. It will only do this if [ContentSettings]/PreViewCache in site.ini is enabled. \param $objectID The ID of the content object to generate caches for. */ static public function generateObjectViewCache( $objectID ) { eZContentCacheManager::generateObjectViewCache( $objectID ); } /*! \static Clears the related viewcaches for the content object using the smart viewcache system. \param $objectID The ID of the content object to clear caches for \param $versionNum The version of the object to use or \c true for current version \param $additionalNodeList An array with node IDs to add to clear list, or \c false for no additional nodes. */ static public function clearObjectViewCache( $objectID, $versionNum = true, $additionalNodeList = false ) { eZContentCacheManager::clearContentCacheIfNeeded( $objectID, $versionNum, $additionalNodeList ); } static public function publishNode( $parentNodeID, $objectID, $versionNum, $mainNodeID ) { $object = eZContentObject::fetch( $objectID ); $nodeAssignment = eZNodeAssignment::fetch( $objectID, $versionNum, $parentNodeID ); $version = $object->version( $versionNum ); $fromNodeID = $nodeAssignment->attribute( 'from_node_id' ); $originalObjectID = $nodeAssignment->attribute( 'contentobject_id' ); $nodeID = $nodeAssignment->attribute( 'parent_node' ); $opCode = $nodeAssignment->attribute( 'op_code' ); $parentNode = eZContentObjectTreeNode::fetch( $nodeID ); // if parent doesn't exist, return. See issue #18320 if ( !$parentNode instanceof eZContentObjectTreeNode ) { eZDebug::writeError( "Parent node doesn't exist. object id: $objectID, node_assignment id: " . $nodeAssignment->attribute( 'id' ), __METHOD__ ); return; } $parentNodeID = $parentNode->attribute( 'node_id' ); $existingNode = null; $db = eZDB::instance(); $db->begin(); if ( strlen( $nodeAssignment->attribute( 'parent_remote_id' ) ) > 0 ) { $existingNode = eZContentObjectTreeNode::fetchByRemoteID( $nodeAssignment->attribute( 'parent_remote_id' ) ); } if ( !$existingNode ); { $existingNode = eZContentObjectTreeNode::findNode( $nodeID , $object->attribute( 'id' ), true ); } $updateSectionID = false; // now we check the op_code to see what to do if ( ( $opCode & 1 ) == eZNodeAssignment::OP_CODE_NOP ) { // There is nothing to do so just return $db->commit(); if ( $mainNodeID == false ) { return $object->attribute( 'main_node_id' ); } return; } $updateFields = false; if ( $opCode == eZNodeAssignment::OP_CODE_MOVE || $opCode == eZNodeAssignment::OP_CODE_CREATE ) { // if ( $fromNodeID == 0 || $fromNodeID == -1) if ( $opCode == eZNodeAssignment::OP_CODE_CREATE || $opCode == eZNodeAssignment::OP_CODE_SET ) { // If the node already exists it means we have a conflict (for 'CREATE'). // We resolve this by leaving node-assignment data be. if ( $existingNode == null ) { $parentNode = eZContentObjectTreeNode::fetch( $nodeID ); $user = eZUser::currentUser(); if ( !eZSys::isShellExecution() and !$user->isAnonymous() ) { eZContentBrowseRecent::createNew( $user->id(), $parentNode->attribute( 'node_id' ), $parentNode->attribute( 'name' ) ); } $updateFields = true; $existingNode = $parentNode->addChild( $object->attribute( 'id' ), true ); if ( $fromNodeID == -1 ) { $updateSectionID = true; } } elseif ( $opCode == eZNodeAssignment::OP_CODE_SET ) { $updateFields = true; } } elseif ( $opCode == eZNodeAssignment::OP_CODE_MOVE ) { if ( $fromNodeID == 0 || $fromNodeID == -1 ) { eZDebug::writeError( "NodeAssignment '" . $nodeAssignment->attribute( 'id' ) . "' is marked with op_code='$opCode' but has no data in from_node_id. Cannot use it for moving node.", __METHOD__ ); } else { // clear cache for old placement. $additionalNodeIDList = array( $fromNodeID ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID, $versionNum, $additionalNodeIDList ); $originalNode = eZContentObjectTreeNode::fetchNode( $originalObjectID, $fromNodeID ); if ( $originalNode->attribute( 'main_node_id' ) == $originalNode->attribute( 'node_id' ) ) { $updateSectionID = true; } $originalNode->move( $parentNodeID ); $existingNode = eZContentObjectTreeNode::fetchNode( $originalObjectID, $parentNodeID ); $updateFields = true; } } } elseif ( $opCode == eZNodeAssignment::OP_CODE_REMOVE ) { $db->commit(); return; } if ( $updateFields ) { if ( strlen( $nodeAssignment->attribute( 'parent_remote_id' ) ) > 0 ) { $existingNode->setAttribute( 'remote_id', $nodeAssignment->attribute( 'parent_remote_id' ) ); } $existingNode->setAttribute( 'sort_field', $nodeAssignment->attribute( 'sort_field' ) ); $existingNode->setAttribute( 'sort_order', $nodeAssignment->attribute( 'sort_order' ) ); } $existingNode->setAttribute( 'contentobject_is_published', 1 ); eZDebug::createAccumulatorGroup( 'nice_urls_total', 'Nice urls' ); if ( $mainNodeID > 0 ) { $existingNodeID = $existingNode->attribute( 'node_id' ); if ( $existingNodeID != $mainNodeID ) { eZContentBrowseRecent::updateNodeID( $existingNodeID, $mainNodeID ); } $existingNode->setAttribute( 'main_node_id', $mainNodeID ); } else { $existingNode->setAttribute( 'main_node_id', $existingNode->attribute( 'node_id' ) ); } $existingNode->store(); if ( $updateSectionID ) { eZContentOperationCollection::updateSectionID( $objectID, $versionNum ); } $db->commit(); if ( $mainNodeID == false ) { return $existingNode->attribute( 'node_id' ); } } static public function updateSectionID( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); if ( $versionNum == 1 or $object->attribute( 'current_version' ) == $versionNum ) { $newMainAssignment = null; $newMainAssignments = eZNodeAssignment::fetchForObject( $objectID, $versionNum, 1 ); if ( isset( $newMainAssignments[0] ) ) { $newMainAssignment = $newMainAssignments[0]; } // we should not update section id for toplevel nodes if ( $newMainAssignment && $newMainAssignment->attribute( 'parent_node' ) != 1 ) { // We should check if current object already has been updated for section_id // If yes we should not update object section_id by $parentNodeSectionID $sectionID = $object->attribute( 'section_id' ); if ( $sectionID > 0 ) return; $newParentObject = $newMainAssignment->getParentObject(); if ( !$newParentObject ) { return array( 'status' => eZModuleOperationInfo::STATUS_CANCELLED ); } $parentNodeSectionID = $newParentObject->attribute( 'section_id' ); $object->setAttribute( 'section_id', $parentNodeSectionID ); $object->store(); } return; } $newMainAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $versionNum, 1 ); $newMainAssignment = ( count( $newMainAssignmentList ) ) ? array_pop( $newMainAssignmentList ) : null; $currentVersion = $object->attribute( 'current' ); // Here we need to fetch published nodes and not old node assignments. $oldMainNode = $object->mainNode(); if ( $newMainAssignment && $oldMainNode && $newMainAssignment->attribute( 'parent_node' ) != $oldMainNode->attribute( 'parent_node_id' ) ) { $oldMainParentNode = $oldMainNode->attribute( 'parent' ); if ( $oldMainParentNode ) { $oldParentObject = $oldMainParentNode->attribute( 'object' ); $oldParentObjectSectionID = $oldParentObject->attribute( 'section_id' ); if ( $oldParentObjectSectionID == $object->attribute( 'section_id' ) ) { $newParentNode = $newMainAssignment->attribute( 'parent_node_obj' ); if ( !$newParentNode ) return; $newParentObject = $newParentNode->attribute( 'object' ); if ( !$newParentObject ) return; $newSectionID = $newParentObject->attribute( 'section_id' ); if ( $newSectionID != $object->attribute( 'section_id' ) ) { $oldSectionID = $object->attribute( 'section_id' ); $object->setAttribute( 'section_id', $newSectionID ); $db = eZDB::instance(); $db->begin(); $object->store(); $mainNodeID = $object->attribute( 'main_node_id' ); if ( $mainNodeID > 0 ) { eZContentObjectTreeNode::assignSectionToSubTree( $mainNodeID, $newSectionID, $oldSectionID ); } $db->commit(); } } } } } static public function removeOldNodes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $moveToTrash = true; $assignedExistingNodes = $object->attribute( 'assigned_nodes' ); $curentVersionNodeAssignments = $version->attribute( 'node_assignments' ); $removeParentNodeList = array(); $removeAssignmentsList = array(); foreach ( $curentVersionNodeAssignments as $nodeAssignment ) { $nodeAssignmentOpcode = $nodeAssignment->attribute( 'op_code' ); if ( $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE || $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE_NOP ) { $removeAssignmentsList[] = $nodeAssignment->attribute( 'id' ); if ( $nodeAssignmentOpcode == eZNodeAssignment::OP_CODE_REMOVE ) { $removeParentNodeList[] = $nodeAssignment->attribute( 'parent_node' ); } } } $db = eZDB::instance(); $db->begin(); foreach ( $assignedExistingNodes as $node ) { if ( in_array( $node->attribute( 'parent_node_id' ), $removeParentNodeList ) ) { eZContentObjectTreeNode::removeSubtrees( array( $node->attribute( 'node_id' ) ), $moveToTrash ); } } if ( count( $removeAssignmentsList ) > 0 ) { eZNodeAssignment::purgeByID( $removeAssignmentsList ); } $db->commit(); } // New function which resets the op_code field when the object is published. static public function resetNodeassignmentOpcodes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nodeAssignments = $version->attribute( 'node_assignments' ); foreach ( $nodeAssignments as $nodeAssignment ) { if ( ( $nodeAssignment->attribute( 'op_code' ) & 1 ) == eZNodeAssignment::OP_CODE_EXECUTE ) { $nodeAssignment->setAttribute( 'op_code', ( $nodeAssignment->attribute( 'op_code' ) & ~1 ) ); $nodeAssignment->store(); } } } /** * Registers the object in search engine. * * @note Transaction unsafe. If you call several transaction unsafe methods you must enclose * the calls within a db transaction; thus within db->begin and db->commit. * * @param int $objectID Id of the object. */ static public function registerSearchObject( $objectID ) { $objectID = (int)$objectID; eZDebug::createAccumulatorGroup( 'search_total', 'Search Total' ); $ini = eZINI::instance( 'site.ini' ); $insertPendingAction = false; $object = null; switch ( $ini->variable( 'SearchSettings', 'DelayedIndexing' ) ) { case 'enabled': $insertPendingAction = true; break; case 'classbased': $classList = $ini->variable( 'SearchSettings', 'DelayedIndexingClassList' ); $object = eZContentObject::fetch( $objectID ); if ( is_array( $classList ) && in_array( $object->attribute( 'class_identifier' ), $classList ) ) { $insertPendingAction = true; } } if ( $insertPendingAction ) { eZDB::instance()->query( "INSERT INTO ezpending_actions( action, param ) VALUES ( 'index_object', '$objectID' )" ); return; } if ( $object === null ) $object = eZContentObject::fetch( $objectID ); // Register the object in the search engine. $needCommit = eZSearch::needCommit(); if ( eZSearch::needRemoveWithUpdate() ) { eZDebug::accumulatorStart( 'remove_object', 'search_total', 'remove object' ); eZSearch::removeObject( $object, $needCommit ); eZDebug::accumulatorStop( 'remove_object' ); } eZDebug::accumulatorStart( 'add_object', 'search_total', 'add object' ); if ( !eZSearch::addObject( $object, $needCommit ) ) { eZDebug::writeError( "Failed adding object ID {$object->attribute( 'id' )} in the search engine", __METHOD__ ); } eZDebug::accumulatorStop( 'add_object' ); } /*! \note Transaction unsafe. If you call several transaction unsafe methods you must enclose the calls within a db transaction; thus within db->begin and db->commit. */ static public function createNotificationEvent( $objectID, $versionNum ) { $event = eZNotificationEvent::create( 'ezpublish', array( 'object' => $objectID, 'version' => $versionNum ) ); $event->store(); } /*! Copies missing translations from published version to the draft. */ static public function copyTranslations( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $publishedVersionNum = $object->attribute( 'current_version' ); if ( !$publishedVersionNum ) { return; } $publishedVersion = $object->version( $publishedVersionNum ); $publishedVersionTranslations = $publishedVersion->translations(); $publishedLanguages = eZContentLanguage::languagesByMask( $object->attribute( 'language_mask' ) ); $publishedLanguageCodes = array_keys( $publishedLanguages ); $version = $object->version( $versionNum ); $versionTranslationList = $version->translationList( false, false ); foreach ( $publishedVersionTranslations as $translation ) { if ( in_array( $translation->attribute( 'language_code' ), $versionTranslationList ) || !in_array( $translation->attribute( 'language_code' ), $publishedLanguageCodes ) ) { continue; } $contentObjectAttributes = $translation->objectAttributes(); foreach ( $contentObjectAttributes as $attribute ) { $clonedAttribute = $attribute->cloneContentObjectAttribute( $versionNum, $publishedVersionNum, $objectID ); $clonedAttribute->sync(); } } $version->updateLanguageMask(); } /*! Updates non-translatable attributes. */ static public function updateNontranslatableAttributes( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $version = $object->version( $versionNum ); $nonTranslatableAttributes = $version->nonTranslatableAttributesToUpdate(); if ( $nonTranslatableAttributes ) { $attributes = $version->contentObjectAttributes( $version->initialLanguageCode() ); $attributeByClassAttrID = array(); foreach ( $attributes as $attribute ) { $attributeByClassAttrID[$attribute->attribute( 'contentclassattribute_id' )] = $attribute; } foreach ( $nonTranslatableAttributes as $attributeToUpdate ) { $originalAttribute =& $attributeByClassAttrID[$attributeToUpdate->attribute( 'contentclassattribute_id' )]; if ( $originalAttribute ) { unset( $tmp ); $tmp = $attributeToUpdate; $tmp->initialize( $attributeToUpdate->attribute( 'version' ), $originalAttribute ); $tmp->setAttribute( 'id', $attributeToUpdate->attribute( 'id' ) ); $tmp->setAttribute( 'language_code', $attributeToUpdate->attribute( 'language_code' ) ); $tmp->setAttribute( 'language_id', $attributeToUpdate->attribute( 'language_id' ) ); $tmp->setAttribute( 'attribute_original_id', $originalAttribute->attribute( 'id' ) ); $tmp->store(); $tmp->postInitialize( $attributeToUpdate->attribute( 'version' ), $originalAttribute ); } } } } static public function removeTemporaryDrafts( $objectID, $versionNum ) { $object = eZContentObject::fetch( $objectID ); $object->cleanupInternalDrafts( eZUser::currentUserID() ); } /** * Moves a node * * @param int $nodeID * @param int $objectID * @param int $newParentNodeID * * @return array An array with operation status, always true */ static public function moveNode( $nodeID, $objectID, $newParentNodeID ) { if( !eZContentObjectTreeNodeOperations::move( $nodeID, $newParentNodeID ) ) { eZDebug::writeError( "Failed to move node $nodeID as child of parent node $newParentNodeID", __METHOD__ ); return array( 'status' => false ); } eZContentObject::fixReverseRelations( $objectID, 'move' ); return array( 'status' => true ); } /** * Adds a new nodeAssignment * * @param int $nodeID * @param int $objectId * @param array $selectedNodeIDArray * * @return array An array with operation status, always true */ static public function addAssignment( $nodeID, $objectID, $selectedNodeIDArray ) { $userClassIDArray = eZUser::contentClassIDs(); $object = eZContentObject::fetch( $objectID ); $class = $object->contentClass(); $nodeAssignmentList = eZNodeAssignment::fetchForObject( $objectID, $object->attribute( 'current_version' ), 0, false ); $assignedNodes = $object->assignedNodes(); $parentNodeIDArray = array(); foreach ( $assignedNodes as $assignedNode ) { $append = false; foreach ( $nodeAssignmentList as $nodeAssignment ) { if ( $nodeAssignment['parent_node'] == $assignedNode->attribute( 'parent_node_id' ) ) { $append = true; break; } } if ( $append ) { $parentNodeIDArray[] = $assignedNode->attribute( 'parent_node_id' ); } } $db = eZDB::instance(); $db->begin(); $locationAdded = false; $node = eZContentObjectTreeNode::fetch( $nodeID ); foreach ( $selectedNodeIDArray as $selectedNodeID ) { if ( !in_array( $selectedNodeID, $parentNodeIDArray ) ) { $parentNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $parentNodeObject = $parentNode->attribute( 'object' ); $canCreate = ( ( $parentNode->checkAccess( 'create', $class->attribute( 'id' ), $parentNodeObject->attribute( 'contentclass_id' ) ) == 1 ) || ( $parentNode->canAddLocation() && $node->canRead() ) ); if ( $canCreate ) { $insertedNode = $object->addLocation( $selectedNodeID, true ); // Now set is as published and fix main_node_id $insertedNode->setAttribute( 'contentobject_is_published', 1 ); $insertedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) ); $insertedNode->setAttribute( 'contentobject_version', $node->attribute( 'contentobject_version' ) ); // Make sure the url alias is set updated. $insertedNode->updateSubTreePath(); $insertedNode->sync(); $locationAdded = true; } } } if ( $locationAdded ) { //call appropriate method from search engine eZSearch::addNodeAssignment( $nodeID, $objectID, $selectedNodeIDArray ); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } } $db->commit(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Removes nodes * * This function does not check about permissions, this is the responsibility of the caller! * * @param array $removeNodeIdList Array of Node ID to remove * * @return array An array with operation status, always true */ static public function removeNodes( array $removeNodeIdList ) { $mainNodeChanged = array(); $nodeAssignmentIdList = array(); $objectIdList = array(); $db = eZDB::instance(); $db->begin(); foreach ( $removeNodeIdList as $nodeId ) { $node = eZContentObjectTreeNode::fetch($nodeId); $objectId = $node->attribute( 'contentobject_id' ); foreach ( eZNodeAssignment::fetchForObject( $objectId, eZContentObject::fetch( $objectId )->attribute( 'current_version' ), 0, false ) as $nodeAssignmentKey => $nodeAssignment ) { if ( $nodeAssignment['parent_node'] == $node->attribute( 'parent_node_id' ) ) { $nodeAssignmentIdList[$nodeAssignment['id']] = 1; } } if ( $nodeId == $node->attribute( 'main_node_id' ) ) $mainNodeChanged[$objectId] = 1; $node->removeThis(); if ( !isset( $objectIdList[$objectId] ) ) $objectIdList[$objectId] = eZContentObject::fetch( $objectId ); } eZNodeAssignment::purgeByID( array_keys( $nodeAssignmentIdList ) ); foreach ( array_keys( $mainNodeChanged ) as $objectId ) { $allNodes = $objectIdList[$objectId]->assignedNodes(); // Registering node that will be promoted as 'main' $mainNodeChanged[$objectId] = $allNodes[0]; eZContentObjectTreeNode::updateMainNodeID( $allNodes[0]->attribute( 'node_id' ), $objectId, false, $allNodes[0]->attribute( 'parent_node_id' ) ); } // Give other search engines that the default one a chance to reindex // when removing locations. if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { foreach ( array_keys( $objectIdList ) as $objectId ) eZContentOperationCollection::registerSearchObject( $objectId ); } $db->commit(); //call appropriate method from search engine eZSearch::removeNodes( $removeNodeIdList ); $userClassIdList = eZUser::contentClassIDs(); foreach ( $objectIdList as $objectId => $object ) { eZContentCacheManager::clearObjectViewCacheIfNeeded( $objectId ); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIdList ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } } // we don't clear template block cache here since it's cleared in eZContentObjectTreeNode::removeNode() return array( 'status' => true ); } /** * Deletes a content object, or a list of content objects * * @param array $deleteIDArray * @param bool $moveToTrash * * @return array An array with operation status, always true */ static public function deleteObject( $deleteIDArray, $moveToTrash = false ) { $ini = eZINI::instance(); $delayedIndexingValue = $ini->variable( 'SearchSettings', 'DelayedIndexing' ); if ( $delayedIndexingValue === 'enabled' || $delayedIndexingValue === 'classbased' ) { $pendingActionsToDelete = array(); $classList = $ini->variable( 'SearchSettings', 'DelayedIndexingClassList' ); // Will be used below if DelayedIndexing is classbased $assignedNodesByObject = array(); $nodesToDeleteByObject = array(); $aNodes = eZContentObjectTreeNode::fetch( $deleteIDArray ); if( !is_array( $aNodes ) ) $aNodes = array( $aNodes ); foreach ( $aNodes as $node ) { $object = $node->object(); $objectID = $object->attribute( 'id' ); $assignedNodes = $object->attribute( 'assigned_nodes' ); // Only delete pending action if this is the last object's node that is requested for deletion // But $deleteIDArray can also contain all the object's node (mainly if this method is called programmatically) // So if this is not the last node, then store its id in a temp array // This temp array will then be compared to the whole object's assigned nodes array if ( count( $assignedNodes ) > 1 ) { // $assignedNodesByObject will be used as a referent to check if we want to delete all lasting nodes if ( !isset( $assignedNodesByObject[$objectID] ) ) { $assignedNodesByObject[$objectID] = array(); foreach ( $assignedNodes as $assignedNode ) { $assignedNodesByObject[$objectID][] = $assignedNode->attribute( 'node_id' ); } } // Store the node assignment we want to delete // Then compare the array to the referent node assignment array $nodesToDeleteByObject[$objectID][] = $node->attribute( 'node_id' ); $diff = array_diff( $assignedNodesByObject[$objectID], $nodesToDeleteByObject[$objectID] ); if ( !empty( $diff ) ) // We still have more node assignments for object, pending action is not to be deleted considering this iteration { continue; } } if ( $delayedIndexingValue !== 'classbased' || ( is_array( $classList ) && in_array( $object->attribute( 'class_identifier' ), $classList ) ) ) { $pendingActionsToDelete[] = $objectID; } } if ( !empty( $pendingActionsToDelete ) ) { $filterConds = array( 'param' => array ( $pendingActionsToDelete ) ); eZPendingActions::removeByAction( 'index_object', $filterConds ); } } eZContentObjectTreeNode::removeSubtrees( $deleteIDArray, $moveToTrash ); return array( 'status' => true ); } /** * Changes an contentobject's status * * @param int $nodeID * * @return array An array with operation status, always true */ static public function changeHideStatus( $nodeID ) { $action = 'hide'; $curNode = eZContentObjectTreeNode::fetch( $nodeID ); if ( is_object( $curNode ) ) { if ( $curNode->attribute( 'is_hidden' ) ) { eZContentObjectTreeNode::unhideSubTree( $curNode ); $action = 'show'; } else eZContentObjectTreeNode::hideSubTree( $curNode ); } //call appropriate method from search engine eZSearch::updateNodeVisibility( $nodeID, $action ); return array( 'status' => true ); } /** * Swap a node with another one * * @param int $nodeID * @param int $selectedNodeID * @param array $nodeIdList * * @return array An array with operation status, always true */ static public function swapNode( $nodeID, $selectedNodeID, $nodeIdList = array() ) { $userClassIDArray = eZUser::contentClassIDs(); $node = eZContentObjectTreeNode::fetch( $nodeID ); $selectedNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $object = $node->object(); $nodeParentNodeID = $node->attribute( 'parent_node_id' ); $nodeParent = $node->attribute( 'parent' ); $objectID = $object->attribute( 'id' ); $objectVersion = $object->attribute( 'current_version' ); $selectedObject = $selectedNode->object(); $selectedObjectID = $selectedObject->attribute( 'id' ); $selectedObjectVersion = $selectedObject->attribute( 'current_version' ); $selectedNodeParentNodeID = $selectedNode->attribute( 'parent_node_id' ); $selectedNodeParent = $selectedNode->attribute( 'parent' ); $db = eZDB::instance(); $db->begin(); $node->setAttribute( 'contentobject_id', $selectedObjectID ); $node->setAttribute( 'contentobject_version', $selectedObjectVersion ); $selectedNode->setAttribute( 'contentobject_id', $objectID ); $selectedNode->setAttribute( 'contentobject_version', $objectVersion ); // fix main node id if ( $node->isMain() && !$selectedNode->isMain() ) { $node->setAttribute( 'main_node_id', $selectedNode->attribute( 'main_node_id' ) ); $selectedNode->setAttribute( 'main_node_id', $selectedNode->attribute( 'node_id' ) ); } else if ( $selectedNode->isMain() && !$node->isMain() ) { $selectedNode->setAttribute( 'main_node_id', $node->attribute( 'main_node_id' ) ); $node->setAttribute( 'main_node_id', $node->attribute( 'node_id' ) ); } $node->store(); $selectedNode->store(); // clear user policy cache if this was a user object if ( in_array( $object->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $object->attribute( 'id' ) ); } if ( in_array( $selectedObject->attribute( 'contentclass_id' ), $userClassIDArray ) ) { eZUser::purgeUserCacheByUserId( $selectedObject->attribute( 'id' ) ); } // modify path string $changedOriginalNode = eZContentObjectTreeNode::fetch( $nodeID ); $changedOriginalNode->updateSubTreePath(); $changedTargetNode = eZContentObjectTreeNode::fetch( $selectedNodeID ); $changedTargetNode->updateSubTreePath(); // modify section if ( $changedOriginalNode->isMain() ) { $changedOriginalObject = $changedOriginalNode->object(); $parentObject = $nodeParent->object(); if ( $changedOriginalObject->attribute( 'section_id' ) != $parentObject->attribute( 'section_id' ) ) { eZContentObjectTreeNode::assignSectionToSubTree( $changedOriginalNode->attribute( 'main_node_id' ), $parentObject->attribute( 'section_id' ), $changedOriginalObject->attribute( 'section_id' ) ); } } if ( $changedTargetNode->isMain() ) { $changedTargetObject = $changedTargetNode->object(); $selectedParentObject = $selectedNodeParent->object(); if ( $changedTargetObject->attribute( 'section_id' ) != $selectedParentObject->attribute( 'section_id' ) ) { eZContentObjectTreeNode::assignSectionToSubTree( $changedTargetNode->attribute( 'main_node_id' ), $selectedParentObject->attribute( 'section_id' ), $changedTargetObject->attribute( 'section_id' ) ); } } eZContentObject::fixReverseRelations( $objectID, 'swap' ); eZContentObject::fixReverseRelations( $selectedObjectID, 'swap' ); $db->commit(); // clear cache for new placement. eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); eZSearch::swapNode( $nodeID, $selectedNodeID, $nodeIdList = array() ); return array( 'status' => true ); } /** * Assigns a node to a section * * @param int $nodeID * @param int $selectedSectionID * * @return array An array with operation status, always true */ static public function updateSection( $nodeID, $selectedSectionID ) { eZContentObjectTreeNode::assignSectionToSubTree( $nodeID, $selectedSectionID ); } /** * Changes the status of a translation * * @param int $objectID * @param int $status * * @return array An array with operation status, always true */ static public function changeTranslationAvailableStatus( $objectID, $status = false ) { $object = eZContentObject::fetch( $objectID ); if ( !$object->canEdit() ) { return array( 'status' => false ); } if ( $object->isAlwaysAvailable() & $status == false ) { $object->setAlwaysAvailableLanguageID( false ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); } else if ( !$object->isAlwaysAvailable() & $status == true ) { $object->setAlwaysAvailableLanguageID( $object->attribute( 'initial_language_id' ) ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); } return array( 'status' => true ); } /** * Changes the sort order for a node * * @param int $nodeID * @param string $sortingField * @param bool $sortingOrder * * @return array An array with operation status, always true */ static public function changeSortOrder( $nodeID, $sortingField, $sortingOrder = false ) { $curNode = eZContentObjectTreeNode::fetch( $nodeID ); if ( is_object( $curNode ) ) { $db = eZDB::instance(); $db->begin(); $curNode->setAttribute( 'sort_field', $sortingField ); $curNode->setAttribute( 'sort_order', $sortingOrder ); $curNode->store(); $db->commit(); $object = $curNode->object(); eZContentCacheManager::clearContentCache( $object->attribute( 'id' ) ); } return array( 'status' => true ); } /** * Updates the priority of a node * * @param int $parentNodeID * @param array $priorityArray * @param array $priorityArray * * @return array An array with operation status, always true */ static public function updatePriority( $parentNodeID, $priorityArray = array(), $priorityIDArray = array() ) { $curNode = eZContentObjectTreeNode::fetch( $parentNodeID ); if ( $curNode instanceof eZContentObjectTreeNode ) { $db = eZDB::instance(); $db->begin(); for ( $i = 0, $l = count( $priorityArray ); $i < $l; $i++ ) { $priority = (int) $priorityArray[$i]; $nodeID = (int) $priorityIDArray[$i]; $db->query( "UPDATE ezcontentobject_tree SET priority={$priority} WHERE node_id={$nodeID} AND parent_node_id={$parentNodeID}" ); } $curNode->updateAndStoreModified(); $db->commit(); } return array( 'status' => true ); } /** * Update a node's main assignment * * @param int $mainAssignmentID * @param int $objectID * @param int $mainAssignmentParentID * * @return array An array with operation status, always true */ static public function updateMainAssignment( $mainAssignmentID, $ObjectID, $mainAssignmentParentID ) { eZContentObjectTreeNode::updateMainNodeID( $mainAssignmentID, $ObjectID, false, $mainAssignmentParentID ); eZContentCacheManager::clearContentCacheIfNeeded( $ObjectID ); return array( 'status' => true ); } /** * Updates an contentobject's initial language * * @param int $objectID * @param int $newInitialLanguageID * * @return array An array with operation status, always true */ static public function updateInitialLanguage( $objectID, $newInitialLanguageID ) { $object = eZContentObject::fetch( $objectID ); $language = eZContentLanguage::fetch( $newInitialLanguageID ); if ( $language and !$language->attribute( 'disabled' ) ) { $object->setAttribute( 'initial_language_id', $newInitialLanguageID ); $objectName = $object->name( false, $language->attribute( 'locale' ) ); $object->setAttribute( 'name', $objectName ); $object->store(); if ( $object->isAlwaysAvailable() ) { $object->setAlwaysAvailableLanguageID( $newInitialLanguageID ); } $nodes = $object->assignedNodes(); foreach ( $nodes as $node ) { $node->updateSubTreePath(); } } eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Set the always available flag for a content object * * @param int $objectID * @param int $newAlwaysAvailable * @return array An array with operation status, always true */ static public function updateAlwaysAvailable( $objectID, $newAlwaysAvailable ) { $object = eZContentObject::fetch( $objectID ); $change = false; if ( $object->isAlwaysAvailable() & $newAlwaysAvailable == false ) { $object->setAlwaysAvailableLanguageID( false ); $change = true; } else if ( !$object->isAlwaysAvailable() & $newAlwaysAvailable == true ) { $object->setAlwaysAvailableLanguageID( $object->attribute( 'initial_language_id' ) ); $change = true; } if ( $change ) { eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); if ( !eZSearch::getEngine() instanceof eZSearchEngine ) { eZContentOperationCollection::registerSearchObject( $objectID ); } } return array( 'status' => true ); } /** * Removes a translation for a contentobject * * @param int $objectID * @param array * @return array An array with operation status, always true */ static public function removeTranslation( $objectID, $languageIDArray ) { $object = eZContentObject::fetch( $objectID ); foreach( $languageIDArray as $languageID ) { if ( !$object->removeTranslation( $languageID ) ) { eZDebug::writeError( "Object with id $objectID: cannot remove the translation with language id $languageID!", __METHOD__ ); } } eZContentOperationCollection::registerSearchObject( $objectID ); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Update a contentobject's state * * @param int $objectID * @param int $selectedStateIDList * * @return array An array with operation status, always true */ static public function updateObjectState( $objectID, $selectedStateIDList ) { $object = eZContentObject::fetch( $objectID ); // we don't need to re-assign states the object currently already has assigned $currentStateIDArray = $object->attribute( 'state_id_array' ); $selectedStateIDList = array_diff( $selectedStateIDList, $currentStateIDArray ); // filter out any states the current user is not allowed to assign $canAssignStateIDList = $object->attribute( 'allowed_assign_state_id_list' ); $selectedStateIDList = array_intersect( $selectedStateIDList, $canAssignStateIDList ); foreach ( $selectedStateIDList as $selectedStateID ) { $state = eZContentObjectState::fetchById( $selectedStateID ); $object->assignState( $state ); } //call appropriate method from search engine eZSearch::updateObjectState($objectID, $selectedStateIDList); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Executes the pre-publish trigger for this object, and handles * specific return statuses from the workflow * * @param int $objectID Object ID * @param int $version Version number * * @since 4.2 */ static public function executePrePublishTrigger( $objectID, $version ) { } /** * Creates a RSS/ATOM Feed export for a node * * @param int $nodeID Node ID * * @since 4.3 */ static public function createFeedForNode( $nodeID ) { $hasExport = eZRSSFunctionCollection::hasExportByNode( $nodeID ); if ( isset( $hasExport['result'] ) && $hasExport['result'] ) { eZDebug::writeError( 'There is already a rss/atom export feed for this node: ' . $nodeID, __METHOD__ ); return array( 'status' => false ); } $node = eZContentObjectTreeNode::fetch( $nodeID ); $currentClassIdentifier = $node->attribute( 'class_identifier' ); $config = eZINI::instance( 'site.ini' ); $feedItemClasses = $config->variable( 'RSSSettings', 'DefaultFeedItemClasses' ); if ( !$feedItemClasses || !isset( $feedItemClasses[ $currentClassIdentifier ] ) ) { eZDebug::writeError( "EnableRSS: content class $currentClassIdentifier is not defined in site.ini[RSSSettings]DefaultFeedItemClasses[<class_id>].", __METHOD__ ); return array( 'status' => false ); } $object = $node->object(); $objectID = $object->attribute('id'); $currentUserID = eZUser::currentUserID(); $rssExportItems = array(); $db = eZDB::instance(); $db->begin(); $rssExport = eZRSSExport::create( $currentUserID ); $rssExport->setAttribute( 'access_url', 'rss_feed_' . $nodeID ); $rssExport->setAttribute( 'node_id', $nodeID ); $rssExport->setAttribute( 'main_node_only', '1' ); $rssExport->setAttribute( 'number_of_objects', $config->variable( 'RSSSettings', 'NumberOfObjectsDefault' ) ); $rssExport->setAttribute( 'rss_version', $config->variable( 'RSSSettings', 'DefaultVersion' ) ); $rssExport->setAttribute( 'status', eZRSSExport::STATUS_VALID ); $rssExport->setAttribute( 'title', $object->name() ); $rssExport->store(); $rssExportID = $rssExport->attribute( 'id' ); foreach( explode( ';', $feedItemClasses[$currentClassIdentifier] ) as $classIdentifier ) { $iniSection = 'RSSSettings_' . $classIdentifier; if ( $config->hasVariable( $iniSection, 'FeedObjectAttributeMap' ) ) { $feedObjectAttributeMap = $config->variable( $iniSection, 'FeedObjectAttributeMap' ); $subNodesMap = $config->hasVariable( $iniSection, 'Subnodes' ) ? $config->variable( $iniSection, 'Subnodes' ) : array(); $rssExportItem = eZRSSExportItem::create( $rssExportID ); $rssExportItem->setAttribute( 'class_id', eZContentObjectTreeNode::classIDByIdentifier( $classIdentifier ) ); $rssExportItem->setAttribute( 'title', $feedObjectAttributeMap['title'] ); if ( isset( $feedObjectAttributeMap['description'] ) ) $rssExportItem->setAttribute( 'description', $feedObjectAttributeMap['description'] ); if ( isset( $feedObjectAttributeMap['category'] ) ) $rssExportItem->setAttribute( 'category', $feedObjectAttributeMap['category'] ); if ( isset( $feedObjectAttributeMap['enclosure'] ) ) $rssExportItem->setAttribute( 'enclosure', $feedObjectAttributeMap['enclosure'] ); $rssExportItem->setAttribute( 'source_node_id', $nodeID ); $rssExportItem->setAttribute( 'status', eZRSSExport::STATUS_VALID ); $rssExportItem->setAttribute( 'subnodes', isset( $subNodesMap[$currentClassIdentifier] ) && $subNodesMap[$currentClassIdentifier] === 'true' ); $rssExportItem->store(); } else { eZDebug::writeError( "site.ini[$iniSection]Source[] setting is not defined.", __METHOD__ ); } } $db->commit(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Removes a RSS/ATOM Feed export for a node * * @param int $nodeID Node ID * * @since 4.3 */ static public function removeFeedForNode( $nodeID ) { $rssExport = eZPersistentObject::fetchObject( eZRSSExport::definition(), null, array( 'node_id' => $nodeID, 'status' => eZRSSExport::STATUS_VALID ), true ); if ( !$rssExport instanceof eZRSSExport ) { eZDebug::writeError( 'DisableRSS: There is no rss/atom feeds left to delete for this node: '. $nodeID, __METHOD__ ); return array( 'status' => false ); } $node = eZContentObjectTreeNode::fetch( $nodeID ); if ( !$node instanceof eZContentObjectTreeNode ) { eZDebug::writeError( 'DisableRSS: Could not fetch node: '. $nodeID, __METHOD__ ); return array( 'status' => false ); } $objectID = $node->attribute('contentobject_id'); $rssExport->removeThis(); eZContentCacheManager::clearContentCacheIfNeeded( $objectID ); return array( 'status' => true ); } /** * Sends the published object/version for publishing to the queue * Used by the content/publish operation * @param int $objectId * @param int $version * * @return array( status => int ) * @since 4.5 */ public static function sendToPublishingQueue( $objectId, $version ) { $behaviour = ezpContentPublishingBehaviour::getBehaviour(); if ( $behaviour->disableAsynchronousPublishing ) $asyncEnabled = false; else $asyncEnabled = ( eZINI::instance( 'content.ini' )->variable( 'PublishingSettings', 'AsynchronousPublishing' ) == 'enabled' ); $accepted = true; if ( $asyncEnabled === true ) { // Filter handlers $ini = eZINI::instance( 'content.ini' ); $filterHandlerClasses = $ini->variable( 'PublishingSettings', 'AsynchronousPublishingFilters' ); if ( count( $filterHandlerClasses ) ) { $versionObject = eZContentObjectVersion::fetchVersion( $version, $objectId ); foreach( $filterHandlerClasses as $filterHandlerClass ) { if ( !class_exists( $filterHandlerClass ) ) { eZDebug::writeError( "Unknown asynchronous publishing filter handler class '$filterHandlerClass'", __METHOD__ ); continue; } $handler = new $filterHandlerClass( $versionObject ); if ( !( $handler instanceof ezpAsynchronousPublishingFilterInterface ) ) { eZDebug::writeError( "Asynchronous publishing filter handler class '$filterHandlerClass' does not implement ezpAsynchronousPublishingFilterInterface", __METHOD__ ); continue; } $accepted = $handler->accept(); if ( !$accepted ) { eZDebugSetting::writeDebug( "Object #{$objectId}/{$version} was excluded from asynchronous publishing by $filterHandlerClass", __METHOD__ ); break; } } } unset( $filterHandlerClasses, $handler ); } if ( $asyncEnabled && $accepted ) { // if the object is already in the process queue, we move ahead // this test should NOT be necessary since http://issues.ez.no/17840 was fixed if ( ezpContentPublishingQueue::isQueued( $objectId, $version ) ) { return array( 'status' => eZModuleOperationInfo::STATUS_CONTINUE ); } // the object isn't in the process queue, this means this is the first time we execute this method // the object must be queued else { ezpContentPublishingQueue::add( $objectId, $version ); return array( 'status' => eZModuleOperationInfo::STATUS_HALTED, 'redirect_url' => "content/queued/{$objectId}/{$version}" ); } } else { return array( 'status' => eZModuleOperationInfo::STATUS_CONTINUE ); } } } ?>
davidrousse/ezpuplish
app/ezpublish_legacy/kernel/content/ezcontentoperationcollection.php
PHP
gpl-2.0
59,543
Rails.application.routes.draw do get 'dashboard/index' get 'pages/home' devise_for :users, path_names: { sign_in: 'login', sign_out: 'logout', password: 'secret', confirmation: 'verification', unlock: 'unlock', registration: 'account', sign_up: 'registration' } devise_scope :user do # HACK: For debugging purposes until I actualy make a link get '/logout' => 'devise/sessions#destroy' end root to: 'dashboard#index' end
joshminnie/maxwell
config/routes.rb
Ruby
gpl-2.0
497
<?php /** * @info * * Generic relationship display template */ ?> <div id="relationship-<?php print $relationship->relation_type . '-' . $relationship->rid; ?>" class="<?php print $classes; ?> clearfix"<?php print $attributes; ?>> <?php if ($view_mode !== 'full'): ?> <?php endif; ?> <?php if ($view_mode === 'full'): ?> <?php endif; ?> </div>
Trellon/crmcoredemo
profiles/crm_core_np/themes/crm_core_demo/templates/relationships/relationship.tpl.php
PHP
gpl-2.0
360
package com.austinv11.collectiveframework.utils; /** * Simple class for figuring out how long things take to be done */ public class TimeProfiler { private long startTime; /** * Starts a profiler at the current instant */ public TimeProfiler() { startTime = System.currentTimeMillis(); } /** * Gets the amount of time lapsed from instantiation to the method call * @return The time (in ms) */ public long getTime() { return System.currentTimeMillis()-startTime; } /** * Gets the time this object was instantiated at * @return The time (in ms) */ public long getStartTime() { return startTime; } }
austinv11/CollectiveFramework
src/main/java/com/austinv11/collectiveframework/utils/TimeProfiler.java
Java
gpl-2.0
640
<?php /** * "YAML for Joomla Template" - http://www.jyaml.de * * (en) CSS-Tidy Plugin to reduce filesize of stylsheets * (en) CSS-Tidy Plugin zum reduzieren der Dateigröße der Stylesheets * * @version $Id: css_optimizer.php 423 2008-07-01 11:44:05Z hieblmedia $ * @copyright Copyright 2005-2008, Reinhard Hiebl * @license CC-A 2.0/JYAML-C(all media,html,css,js,...) and GNU/GPL(php), - see http://www.jyaml.de/en/license-conditions.html * @link http://www.jyaml.de * @package yamljoomla * @revision $Revision: 423 $ * @lastmodified $Date: 2008-07-01 13:44:05 +0200 (Di, 01. Jul 2008) $ */ /* No direct access to this file | Kein direkter Zugriff zu dieser Datei */ defined( '_JEXEC' ) or die( 'Restricted access' ); class css_optimizer extends JYAML { var $JYAML = array(); // can overwrite share $jyaml object var $JYAMLc = array(); // can overwrite share of $jyaml->config object var $jyaml; function css_optimizer($params, $jyaml) { global $mainframe; $this->jyaml = $jyaml; /// !!!!!!!!!! Check with jigsaw css validator response for valid stylesheets before process tidy /* not implemented yet */ $logs = array(); // setting/params $output_path = 'slim'; //$exclude_files = $params->get( 'exclude_files', '' ); //$exclude_folders = $params->get( 'exclude_folders', '' ); $exclude['folders'] = array('patches'); $compression = $params->get( 'compression', 'default' ); $merge_files = $params->get( 'merge_files', false ); $css = ''; $hash_array = array(); $stylesheets = array(); $old_size = 0; $new_site = 0; // Set Paths $path = JPATH_SITE.DS.'templates'.DS.$jyaml->template.DS.'css'.DS.$jyaml->config->design; $path_new = JPATH_SITE.DS.'templates'.DS.$jyaml->template.DS.'css'.DS.$jyaml->config->design.'.'.$output_path; // set new folder for css in template configuration $this->JYAMLc['css_folder'] = $jyaml->config->css_folder.'.'.$output_path; // If tidy dir exists then return or otherwise start tidy with url request if (!$merge_files && !JRequest::getVar('doOptimizeCSS', false) ) { return true; } // Delete tidy folder to reduce non used files - only if merge_files is disabled if (!$merge_files && JRequest::getVar('doOptimizeCSS', false)) if ( JFolder::exists($path_new) ) JFolder::delete($path_new); /** * Merge **/ if ($merge_files) { // Get current basic layout file and files set in configuration $basic_file = $path.DS.'layout_'.$jyaml->config->layout.'.css'; $basic_patch_ext = 'patches'.DS.'patch_'; $hash_array[] = $basic_file; $css = JFile::read($basic_file); // Get files in configuration foreach ($jyaml->config->addStylesheets as $file => $attribs) { if ($attribs['browser']) { $stylesheets[$file] = $attribs; continue; } if (strpos($file, '{DesignCssFolder}')!==false) { $file = str_replace('/{DesignCssFolder}/', '', $file); } else { $file = "../..".$file; } $css .= "\n@import url(".$file.");\n"; $hash_array[] = $file; } // Remove stylesheets from configuration - else debug view errors $this->JYAMLc['addStylesheets'] = $stylesheets; // Generate Hashname with Stylesheet names - faster as each site. $hash = $this->genHash($hash_array); if ($hash) { $file = $path_new.DS.'layout_'.$hash.'.css'; if (!JFile::exists($file) || JRequest::getVar('doTidy', false)) { $merged_css = $this->getImports($css); $old_size = $this->get_size(mb_strlen($merged_css)); $merged_css = $this->optimize_css($merged_css); $new_size = $this->get_size(mb_strlen($merged_css)); JFile::write($file, $merged_css); if (!JFolder::exists($path_new.DS.'patches')) JFolder::create($path_new.DS.'patches'); JFile::copy($path.DS.'patches'.DS.'patch_'.$jyaml->config->layout.'.css', $path_new.DS.'patches'.DS.'patch_'.$hash.'.css'); $this->JYAMLc['layout'] = $hash; } else { $this->JYAMLc['layout'] = $hash; return true; } } else { return false; } } // Copy all Files for compatibility without excludes from settings NOT Tidy (1:1) // Get files $files = $this->getCSSFiles($path, $jyaml, $exclude); if ( $fa=$files['all'] ) { // Copy all Files foreach ($fa as $file) { $css_code = JFile::read($file); $path_file = dirname($file); $path_tidy = str_replace($path, $path_new, dirname($file)); $file_tidy = $path_tidy.DS.basename($file); JFolder::create($path_tidy); JFile::write($file_tidy, $css_code); } } if ($fi=$files['included']) { // Copy optimized included files foreach ($fi as $file) { $css_code = JFile::read($file); $css_code = $this->optimize_css($css_code); $path_file = dirname($file); $path_tidy = str_replace($path, $path_new, dirname($file)); $file_tidy = $path_tidy.DS.basename($file); JFolder::create($path_tidy); JFile::write($file_tidy, $css_code); } } // Debug Mode if ($jyaml->config->debug) { $sizeinfo = 'Filesiez before: '.$old_size.' KB - Filesize after: '. $new_size.' KB<br />'; $sizeinfo .= '<strong style="color:green;">Reduced overall size to: '.round(100-$new_size/($old_size/100), 2)."%</strong>"; $this->JYAML['pgl_logs_onBefore'][] = '<div style="text-align:left; background:#000; border:1px solid #ccc; margin:0 .5em; padding:.5em 1em; color:#fff;" class="trans75"><span style="text-decoration:underline;">CSS Optimizer Log</span><br />'; $this->JYAML['pgl_logs_onBefore'][] = $sizeinfo.'</div>'; } else { //$mainframe->enqueueMessage( 'CSS Tidy has parsed CSS files' ); } } function get_size($size) { $size = $size / 1024; return round($size, 2); } function genHash($array=false) { if ($array) { return md5( implode($array, '')); } else { return false; } } function getImports($matches=false) { if (is_array($matches)) { $file = str_replace(array("(", ")", "\"", "'"), "", $matches[1]); $file = str_replace("/", DS, $file); $path = JPATH_SITE.DS.'templates'.DS.$this->jyaml->template.DS.'css'.DS.$this->jyaml->config->design; if (strpos($file, $path)===false) $file = $path.DS.$file; $file_tmp = $file; // Get content and replace recusive paths $content = false; if (JFile::exists($file)) { $matches = JFile::read($file); // Replace recurisve paths to can find file $matches = preg_replace("/@import\s+url\((.*)\);/", "@import url(".dirname($file_tmp)."/\\1);", $matches); } else { $matches = $file; } $matches = $this->replaceCssURLs($matches, dirname($file)); } return preg_replace_callback("/@import\s+url(.*);/", array( &$this, 'getImports' ), $matches); } function replaceCssURLs($code, $dir) { $dir = str_replace(JPATH_SITE.DS.'templates'.DS.$this->jyaml->template, '', $dir); $dir = '../..'.str_replace('\\', '/', $dir).'/'; $code = str_replace(array("('", "(\""), "(", $code); $code = str_replace(array("')", "\")"), ")", $code); $code = preg_replace("/(.*:)\s+?url\((.*\))/", "\\1 url($dir\\2", $code); return $code; } function getCSSFiles($path, $jyaml, $exclude=array(), $recurse=true) { $files = array(); $files['all'] = JFolder::files($path, '.css$', $recurse, true); $files['included'] = JFolder::files($path, '.css$', $recurse, true, $exclude['folders']); return $files; } function viewLog($css, $file, $file_tidy) { $ratio = $css->print->get_ratio(); $diff = $css->print->get_diff(); if ($ratio > 0) { $ratio = '<span style="color:green;">'.$ratio.'%</span> ('.$diff.' Bytes)'; } else { $ratio = '<span style="color:red;">'.$ratio.'%</span> ('.$diff.' Bytes)'; } $log = '<div class="trans75" style="text-align:left; background:#000; border:1px solid #ccc; margin:1em; padding:1em; color:#fff;">'; $log .= '<fieldset style="border:1px solid #eee; background:transparent; padding:.5em;">'; $log .= '<legend style="padding:0 .5em;"> Result: '.$ratio.'</legend>'; $log .= 'Source File: '.str_replace(JPATH_SITE, '', $file).' --- Size: <span style="color:red;">'.$css->print->size('input').'</span>kb<br />'; $log .= 'Destination File: '.str_replace(JPATH_SITE, '', $file_tidy).' --- Size: <span style="color:green; font-weight:bold;">'.$css->print->size('output').'</span>kb'; if (count($css->log) > 0) { $log .= '<br /><br /><fieldset id="messages"><legend>Messages</legend>'; $log .= '<div><dl>'; foreach ($css->log as $line => $array) { $log .= '<dt>Line: '.$line.'</dt>'; for ($i = 0; $i < count($array); $i ++) { $log .= '<dd class="'.$array[$i]['t'].'">'.$array[$i]['m'].'</dd>'; } } $log .= '</dl></div></fieldset>'; } $log .= '</fieldset>'; $log .= '</div>'; return $log; } function optimize_css($css) { $css = preg_replace('/@charset\s+[\'"](\S*)\b[\'"];/i', '', $css); /* Replace Hacks */ $css = preg_replace("#/\*\*/:/\*\*/#sU", "~~IE6HACK1~~", $css); // IE6.0 Hack /**/:/**/ $replace = array( "#/\*.+\*/#sU" => "", // Strip comments "#\s\s+#" => " " // Strip whitespaces ); $search = array_keys($replace); $css = preg_replace($search, $replace, $css); $replace = array( ": " => ":", "; " => ";", " {" => "{", " }" => "}", ", " => ",", "{ " => "{", ";}" => "}", // Strip optional semicolons. "\n" => "", // Remove linebreaks ); $search = array_keys($replace); $css = str_replace($search, $replace, $css); $csscomment = "@charset \"UTF-8\";\n"; $csscomment .= "/**\n"; $csscomment .= " * \"YAML for Joomla Template\" - http://www.jyaml.de\n"; $csscomment .= " * @created by JYAML CSS Optimizer\n"; $csscomment .= " * @package jyaml\n"; $csscomment .= "*/\n"; /* Replace Hacks */ $css = str_replace("~~IE6HACK1~~", "/**/:/**/", $css); // IE6.0 Hack /**/:/**/ $css = $csscomment.trim($css); return $css; } } ?>
albertobraschi/Hab
templates/hm_yaml/plugins/css_optimizer/css_optimizer.php
PHP
gpl-2.0
11,216
// Complex API code public class ComplexPricingStrategy { int calculateAirlinePricing(String source, String destination) { return source.length() + destination.length(); } int calculateProprtyValuation(String location) { return (location.length() * 150 % 40 + 12345 - 50) >> 1; } int calculateOilValuation(String location) { int arbitrary_oil_weight = 87; int complex_oil_expression = (arbitrary_oil_weight * 13) * 321; return (complex_oil_expression * location.length()) << 2; } }
craigcabrey/swen-343-base-patterns-examples
gateway/ComplexPricingStrategy.java
Java
gpl-2.0
509
from netools import nextIpInPool, ping, aliveHost, hostsUnDone def main(): aliveHosts = [] # pool IP ipStart = "192.168.56.1" ipEnd = "192.168.56.5" print"Pools: ", ipStart + " -> " + ipEnd print"Scanning online Router on network..." aliveHosts = aliveHost(ipStart, ipEnd) print "online Router:" print aliveHosts # print"New Hosts Alive in Pools:",hostsUnDone(aliveHosts, aliveHost(ipStart,ipEnd)) if __name__ == '__main__': main()
gravufo/commotion-router-testbench
ping/mainTest.py
Python
gpl-2.0
479
<?php /** * @package WordPress * @subpackage Increase * @since Increase 1.1.5 * * Post, Page & Project Options Functions * Created by CMSMasters * */ require_once(CMSMS_OPTIONS . '/cmsms-theme-options-general.php'); require_once(CMSMS_OPTIONS . '/cmsms-theme-options-post.php'); require_once(CMSMS_OPTIONS . '/cmsms-theme-options-page.php'); require_once(CMSMS_OPTIONS . '/cmsms-theme-options-project.php'); require_once(CMSMS_OPTIONS . '/cmsms-theme-options-testimonial.php'); global $custom_meta_fields, $custom_post_meta_fields, $custom_page_meta_fields, $custom_project_meta_fields, $custom_testimonial_meta_fields; if ( (isset($_GET['post_type']) && $_GET['post_type'] == 'page') || (isset($_POST['post_type']) && $_POST['post_type'] == 'page') || (isset($_GET['post']) && get_post_type($_GET['post']) == 'page') ) { $custom_all_meta_fields = array_merge($custom_page_meta_fields, $custom_meta_fields); } elseif ( (isset($_GET['post_type']) && $_GET['post_type'] == 'project') || (isset($_POST['post_type']) && $_POST['post_type'] == 'project') || (isset($_GET['post']) && get_post_type($_GET['post']) == 'project') ) { $custom_all_meta_fields = array_merge($custom_project_meta_fields, $custom_meta_fields); } elseif ( (isset($_GET['post_type']) && $_GET['post_type'] == 'testimonial') || (isset($_POST['post_type']) && $_POST['post_type'] == 'testimonial') || (isset($_GET['post']) && get_post_type($_GET['post']) == 'testimonial') ) { $custom_all_meta_fields = array_merge($custom_testimonial_meta_fields, $custom_meta_fields); } elseif ( (!isset($_GET['action']) && !isset($_GET['post_type'])) || (!isset($_GET['action']) && isset($_GET['post_type']) && $_GET['post_type'] != 'testimonial') || (isset($_POST['post_type']) && $_POST['post_type'] == 'post') || (isset($_GET['post']) && get_post_type($_GET['post']) == 'post') ) { $custom_all_meta_fields = array_merge($custom_post_meta_fields, $custom_meta_fields); } function cmsms_admin_enqueue_scripts($hook) { if ( ($hook == 'post.php') || ($hook == 'post-new.php') ) { wp_register_style('cmsms_theme_options_css', get_template_directory_uri() . '/framework/admin/options/css/cmsms-theme-options.css', array(), '1.0.0', 'screen'); wp_enqueue_style('wp-color-picker'); wp_enqueue_style('cmsms_theme_options_css'); wp_register_script('cmsms_theme_options_js', get_template_directory_uri() . '/framework/admin/options/js/cmsms-theme-options.js', array('jquery'), '1.0.0', true); wp_register_script('cmsms_theme_options_js_hide', get_template_directory_uri() . '/framework/admin/options/js/cmsms-theme-options-toggle.js', array('jquery'), '1.0.0', true); wp_enqueue_script('wp-color-picker'); wp_enqueue_script('cmsms_theme_options_js'); wp_enqueue_script('cmsms_theme_options_js_hide'); } } add_action('admin_enqueue_scripts', 'cmsms_admin_enqueue_scripts'); function show_cmsms_meta_box() { global $post, $custom_all_meta_fields; $cmsms_option = cmsms_get_global_options(); echo '<input type="hidden" name="custom_meta_box_nonce" value="' . wp_create_nonce(basename(__FILE__)) . '" />'; foreach ($custom_all_meta_fields as $field) { $meta = get_post_meta($post->ID, $field['id'], true); if (isset($field['std']) && $meta === '') { $meta = $field['std']; } if (!isset($field['hide'])) { $field['hide'] = 'false'; } if ( $field['type'] != 'tabs' && $field['type'] != 'tab_start' && $field['type'] != 'tab_finish' && $field['type'] != 'content_start' && $field['type'] != 'content_finish' ) { echo '<tr class="cmsms_tr_' . $field['type'] . '"' . (($field['hide'] == 'true') ? ' style="display:none;"' : '') . '>' . '<th>' . '<label for="' . $field['id'] . '">' . $field['label'] . '</label>' . '</th>' . '<td>'; } switch ($field['type']) { case 'tab_start': echo '<div id="' . $field['id'] . '" class="nav-tab-content' . (($field['std'] === 'true') ? ' nav-tab-content-active' : '') . '">' . '<table class="form-table">'; break; case 'tab_finish': echo '</table>' . '</div>'; break; case 'content_start': echo '<table id="' . $field['id'] . '" class="form-table' . (($field['box'] === 'true') ? ' cmsms_box' : '') . '"' . (($field['hide'] === 'true') ? ' style="display:none;"' : '') . '>'; break; case 'content_finish': echo '</table>'; break; case 'tabs': echo '<h4 class="nav-tab-wrapper" id="' . $field['id'] . '">'; foreach ($field['options'] as $option) { echo '<a href="#' . $option['value'] . '" class="nav-tab' . (($field['std'] === $option['value']) ? ' nav-tab-active' : '') . '">' . $option['label'] . '</a>'; } echo '</h4>'; break; case 'text': echo '<input type="text" name="' . $field['id'] . '" id="' . $field['id'] . '" value="' . $meta . '" size="30" />' . '<br />' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'textcode': echo '<input type="text" name="' . $field['id'] . '" id="' . $field['id'] . '" value="' . htmlspecialchars(stripslashes($meta)) . '" size="30" />' . '<br />' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'text_long': echo '<input type="text" name="' . $field['id'] . '" id="' . $field['id'] . '" value="' . $meta . '" size="70" />' . '<br />' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'number': echo '<input type="text" name="' . $field['id'] . '" id="' . $field['id'] . '" value="' . $meta . '" size="5" />' . '<br />' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'textarea': echo '<textarea name="' . $field['id'] . '" id="' . $field['id'] . '" cols="50" rows="4">' . $meta . '</textarea>' . '<br />' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'checkbox': echo '<input type="checkbox" name="' . $field['id'] . '" id="' . $field['id'] . '" value="true"' . (($meta === 'false') ? '' : ' checked="checked"') . ' /> &nbsp; ' . '<label for="' . $field['id'] . '">' . $field['desc'] . '</label>'; break; case 'radio': foreach ($field['options'] as $option) { echo '<input type="radio" name="' . $field['id'] . '" id="' . $field['id'] . '_' . $option['value'] . '" value="' . $option['value'] . '"' . (($meta === $option['value']) ? ' checked="checked"' : '') . ' /> &nbsp; ' . '<label for="' . $field['id'] . '_' . $option['value'] . '">' . $option['label'] . '</label>' . '<br />'; } echo '<span class="description">' . $field['desc'] . '</span>'; break; case 'radio_img': echo '<table>' . '<tr>'; foreach ($field['options'] as $option) { echo '<td style="text-align:center;">' . '<input type="radio" name="' . $field['id'] . '" id="' . $field['id'] . '_' . $option['value'] . '" value="' . $option['value'] . '"' . (($meta === $option['value']) ? ' checked="checked"' : '') . ' />' . '<br />' . '<label for="' . $field['id'] . '_' . $option['value'] . '">' . '<img src="' . $option['img'] . '" alt="' . $option['label'] . '" />' . '<br />' . $option['label'] . '</label>' . '</td>'; } echo '</tr>' . '</table>' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'checkbox_group': $i = 0; foreach ($field['options'] as $option) { echo '<input type="checkbox" value="' . $option['value'] . '" name="' . $field['id'] . '[' . $i . ']" id="' . $field['id'] . '_' . $option['value'] . '"' . (($meta && in_array($option['value'], $meta)) ? ' checked="checked"' : '') . ' /> &nbsp; ' . '<label for="' . $field['id'] . '_' . $option['value'] . '">' . $option['label'] . '</label>' . '<br />'; $i++; } echo '<span class="description">' . $field['desc'] . '</span>'; break; case 'select': echo '<select name="' . $field['id'] . '" id="' . $field['id'] . '">'; foreach ($field['options'] as $option) { echo '<option value="' . $option['value'] . '"' . (($meta === $option['value']) ? ' selected="selected"' : '') . '>' . $option['label'] . ' &nbsp;</option>'; } echo '</select>' . '<br />' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'select_sidebar': echo '<select name="' . $field['id'] . '" id="' . $field['id'] . '">' . '<option value="">' . __('Default Sidebar', 'cmsmasters') . ' &nbsp;</option>'; if (!empty($cmsms_option[CMSMS_SHORTNAME . '_sidebar'])) { foreach ($cmsms_option[CMSMS_SHORTNAME . '_sidebar'] as $sidebar_id => $sidebar_name) { echo '<option value="' . generateSlug($sidebar_name, 45) . '"' . (($meta !== '' && $meta === generateSlug($sidebar_name, 45)) ? ' selected="selected"' : '') . '>' . $sidebar_name . ' &nbsp;</option>'; } } echo '</select>' . '<br />' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'select_slider': $sliderManager = new cmsmsSliderManager(); $sliders = $sliderManager->getSliders(); echo '<select name="' . $field['id'] . '" id="' . $field['id'] . '">' . '<option value="">' . __('Select Slider', 'cmsmasters') . ' &nbsp;</option>'; if (!empty($sliders)) { foreach ($sliders as $slider) { echo '<option value="' . $slider['id'] . '"' . (($meta !== '' && (int) $meta === $slider['id']) ? ' selected="selected"' : '') . '>' . $slider['name'] . ' &nbsp;</option>'; } } echo '</select>' . '<br />' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'select_post_categ': $categories = get_categories(); echo '<select name="' . $field['id'] . '" id="' . $field['id'] . '">' . '<option value="">' . __('Select Blog Category', 'cmsmasters') . ' &nbsp;</option>'; foreach ($categories as $category) { echo '<option value="' . $category->cat_ID . '"' . (($meta !== '' && $meta === $category->cat_ID) ? ' selected="selected"' : '') . '>' . $category->cat_name . ' &nbsp;</option>'; } echo '</select>' . '<br />' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'select_project_type': $types = get_terms('pj-categs', array( 'orderby' => 'name', 'hide_empty' => 0 )); echo '<select name="' . $field['id'] . '" id="' . $field['id'] . '">' . '<option value="">' . __('Select Project Type', 'cmsmasters') . ' &nbsp;</option>'; if (is_array($types) && !empty($types)) { foreach ($types as $type) { echo '<option value="' . $type->slug . '"' . (($meta !== '' && $meta === $type->slug) ? ' selected="selected"' : '') . '>' . $type->name . ' &nbsp;</option>'; } } echo '</select>' . '<br />' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'select_tl_categ': $tl_categs = get_terms('tl-categs', array( 'hide_empty' => 0 )); echo '<select name="' . $field['id'] . '" id="' . $field['id'] . '">' . '<option value="">' . __('Select Testimonial Category', 'cmsmasters') . ' &nbsp;</option>'; if (is_array($tl_categs) && !empty($tl_categs)) { foreach ($tl_categs as $tl_categ) { echo '<option value="' . $tl_categ->slug . '"' . (($meta !== '' && $meta === $tl_categ->slug) ? ' selected="selected"' : '') . '>' . $tl_categ->name . ' &nbsp;</option>'; } } echo '</select>' . '<br />' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'image': $image = $field['std']; if (is_numeric($image)) { $image = wp_get_attachment_image_src($image, 'medium'); $image = $image[0]; } echo '<span class="custom_default_image" style="display:none">' . $image . '</span>'; if (is_numeric($meta)) { $image = wp_get_attachment_image_src($meta, 'medium'); $image = $image[0]; } echo '<input id="' . $field['id'] . '" name="' . $field['id'] . '" type="hidden" class="custom_upload_image" value="' . $meta . '" />' . '<img src="' . $image . '" class="custom_preview_image" alt="" style="max-width:250px;" />' . '<br />' . '<input id="' . $field['id'] . '_image_button" class="cmsms_options_upload_image_button button" type="button" value="' . __('Choose Image', 'cmsmasters') . '" />' . '<small>&nbsp; ' . '<a href="#" class="custom_clear_image_button">' . (($field['cancel'] == 'true') ? __('Cancel', 'cmsmasters') : __('Default Image', 'cmsmasters')) . '</a>' . '</small>' . '<div style="clear:both;"></div>' . '<br />' . '<span class="description">' . $field['desc'] . '</span>' . '<script type="text/javascript">' . 'jQuery(document).ready(function () { ' . '(function ($) { ' . "$('#" . $field['id'] . "_image_button').bind('click', function (e) { " . 'e.preventDefault(); ' . '$(e.target).cmsmsMediaUploader( { ' . "frameId : 'cmsms-" . $field['id'] . "-media-frame', " . "frameClass : 'media-frame cmsms-media-frame cmsms-" . $field['id'] . "-media-frame', " . "frameTitle : '" . __('Choose image', 'cmsmasters') . "', " . "frameButton : '" . __('Choose', 'cmsmasters') . "', " . 'multiple : false ' . '} ); ' . '} ); ' . '} )(jQuery); ' . '} ); ' . '</script>'; break; case 'color': echo '<input type="text" id="' . $field['id'] . '" name="' . $field['id'] . '" value="' . $meta . '" class="my-color-field" data-default-color="' . $field['std'] . '" />' . '<script type="text/javascript">' . 'jQuery(document).ready(function () { ' . '(function ($) { ' . "$('#" . $field['id'] . "').wpColorPicker(); " . '} )(jQuery); ' . '} ); ' . '</script>'; break; case 'icon': echo '<input type="hidden" name="' . $field['id'] . '" id="' . $field['id'] . '" value="' . $meta . '" />' . '<ul class="cmsms_heading_icons_list">'; if (!empty($cmsms_option[CMSMS_SHORTNAME . '_heading_icons'])) { foreach ($cmsms_option[CMSMS_SHORTNAME . '_heading_icons'] as $icon_numb => $icon_id) { $image = wp_get_attachment_image_src($icon_id, 'thumbnail'); echo '<li id="cmsms_heading_icon_' . $icon_numb . '" class="cmsms_heading_icon ' . (($meta !== '' && $meta === $icon_id) ? ' selected' : '') . '">' . '<a href="' . $icon_id . '">' . '<img src="' . $image[0] . '" alt="" />' . '</a>' . '</li>'; } } else { echo '<li>' . __('Add new heading icons', 'cmsmasters') . ' <a href="' . admin_url() . 'admin.php?page=cmsms-settings-icon&tab=heading">' . __('here', 'cmsmasters') . '</a>.</li>'; } echo '</ul>' . '<div style="clear:both;"></div>' . '<a href="#" class="cmsms_heading_icons_cancel">' . __('Cancel', 'cmsmasters') . '</a>' . '<div style="clear:both;"></div>' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'repeatable': echo '<ul id="' . $field['id'] . '-repeatable" class="custom_repeatable">'; $i = 0; if ($meta) { foreach ($meta as $row) { if ($row !== '') { echo '<li>' . '<span class="sort hndle">|||</span>' . '<input type="text" name="' . $field['id'] . '[' . $i . ']" id="' . $field['id'] . '[' . $i . ']" value="' . $row . '" size="30" />' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } else if ($i === 0) { echo '<li style="display:none;">' . '<span class="sort hndle">|||</span>' . '<input type="text" name="' . $field['id'] . '[' . $i . ']" id="' . $field['id'] . '[' . $i . ']" value="" size="30" />' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } $i++; } } else { echo '<li style="display:none;">' . '<span class="sort hndle">|||</span>' . '<input type="text" name="' . $field['id'] . '[' . $i . ']" id="' . $field['id'] . '[' . $i . ']" value="" size="30" />' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } echo '</ul>' . '<a class="repeatable-add button" href="#">+</a>' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'repeatable_link': $post_items = get_posts(array( 'post_type' => 'post', 'posts_per_page' => -1 )); $page_items = get_posts(array( 'post_type' => 'page', 'posts_per_page' => -1 )); $project_items = get_posts(array( 'post_type' => 'project', 'posts_per_page' => -1 )); echo '<div class="ovh">' . '<div class="fl"><strong>' . __('Title', 'cmsmasters') . '</strong></div>' . '<div class="fl"><strong>' . __('Link', 'cmsmasters') . '</strong></div>' . '</div>' . '<ul id="' . $field['id'] . '-repeatable" class="custom_repeatable">'; $i = 0; if ($meta !== '') { foreach ($meta as $row) { if ($row[0] !== '' && $row[1] !== '') { echo '<li>' . '<span class="sort hndle"></span>' . '<input type="text" name="' . $field['id'] . '[' . $i . '][0]" id="' . $field['id'] . '[' . $i . '][0]" value="' . $row[0] . '" size="10" class="cmsms_name" />' . '<input type="text" name="' . $field['id'] . '[' . $i . '][1]" id="' . $field['id'] . '[' . $i . '][1]" value="' . $row[1] . '" size="25" class="cmsms_link" />' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } else if ($i === 0) { echo '<li style="display:none;">' . '<span class="sort hndle"></span>' . '<input type="text" name="' . $field['id'] . '[' . $i . '][0]" id="' . $field['id'] . '[' . $i . '][0]" value="" size="10" class="cmsms_name" />' . '<input type="text" name="' . $field['id'] . '[' . $i . '][1]" id="' . $field['id'] . '[' . $i . '][1]" value="" size="25" class="cmsms_link" />' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } $i++; } } else { echo '<li style="display:none;">' . '<span class="sort hndle"></span>' . '<input type="text" name="' . $field['id'] . '[' . $i . '][0]" id="' . $field['id'] . '[' . $i . '][0]" value="" size="10" class="cmsms_name" />' . '<input type="text" name="' . $field['id'] . '[' . $i . '][1]" id="' . $field['id'] . '[' . $i . '][1]" value="" size="25" class="cmsms_link" />' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } echo '</ul>' . '<select name="' . $field['id'] . '-select" id="' . $field['id'] . '-select">' . '<optgroup label="' . __('Blank Field', 'cmsmasters') . '">' . '<option value="">' . __('Select Link', 'cmsmasters') . '</option>' . '</optgroup>' . '<optgroup label="' . __('Posts', 'cmsmasters') . '">'; foreach ($post_items as $post_item) { echo '<option value="' . get_permalink($post_item->ID) . '">' . $post_item->post_title . '</option>'; } echo '</optgroup>' . '<optgroup label="' . __('Pages', 'cmsmasters') . '">'; foreach ($page_items as $page_item) { echo '<option value="' . get_permalink($page_item->ID) . '">' . $page_item->post_title . '</option>'; } echo '</optgroup>' . '<optgroup label="' . __('Projects', 'cmsmasters') . '">'; foreach ($project_items as $project_item) { echo '<option value="' . get_permalink($project_item->ID) . '">' . $project_item->post_title . '</option>'; } echo '</optgroup>' . '</select> &nbsp; ' . '<a class="repeatable-link-add button" href="#">+</a>' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'repeatable_multiple': echo '<div class="ovh">' . '<div class="fl"><strong>' . __('Title', 'cmsmasters') . '</strong></div>' . '<div class="fl"><strong>' . __('Values', 'cmsmasters') . '</strong></div>' . '</div>' . '<ul id="' . $field['id'] . '-repeatable" class="custom_repeatable">'; $i = 0; if ($meta !== '') { foreach ($meta as $row) { if ($row[0] !== '' && $row[1] !== '') { echo '<li>' . '<span class="sort hndle"></span>' . '<input type="text" name="' . $field['id'] . '[' . $i . '][0]" id="' . $field['id'] . '[' . $i . '][0]" value="' . $row[0] . '" size="10" class="cmsms_name" />' . '<textarea name="' . $field['id'] . '[' . $i . '][1]" id="' . $field['id'] . '[' . $i . '][1]" cols="25" rows="2" class="cmsms_val">' . $row[1] . '</textarea>' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } else if ($i === 0) { echo '<li style="display:none;">' . '<span class="sort hndle"></span>' . '<input type="text" name="' . $field['id'] . '[' . $i . '][0]" id="' . $field['id'] . '[' . $i . '][0]" value="" size="10" class="cmsms_name" />' . '<textarea name="' . $field['id'] . '[' . $i . '][1]" id="' . $field['id'] . '[' . $i . '][1]" cols="25" rows="2" class="cmsms_val"></textarea>' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } $i++; } } else { echo '<li style="display:none;">' . '<span class="sort hndle"></span>' . '<input type="text" name="' . $field['id'] . '[' . $i . '][0]" id="' . $field['id'] . '[' . $i . '][0]" value="" size="10" class="cmsms_name" />' . '<textarea name="' . $field['id'] . '[' . $i . '][1]" id="' . $field['id'] . '[' . $i . '][1]" cols="25" rows="2" class="cmsms_val"></textarea>' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } echo '</ul>' . '<a class="repeatable-multiple-add button" href="#">+</a>' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'repeatable_media': echo '<select name="' . $field['id'] . '-select" id="' . $field['id'] . '-select">' . '<option value="">' . __('Select Format', 'cmsmasters') . ' &nbsp;</option>'; foreach ($field['media'] as $key => $value) { echo '<option value="' . $key . '">' . $value . '</option>'; } echo '</select> &nbsp; ' . '<a class="repeatable-media-add button" href="#">+</a>' . '<br />' . '<ul id="' . $field['id'] . '-repeatable" class="custom_repeatable">'; $i = 0; if ($meta !== '') { foreach ($meta as $row) { if ($row[1] !== '') { echo '<li>' . '<input type="text" readonly="readonly" name="' . $field['id'] . '[' . $i . '][0]" id="' . $field['id'] . '[' . $i . '][0]" value="' . $row[0] . '" size="5" class="cmsms_format" />' . '<input type="text" name="' . $field['id'] . '[' . $i . '][1]" id="' . $field['id'] . '[' . $i . '][1]" value="' . $row[1] . '" size="30" class="cmsms_link" />' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } else if ($i === 0) { echo '<li style="display:none;">' . '<input type="text" readonly="readonly" name="' . $field['id'] . '[' . $i . '][0]" id="' . $field['id'] . '[' . $i . '][0]" value="" size="5" class="cmsms_format" />' . '<input type="text" name="' . $field['id'] . '[' . $i . '][1]" id="' . $field['id'] . '[' . $i . '][1]" value="" size="30" class="cmsms_link" />' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } $i++; } } else { echo '<li style="display:none;">' . '<input type="text" readonly="readonly" name="' . $field['id'] . '[' . $i . '][0]" id="' . $field['id'] . '[' . $i . '][0]" value="" size="5" class="cmsms_format" />' . '<input type="text" name="' . $field['id'] . '[' . $i . '][1]" id="' . $field['id'] . '[' . $i . '][1]" value="" size="30" class="cmsms_link" />' . '<a class="repeatable-remove button" href="#">x</a>' . '</li>'; } echo '</ul>' . '<span class="description">' . $field['desc'] . '</span>'; break; case 'images_list': if ($meta !== '') { $ids = array(); $meta_array = explode(',', $meta); foreach ($meta_array as $meta_val) { $ids[] = str_replace('img_', '', $meta_val); } } echo '<a href="#" id="' . $field['id'] . '_images_button" class="button open_gallery_post_image_list">' . __('Choose images', 'cmsmasters') . '</a>' . '<ul class="gallery_post_image_list selected_list">'; if ($meta !== '') { foreach ($ids as $id) { $image = wp_get_attachment_image_src($id, 'thumbnail'); echo '<li>' . '<a href="' . $id . '" style="background-image:url(' . $image[0] . ');">' . '<span></span>' . '</a>' . '</li>'; } } echo '</ul>' . '<input type="hidden" id="' . $field['id'] . '" name="' . $field['id'] . '" value="' . $meta . '" class="gallery_post_images" />' . '<span class="description">' . $field['desc'] . '</span>' . '<script type="text/javascript">' . '(function ($) { ' . "$(document.body).delegate('#" . $field['id'] . "_images_button', 'click', function (e) { " . 'e.preventDefault(); ' . '$(e.target).cmsmsMediaUploader( { ' . "frameId : 'cmsms-" . $field['id'] . "-media-frame', " . "frameClass : 'media-frame cmsms-media-frame cmsms-" . $field['id'] . "-media-frame', " . "frameTitle : '" . __('Choose images', 'cmsmasters') . "', " . "frameButton : '" . __('Choose', 'cmsmasters') . "', " . 'multiple : true ' . '} ); ' . '} ); ' . '} )(jQuery); ' . '</script>'; break; } if ( $field['type'] != 'tabs' && $field['type'] != 'tab_start' && $field['type'] != 'tab_finish' && $field['type'] != 'content_start' && $field['type'] != 'content_finish' ) { echo '</td>' . '</tr>'; } } } function save_custom_meta($post_id) { global $custom_all_meta_fields; if (!isset($_POST['custom_meta_box_nonce']) || !wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) { return $post_id; } if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } if ($_POST['post_type'] == 'page') { if (!current_user_can('edit_page', $post_id)) { return $post_id; } } elseif (!current_user_can('edit_post', $post_id)) { return $post_id; } foreach ($custom_all_meta_fields as $field) { if ( $field['type'] != 'tabs' && $field['type'] != 'tab_start' && $field['type'] != 'tab_finish' && $field['type'] != 'content_start' && $field['type'] != 'content_finish' ) { $old = get_post_meta($post_id, $field['id'], true); if (isset($_POST[$field['id']])) { $new = $_POST[$field['id']]; } else { $new = ''; } if ($field['type'] == 'checkbox' && $new === '') { $new = 'false'; } if (isset($new) && $new !== $old) { update_post_meta($post_id, $field['id'], $new); } elseif (isset($old) && $new === '') { delete_post_meta($post_id, $field['id'], $old); } } } } add_action('save_post', 'save_custom_meta');
successdt/offshore_home
wp-content/themes/increase/framework/admin/options/cmsms-theme-options.php
PHP
gpl-2.0
27,194
package edu.ucdenver.bios.glimmpseweb.client.shared; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.VerticalPanel; import edu.ucdenver.bios.glimmpseweb.client.GlimmpseConstants; public class GlimmpseLogoPanel extends Composite { private static final String STYLE = "glimmpseLogo"; public GlimmpseLogoPanel() { VerticalPanel panel = new VerticalPanel(); HTML name = new HTML(""); // layout panel.add(name); // set style name.setStyleName(STYLE); initWidget(panel); } }
SampleSizeShop/GlimmpseWeb
src/edu/ucdenver/bios/glimmpseweb/client/shared/GlimmpseLogoPanel.java
Java
gpl-2.0
644
import { EditorState } from 'prosemirror-state'; import { EditorView } from 'prosemirror-view'; import { CommandStateBuilder, SchemaType, CreateToggleOptions, ToggleOptions, CommandSpec, } from './types'; export const createCommandSpec = (builder: CommandStateBuilder): CommandSpec => { return (view: EditorView) => (state: EditorState) => builder(view.dispatch, state); }; export const createTypeToggle = <S extends SchemaType>(options: CreateToggleOptions<S>) => { const { getTypeFromSchema, withAttrs, commandFn, isActiveFn } = options; return createCommandSpec((dispatch, state) => { const type = getTypeFromSchema(state.schema); const toggleOptions: ToggleOptions<S> = { state, type, withAttrs }; return { run: () => commandFn({ ...toggleOptions, dispatch }), canRun: commandFn(toggleOptions), isActive: type && isActiveFn(toggleOptions), }; }); };
pubpub/pubpub
client/components/Editor/commands/util.ts
TypeScript
gpl-2.0
882
namespace ATRGamers.ATRSeeder.Core.ServerManagement { public interface IServerManager { } }
ATRGamers/ATRSeeder
PureSeeder.Core/ServerManagement/IServerManager.cs
C#
gpl-2.0
116
<?php /** * @version $Id: view.html.php 2012-01-30 15:24:18Z $ * @package BlastChat Chat * @author BlastChat * @copyright Copyright (C) 2004-2013 BlastChat. All rights reserved. * @license GNU/GPL, see LICENSE.php * @HomePage <http://www.blastchat.com> * This file is part of BlastChat Chat. * BlastChat Chat is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * BlastChat Chat is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with BlastChat Chat. If not, see <http://www.gnu.org/licenses/>. */ // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import Joomla view library jimport('joomla.application.component.view'); /** * HTML View class for the HelloWorld Component */ class BlastChatChatViewBlastChatChat extends JViewLegacy { // Overwriting JView display method function display($tpl = null) { // Display the view parent::display($tpl); } }
albert1974/WebMatrix
components/com_blastchatchat/views/blastchatchat/view.html.php
PHP
gpl-2.0
1,414
account = Account.find_by_master(true) uniq_email_addresses = account.email_contact_routes.all(:select => :email_address, :conditions => {:routable_type => "Party"}, :group => :email_address).map(&:email_address) puts uniq_email_addresses.size uniq_email_addresses.uniq! puts uniq_email_addresses.size email_count = 0 party_count = 0 duplicate_email_addresses = [] uniq_email_addresses.each do |email_address| email_count = account.email_contact_routes.count(:conditions => {:routable_type => "Party", :email_address => email_address}) next unless email_count > 1 duplicate_email_addresses << email_address end puts duplicate_email_addresses.inspect result = {} ids = nil duplicate_email_addresses.each do |email_address| ids = account.email_contact_routes.all(:select => :routable_id, :conditions => {:routable_type => "Party", :email_address => email_address}).map(&:routable_id) result.merge!(email_address => ids) end puts result.inspect ids = [] result.each do |k,v| ids += v[1..-1] end puts ids.inspect account.parties.all(:conditions => {:id => ids}).map(&:destroy)
xlsuite/xlsuite
script/cleaning_up_parties_with_duplicate_email_address.rb
Ruby
gpl-2.0
1,085
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Modelo; import java.util.ArrayList; import java.util.HashMap; import javax.swing.table.AbstractTableModel; /** * * @author zirex */ public class Insumo { private Conexion con; private String id; private String nombre; private int cantidad; private String medida; private String estado; private String nombre_tipo; public Insumo(String id, String nombre, int cantidad, String medida, String nombre_tipo) { this.con= new Conexion(); ArrayList<HashMap> res= this.con.query("SELECT * FROM insumo WHERE id='"+id+"';"); if(res.isEmpty()){ this.con.query("INSERT INTO insumo (id, nombre, cantidad, medida, nombre_tipo) VALUES('"+id+"', '"+nombre+"', "+cantidad+", '"+medida+"', '"+nombre_tipo+"');"); this.id = id; this.nombre = nombre; this.cantidad = cantidad; this.medida = medida; this.estado= "1"; this.nombre_tipo = nombre_tipo; } else{ this.id= res.get(0).get("id")+""; this.nombre= res.get(0).get("nombre").toString(); this.cantidad= Integer.valueOf(res.get(0).get("cantidad")+""); this.medida= res.get(0).get("medida").toString(); this.estado= res.get(0).get("estado").toString(); this.nombre_tipo= res.get(0).get("nombre_tipo")+""; } } public Insumo(String id, String nombre, int cantidad, String medida, String estado, String nombre_tipo) { this.con=new Conexion(); this.id = id; this.nombre = nombre; this.cantidad = cantidad; this.medida = medida; this.estado= estado; this.nombre_tipo= nombre_tipo; } public static boolean addTipo(String tipo){ Conexion con = new Conexion(); ArrayList<HashMap> res= con.query("SELECT * FROM tipo WHERE nombre_tipo= '"+tipo+"';"); if(res.isEmpty()){ con.query("INSERT INTO tipo VALUES ('"+tipo+"');"); return true; } else{ return false; } } public static ArrayList<String> consulTipo(){ Conexion con= new Conexion(); ArrayList<String> tipos= new ArrayList<String>(); ArrayList<HashMap> res= con.query("SELECT * FROM tipo"); for (HashMap tipo : res) { tipos.add(tipo.get("nombre_tipo").toString()); } return tipos; } public static ArrayList<String[]> getInsumos() { Conexion con = new Conexion(); ArrayList<String[]> ins = new ArrayList<String[]>(); ArrayList<HashMap> inms = con.query("SELECT * FROM insumo WHERE estado= 1"); for (HashMap inm: inms) { String m[] = {inm.get("id").toString(), inm.get("nombre").toString(), inm.get("nombre_tipo").toString(), inm.get("cantidad").toString(), inm.get("medida").toString()}; ins.add(m); } return ins; } public static AbstractTableModel tablaIns(){ AbstractTableModel tabla= new AbstractTableModel() { private Conexion con; private String[] ColumnName= {"Id", "Nombre", "Tipo", "Cant.", "Medida", "Estado"}; private Object [][] cons= this.contenido(); private Object[][] contenido(){ boolean activo= true; boolean inactivo= false; this.con= new Conexion(); Object [][] datos; ArrayList<HashMap> res= con.query("SELECT * FROM insumo"); datos= new Object[res.size()][ColumnName.length]; int i=0; for (HashMap fila : res) { String [] col= {fila.get("id").toString(), fila.get("nombre").toString(), fila.get("nombre_tipo").toString(), fila.get("cantidad").toString(), fila.get("medida").toString(), fila.get("estado").toString()}; for(int j=0; j<ColumnName.length; j++){ if(j !=5){ datos[i][j]= col[j]; } else{ if(Integer.parseInt(col[j]+"") == 1){ datos[i][j]= activo; } else{ datos[i][j]= inactivo; } } } i++; } return datos; } @Override public int getRowCount() { return this.cons.length; } @Override public int getColumnCount() { return this.ColumnName.length; } @Override public Object getValueAt(int i, int i1) { return this.cons[i][i1]; } @Override public String getColumnName(int columnIndex){ return this.ColumnName[columnIndex]; } @Override public Class<?> getColumnClass(int c){ return this.cons[0][c].getClass(); } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex){ if(columnIndex == 5){ boolean value= Boolean.parseBoolean(aValue.toString()); String estado= "0"; if(value == true){ estado= "1"; } Insumo i= Insumo.existe(this.cons[rowIndex][0].toString()); i.setEstado(estado); this.cons[rowIndex][columnIndex]= value; // Disparamos el Evento TableDataChanged (La tabla ha cambiado) //fireTableCellUpdated(rowIndex, columnIndex); } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex==5; } }; return tabla; } public String getEstado() { return estado; } public int getCantidad() { return cantidad; } public String getId() { return id; } public String getMedida() { return medida; } public String getNombre() { return nombre; } public String getTipo() { return nombre_tipo; } public void setEstado(String estado) { this.con.query("UPDATE insumo SET estado='"+estado+"' WHERE id='"+this.id+"';"); this.estado = estado; } public void setMedida(String medida) { this.con.query("UPDATE insumo SET medida='"+medida+"' WHERE id='"+this.id+"';"); this.medida = medida; } public void setTipo(String nombre_tipo) { this.con.query("UPDATE insumo SET nombre_tipo='"+nombre_tipo+"' WHERE id='"+this.id+"';"); this.nombre_tipo = nombre_tipo; } public void setCantidad(int cantidad, int opc) { if(opc==1){ this.con.query("UPDATE insumo SET cantidad= cantidad +"+cantidad+" WHERE id='"+this.id+"';"); this.cantidad+=cantidad; } else{ this.con.query("UPDATE insumo SET cantidad= cantidad -"+cantidad+" WHERE id='"+this.id+"';"); this.cantidad-=cantidad; } } public void setNombre(String nombre) { this.con.query("UPDATE insumo SET nombre= '"+nombre+"' WHERE id= '"+this.id+"';"); this.nombre = nombre; } public static Insumo existe(String id){ Conexion c= new Conexion(); ArrayList<HashMap> res= c.query("SELECT nombre, nombre_tipo, cantidad, medida, estado FROM insumo WHERE id= '"+id+"';"); if(!res.isEmpty()){ return new Insumo(id, res.get(0).get("nombre")+"", Integer.parseInt(res.get(0).get("cantidad")+""), res.get(0).get("medida").toString(), res.get(0).get("estado")+"", res.get(0).get("nombre_tipo").toString()); } return null; } public static boolean update(String valores, String id) { Conexion conn= new Conexion(); boolean res = false; String q = " UPDATE insumo SET " + valores + " WHERE id= " + id; ArrayList<HashMap> oper= conn.query(q); if(oper==null) res=true; return res; } @Override public String toString() { return "Insumo{" + "id=" + id + ", nombre=" + nombre + ", tipo=" + nombre_tipo + ", cantidad=" + cantidad + ", medida=" + medida + ", estado=" + estado + '}'; } }
supermavp/avisoft
appAvisoft/src/Modelo/Insumo.java
Java
gpl-2.0
8,936
package com.charlesdream.office.word.objects; import com.charlesdream.office.BaseObject; import com.jacob.com.Dispatch; /** * @author Charles Cui on 3/5/2016. * @since 1.0 */ public class SeriesCollection extends BaseObject { public SeriesCollection(Dispatch dispatch) { super(dispatch); } }
Lotusun/OfficeHelper
src/main/java/com/charlesdream/office/word/objects/SeriesCollection.java
Java
gpl-2.0
314
<?php /** * @package Gantry5 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2015 RocketTheme, LLC * @license GNU/GPLv2 and later * * http://www.gnu.org/licenses/gpl-2.0.html */ namespace Gantry\Framework; use Gantry\Component\Gantry\GantryTrait; use Gantry\Joomla\CacheHelper; use Gantry\Joomla\StyleHelper; use Joomla\Utilities\ArrayHelper; class Assignments { use GantryTrait; protected $style_id; public function __construct($style_id) { $this->style_id = $style_id; } public function get() { return $this->getMenu(); } public function set($data) { if (isset($data['assignment'])) { $this->setAssignment($data['assignment']); } if (isset($data['menu'])) { $this->setMenu($data['menu']); } } public function types() { return ['menu']; } public function getMenu() { require_once JPATH_ADMINISTRATOR . '/components/com_menus/helpers/menus.php'; $data = \MenusHelper::getMenuLinks(); $userid = \JFactory::getUser()->id; $list = []; foreach ($data as $menu) { $items = []; foreach ($menu->links as $link) { $items[] = [ 'name' => 'menu[' . $link->value . ']', 'field' => ['id', 'link' . $link->value], 'value' => $link->template_style_id == $this->style_id, 'disabled' => $link->type != 'component' || $link->checked_out && $link->checked_out != $userid, 'label' => str_repeat('—', max(0, $link->level-1)) . ' ' . $link->text ]; } $group = [ 'label' => $menu->title ?: $menu->menutype, 'items' => $items ]; $list[] = $group; } return $list; } public function setMenu($data) { $active = array_keys(array_filter($data, function($value) {return $value == 1; })); // Detect disabled template. $extension = \JTable::getInstance('Extension'); $template = static::gantry()['theme.name']; if ($extension->load(array('enabled' => 0, 'type' => 'template', 'element' => $template, 'client_id' => 0))) { throw new \RuntimeException(\JText::_('COM_TEMPLATES_ERROR_SAVE_DISABLED_TEMPLATE')); } $style = \JTable::getInstance('Style', 'TemplatesTable'); if (!$style->load($this->style_id) || $style->client_id != 0) { throw new \RuntimeException('Template style does not exist'); } $user = \JFactory::getUser(); $n = 0; if ($user->authorise('core.edit', 'com_menus')) { $db = \JFactory::getDbo(); $user = \JFactory::getUser(); if (!empty($active) && is_array($active)) { ArrayHelper::toInteger($active); // Update the mapping for menu items that this style IS assigned to. $query = $db->getQuery(true) ->update('#__menu') ->set('template_style_id = ' . (int) $style->id) ->where('id IN (' . implode(',', $active) . ')') ->where('template_style_id != ' . (int) $style->id) ->where('checked_out IN (0,' . (int) $user->id . ')'); $db->setQuery($query); $db->execute(); $n += $db->getAffectedRows(); } // Remove style mappings for menu items this style is NOT assigned to. // If unassigned then all existing maps will be removed. $query = $db->getQuery(true) ->update('#__menu') ->set('template_style_id = 0'); if (!empty($active)) { $query->where('id NOT IN (' . implode(',', $active) . ')'); } $query->where('template_style_id = ' . (int) $style->id) ->where('checked_out IN (0,' . (int) $user->id . ')'); $db->setQuery($query); $db->execute(); $n += $db->getAffectedRows(); } // Clean the cache. CacheHelper::cleanTemplates(); return ($n > 0); } public function getAssignment() { $style = StyleHelper::getStyle($this->style_id); return $style->home; } public function setAssignment($value) { $options = $this->assignmentOptions(); if (!isset($options[$value])) { throw new \RuntimeException('Invalid value for default assignment!', 400); } $style = StyleHelper::getStyle($this->style_id); $style->home = $value; if (!$style->check() || !$style->store()) { throw new \RuntimeException($style->getError()); } // Clean the cache. CacheHelper::cleanTemplates(); } public function assignmentOptions() { if ((string)(int) $this->style_id !== (string) $this->style_id) { return []; } $languages = \JHtml::_('contentlanguage.existing'); $options = ['- Make Default -', 'All Languages']; foreach ($languages as $language) { $options[$language->value] = $language->text; } return $options; } }
afend/RULug
libraries/gantry5/classes/Gantry/Framework/Assignments.php
PHP
gpl-2.0
5,407
/** *@author Gilberto Vargas Hernández *Clase que nos ayuda a clasificar los tipos de token que puede procesar un ensamblador */ import java.util.*; import java.util.regex.*; public class Clasificador{ /** *Funcion que clasifica una string en sus 3 tipos de componentes *@param String s, la cadena a clasificar *@return una arreglo de String, si es de tamaño 1 con el error, tamaño 3 si todo salio bien */ public static String[] procesar(String s){ //Retorna un arreglo de cadenas separando las instrucciones de tamaño 3. Si la linea no es correcta retorna un arreglo de tamaño 1 con el error //Divide la cadena en 2, la parte que pertenece a un comentario y la parte de la instrucción String comentario = Clasificador.obtenerComentario(s); String instruccion = Clasificador.removerComentario(s); //Crea la variable que vamos a retornar al ginal String[] ret=null; //En una lista se van a guardar los tokens que hay en la cadena recibida. List<String> tokens = new ArrayList<String>(); StringTokenizer tok = new StringTokenizer(instruccion, "\t "); //Extrae los tokens while(tok.hasMoreTokens()){ tokens.add(tok.nextToken()); } //Dependiendo de la cantidad de tokens extraidos, se evalua la forma de la cadena switch(tokens.size()){ case 1: //Para el caso 1, solo podría ser un CODOP y debe iniciar con espacio o tabulador if(Clasificador.esCodop(tokens.get(0))){ if(s.charAt(0)==' ' || s.charAt(0)=='\t'){ ret = new String[3]; ret[0] = "NULL"; ret[1] = tokens.get(0); ret[2] = "NULL"; }else{ ret = new String[1]; if(Clasificador.esEtiqueta(tokens.get(0))){ ret[0] = "Se esperaba un codop al final de la linea"; }else{ ret[0] = "La linea debe comenzar con un espacio"; } } }else{ ret = new String[1]; if(s.charAt(0)==' ' || s.charAt(0)=='\t'){ ret[0] = Clasificador.errorCodop(tokens.get(0)); }else if(Clasificador.esEtiqueta(tokens.get(0))){ ret[0] = "Se esperaba un codop al final de la linea"; }else{ ret[0] = "La linea debe comenzar con un espacio"; } } break; case 2: //Cuando hay 2 operandos, en caso de que el primero sea una etiqueta, el segundo debe ser un CODOP //Pero si el primero es un CODOP el segundo debe ser un operando //Si no se cumple cualquier cosa, significa que hay un error if(Clasificador.esEtiqueta(tokens.get(0)) && s.charAt(0)!=' ' && s.charAt(0)!='\t' && Clasificador.esCodop(tokens.get(1))){ ret = new String[3]; ret[0] = tokens.get(0); ret[1] = tokens.get(1); ret[2] = "NULL"; }else if(Clasificador.esCodop(tokens.get(0)) && Clasificador.esOperando(tokens.get(1)) && (s.charAt(0)==' ' || s.charAt(0)=='\t')){ ret = new String[3]; ret[0] = "NULL"; ret[1] = tokens.get(0); ret[2] = tokens.get(1); }else if(Clasificador.esEtiqueta(tokens.get(0)) && s.charAt(0)!=' ' && s.charAt(0)!='\t'){ ret = new String[1]; ret[0] = Clasificador.errorCodop(tokens.get(1)); return ret; }else if(s.charAt(0)==' ' || s.charAt(0)=='\t'){ ret = new String[1]; ret[0] = Clasificador.errorCodop(tokens.get(1)); return ret; }else if(Clasificador.esCodop(tokens.get(0)) && (s.charAt(0)==' ' || s.charAt(0)=='\t')){ ret = new String[1]; ret[0] = Clasificador.errorOperando(tokens.get(1)); return ret; }else{ ret = new String[1]; ret[0] = Clasificador.errorEtiqueta(tokens.get(0)); return ret; } break; case 3: //Si la linea tiene 3 instrucciones, el unico orden en que pueden ir debe ser //Etiqueta - CODOP - OPERANDO if(Clasificador.esEtiqueta(tokens.get(0))){ if(!Character.isLetter(s.charAt(0))){ ret = new String[1]; ret[0] = "Las etiqutaes deben aparecer al inicio de la linea"; } if(Clasificador.esCodop(tokens.get(1))){ if(Clasificador.esOperando(tokens.get(2))){ ret = new String[3]; ret[0]=tokens.get(0); ret[1]=tokens.get(1); ret[2]=tokens.get(2); }else{ ret = new String[1]; ret[0] = Clasificador.errorOperando(tokens.get(2));; } }else{ ret = new String[1]; ret[0] = Clasificador.errorCodop(tokens.get(1));; } }else{ ret = new String[1]; ret[0] = Clasificador.errorEtiqueta(tokens.get(0));; } break; case 0: //Si la linea no tiene ninguna instruccion significa que esta vacia ret = new String[1]; ret[0] = "LV"; break; default: //Si la linea tiene demasiadas instrucciones significa que no hay como evaluar la cadena ret = new String[1]; ret[0]="Error en la cantidad de tokens"; } return ret; } /** *Toma el comentario de una cadena *@param String s, la cadena de la cual tomará el comentario *@return Una cadena con el comentario dentro de la cadena, cadena vacia en caso contrario */ public static String obtenerComentario(String s){ //El comentario inicia en la primer incidencia de un ';', por lo que una subcadena de donde se encuentra el primer ';' al final es el comentario int idx = s.indexOf(';'); return (idx>=0?s.substring(idx+1):""); } /** *Retorna la cadena de entrada quitandole el comentario *@param String s, la cadena a ser procesada *@return la cadena pero sin el comentario */ public static String removerComentario(String s){ //Se busca un ';' y se extrae la subcadena hasta la posicion de ';', sino se retorna la cadena completa int idx = s.indexOf(';'); return (idx>=0?s.substring(0,idx):s); } /** *Comprueba si la cadena es una etiqueta 1 *@param String s, la cadena a ser verificada *@return true si la cadena es una etiqueta, falso en caso contrario */ public static boolean esEtiqueta(String s){ //La cadena debe ser de longitud 8 como maximo //Debe comenzar con una letra //Y el resto deben ser letras, numeros o '_' Pattern p = Pattern.compile("[a-zA-Z]{1}[a-zA-Z_0-9]{"+(s.length()-1)+"}"); Matcher m = p.matcher(s); return m.find() && s.length()<=8; } /** *Comprueba si la cadena es un codigo de operación *@param String s, la cadena a ser verificada *@return true si la cadena es un codigo de operacion, falso en caso contrario */ public static boolean esCodop(String s){ //La cadena debe ser de longitud 5 como maximo //Debe comenzar con una letra //El resto de la letra pueden ser letras, numeros o '_' //Puede contener un '.' como maximo, la bandera controla la cantidad de '.' que se han encontrado int puntos = s.length() - s.replace(".", "").length(); if(puntos>1){ return false; } Pattern p = Pattern.compile("[a-zA-Z]{1}[a-zA-Z_0-9.]{"+(s.length()-1)+"}"); Matcher m = p.matcher(s); return m.find()&&s.length()<=5; } /** *Comprueba si la cadena es un operando *@param String s, la cadena a ser verificada *@return true si la cadena es un operando, falso en caso contrario */ public static boolean esOperando(String s){ //Para esta practica no hay una regla de operandos return true; } /** *Calcula el error que tiene la cadena al ser evaluada como etiqueta *@param String s, la cadena a ser verificada *@return Una cadena con la descripción del errot */ public static String errorEtiqueta(String s){ if(s.length()>8){ return "El tamaño de la etiqueta exede el limite (8)"; } if(!Character.isLetter(s.charAt(0))){ return "La etiqueta no comienza con letra"; } Pattern p = Pattern.compile("[^a-zA-Z_0-9]"); Matcher m = p.matcher(s); if(m.find()){ return "La etiqueta contiene simbolos no permitidos"; } return "Error desconocido"; } /** *Calcula el error que tiene la cadena al ser evaluada como codop *@param String s, la cadena a ser verificada *@return Una cadena con la descripción del errot */ public static String errorCodop(String s){ if(s.length()>5){ return "El tamaño del codop exede el limite (5)"; } int puntos = s.length() - s.replace(".", "").length(); if(puntos>1){ return "El codop tiene mas de un '.'"; } if(!Character.isLetter(s.charAt(0))){ return "El codop no comienza con letra"; } Pattern p = Pattern.compile("[^a-zA-Z._0-9]"); Matcher m = p.matcher(s); if(m.find()){ return "El codop contiene simbolos no permitidos"; } return "Error desconocido"; } /** *Calcula el error que tiene la cadena al ser evaluada como operando *@param String s, la cadena a ser verificada *@return Una cadena con la descripción del errot */ public static String errorOperando(String s){ //Al no haber ninguna restriccion aun nunca caera aqui. return ""; } }
TachoMex/Progsis
Practica 1/Clasificador.java
Java
gpl-2.0
8,653
using System.Text.RegularExpressions; namespace Pyratron.PyraChat.IRC.Messages.Receive.Numerics { /// <summary> /// RPL_AWAY message. (301) /// </summary> public class AwayMessage : ReceivableMessage { /// <summary> /// User who is away. /// </summary> public User User { get; } /// <summary> /// Away reason/message. /// </summary> public string Reason { get; } public AwayMessage(Message msg) : base(msg) { User = msg.Client.UserFromNick(msg.Destination); Reason = msg.Parameters[1]; if (User != null) { User.SetIsAway(msg.Client, true, Reason); msg.Client.OnReplyAway(this); } } public static bool CanProcess(Message msg) { return msg.Type == "301"; } } }
Pyratron/PyraChat
Source/IRC/Messages/Receive/Numerics/AwayMessage.cs
C#
gpl-2.0
905
var InlineDonation = function(){ this.clientToken = document.getElementById('client_token').value; this.setupEvents(); } InlineDonation.prototype.setupEvents = function(){ jQuery(document.body).on('keyup', '#donation-form input', this.clearInvalidEntries); this.setup(); } InlineDonation.prototype.setup = function(){ braintree.setup(this.clientToken, 'dropin',{ container: 'dropin-container', form: 'donation-form', onReady: function(integration){ inlineDonation.integration = integration; }, onPaymentMethodReceived: function(response){ inlineDonation.onPaymentMethodReceived(response); } }) } InlineDonation.prototype.onPaymentMethodReceived = function(response){ inlineDonation.paymentMethodReceived = true; var element = document.getElementById('payment_method_nonce'); if(element != null){ element.value = response.nonce; } else{ element = document.createElement('input'); element.type = 'hidden'; element.name = 'payment_method_nonce'; element.id = 'payment_method_nonce'; element.value = response.nonce; jQuery('#donation-form').append(element); } inlineDonation.validateInputFields(); } InlineDonation.prototype.validateInputFields = function(){ var hasFailures = false; jQuery('#donation-form input').each(function(){ if(jQuery(this).val() === ""){ jQuery(this).parent().find('div.invalid-input-field').show().addClass('active'); hasFailures = true; } }); if(! hasFailures){ inlineDonation.submitPayment(); } } InlineDonation.prototype.submitPayment = function(){ var data = jQuery('#donation-form').serialize(); var url = jQuery('#ajax_url').val(); jQuery('.overlay-payment-processing').addClass('active'); jQuery.ajax({ type:'POST', url: url, dataType: 'json', data: data }).done(function(response){ jQuery('.overlay-payment-processing').removeClass('active'); if(response.result === 'success'){ inlineDonation.redirect(response.url); } else{ inlineDonation.showErrorMessage(response.message); } }).fail(function(response){ jQuery('.overlay-payment-processing').removeClass('active'); inlineDonation.showErrorMessage(response.message); }); } InlineDonation.prototype.redirect = function(url){ window.location.replace(url); } InlineDonation.prototype.showErrorMessage = function(message){ jQuery('#error_messages').html(message); } InlineDonation.prototype.clearInvalidEntries = function(){ jQuery(this).parent().find('div.invalid-input-field').hide().removeClass('active'); } InlineDonation.prototype.clearErrorMessages = function(){ jQuery('#error_messages').empty(); } InlineDonation.prototype.clearInvalidEntries = function(){ jQuery(this).parent().find('div.invalid-input-field').hide().removeClass('active'); } InlineDonation.prototype.displayOverlay = function(callback){ jQuery('#donation_overlay').fadeIn(400, callback); } InlineDonation.prototype.hideOverlay = function(callback){ jQuery('#donation_overlay').fadeOut(400, callback); } var inlineDonation = new InlineDonation();
namwoody/kart-zill.com
wp-content/plugins/woo-payment-gateway/assets/js/donations-inline.js
JavaScript
gpl-2.0
3,123
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "FastMixerState.h" namespace android { FastTrack::FastTrack() : mBufferProvider(NULL), mVolumeProvider(NULL), mSampleRate(0), mChannelMask(AUDIO_CHANNEL_OUT_STEREO), mGeneration(0) { } FastTrack::~FastTrack() { } FastMixerState::FastMixerState() : mFastTracksGen(0), mTrackMask(0), mOutputSink(NULL), mOutputSinkGen(0), mFrameCount(0), mCommand(INITIAL), mColdFutexAddr(NULL), mColdGen(0), mDumpState(NULL), mTeeSink(NULL) { } FastMixerState::~FastMixerState() { } } // namespace android
rex-xxx/mt6572_x201
frameworks/av/services/audioflinger/FastMixerState.cpp
C++
gpl-2.0
1,146
/* * Copyright 2009-2014 PrimeTek. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.primefaces.rio.service; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import javax.faces.bean.ApplicationScoped; import javax.faces.bean.ManagedBean; import org.primefaces.rio.domain.Car; @ManagedBean(name = "carService") @ApplicationScoped public class CarService { private final static String[] colors; private final static String[] brands; static { colors = new String[10]; colors[0] = "Black"; colors[1] = "White"; colors[2] = "Green"; colors[3] = "Red"; colors[4] = "Blue"; colors[5] = "Orange"; colors[6] = "Silver"; colors[7] = "Yellow"; colors[8] = "Brown"; colors[9] = "Maroon"; brands = new String[10]; brands[0] = "BMW"; brands[1] = "Mercedes"; brands[2] = "Volvo"; brands[3] = "Audi"; brands[4] = "Renault"; brands[5] = "Fiat"; brands[6] = "Volkswagen"; brands[7] = "Honda"; brands[8] = "Jaguar"; brands[9] = "Ford"; } public List<Car> createCars(int size) { List<Car> list = new ArrayList<Car>(); for(int i = 0 ; i < size ; i++) { list.add(new Car(getRandomId(), getRandomBrand(), getRandomYear(), getRandomColor(), getRandomPrice(), getRandomSoldState())); } return list; } private String getRandomId() { return UUID.randomUUID().toString().substring(0, 8); } private int getRandomYear() { return (int) (Math.random() * 50 + 1960); } private String getRandomColor() { return colors[(int) (Math.random() * 10)]; } private String getRandomBrand() { return brands[(int) (Math.random() * 10)]; } private int getRandomPrice() { return (int) (Math.random() * 100000); } private boolean getRandomSoldState() { return (Math.random() > 0.5) ? true: false; } public List<String> getColors() { return Arrays.asList(colors); } public List<String> getBrands() { return Arrays.asList(brands); } }
paco30amigos/sieni
SIENI/rio/tag/src/main/java/org/primefaces/rio/service/CarService.java
Java
gpl-2.0
2,580
#include <sys/time.h> #include <pangomm/init.h> #include "pbd/compose.h" #include "pbd/xml++.h" #include "canvas/group.h" #include "canvas/canvas.h" #include "canvas/root_group.h" #include "canvas/rectangle.h" #include "benchmark.h" using namespace std; using namespace Canvas; class RenderFromLog : public Benchmark { public: RenderFromLog (string const & session) : Benchmark (session) {} void do_run (ImageCanvas& canvas) { canvas.set_log_renders (false); list<Rect> const & renders = canvas.renders (); for (list<Rect>::const_iterator i = renders.begin(); i != renders.end(); ++i) { canvas.render_to_image (*i); } } }; int main (int argc, char* argv[]) { if (argc < 2) { cerr << "Syntax: render_parts <session>\n"; exit (EXIT_FAILURE); } Pango::init (); RenderFromLog render_from_log (argv[1]); cout << render_from_log.run () << "\n"; return 0; }
cth103/ardour-cth103
libs/canvas/benchmark/render_from_log.cc
C++
gpl-2.0
890
<?php /*----------------------------------------------------------------- !!!!警告!!!! 以下为系统文件,请勿修改 -----------------------------------------------------------------*/ namespace app\model\console; use app\model\index\Tag_View as Tag_View_Index; //不能非法包含或直接执行 if (!defined('IN_GINKGO')) { return 'Access denied'; } /*-------------文章模型-------------*/ class Tag_View extends Tag_View_Index { }
baigoStudio/baigoCMS
app/model/console/tag_view.mdl.php
PHP
gpl-2.0
472
package com.reform.dbstorm.zookeeper; /** * 状态监听器. * * @author huaiyu.du@opi-corp.com 2012-1-29 下午4:45:03 */ public interface StateListener { /** * 新连接建立或重连. */ void onNewSession(); /** * 状态发生改变. */ void onStateChange(); }
deyami/dbstorm
dbstorm-zookeeper/src/main/java/com/reform/dbstorm/zookeeper/StateListener.java
Java
gpl-2.0
285
/** * @author Adam Charron <adam.c@vanillaforums.com> * @copyright 2009-2021 Vanilla Forums Inc. * @license gpl-2.0-only */ import { cx } from "@emotion/css"; import { LoadStatus } from "@library/@types/api/core"; import { IUser, IUserFragment } from "@library/@types/api/users"; import { hasUserViewPermission } from "@library/features/users/modules/hasUserViewPermission"; import { useUser, useCurrentUserID } from "@library/features/users/userHooks"; import { dropDownClasses } from "@library/flyouts/dropDownStyles"; import { useDevice, Devices } from "@library/layout/DeviceContext"; import LazyModal from "@library/modal/LazyModal"; import ModalSizes from "@library/modal/ModalSizes"; import { UserCardContext, useUserCardContext } from "@library/features/userCard/UserCard.context"; import { UserCardMinimal, UserCardSkeleton, UserCardView } from "@library/features/userCard/UserCard.views"; import { useUniqueID } from "@library/utility/idUtils"; import Popover, { positionDefault } from "@reach/popover"; import { t } from "@vanilla/i18n"; import { useFocusWatcher } from "@vanilla/react-utils"; import React, { useCallback, useRef, useState } from "react"; import { UserCardError } from "@library/features/userCard/UserCard.views"; import { hasPermission } from "@library/features/users/Permission"; import { getMeta } from "@library/utility/appUtils"; interface IProps { /** UserID of the user being loaded. */ userID: number; /** A fragment can help display some data while the full user is loaded. */ userFragment?: Partial<IUserFragment>; /** If a full user is passed, no network requests will be made, and the user will be displayed immediately. */ user?: IUser; /** Callback in the even the close button in the card is clicked. */ onClose?: () => void; /** Show a skeleton */ forceSkeleton?: boolean; } /** * Component representing the inner contents of a user card. */ export function UserCard(props: IProps) { if (!hasUserViewPermission()) { return <></>; } if (props.user) { // We have a full user, just render the view. return <UserCardView user={props.user} onClose={props.onClose} />; } else { return <UserCardDynamic {...props} />; } } export function UserCardPopup(props: React.PropsWithChildren<IProps> & { forceOpen?: boolean }) { const [_isOpen, _setIsOpen] = useState(false); const isOpen = props.forceOpen ?? _isOpen; function setIsOpen(newOpen: boolean) { _setIsOpen(newOpen); // Kludge for interaction with old flyout system. if (newOpen && window.closeAllFlyouts) { window.closeAllFlyouts(); } } const triggerID = useUniqueID("popupTrigger"); const contentID = triggerID + "-content"; const triggerRef = useRef<HTMLElement>(null); const contentRef = useRef<HTMLElement>(null); const device = useDevice(); const forceModal = device === Devices.MOBILE || device === Devices.XS; if (!hasUserViewPermission()) { return <>{props.children}</>; } return ( <UserCardContext.Provider value={{ isOpen, setIsOpen, triggerRef, contentRef, triggerID, contentID, }} > {props.children} {!forceModal && isOpen && ( // If we aren't a modal, and we're open, show the flyout. <Popover targetRef={triggerRef} position={positionPreferTopMiddle}> <UserCardFlyout {...props} onClose={() => { setIsOpen(false); }} /> </Popover> )} {forceModal && ( // On mobile we are forced into a modal, which is controlled by the `isVisible` param instead of conditional rendering. <LazyModal isVisible={isOpen} size={ModalSizes.SMALL} exitHandler={() => { setIsOpen(false); }} > <UserCard {...props} onClose={() => { setIsOpen(false); }} /> </LazyModal> )} </UserCardContext.Provider> ); } /** * Call this hook to get the props for a user card trigger. * Simply spread the `props` over the component and pass the `triggerRef` to the underlying element. */ export function useUserCardTrigger(): { props: React.HTMLAttributes<HTMLElement>; triggerRef: React.RefObject<HTMLElement | null>; isOpen?: boolean; } { const context = useUserCardContext(); const handleFocusChange = useCallback( (hasFocus, newActiveElement) => { if ( !hasFocus && newActiveElement !== context.contentRef.current && !context.contentRef.current?.contains(newActiveElement) ) { context.setIsOpen(false); } }, [context.setIsOpen, context.contentRef], ); useFocusWatcher(context.triggerRef, handleFocusChange); return { props: hasUserViewPermission() ? { "aria-controls": context.contentID, "aria-expanded": context.isOpen, "aria-haspopup": context.isOpen, role: "button", onClick: (e) => { e.preventDefault(); context.setIsOpen(!context.isOpen); }, onKeyPress: (e) => { if (e.key === " " || e.key === "Enter") { e.preventDefault(); context.setIsOpen(!context.isOpen); } if (e.key === "Escape") { e.preventDefault(); context.setIsOpen(false); context.triggerRef.current?.focus(); } }, } : {}, triggerRef: context.triggerRef, isOpen: context.isOpen, }; } /** * Calculate a position for the user card that is centered if possible. */ function positionPreferTopMiddle(targetRect?: DOMRect | null, popoverRect?: DOMRect | null): React.CSSProperties { const posDefault = positionDefault(targetRect, popoverRect); const halfPopoverWidth = (popoverRect?.width ?? 0) / 2; const halfTriggerWidth = (targetRect?.width ?? 0) / 2; const left = (targetRect?.left ?? 0) + halfTriggerWidth + window.pageXOffset - halfPopoverWidth; const minimumInset = 16; if (left < minimumInset || left + halfPopoverWidth * 2 > window.innerWidth - minimumInset) { // We have a collision. // Just use default positioning. return posDefault; } return { ...posDefault, left, }; } /** * The content of the user card, wrapped in a flyout. */ export function UserCardFlyout(props: React.ComponentProps<typeof UserCard>) { const context = useUserCardContext(); const handleFocusChange = useCallback( (hasFocus, newActiveElement) => { if (newActiveElement && !hasFocus && newActiveElement !== context.triggerRef.current) { context.setIsOpen(false); } }, [context.setIsOpen, context.triggerRef], ); useFocusWatcher(context.contentRef, handleFocusChange); return ( <div ref={context.contentRef as any} className={cx(dropDownClasses().contentsBox, "isMedium")} onKeyDown={(e) => { if (e.key === "Escape") { e.preventDefault(); context.setIsOpen(false); context.triggerRef.current?.focus(); } }} onClick={(e) => { e.stopPropagation(); e.nativeEvent.stopPropagation(); e.nativeEvent.stopImmediatePropagation(); }} > <UserCard {...props} /> </div> ); } /** * Wrapper around `UserCardView` that loads the data dynamically. */ function UserCardDynamic(props: IProps) { const { userFragment, forceSkeleton = false } = props; const user = useUser({ userID: props.userID }); const currentUseID = useCurrentUserID(); const isOwnUser = userFragment?.userID === currentUseID; const hasPersonalInfoView = hasPermission("personalInfo.view"); let bannedPrivateProfile = getMeta("ui.bannedPrivateProfile", "0"); bannedPrivateProfile = bannedPrivateProfile === "" ? "0" : "1"; const privateBannedProfileEnabled = bannedPrivateProfile !== "0"; let banned = userFragment?.banned ?? 0; let isBanned = banned === 1; if ((userFragment?.private || (privateBannedProfileEnabled && isBanned)) && !hasPersonalInfoView && !isOwnUser) { return <UserCardMinimal userFragment={userFragment} onClose={props.onClose} />; } if (forceSkeleton || user.status === LoadStatus.PENDING || user.status === LoadStatus.LOADING) { return <UserCardSkeleton userFragment={userFragment} onClose={props.onClose} />; } if (user.error && user?.error?.response.status === 404) { return <UserCardError onClose={props.onClose} />; } if (!user.data || user.status === LoadStatus.ERROR) { return <UserCardError error={t("Failed to load user")} onClose={props.onClose} />; } return <UserCardView user={user.data} onClose={props.onClose} />; }
vanilla/vanilla
library/src/scripts/features/userCard/UserCard.tsx
TypeScript
gpl-2.0
9,807
//=================================================================================== // Microsoft patterns & practices // Composite Application Guidance for Windows Presentation Foundation and Silverlight //=================================================================================== // Copyright (c) Microsoft Corporation. All rights reserved. // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT // LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE. //=================================================================================== // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. //=================================================================================== using System.Windows.Controls.Primitives; using Microsoft.Practices.Prism.Regions.Behaviors; namespace Microsoft.Practices.Prism.Regions { /// <summary> /// Adapter that creates a new <see cref="Region"/> and binds all /// the views to the adapted <see cref="Selector"/>. /// It also keeps the <see cref="IRegion.ActiveViews"/> and the selected items /// of the <see cref="Selector"/> in sync. /// </summary> public class SelectorRegionAdapter : RegionAdapterBase<Selector> { /// <summary> /// Initializes a new instance of <see cref="SelectorRegionAdapter"/>. /// </summary> /// <param name="regionBehaviorFactory">The factory used to create the region behaviors to attach to the created regions.</param> public SelectorRegionAdapter(IRegionBehaviorFactory regionBehaviorFactory) : base(regionBehaviorFactory) { } /// <summary> /// Adapts an <see cref="Selector"/> to an <see cref="IRegion"/>. /// </summary> /// <param name="region">The new region being used.</param> /// <param name="regionTarget">The object to adapt.</param> protected override void Adapt(IRegion region, Selector regionTarget) { } /// <summary> /// Attach new behaviors. /// </summary> /// <param name="region">The region being used.</param> /// <param name="regionTarget">The object to adapt.</param> /// <remarks> /// This class attaches the base behaviors and also listens for changes in the /// activity of the region or the control selection and keeps the in sync. /// </remarks> protected override void AttachBehaviors(IRegion region, Selector regionTarget) { if (region == null) throw new System.ArgumentNullException("region"); // Add the behavior that syncs the items source items with the rest of the items region.Behaviors.Add(SelectorItemsSourceSyncBehavior.BehaviorKey, new SelectorItemsSourceSyncBehavior() { HostControl = regionTarget }); base.AttachBehaviors(region, regionTarget); } /// <summary> /// Creates a new instance of <see cref="Region"/>. /// </summary> /// <returns>A new instance of <see cref="Region"/>.</returns> protected override IRegion CreateRegion() { return new Region(); } } }
dennyli/HandySolution
Tools/Prism4.1/Prism/Regions/SelectorRegionAdapter.cs
C#
gpl-2.0
3,791
<?php class bx_plugins_xhtml extends bx_plugin implements bxIplugin { protected $res = array(); static public $instance = array(); protected $idMapper = null; /*** magic methods and functions ***/ public static function getInstance($mode) { if (!isset(bx_plugins_xhtml::$instance[$mode])) { bx_plugins_xhtml::$instance[$mode] = new bx_plugins_xhtml($mode); } return bx_plugins_xhtml::$instance[$mode]; } public function __construct($mode = "output") { $this->mode = $mode; } public function getPermissionList() { return array( "xhtml-back-edit_bxe", "xhtml-back-edit_fck", "xhtml-back-edit_kupu", "xhtml-back-edit_assets", "xhtml-back-edit_oneform", "xhtml-back-create" ); } /** * gets the unique id of a resource associated to a request triple * * @param string $path the collection uri path * @param string $name the filename part * @param string $ext the extension * @return string id */ public function getIdByRequest($path, $name = NULL, $ext = NULL) { $lang = $GLOBALS['POOL']->config->getOutputLanguage(); $name = "$name.$lang"; $perm = bx_permm::getInstance(); if (!isset($this->idMapper[$path.$name])) { $id = str_replace($path,"",bx_resourcemanager::getResourceId($path,$name,$ext)); // // fixing problem when using e.g. gallery-plugin and xhtml-plugin in one .configxml // // when calling foobar.jpg the xhtml-plugin looks for foobar.<lang>.xhtml and doesn't // find this file, in this case use "defaultFilename"-parameter // // this is just a HACK, someone have to look for a more generic way // if ($id == "") { if (!is_null($this->getParameter($path, "defaultFilename"))) { $name = $this->getParameter($path, "defaultFilename").".".$lang; $ext = "html"; $id = str_replace($path,"",bx_resourcemanager::getResourceId($path,$name,$ext)); } else if (!empty($_GET['admin'])) { if ($perm->isAllowed($path.$id,array('admin'))) { $id = $name.".".$ext; } } } $this->idMapper[$path.$name] = $id; } if (!$perm->isAllowed($path.$id,array('read'))) { throw new BxPageNotAllowedException(); } return $this->idMapper[$path.$name]; } public function getRequestById($path, $id) { return ($path."index.html"); } public function getContentById($path, $id) { $dom = new domDocument(); $res = $this->getResourceById($path,$id); if (!$res && !empty($_GET['admin'])) { $res = $this->getResourceById($path,$id,true); $dom->load($res->getContentUriSample()); } else { $dom->load($res->getContentUri()); } $dom->xinclude(); return $dom; } public function getChildren($coll, $id) { if ($id != "" && $id != $coll->uri) { return array(); } $children = $this->getChildrenByMimeType($coll,"text/html"); /* $children = array_merge($children,$this->getChildrenByMimeType($coll,"text/wiki")); */ return $children; } protected function getChildrenByMimeType($coll, $mimetype) { $res = array(); $ch = bx_resourcemanager::getChildrenByMimeType($coll,$mimetype); foreach( $ch as $path ) { $r = $this->getResourceById($coll->uri,str_replace($coll->uri,"", $path)); if ($r) { $res[] = $r; } } return $res; } /** * gets the resource object associated to an id * * this is the preferred method of doing things ;) * * @param string $id the id of the resource * @return object resource */ public function getResourceById($path, $id, $mock = false) { $perm = bx_permm::getInstance(); if($id == "thisfiledoesnotexist.xhtml") { if (!$perm->isAllowed($path, array('xhtml-back-create'))) { throw new BxPageNotAllowedException(); } } $id = $path.$id; if (!isset($this->res[$id])) { $mimetype = bx_resourcemanager::getMimeType($id); if ($mimetype == "text/html") { $this->res[$id] = new bx_resources_text_html($id); } else if ($mimetype == "text/wiki") { $this->res[$id] = new bx_resources_text_wiki($id); } else if ($mock) { $this->res[$id] = new bx_resources_text_html($id,true); } else { $this->res[$id] = null; } } return $this->res[$id]; } public function handlePOST($path, $id, $data, $mode = null) { if ($mode == "XPathInsert") { $file = $this->getContentUriById($path,$id); $dom = new DomDocument(); $dom->load($file); $xp = new DomXPath($dom); $xp->registerNamespace("xhtml","http://www.w3.org/1999/xhtml"); foreach($data as $xpath => $value) { $res = $xp->query($xpath); if ($res && $res->item(0)) { bx_helpers_xml::innerXML($res->item(0),$value); } } $dom->save($file); } elseif ($mode == "FullXML") { $res = $this->getResourceById($path,$id); $ret = 204; if ($res->mock) { $ret = 201; $res->create(); } $file = $this->getContentUriById($path,$id); //FIXME: resource should handle the save, not the plugin, actually.. if (!file_put_contents($file,($data['fullxml']))) { print '<span style="color: red;">File '.$file.' could not be written</span><br/>'; print 'Here is your modified content (it was not saved...):<br/>'; print '<div style="border: 1px black solid; white-space: pre;">'.(htmlentities(($data['fullxml']))).'</div>'; return false; } return $ret; } } public function getAddResourceParams($type,$uri) { $dom = new domDocument(); $fields = $dom->createElement('fields'); $nameNode = $dom->createElement('field'); $nameNode->setAttribute('name', 'name'); $nameNode->setAttribute('required', 'yes'); $nameNode->setAttribute('type', 'text'); if(!empty($_REQUEST['name'])) { $nameNode->setAttribute('value', $_REQUEST['name']); } $langNode = $dom->createElement('field'); $langNode->setAttribute('name', 'lang'); $langNode->setAttribute('type', 'select'); $typeNode = $dom->createElement('field'); $typeNode->setAttribute('name', 'type'); $typeNode->setAttribute('type', 'hidden'); $typeNode->setAttribute('value', $type); foreach(bx_config::getConfProperty('outputLanguages') as $l =>$lang) { $langopt = $dom->createElement('option'); $langopt->setAttribute('name', $lang); $langopt->setAttribute('value', $lang); if ($lang == BX_DEFAULT_LANGUAGE) { $langopt->setAttribute('selected','selected'); } $langNode->appendChild($langopt); } $templNode = $dom->createElement('field'); $templNode->setAttribute("name", 'template'); $templNode->setAttribute("type", 'select'); $templateDir = sprintf("%s/%s/templates", BX_THEMES_DIR, bx_config::getConfProperty('theme')); foreach($this->getAddResourceTemplates($templateDir) as $t => $template) { $templ = $dom->createElement('option'); $templ->setAttribute("name", $template); $templ->setAttribute("value", $template); $templNode->appendChild($templ); } $editorNode = $dom->createElement('field'); $editorNode->setAttribute('name', 'editor'); $editorNode->setAttribute('type', 'select'); switch($type) { case 'xhtml': $id = 'thisfiledoesnotexist.xhtml'; break; } foreach($this->getEditorsById($uri, $id) as $editor) { $editorOpt = $dom->createElement('option'); $editorOpt->setAttribute("name", $editor); $editorOpt->setAttribute("value", $editor); $editorNode->appendChild($editorOpt); } $fields->appendChild($langNode); $fields->appendChild($templNode); if(isset($id)) { $fields->appendChild($editorNode); } $fields->appendChild($nameNode); $fields->appendChild($typeNode); $dom->appendChild($fields); return $dom; } public function getAddResourceTemplates($templatePath) { $templates = array(); if (is_dir($templatePath)) { $td = opendir($templatePath); if ($td) { while($f = readdir($td)) { if (is_file(sprintf("%s/%s", $templatePath, $f))) { array_push($templates, $f); } } } } asort($templates); return $templates; } /** * implements addResource * Instantiates ressource class and calls its addResource() method * FIXME: no dynamic resource lookup yet - just instantiates text/html resource * * @param $name string ressourcename * @param $parentUri string Parent-uri of new resource * @param $options array options (lang, template, ...) * @return bool true|false * @access public */ public function addResource($name, $parentUri, $options=array(), $resourceType = null) { $type = (isset($options['type'])) ? $options['type'] : "xhtml"; $lang = (isset($options['lang'])) ? $options['lang'] : BX_DEFAULT_LANGUAGE; $id = sprintf("%s%s.%2s.xhtml", $parentUri, $name, $lang); $res = null; switch($type) { case "xhtml": $res = new bx_resources_text_html($id, true); break; } if (is_object($res)) { return $res->addResource($name, $parentUri, $options); } return false; } /** pipeline methods **/ public function getMimeTypes() { //return array("text/html","text/wiki"); return array("text/html"); } public function getResourceTypes() { return array("xhtml"); } public function isRealResource($path , $id) { return true; } public function adminResourceExists($path, $id, $ext=null, $sample = false) { if ($ext == "xhtml") { $res = $this->getResourceById($path, $id.".".$ext,$sample); if ($res) { return $this; } } else { return null; } } public function getLastModifiedById($path, $id) { if ($this->getParameter($path, "lastmodified") == "now") { return time(); } return parent::getLastModifiedById($path,$id); } } ?>
chregu/fluxcms
inc/bx/plugins/xhtml.php
PHP
gpl-2.0
11,558
<?php /** * @file * Contains \Drupal\simplenews\Plugin\migrate\source\d7\Newsletter. */ namespace Drupal\simplenews\Plugin\migrate\source\d7; use Drupal\migrate_drupal\Plugin\migrate\source\DrupalSqlBase; /** * Migration source for Newsletter entities in D7. * * @MigrateSource( * id = "simplenews_newsletter" * ) */ class Newsletter extends DrupalSqlBase { /** * {@inheritdoc} */ public function fields() { return [ 'newsletter_id' => $this->t('Newsletter ID'), 'name' => $this->t('Name'), 'description' => $this->t('Description'), 'format' => $this->t('HTML or plaintext'), 'priority' => $this->t('Priority'), 'receipt' => $this->t('Request read receipt'), 'from_name' => $this->t('Name of the e-mail author'), 'email_subject' => $this->t('Newsletter subject'), 'from_address' => $this->t('E-mail author address'), 'hyperlinks' => $this->t('Indicates if hyperlinks should be kept inline or extracted'), 'new_account' => $this->t('Indicates how to integrate with the register form'), 'opt_inout' => $this->t('Defines the Opt-In/out options'), 'block' => $this->t('TRUE if a block should be provided for this newsletter'), 'weight' => $this->t('Weight of the newsletter when displayed in listings'), ]; } /** * {@inheritdoc} */ public function getIds() { return ['newsletter_id' => ['type' => 'serial']]; } /** * {@inheritdoc} */ public function query() { return $this->select('simplenews_newsletter', 'n') ->fields('n') ->orderBy('newsletter_id'); } /** * {@inheritdoc} */ public function calculateDependencies() { $this->dependencies = parent::calculateDependencies(); // Declare dependency to the provider of the base class. $this->addDependency('module', 'migrate_drupal'); return $this->dependencies; } }
dropdog/rightclick
profiles/rightclick/modules/contrib/simplenews/src/Plugin/migrate/source/d7/Newsletter.php
PHP
gpl-2.0
1,904
var Table = require ('../table.js'); var Command = require('../command.js'); require('../actions/report-action.js'); require('../actions/move-action.js'); require('../actions/right-action.js'); require('../actions/left-action.js'); require('../actions/place-action.js'); exports.Valid_PLACE = function(test){ var cmd = Command.GetCommand(['place', '1', '2', 'north']); test.notEqual(cmd, null); test.equal(cmd.data.x, 1); test.equal(cmd.data.y, 2); test.equal(cmd.data.f.getName(), 'NORTH'); test.done(); } exports.Invalid_PLACE = function(test){ var cmd = Command.GetCommand(['place', '1', '2', 'northf']); test.equal(cmd, null); test.done(); } exports.Valid_MOVE = function(test){ var cmd = Command.GetCommand(['MOVE']); test.notEqual(cmd, null); test.done(); } exports.Valid_LEFT = function(test){ var cmd = Command.GetCommand(['left']); test.notEqual(cmd, null); test.done(); } exports.Valid_RIGHT = function(test){ var cmd = Command.GetCommand(['Right']); test.notEqual(cmd, null); test.done(); } exports.Invalid_Command = function(test){ var cmd = Command.GetCommand(['Oops']); test.equal(cmd, null); test.done(); } exports.Valid_Execution = function(test){ // Create dummy Context var ctx = { table: new Table(5,5), robot:null, Feedback:{Show:function(msg){}}, Logger:{Log:function(msg){}} } Command.GetCommand(['place', '1', '1', 'east']).Execute(ctx); Command.GetCommand(['move']).Execute(ctx); Command.GetCommand(['left']).Execute(ctx); Command.GetCommand(['move']).Execute(ctx); Command.GetCommand(['move']).Execute(ctx); test.equal(ctx.robot.x, 2); test.equal(ctx.robot.y, 3); test.equal(ctx.robot.f.getName(), 'NORTH'); test.done(); } exports.Valid_IgnoreFallingMove = function(test){ // Create dummy Context var ctx = { table: new Table(5,5), robot:null, Feedback:{Show:function(msg){}}, Logger:{Log:function(msg){}} } Command.GetCommand(['place', '4', '1', 'east']).Execute(ctx); Command.GetCommand(['move']).Execute(ctx); test.equal(ctx.robot.x, 4); test.equal(ctx.robot.y, 1); test.equal(ctx.robot.f.getName(), 'EAST'); test.done(); }
PierreKel/ToyRobot
test/command-test.js
JavaScript
gpl-2.0
2,117
<?php // Prepare a category list. function view_macro_category($args) { global $pagestore, $MinEntries, $DayLimit, $full, $page, $Entity; global $FlgChr; $text = ''; if(strstr($args, '*')) // Category containing all pages. { $list = $pagestore->allpages(); } else if(strstr($args, '?')) // New pages. { $list = $pagestore->newpages(); } else if(strstr($args, '~')) // Zero-length (deleted) pages. { $list = $pagestore->emptypages(); } else // Ordinary list of pages. { $parsed = parseText($args, array('parse_wikiname', 'parse_freelink'), ''); $pagenames = array(); preg_replace('/' . $FlgChr . '(\\d+)' . $FlgChr . '/e', '$pagenames[]=$Entity[\\1][1]', $parsed); $list = $pagestore->givenpages($pagenames); } if(count($list) == 0) { return ''; } usort($list, 'catSort'); $now = time(); for($i = 0; $i < count($list); $i++) { if($DayLimit && $i >= $MinEntries && !$full && ($now - $list[$i][0]) > $DayLimit * 24 * 60 * 60) { break; } $text = $text . html_category($list[$i][0], $list[$i][1], $list[$i][2], $list[$i][3], $list[$i][5], $list[$i][7]); if($i < count($list) - 1) // Don't put a newline on the last one. { $text = $text . html_newline(); } } if($i < count($list)) { $text = $text . html_fulllist($page, count($list)); } return $text; } // Prepare a list of pages sorted by size. function view_macro_pagesize() { global $pagestore; $first = 1; $list = $pagestore->allpages(); usort($list, 'sizeSort'); $text = ''; foreach($list as $page) { if(!$first) // Don't prepend newline to first one. { $text = $text . "\n"; } else { $first = 0; } $text = $text . $page[4] . ' ' . html_ref($page[1], $page[1]); } return html_code($text); } // Prepare a list of pages and those pages they link to. function view_macro_linktab() { global $pagestore, $LkTbl; $lastpage = ''; $text = ''; $q1 = $pagestore->dbh->query("SELECT page, link FROM $LkTbl ORDER BY page"); while(($result = $pagestore->dbh->result($q1))) { if($lastpage != $result[0]) { if($lastpage != '') { $text = $text . "\n"; } $text = $text . html_ref($result[0], $result[0]) . ' |'; $lastpage = $result[0]; } $text = $text . ' ' . html_ref($result[1], $result[1]); } return html_code($text); } // Prepare a list of pages with no incoming links. function view_macro_orphans() { global $pagestore, $LkTbl; $text = ''; $first = 1; $pages = $pagestore->allpages(); usort($pages, 'nameSort'); foreach($pages as $page) { $q2 = $pagestore->dbh->query("SELECT page FROM $LkTbl " . "WHERE link='$page[1]' AND page!='$page[1]'"); if(!($r2 = $pagestore->dbh->result($q2)) || empty($r2[0])) { if(!$first) // Don't prepend newline to first one. { $text = $text . "\n"; } else { $first = 0; } $text = $text . html_ref($page[1], $page[1]); } } return html_code($text); } // Prepare a list of pages linked to that do not exist. function view_macro_wanted() { global $pagestore, $LkTbl, $PgTbl; $text = ''; $first = 1; $q1 = $pagestore->dbh->query("SELECT link, SUM(count) AS ct FROM $LkTbl " . "GROUP BY link ORDER BY ct DESC, link"); while(($result = $pagestore->dbh->result($q1))) { $q2 = $pagestore->dbh->query("SELECT MAX(version) FROM $PgTbl " . "WHERE title='$result[0]'"); if(!($r2 = $pagestore->dbh->result($q2)) || empty($r2[0])) { if(!$first) // Don't prepend newline to first one. { $text = $text . "\n"; } else { $first = 0; } $text = $text . '(' . html_url(findURL($result[0]), $result[1]) . ') ' . html_ref($result[0], $result[0]); } } return html_code($text); } // Prepare a list of pages sorted by how many links they contain. function view_macro_outlinks() { global $pagestore, $LkTbl; $text = ''; $first = 1; $q1 = $pagestore->dbh->query("SELECT page, SUM(count) AS ct FROM $LkTbl " . "GROUP BY page ORDER BY ct DESC, page"); while(($result = $pagestore->dbh->result($q1))) { if(!$first) // Don't prepend newline to first one. { $text = $text . "\n"; } else { $first = 0; } $text = $text . '(' . $result[1] . ') ' . html_ref($result[0], $result[0]); } return html_code($text); } // Prepare a list of pages sorted by how many links to them exist. function view_macro_refs() { global $pagestore, $LkTbl, $PgTbl; $text = ''; $first = 1; $q1 = $pagestore->dbh->query("SELECT link, SUM(count) AS ct FROM $LkTbl " . "GROUP BY link ORDER BY ct DESC, link"); while(($result = $pagestore->dbh->result($q1))) { $q2 = $pagestore->dbh->query("SELECT MAX(version) FROM $PgTbl " . "WHERE title='$result[0]'"); if(($r2 = $pagestore->dbh->result($q2)) && !empty($r2[0])) { if(!$first) // Don't prepend newline to first one. { $text = $text . "\n"; } else { $first = 0; } $text = $text . '(' . html_url(findURL($result[0]), $result[1]) . ') ' . html_ref($result[0], $result[0]); } } return html_code($text); } // This macro inserts an HTML anchor into the text. function view_macro_anchor($args) { preg_match('/([-A-Za-z0-9]*)/', $args, $result); if($result[1] != '') { return html_anchor($result[1]); } else { return ''; } } // This macro transcludes another page into a wiki page. function view_macro_transclude($args) { global $pagestore, $ParseEngine, $ParseObject; static $visited_array = array(); static $visited_count = 0; if(!validate_page($args)) { return '[[Transclude ' . $args . ']]'; } $visited_array[$visited_count++] = $ParseObject; for($i = 0; $i < $visited_count; $i++) { if($visited_array[$i] == $args) { $visited_count--; return '[[Transclude ' . $args . ']]'; } } $pg = $pagestore->page($args); $pg->read(); if(!$pg->exists) { $visited_count--; return '[[Transclude ' . $args . ']]'; } $result = parseText($pg->text, $ParseEngine, $args); $visited_count--; return $result; } ?>
apenwarr/gracefultavi
parse/macros.php
PHP
gpl-2.0
6,661
<?php namespace Drupal\better_messages\Form; use Drupal\Core\Form\ConfigFormBase; use Drupal\Core\Form\FormStateInterface; class BetterMessagesSettingsForm extends ConfigFormBase { public function getFormId() { return 'better_messages_settings_form'; } protected function getEditableConfigNames() { return ['better_messages.settings']; } public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config('better_messages.settings'); $settings = $config->get(); $form['position'] = array( '#type' => 'details', '#title' => t('Messages positions and basic properties'), '#weight' => -5, '#open' => TRUE ); $form['position']['pos'] = array( '#type' => 'radios', '#title' => t('Set position of Message'), '#default_value' => $settings['position'], '#description' => t('Position of message relative to screen'), '#attributes' => array('class' => array('better-messages-admin-radios')), '#options' => array( 'center' => t('Center screen'), 'tl' => t('Top left'), 'tr' => t('Top right'), 'bl' => t('Bottom left'), 'br' => t('Bottom right') ), ); $form['position']['fixed'] = array( '#type' => 'checkbox', '#default_value' => $settings['fixed'], '#title' => t('Keep fixed position of message as you scroll.'), ); $form['position']['width'] = array( '#type' => 'textfield', '#title' => t('Custom width'), '#description' => t('Width in pixel. Example: 400px<br />Or percentage. Example: 100%'), '#default_value' => $settings['width'], '#size' => 20, '#maxlength' => 20, '#required' => TRUE ); $form['position']['horizontal'] = array( '#type' => 'textfield', '#title' => t('Left/Right spacing'), '#description' => t('In active when position is set to "center".<br />In pixel. Example: 10'), '#default_value' => $settings['horizontal'], '#size' => 20, '#maxlength' => 20, '#required' => TRUE, ); $form['position']['vertical'] = array( '#type' => 'textfield', '#title' => t('Top/Down spacing'), '#description' => t('Inactive when position is set to "center".<br />In pixel. Example: 10'), '#default_value' => $settings['vertical'], '#size' => 20, '#maxlength' => 20, '#required' => TRUE, ); $form['animation'] = array( '#type' => 'details', '#title' => t('Messages animation settings'), '#weight' => -3, '#open' => TRUE ); $form['animation']['popin_effect'] = array( '#type' => 'select', '#title' => t('Pop-in (show) message box effect'), '#default_value' => $settings['popin']['effect'], '#options' => array( 'fadeIn' => t('Fade in'), 'slideDown' => t('Slide down'), ), ); $form['animation']['popin_duration'] = array( '#type' => 'textfield', '#title' => t('Duration of (show) effect'), '#description' => t('A string representing one of the three predefined speeds ("slow", "normal", or "fast").<br />Or the number of milliseconds to run the animation (e.g. 1000).'), '#default_value' => $settings['popin']['duration'], '#size' => 20, '#maxlength' => 20, ); $form['animation']['popout_effect'] = array( '#type' => 'select', '#title' => t('Pop-out (close) message box effect'), '#default_value' => $settings['popout']['effect'], '#options' => array( 'fadeIn' => t('Fade out'), 'slideUp' => t('Slide Up'), ), ); $form['animation']['popout_duration'] = array( '#type' => 'textfield', '#title' => t('Duration of (close) effect'), '#description' => t('A string representing one of the three predefined speeds ("slow", "normal", or "fast").<br />Or the number of milliseconds to run the animation (e.g. 1000).'), '#default_value' => $settings['popout']['duration'], '#size' => 20, '#maxlength' => 20, ); $form['animation']['autoclose'] = array( '#type' => 'textfield', '#title' => t('Number of seconds to auto close after the page has loaded'), '#description' => t('0 for never. You can set it as 0.25 for quarter second'), '#default_value' => $settings['autoclose'], '#size' => 20, '#maxlength' => 20, ); $form['animation']['disable_autoclose'] = array( '#type' => 'checkbox', '#title' => t('Disable auto close if messages inculde an error message'), '#default_value' => $settings['disable_autoclose'], ); $form['animation']['show_countdown'] = array( '#type' => 'checkbox', '#title' => t('Show countdown timer'), '#default_value' => $settings['show_countdown'], ); $form['animation']['hover_autoclose'] = array( '#type' => 'checkbox', '#title' => t('Stop auto close timer when hover'), '#default_value' => $settings['hover_autoclose'], ); $form['animation']['open_delay'] = array( '#type' => 'textfield', '#title' => t('Number of seconds to delay message after the page has loaded'), '#description' => t('0 for never. You can set it as 0.25 for quarter second'), '#default_value' => $settings['opendelay'], '#size' => 20, '#maxlength' => 20, ); $form['jquery_ui'] = array( '#type' => 'details', '#title' => t('jQuery UI enhancements'), '#weight' => 10, '#description' => t('These settings require !jquery_ui'), '#open' => TRUE ); $form['jquery_ui']['draggable'] = array( '#type' => 'checkbox', '#title' => t('Make Better Messages draggable'), '#default_value' => $settings['jquery_ui']['draggable'], ); $form['jquery_ui']['resizable'] = array( '#type' => 'checkbox', '#title' => t('Make Better Messages resizable'), '#default_value' => $settings['jquery_ui']['resizable'], ); $form['extra'] = array( '#type' => 'details', '#title' => t('Better Messages visibility'), '#description' => t('Changes in this section will apply only after cache clearing'), '#weight' => 0, '#open' => TRUE ); $form['extra']['admin'] = array( '#type' => 'checkbox', '#title' => t('Use Better Messages popup for the admin user (UID 1)'), '#default_value' => $settings['extra']['admin'] ); $options = array(t('Show on every page except the listed pages.'), t('Show on only the listed pages.')); $description = t("Enter one page per line as Drupal paths. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page.", array('%blog' => 'blog', '%blog-wildcard' => 'blog/*', '%front' => '<front>')); $form['extra']['visibility'] = array( '#type' => 'radios', '#title' => t('Show Better Messages on specific pages'), '#options' => $options, '#default_value' => $settings['extra']['visibility'], ); $form['extra']['pages'] = array( '#type' => 'textarea', '#title' => t('Pages'), '#default_value' => $settings['extra']['pages'], '#description' => $description, ); return parent::buildForm($form, $form_state); } public function validateForm(array &$form, FormStateInterface $form_state) { } public function submitForm(array &$form, FormStateInterface $form_state) { $this->config('better_messages.settings') ->set('position', $form_state->getValue('pos')) ->set('fixed', $form_state->getValue('fixed')) ->set('width', $form_state->getValue('width')) ->set('horizontal', $form_state->getValue('horizontal')) ->set('popin.effect', $form_state->getValue('popin_effect')) ->set('popin.duration', $form_state->getValue('popin_duration')) ->set('popout.effect', $form_state->getValue('popout_effect')) ->set('popout.duration', $form_state->getValue('popout_duration')) ->set('autoclose', $form_state->getValue('autoclose')) ->set('disable_autoclose', $form_state->getValue('disable_autoclose')) ->set('show_countdown', $form_state->getValue('show_countdown')) ->set('hover_autoclose', $form_state->getValue('hover_autoclose')) ->set('opendelay', $form_state->getValue('open_delay')) ->set('jquery_ui.draggable', $form_state->getValue('draggable')) ->set('jquery_ui.resizable', $form_state->getValue('resizable')) ->set('extra.admin', $form_state->getValue('admin')) ->set('extra.visibility', $form_state->getValue('visibility')) ->set('extra.pages', $form_state->getValue('pages')) ->save(); parent::submitForm($form, $form_state); } }
cooper-webdesign/cooper.dk
modules/better_messages/src/Form/BetterMessagesSettingsForm.php
PHP
gpl-2.0
8,436
<?php /** * @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version 2012.9 * @package kernel */ $tpl = eZTemplate::factory(); $tpl->setVariable( 'generated', false ); $tpl->setVariable( 'wrong_email', false ); $tpl->setVariable( 'link', false ); $tpl->setVariable( 'wrong_key', false ); $http = eZHTTPTool::instance(); $module = $Params['Module']; $hashKey = $Params["HashKey"]; $ini = eZINI::instance(); if ( strlen( $hashKey ) == 32 ) { $forgotPasswdObj = eZForgotPassword::fetchByKey( $hashKey ); if ( $forgotPasswdObj ) { $userID = $forgotPasswdObj->attribute( 'user_id' ); $user = eZUser::fetch( $userID ); $email = $user->attribute( 'email' ); $ini = eZINI::instance(); $passwordLength = $ini->variable( "UserSettings", "GeneratePasswordLength" ); $newPassword = eZUser::createPassword( $passwordLength ); $userToSendEmail = $user; $db = eZDB::instance(); $db->begin(); // Change user password if ( eZOperationHandler::operationIsAvailable( 'user_password' ) ) { $operationResult = eZOperationHandler::execute( 'user', 'password', array( 'user_id' => $userID, 'new_password' => $newPassword ) ); } else { eZUserOperationCollection::password( $userID, $newPassword ); } $receiver = $email; $mail = new eZMail(); if ( !$mail->validate( $receiver ) ) { } $tpl = eZTemplate::factory(); $tpl->setVariable( 'user', $userToSendEmail ); $tpl->setVariable( 'object', $userToSendEmail->attribute( 'contentobject' ) ); $tpl->setVariable( 'password', $newPassword ); $templateResult = $tpl->fetch( 'design:user/forgotpasswordmail.tpl' ); $emailSender = $ini->variable( 'MailSettings', 'EmailSender' ); if ( !$emailSender ) $emailSender = $ini->variable( 'MailSettings', 'AdminEmail' ); $mail->setSender( $emailSender ); $mail->setReceiver( $receiver ); $subject = ezpI18n::tr( 'kernel/user/register', 'Registration info' ); if ( $tpl->hasVariable( 'subject' ) ) $subject = $tpl->variable( 'subject' ); if ( $tpl->hasVariable( 'content_type' ) ) $mail->setContentType( $tpl->variable( 'content_type' ) ); $mail->setSubject( $subject ); $mail->setBody( $templateResult ); $mailResult = eZMailTransport::send( $mail ); $tpl->setVariable( 'generated', true ); $tpl->setVariable( 'email', $email ); $forgotPasswdObj->remove(); $db->commit(); } else { $tpl->setVariable( 'wrong_key', true ); } } else if ( strlen( $hashKey ) > 4 ) { $tpl->setVariable( 'wrong_key', true ); } if ( $module->isCurrentAction( "Generate" ) ) { $ini = eZINI::instance(); $passwordLength = $ini->variable( "UserSettings", "GeneratePasswordLength" ); $password = eZUser::createPassword( $passwordLength ); $passwordConfirm = $password; // $http->setSessionVariable( "GeneratedPassword", $password ); if ( $module->hasActionParameter( "Email" ) ) { $email = $module->actionParameter( "Email" ); if ( trim( $email ) != "" ) { $users = eZPersistentObject::fetchObjectList( eZUser::definition(), null, array( 'email' => $email ), null, null, true ); } if ( isset($users) && count($users) > 0 ) { $user = $users[0]; $time = time(); $userID = $user->id(); $hashKey = md5( $userID . ':' . $time . ':' . mt_rand() ); // Create forgot password object if ( eZOperationHandler::operationIsAvailable( 'user_forgotpassword' ) ) { $operationResult = eZOperationHandler::execute( 'user', 'forgotpassword', array( 'user_id' => $userID, 'password_hash' => $hashKey, 'time' => $time ) ); } else { eZUserOperationCollection::forgotpassword( $userID, $hashKey, $time ); } $userToSendEmail = $user; $receiver = $email; $mail = new eZMail(); if ( !$mail->validate( $receiver ) ) { } $tpl = eZTemplate::factory(); $tpl->setVariable( 'user', $userToSendEmail ); $tpl->setVariable( 'object', $userToSendEmail->attribute( 'contentobject' ) ); $tpl->setVariable( 'password', $password ); $tpl->setVariable( 'link', true ); $tpl->setVariable( 'hash_key', $hashKey ); $templateResult = $tpl->fetch( 'design:user/forgotpasswordmail.tpl' ); if ( $tpl->hasVariable( 'content_type' ) ) $mail->setContentType( $tpl->variable( 'content_type' ) ); $emailSender = $ini->variable( 'MailSettings', 'EmailSender' ); if ( !$emailSender ) $emailSender = $ini->variable( 'MailSettings', 'AdminEmail' ); $mail->setSender( $emailSender ); $mail->setReceiver( $receiver ); $subject = ezpI18n::tr( 'kernel/user/register', 'Registration info' ); if ( $tpl->hasVariable( 'subject' ) ) $subject = $tpl->variable( 'subject' ); $mail->setSubject( $subject ); $mail->setBody( $templateResult ); $mailResult = eZMailTransport::send( $mail ); $tpl->setVariable( 'email', $email ); } else { $tpl->setVariable( 'wrong_email', $email ); } } } $Result = array(); $Result['content'] = $tpl->fetch( 'design:user/forgotpassword.tpl' ); $Result['path'] = array( array( 'text' => ezpI18n::tr( 'kernel/user', 'User' ), 'url' => false ), array( 'text' => ezpI18n::tr( 'kernel/user', 'Forgot password' ), 'url' => false ) ); if ( $ini->variable( 'SiteSettings', 'LoginPage' ) == 'custom' ) { $Result['pagelayout'] = 'loginpagelayout.tpl'; } ?>
davidrousse/ezpuplish
app/ezpublish_legacy/kernel/user/forgotpassword.php
PHP
gpl-2.0
6,895
/********************************************************************** Audacity: A Digital Audio Editor SoundTouchEffect.cpp Dominic Mazzoni, Vaughan Johnson This abstract class contains all of the common code for an effect that uses SoundTouch to do its processing (ChangeTempo and ChangePitch). **********************************************************************/ #include "../Audacity.h" #if USE_SOUNDTOUCH #include <math.h> #include "../LabelTrack.h" #include "../WaveTrack.h" #include "../Project.h" #include "SoundTouchEffect.h" #include "TimeWarper.h" #include "../NoteTrack.h" bool EffectSoundTouch::ProcessLabelTrack(Track *track) { // SetTimeWarper(new RegionTimeWarper(mCurT0, mCurT1, // new LinearTimeWarper(mCurT0, mCurT0, // mCurT1, mCurT0 + (mCurT1-mCurT0)*mFactor))); LabelTrack *lt = (LabelTrack*)track; if (lt == NULL) return false; lt->WarpLabels(*GetTimeWarper()); return true; } #ifdef USE_MIDI bool EffectSoundTouch::ProcessNoteTrack(Track *track) { NoteTrack *nt = (NoteTrack *) track; if (nt == NULL) return false; nt->WarpAndTransposeNotes(mCurT0, mCurT1, *GetTimeWarper(), mSemitones); return true; } #endif bool EffectSoundTouch::Process() { // Assumes that mSoundTouch has already been initialized // by the subclass for subclass-specific parameters. The // time warper should also be set. // Check if this effect will alter the selection length; if so, we need // to operate on sync-lock selected tracks. bool mustSync = true; if (mT1 == GetTimeWarper()->Warp(mT1)) { mustSync = false; } //Iterate over each track // Needs Track::All for sync-lock grouping. this->CopyInputTracks(Track::All); bool bGoodResult = true; TrackListIterator iter(mOutputTracks); Track* t; mCurTrackNum = 0; m_maxNewLength = 0.0; t = iter.First(); while (t != NULL) { if (t->GetKind() == Track::Label && (t->GetSelected() || (mustSync && t->IsSyncLockSelected())) ) { if (!ProcessLabelTrack(t)) { bGoodResult = false; break; } } #ifdef USE_MIDI else if (t->GetKind() == Track::Note && (t->GetSelected() || (mustSync && t->IsSyncLockSelected()))) { if (!ProcessNoteTrack(t)) { bGoodResult = false; break; } } #endif else if (t->GetKind() == Track::Wave && t->GetSelected()) { WaveTrack* leftTrack = (WaveTrack*)t; //Get start and end times from track mCurT0 = leftTrack->GetStartTime(); mCurT1 = leftTrack->GetEndTime(); //Set the current bounds to whichever left marker is //greater and whichever right marker is less mCurT0 = wxMax(mT0, mCurT0); mCurT1 = wxMin(mT1, mCurT1); // Process only if the right marker is to the right of the left marker if (mCurT1 > mCurT0) { sampleCount start, end; if (leftTrack->GetLinked()) { double t; WaveTrack* rightTrack = (WaveTrack*)(iter.Next()); //Adjust bounds by the right tracks markers t = rightTrack->GetStartTime(); t = wxMax(mT0, t); mCurT0 = wxMin(mCurT0, t); t = rightTrack->GetEndTime(); t = wxMin(mT1, t); mCurT1 = wxMax(mCurT1, t); //Transform the marker timepoints to samples start = leftTrack->TimeToLongSamples(mCurT0); end = leftTrack->TimeToLongSamples(mCurT1); //Inform soundtouch there's 2 channels mSoundTouch->setChannels(2); //ProcessStereo() (implemented below) processes a stereo track if (!ProcessStereo(leftTrack, rightTrack, start, end)) { bGoodResult = false; break; } mCurTrackNum++; // Increment for rightTrack, too. } else { //Transform the marker timepoints to samples start = leftTrack->TimeToLongSamples(mCurT0); end = leftTrack->TimeToLongSamples(mCurT1); //Inform soundtouch there's a single channel mSoundTouch->setChannels(1); //ProcessOne() (implemented below) processes a single track if (!ProcessOne(leftTrack, start, end)) { bGoodResult = false; break; } } } mCurTrackNum++; } else if (mustSync && t->IsSyncLockSelected()) { t->SyncLockAdjust(mT1, GetTimeWarper()->Warp(mT1)); } //Iterate to the next track t = iter.Next(); } if (bGoodResult) ReplaceProcessedTracks(bGoodResult); delete mSoundTouch; mSoundTouch = NULL; // mT0 = mCurT0; // mT1 = mCurT0 + m_maxNewLength; // Update selection. return bGoodResult; } //ProcessOne() takes a track, transforms it to bunch of buffer-blocks, //and executes ProcessSoundTouch on these blocks bool EffectSoundTouch::ProcessOne(WaveTrack *track, sampleCount start, sampleCount end) { WaveTrack *outputTrack; sampleCount s; mSoundTouch->setSampleRate((unsigned int)(track->GetRate()+0.5)); outputTrack = mFactory->NewWaveTrack(track->GetSampleFormat(), track->GetRate()); //Get the length of the buffer (as double). len is //used simple to calculate a progress meter, so it is easier //to make it a double now than it is to do it later double len = (double)(end - start); //Initiate a processing buffer. This buffer will (most likely) //be shorter than the length of the track being processed. float *buffer = new float[track->GetMaxBlockSize()]; //Go through the track one buffer at a time. s counts which //sample the current buffer starts at. s = start; while (s < end) { //Get a block of samples (smaller than the size of the buffer) sampleCount block = track->GetBestBlockSize(s); //Adjust the block size if it is the final block in the track if (s + block > end) block = end - s; //Get the samples from the track and put them in the buffer track->Get((samplePtr) buffer, floatSample, s, block); //Add samples to SoundTouch mSoundTouch->putSamples(buffer, block); //Get back samples from SoundTouch unsigned int outputCount = mSoundTouch->numSamples(); if (outputCount > 0) { float *buffer2 = new float[outputCount]; mSoundTouch->receiveSamples(buffer2, outputCount); outputTrack->Append((samplePtr)buffer2, floatSample, outputCount); delete[] buffer2; } //Increment s one blockfull of samples s += block; //Update the Progress meter if (TrackProgress(mCurTrackNum, (s - start) / len)) return false; } // Tell SoundTouch to finish processing any remaining samples mSoundTouch->flush(); // this should only be used for changeTempo - it dumps data otherwise with pRateTransposer->clear(); unsigned int outputCount = mSoundTouch->numSamples(); if (outputCount > 0) { float *buffer2 = new float[outputCount]; mSoundTouch->receiveSamples(buffer2, outputCount); outputTrack->Append((samplePtr)buffer2, floatSample, outputCount); delete[] buffer2; } // Flush the output WaveTrack (since it's buffered, too) outputTrack->Flush(); // Clean up the buffer delete[]buffer; // Take the output track and insert it in place of the original // sample data track->ClearAndPaste(mCurT0, mCurT1, outputTrack, true, false, GetTimeWarper()); double newLength = outputTrack->GetEndTime(); m_maxNewLength = wxMax(m_maxNewLength, newLength); // Delete the outputTrack now that its data is inserted in place delete outputTrack; //Return true because the effect processing succeeded. return true; } bool EffectSoundTouch::ProcessStereo(WaveTrack* leftTrack, WaveTrack* rightTrack, sampleCount start, sampleCount end) { mSoundTouch->setSampleRate((unsigned int)(leftTrack->GetRate()+0.5)); WaveTrack* outputLeftTrack = mFactory->NewWaveTrack(leftTrack->GetSampleFormat(), leftTrack->GetRate()); WaveTrack* outputRightTrack = mFactory->NewWaveTrack(rightTrack->GetSampleFormat(), rightTrack->GetRate()); //Get the length of the buffer (as double). len is //used simple to calculate a progress meter, so it is easier //to make it a double now than it is to do it later double len = (double)(end - start); //Initiate a processing buffer. This buffer will (most likely) //be shorter than the length of the track being processed. // Make soundTouchBuffer twice as big as MaxBlockSize for each channel, // because Soundtouch wants them interleaved, i.e., each // Soundtouch sample is left-right pair. sampleCount maxBlockSize = leftTrack->GetMaxBlockSize(); float* leftBuffer = new float[maxBlockSize]; float* rightBuffer = new float[maxBlockSize]; float* soundTouchBuffer = new float[maxBlockSize * 2]; // Go through the track one stereo buffer at a time. // sourceSampleCount counts the sample at which the current buffer starts, // per channel. sampleCount sourceSampleCount = start; while (sourceSampleCount < end) { //Get a block of samples (smaller than the size of the buffer) sampleCount blockSize = leftTrack->GetBestBlockSize(sourceSampleCount); //Adjust the block size if it is the final block in the track if (sourceSampleCount + blockSize > end) blockSize = end - sourceSampleCount; // Get the samples from the tracks and put them in the buffers. leftTrack->Get((samplePtr)(leftBuffer), floatSample, sourceSampleCount, blockSize); rightTrack->Get((samplePtr)(rightBuffer), floatSample, sourceSampleCount, blockSize); // Interleave into soundTouchBuffer. for (int index = 0; index < blockSize; index++) { soundTouchBuffer[index*2] = leftBuffer[index]; soundTouchBuffer[(index*2)+1] = rightBuffer[index]; } //Add samples to SoundTouch mSoundTouch->putSamples(soundTouchBuffer, blockSize); //Get back samples from SoundTouch unsigned int outputCount = mSoundTouch->numSamples(); if (outputCount > 0) this->ProcessStereoResults(outputCount, outputLeftTrack, outputRightTrack); //Increment sourceSampleCount one blockfull of samples sourceSampleCount += blockSize; //Update the Progress meter // mCurTrackNum is left track. Include right track. int nWhichTrack = mCurTrackNum; double frac = (sourceSampleCount - start) / len; if (frac < 0.5) frac *= 2.0; // Show twice as far for each track, because we're doing 2 at once. else { nWhichTrack++; frac -= 0.5; frac *= 2.0; // Show twice as far for each track, because we're doing 2 at once. } if (TrackProgress(nWhichTrack, frac)) return false; } // Tell SoundTouch to finish processing any remaining samples mSoundTouch->flush(); unsigned int outputCount = mSoundTouch->numSamples(); if (outputCount > 0) this->ProcessStereoResults(outputCount, outputLeftTrack, outputRightTrack); // Flush the output WaveTracks (since they're buffered, too) outputLeftTrack->Flush(); outputRightTrack->Flush(); // Clean up the buffers. delete [] leftBuffer; delete [] rightBuffer; delete [] soundTouchBuffer; // Take the output tracks and insert in place of the original // sample data. leftTrack->ClearAndPaste(mCurT0, mCurT1, outputLeftTrack, true, false, GetTimeWarper()); rightTrack->ClearAndPaste(mCurT0, mCurT1, outputRightTrack, true, false, GetTimeWarper()); // Track the longest result length double newLength = outputLeftTrack->GetEndTime(); m_maxNewLength = wxMax(m_maxNewLength, newLength); newLength = outputRightTrack->GetEndTime(); m_maxNewLength = wxMax(m_maxNewLength, newLength); // Delete the outputTracks now that their data are inserted in place. delete outputLeftTrack; delete outputRightTrack; //Return true because the effect processing succeeded. return true; } bool EffectSoundTouch::ProcessStereoResults(const unsigned int outputCount, WaveTrack* outputLeftTrack, WaveTrack* outputRightTrack) { float* outputSoundTouchBuffer = new float[outputCount*2]; mSoundTouch->receiveSamples(outputSoundTouchBuffer, outputCount); // Dis-interleave outputSoundTouchBuffer into separate track buffers. float* outputLeftBuffer = new float[outputCount]; float* outputRightBuffer = new float[outputCount]; for (unsigned int index = 0; index < outputCount; index++) { outputLeftBuffer[index] = outputSoundTouchBuffer[index*2]; outputRightBuffer[index] = outputSoundTouchBuffer[(index*2)+1]; } outputLeftTrack->Append((samplePtr)outputLeftBuffer, floatSample, outputCount); outputRightTrack->Append((samplePtr)outputRightBuffer, floatSample, outputCount); delete[] outputSoundTouchBuffer; delete[] outputLeftBuffer; delete[] outputRightBuffer; return true; } #endif // USE_SOUNDTOUCH
bit-trade-one/SoundModuleAP
src/effects/SoundTouchEffect.cpp
C++
gpl-2.0
14,053
import collections import re import sys import warnings from bs4.dammit import EntitySubstitution DEFAULT_OUTPUT_ENCODING = "utf-8" PY3K = (sys.version_info[0] > 2) whitespace_re = re.compile("\s+") def _alias(attr): """Alias one attribute name to another for backward compatibility""" @property def alias(self): return getattr(self, attr) @alias.setter def alias(self): return setattr(self, attr) return alias class NamespacedAttribute(unicode): def __new__(cls, prefix, name, namespace=None): if name is None: obj = unicode.__new__(cls, prefix) elif prefix is None: # Not really namespaced. obj = unicode.__new__(cls, name) else: obj = unicode.__new__(cls, prefix + ":" + name) obj.prefix = prefix obj.name = name obj.namespace = namespace return obj class AttributeValueWithCharsetSubstitution(unicode): """A stand-in object for a character encoding specified in HTML.""" class CharsetMetaAttributeValue(AttributeValueWithCharsetSubstitution): """A generic stand-in for the value of a meta tag's 'charset' attribute. When Beautiful Soup parses the markup '<meta charset="utf8">', the value of the 'charset' attribute will be one of these objects. """ def __new__(cls, original_value): obj = unicode.__new__(cls, original_value) obj.original_value = original_value return obj def encode(self, encoding): return encoding class ContentMetaAttributeValue(AttributeValueWithCharsetSubstitution): """A generic stand-in for the value of a meta tag's 'content' attribute. When Beautiful Soup parses the markup: <meta http-equiv="content-type" content="text/html; charset=utf8"> The value of the 'content' attribute will be one of these objects. """ CHARSET_RE = re.compile("((^|;)\s*charset=)([^;]*)", re.M) def __new__(cls, original_value): match = cls.CHARSET_RE.search(original_value) if match is None: # No substitution necessary. return unicode.__new__(unicode, original_value) obj = unicode.__new__(cls, original_value) obj.original_value = original_value return obj def encode(self, encoding): def rewrite(match): return match.group(1) + encoding return self.CHARSET_RE.sub(rewrite, self.original_value) class HTMLAwareEntitySubstitution(EntitySubstitution): """Entity substitution rules that are aware of some HTML quirks. Specifically, the contents of <script> and <style> tags should not undergo entity substitution. Incoming NavigableString objects are checked to see if they're the direct children of a <script> or <style> tag. """ cdata_containing_tags = set(["script", "style"]) preformatted_tags = set(["pre"]) @classmethod def _substitute_if_appropriate(cls, ns, f): if (isinstance(ns, NavigableString) and ns.parent is not None and ns.parent.name in cls.cdata_containing_tags): # Do nothing. return ns # Substitute. return f(ns) @classmethod def substitute_html(cls, ns): return cls._substitute_if_appropriate( ns, EntitySubstitution.substitute_html) @classmethod def substitute_xml(cls, ns): return cls._substitute_if_appropriate( ns, EntitySubstitution.substitute_xml) class PageElement(object): """Contains the navigational information for some part of the page (either a tag or a piece of text)""" # There are five possible values for the "formatter" argument passed in # to methods like encode() and prettify(): # # "html" - All Unicode characters with corresponding HTML entities # are converted to those entities on output. # "minimal" - Bare ampersands and angle brackets are converted to # XML entities: &amp; &lt; &gt; # None - The null formatter. Unicode characters are never # converted to entities. This is not recommended, but it's # faster than "minimal". # A function - This function will be called on every string that # needs to undergo entity substitution. # # In an HTML document, the default "html" and "minimal" functions # will leave the contents of <script> and <style> tags alone. For # an XML document, all tags will be given the same treatment. HTML_FORMATTERS = { "html" : HTMLAwareEntitySubstitution.substitute_html, "minimal" : HTMLAwareEntitySubstitution.substitute_xml, None : None } XML_FORMATTERS = { "html" : EntitySubstitution.substitute_html, "minimal" : EntitySubstitution.substitute_xml, None : None } def format_string(self, s, formatter='minimal'): """Format the given string using the given formatter.""" if not callable(formatter): formatter = self._formatter_for_name(formatter) if formatter is None: output = s else: output = formatter(s) return output @property def _is_xml(self): """Is this element part of an XML tree or an HTML tree? This is used when mapping a formatter name ("minimal") to an appropriate function (one that performs entity-substitution on the contents of <script> and <style> tags, or not). It's inefficient, but it should be called very rarely. """ if self.parent is None: # This is the top-level object. It should have .is_xml set # from tree creation. If not, take a guess--BS is usually # used on HTML markup. return getattr(self, 'is_xml', False) return self.parent._is_xml def _formatter_for_name(self, name): "Look up a formatter function based on its name and the tree." if self._is_xml: return self.XML_FORMATTERS.get( name, EntitySubstitution.substitute_xml) else: return self.HTML_FORMATTERS.get( name, HTMLAwareEntitySubstitution.substitute_xml) def setup(self, parent=None, previous_element=None): """Sets up the initial relations between this element and other elements.""" self.parent = parent self.previous_element = previous_element if previous_element is not None: self.previous_element.next_element = self self.next_element = None self.previous_sibling = None self.next_sibling = None if self.parent is not None and self.parent.contents: self.previous_sibling = self.parent.contents[-1] self.previous_sibling.next_sibling = self nextSibling = _alias("next_sibling") # BS3 previousSibling = _alias("previous_sibling") # BS3 def replace_with(self, replace_with): if replace_with is self: return if replace_with is self.parent: raise ValueError("Cannot replace a Tag with its parent.") old_parent = self.parent my_index = self.parent.index(self) self.extract() old_parent.insert(my_index, replace_with) return self replaceWith = replace_with # BS3 def unwrap(self): my_parent = self.parent my_index = self.parent.index(self) self.extract() for child in reversed(self.contents[:]): my_parent.insert(my_index, child) return self replace_with_children = unwrap replaceWithChildren = unwrap # BS3 def wrap(self, wrap_inside): me = self.replace_with(wrap_inside) wrap_inside.append(me) return wrap_inside def extract(self): """Destructively rips this element out of the tree.""" if self.parent is not None: del self.parent.contents[self.parent.index(self)] #Find the two elements that would be next to each other if #this element (and any children) hadn't been parsed. Connect #the two. last_child = self._last_descendant() next_element = last_child.next_element if self.previous_element is not None: self.previous_element.next_element = next_element if next_element is not None: next_element.previous_element = self.previous_element self.previous_element = None last_child.next_element = None self.parent = None if self.previous_sibling is not None: self.previous_sibling.next_sibling = self.next_sibling if self.next_sibling is not None: self.next_sibling.previous_sibling = self.previous_sibling self.previous_sibling = self.next_sibling = None return self def _last_descendant(self): "Finds the last element beneath this object to be parsed." last_child = self while hasattr(last_child, 'contents') and last_child.contents: last_child = last_child.contents[-1] return last_child # BS3: Not part of the API! _lastRecursiveChild = _last_descendant def insert(self, position, new_child): if new_child is self: raise ValueError("Cannot insert a tag into itself.") if (isinstance(new_child, basestring) and not isinstance(new_child, NavigableString)): new_child = NavigableString(new_child) position = min(position, len(self.contents)) if hasattr(new_child, 'parent') and new_child.parent is not None: # We're 'inserting' an element that's already one # of this object's children. if new_child.parent is self: current_index = self.index(new_child) if current_index < position: # We're moving this element further down the list # of this object's children. That means that when # we extract this element, our target index will # jump down one. position -= 1 new_child.extract() new_child.parent = self previous_child = None if position == 0: new_child.previous_sibling = None new_child.previous_element = self else: previous_child = self.contents[position - 1] new_child.previous_sibling = previous_child new_child.previous_sibling.next_sibling = new_child new_child.previous_element = previous_child._last_descendant() if new_child.previous_element is not None: new_child.previous_element.next_element = new_child new_childs_last_element = new_child._last_descendant() if position >= len(self.contents): new_child.next_sibling = None parent = self parents_next_sibling = None while parents_next_sibling is None and parent is not None: parents_next_sibling = parent.next_sibling parent = parent.parent if parents_next_sibling is not None: # We found the element that comes next in the document. break if parents_next_sibling is not None: new_childs_last_element.next_element = parents_next_sibling else: # The last element of this tag is the last element in # the document. new_childs_last_element.next_element = None else: next_child = self.contents[position] new_child.next_sibling = next_child if new_child.next_sibling is not None: new_child.next_sibling.previous_sibling = new_child new_childs_last_element.next_element = next_child if new_childs_last_element.next_element is not None: new_childs_last_element.next_element.previous_element = new_childs_last_element self.contents.insert(position, new_child) def append(self, tag): """Appends the given tag to the contents of this tag.""" self.insert(len(self.contents), tag) def insert_before(self, predecessor): """Makes the given element the immediate predecessor of this one. The two elements will have the same parent, and the given element will be immediately before this one. """ if self is predecessor: raise ValueError("Can't insert an element before itself.") parent = self.parent if parent is None: raise ValueError( "Element has no parent, so 'before' has no meaning.") # Extract first so that the index won't be screwed up if they # are siblings. if isinstance(predecessor, PageElement): predecessor.extract() index = parent.index(self) parent.insert(index, predecessor) def insert_after(self, successor): """Makes the given element the immediate successor of this one. The two elements will have the same parent, and the given element will be immediately after this one. """ if self is successor: raise ValueError("Can't insert an element after itself.") parent = self.parent if parent is None: raise ValueError( "Element has no parent, so 'after' has no meaning.") # Extract first so that the index won't be screwed up if they # are siblings. if isinstance(successor, PageElement): successor.extract() index = parent.index(self) parent.insert(index+1, successor) def find_next(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears after this Tag in the document.""" return self._find_one(self.find_all_next, name, attrs, text, **kwargs) findNext = find_next # BS3 def find_all_next(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear after this Tag in the document.""" return self._find_all(name, attrs, text, limit, self.next_elements, **kwargs) findAllNext = find_all_next # BS3 def find_next_sibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears after this Tag in the document.""" return self._find_one(self.find_next_siblings, name, attrs, text, **kwargs) findNextSibling = find_next_sibling # BS3 def find_next_siblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear after this Tag in the document.""" return self._find_all(name, attrs, text, limit, self.next_siblings, **kwargs) findNextSiblings = find_next_siblings # BS3 fetchNextSiblings = find_next_siblings # BS2 def find_previous(self, name=None, attrs={}, text=None, **kwargs): """Returns the first item that matches the given criteria and appears before this Tag in the document.""" return self._find_one( self.find_all_previous, name, attrs, text, **kwargs) findPrevious = find_previous # BS3 def find_all_previous(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns all items that match the given criteria and appear before this Tag in the document.""" return self._find_all(name, attrs, text, limit, self.previous_elements, **kwargs) findAllPrevious = find_all_previous # BS3 fetchPrevious = find_all_previous # BS2 def find_previous_sibling(self, name=None, attrs={}, text=None, **kwargs): """Returns the closest sibling to this Tag that matches the given criteria and appears before this Tag in the document.""" return self._find_one(self.find_previous_siblings, name, attrs, text, **kwargs) findPreviousSibling = find_previous_sibling # BS3 def find_previous_siblings(self, name=None, attrs={}, text=None, limit=None, **kwargs): """Returns the siblings of this Tag that match the given criteria and appear before this Tag in the document.""" return self._find_all(name, attrs, text, limit, self.previous_siblings, **kwargs) findPreviousSiblings = find_previous_siblings # BS3 fetchPreviousSiblings = find_previous_siblings # BS2 def find_parent(self, name=None, attrs={}, **kwargs): """Returns the closest parent of this Tag that matches the given criteria.""" # NOTE: We can't use _find_one because findParents takes a different # set of arguments. r = None l = self.find_parents(name, attrs, 1, **kwargs) if l: r = l[0] return r findParent = find_parent # BS3 def find_parents(self, name=None, attrs={}, limit=None, **kwargs): """Returns the parents of this Tag that match the given criteria.""" return self._find_all(name, attrs, None, limit, self.parents, **kwargs) findParents = find_parents # BS3 fetchParents = find_parents # BS2 @property def next(self): return self.next_element @property def previous(self): return self.previous_element #These methods do the real heavy lifting. def _find_one(self, method, name, attrs, text, **kwargs): r = None l = method(name, attrs, text, 1, **kwargs) if l: r = l[0] return r def _find_all(self, name, attrs, text, limit, generator, **kwargs): "Iterates over a generator looking for things that match." if isinstance(name, SoupStrainer): strainer = name elif text is None and not limit and not attrs and not kwargs: # Optimization to find all tags. if name is True or name is None: return [element for element in generator if isinstance(element, Tag)] # Optimization to find all tags with a given name. elif isinstance(name, basestring): return [element for element in generator if isinstance(element, Tag) and element.name == name] else: strainer = SoupStrainer(name, attrs, text, **kwargs) else: # Build a SoupStrainer strainer = SoupStrainer(name, attrs, text, **kwargs) results = ResultSet(strainer) while True: try: i = next(generator) except StopIteration: break if i: found = strainer.search(i) if found: results.append(found) if limit and len(results) >= limit: break return results #These generators can be used to navigate starting from both #NavigableStrings and Tags. @property def next_elements(self): i = self.next_element while i is not None: yield i i = i.next_element @property def next_siblings(self): i = self.next_sibling while i is not None: yield i i = i.next_sibling @property def previous_elements(self): i = self.previous_element while i is not None: yield i i = i.previous_element @property def previous_siblings(self): i = self.previous_sibling while i is not None: yield i i = i.previous_sibling @property def parents(self): i = self.parent while i is not None: yield i i = i.parent # Methods for supporting CSS selectors. tag_name_re = re.compile('^[a-z0-9]+$') # /^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/ # \---/ \---/\-------------/ \-------/ # | | | | # | | | The value # | | ~,|,^,$,* or = # | Attribute # Tag attribselect_re = re.compile( r'^(?P<tag>\w+)?\[(?P<attribute>\w+)(?P<operator>[=~\|\^\$\*]?)' + r'=?"?(?P<value>[^\]"]*)"?\]$' ) def _attr_value_as_string(self, value, default=None): """Force an attribute value into a string representation. A multi-valued attribute will be converted into a space-separated stirng. """ value = self.get(value, default) if isinstance(value, list) or isinstance(value, tuple): value =" ".join(value) return value def _tag_name_matches_and(self, function, tag_name): if not tag_name: return function else: def _match(tag): return tag.name == tag_name and function(tag) return _match def _attribute_checker(self, operator, attribute, value=''): """Create a function that performs a CSS selector operation. Takes an operator, attribute and optional value. Returns a function that will return True for elements that match that combination. """ if operator == '=': # string representation of `attribute` is equal to `value` return lambda el: el._attr_value_as_string(attribute) == value elif operator == '~': # space-separated list representation of `attribute` # contains `value` def _includes_value(element): attribute_value = element.get(attribute, []) if not isinstance(attribute_value, list): attribute_value = attribute_value.split() return value in attribute_value return _includes_value elif operator == '^': # string representation of `attribute` starts with `value` return lambda el: el._attr_value_as_string( attribute, '').startswith(value) elif operator == '$': # string represenation of `attribute` ends with `value` return lambda el: el._attr_value_as_string( attribute, '').endswith(value) elif operator == '*': # string representation of `attribute` contains `value` return lambda el: value in el._attr_value_as_string(attribute, '') elif operator == '|': # string representation of `attribute` is either exactly # `value` or starts with `value` and then a dash. def _is_or_starts_with_dash(element): attribute_value = element._attr_value_as_string(attribute, '') return (attribute_value == value or attribute_value.startswith( value + '-')) return _is_or_starts_with_dash else: return lambda el: el.has_attr(attribute) # Old non-property versions of the generators, for backwards # compatibility with BS3. def nextGenerator(self): return self.next_elements def nextSiblingGenerator(self): return self.next_siblings def previousGenerator(self): return self.previous_elements def previousSiblingGenerator(self): return self.previous_siblings def parentGenerator(self): return self.parents class NavigableString(unicode, PageElement): PREFIX = '' SUFFIX = '' def __new__(cls, value): """Create a new NavigableString. When unpickling a NavigableString, this method is called with the string in DEFAULT_OUTPUT_ENCODING. That encoding needs to be passed in to the superclass's __new__ or the superclass won't know how to handle non-ASCII characters. """ if isinstance(value, unicode): return unicode.__new__(cls, value) return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING) def __copy__(self): return self def __getnewargs__(self): return (unicode(self),) def __getattr__(self, attr): """text.string gives you text. This is for backwards compatibility for Navigable*String, but for CData* it lets you get the string without the CData wrapper.""" if attr == 'string': return self else: raise AttributeError( "'%s' object has no attribute '%s'" % ( self.__class__.__name__, attr)) def output_ready(self, formatter="minimal"): output = self.format_string(self, formatter) return self.PREFIX + output + self.SUFFIX class PreformattedString(NavigableString): """A NavigableString not subject to the normal formatting rules. The string will be passed into the formatter (to trigger side effects), but the return value will be ignored. """ def output_ready(self, formatter="minimal"): """CData strings are passed into the formatter. But the return value is ignored.""" self.format_string(self, formatter) return self.PREFIX + self + self.SUFFIX class CData(PreformattedString): PREFIX = u'<![CDATA[' SUFFIX = u']]>' class ProcessingInstruction(PreformattedString): PREFIX = u'<?' SUFFIX = u'?>' class Comment(PreformattedString): PREFIX = u'<!--' SUFFIX = u'-->' class Declaration(PreformattedString): PREFIX = u'<!' SUFFIX = u'!>' class Doctype(PreformattedString): @classmethod def for_name_and_ids(cls, name, pub_id, system_id): value = name or '' if pub_id is not None: value += ' PUBLIC "%s"' % pub_id if system_id is not None: value += ' "%s"' % system_id elif system_id is not None: value += ' SYSTEM "%s"' % system_id return Doctype(value) PREFIX = u'<!DOCTYPE ' SUFFIX = u'>\n' class Tag(PageElement): """Represents a found HTML tag with its attributes and contents.""" def __init__(self, parser=None, builder=None, name=None, namespace=None, prefix=None, attrs=None, parent=None, previous=None): "Basic constructor." if parser is None: self.parser_class = None else: # We don't actually store the parser object: that lets extracted # chunks be garbage-collected. self.parser_class = parser.__class__ if name is None: raise ValueError("No value provided for new tag's name.") self.name = name self.namespace = namespace self.prefix = prefix if attrs is None: attrs = {} elif builder.cdata_list_attributes: attrs = builder._replace_cdata_list_attribute_values( self.name, attrs) else: attrs = dict(attrs) self.attrs = attrs self.contents = [] self.setup(parent, previous) self.hidden = False # Set up any substitutions, such as the charset in a META tag. if builder is not None: builder.set_up_substitutions(self) self.can_be_empty_element = builder.can_be_empty_element(name) else: self.can_be_empty_element = False parserClass = _alias("parser_class") # BS3 @property def is_empty_element(self): """Is this tag an empty-element tag? (aka a self-closing tag) A tag that has contents is never an empty-element tag. A tag that has no contents may or may not be an empty-element tag. It depends on the builder used to create the tag. If the builder has a designated list of empty-element tags, then only a tag whose name shows up in that list is considered an empty-element tag. If the builder has no designated list of empty-element tags, then any tag with no contents is an empty-element tag. """ return len(self.contents) == 0 and self.can_be_empty_element isSelfClosing = is_empty_element # BS3 @property def string(self): """Convenience property to get the single string within this tag. :Return: If this tag has a single string child, return value is that string. If this tag has no children, or more than one child, return value is None. If this tag has one child tag, return value is the 'string' attribute of the child tag, recursively. """ if len(self.contents) != 1: return None child = self.contents[0] if isinstance(child, NavigableString): return child return child.string @string.setter def string(self, string): self.clear() self.append(string.__class__(string)) def _all_strings(self, strip=False, types=(NavigableString, CData)): """Yield all strings of certain classes, possibly stripping them. By default, yields only NavigableString and CData objects. So no comments, processing instructions, etc. """ for descendant in self.descendants: if ( (types is None and not isinstance(descendant, NavigableString)) or (types is not None and type(descendant) not in types)): continue if strip: descendant = descendant.strip() if len(descendant) == 0: continue yield descendant strings = property(_all_strings) @property def stripped_strings(self): for string in self._all_strings(True): yield string def get_text(self, separator=u"", strip=False, types=(NavigableString, CData)): """ Get all child strings, concatenated using the given separator. """ return separator.join([s for s in self._all_strings( strip, types=types)]) getText = get_text text = property(get_text) def decompose(self): """Recursively destroys the contents of this tree.""" self.extract() i = self while i is not None: next = i.next_element i.__dict__.clear() i.contents = [] i = next def clear(self, decompose=False): """ Extract all children. If decompose is True, decompose instead. """ if decompose: for element in self.contents[:]: if isinstance(element, Tag): element.decompose() else: element.extract() else: for element in self.contents[:]: element.extract() def index(self, element): """ Find the index of a child by identity, not value. Avoids issues with tag.contents.index(element) getting the index of equal elements. """ for i, child in enumerate(self.contents): if child is element: return i raise ValueError("Tag.index: element not in tag") def get(self, key, default=None): """Returns the value of the 'key' attribute for the tag, or the value given for 'default' if it doesn't have that attribute.""" return self.attrs.get(key, default) def has_attr(self, key): return key in self.attrs def __hash__(self): return str(self).__hash__() def __getitem__(self, key): """tag[key] returns the value of the 'key' attribute for the tag, and throws an exception if it's not there.""" return self.attrs[key] def __iter__(self): "Iterating over a tag iterates over its contents." return iter(self.contents) def __len__(self): "The length of a tag is the length of its list of contents." return len(self.contents) def __contains__(self, x): return x in self.contents def __nonzero__(self): "A tag is non-None even if it has no contents." return True def __setitem__(self, key, value): """Setting tag[key] sets the value of the 'key' attribute for the tag.""" self.attrs[key] = value def __delitem__(self, key): "Deleting tag[key] deletes all 'key' attributes for the tag." self.attrs.pop(key, None) def __call__(self, *args, **kwargs): """Calling a tag like a function is the same as calling its find_all() method. Eg. tag('a') returns a list of all the A tags found within this tag.""" return self.find_all(*args, **kwargs) def __getattr__(self, tag): #print "Getattr %s.%s" % (self.__class__, tag) if len(tag) > 3 and tag.endswith('Tag'): # BS3: soup.aTag -> "soup.find("a") tag_name = tag[:-3] warnings.warn( '.%sTag is deprecated, use .find("%s") instead.' % ( tag_name, tag_name)) return self.find(tag_name) # We special case contents to avoid recursion. elif not tag.startswith("__") and not tag=="contents": return self.find(tag) raise AttributeError( "'%s' object has no attribute '%s'" % (self.__class__, tag)) def __eq__(self, other): """Returns true iff this tag has the same name, the same attributes, and the same contents (recursively) as the given tag.""" if self is other: return True if (not hasattr(other, 'name') or not hasattr(other, 'attrs') or not hasattr(other, 'contents') or self.name != other.name or self.attrs != other.attrs or len(self) != len(other)): return False for i, my_child in enumerate(self.contents): if my_child != other.contents[i]: return False return True def __ne__(self, other): """Returns true iff this tag is not identical to the other tag, as defined in __eq__.""" return not self == other def __repr__(self, encoding=DEFAULT_OUTPUT_ENCODING): """Renders this tag as a string.""" return self.encode(encoding) def __unicode__(self): return self.decode() def __str__(self): return self.encode() if PY3K: __str__ = __repr__ = __unicode__ def encode(self, encoding=DEFAULT_OUTPUT_ENCODING, indent_level=None, formatter="minimal", errors="xmlcharrefreplace"): # Turn the data structure into Unicode, then encode the # Unicode. u = self.decode(indent_level, encoding, formatter) return u.encode(encoding, errors) def _should_pretty_print(self, indent_level): """Should this tag be pretty-printed?""" return ( indent_level is not None and (self.name not in HTMLAwareEntitySubstitution.preformatted_tags or self._is_xml)) def decode(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter="minimal"): """Returns a Unicode representation of this tag and its contents. :param eventual_encoding: The tag is destined to be encoded into this encoding. This method is _not_ responsible for performing that encoding. This information is passed in so that it can be substituted in if the document contains a <META> tag that mentions the document's encoding. """ # First off, turn a string formatter into a function. This # will stop the lookup from happening over and over again. if not callable(formatter): formatter = self._formatter_for_name(formatter) attrs = [] if self.attrs: for key, val in sorted(self.attrs.items()): if val is None: decoded = key else: if isinstance(val, list) or isinstance(val, tuple): val = ' '.join(val) elif not isinstance(val, basestring): val = unicode(val) elif ( isinstance(val, AttributeValueWithCharsetSubstitution) and eventual_encoding is not None): val = val.encode(eventual_encoding) text = self.format_string(val, formatter) decoded = ( unicode(key) + '=' + EntitySubstitution.quoted_attribute_value(text)) attrs.append(decoded) close = '' closeTag = '' prefix = '' if self.prefix: prefix = self.prefix + ":" if self.is_empty_element: close = '/' else: closeTag = '</%s%s>' % (prefix, self.name) pretty_print = self._should_pretty_print(indent_level) space = '' indent_space = '' if indent_level is not None: indent_space = (' ' * (indent_level - 1)) if pretty_print: space = indent_space indent_contents = indent_level + 1 else: indent_contents = None contents = self.decode_contents( indent_contents, eventual_encoding, formatter) if self.hidden: # This is the 'document root' object. s = contents else: s = [] attribute_string = '' if attrs: attribute_string = ' ' + ' '.join(attrs) if indent_level is not None: # Even if this particular tag is not pretty-printed, # we should indent up to the start of the tag. s.append(indent_space) s.append('<%s%s%s%s>' % ( prefix, self.name, attribute_string, close)) if pretty_print: s.append("\n") s.append(contents) if pretty_print and contents and contents[-1] != "\n": s.append("\n") if pretty_print and closeTag: s.append(space) s.append(closeTag) if indent_level is not None and closeTag and self.next_sibling: # Even if this particular tag is not pretty-printed, # we're now done with the tag, and we should add a # newline if appropriate. s.append("\n") s = ''.join(s) return s def prettify(self, encoding=None, formatter="minimal"): if encoding is None: return self.decode(True, formatter=formatter) else: return self.encode(encoding, True, formatter=formatter) def decode_contents(self, indent_level=None, eventual_encoding=DEFAULT_OUTPUT_ENCODING, formatter="minimal"): """Renders the contents of this tag as a Unicode string. :param eventual_encoding: The tag is destined to be encoded into this encoding. This method is _not_ responsible for performing that encoding. This information is passed in so that it can be substituted in if the document contains a <META> tag that mentions the document's encoding. """ # First off, turn a string formatter into a function. This # will stop the lookup from happening over and over again. if not callable(formatter): formatter = self._formatter_for_name(formatter) pretty_print = (indent_level is not None) s = [] for c in self: text = None if isinstance(c, NavigableString): text = c.output_ready(formatter) elif isinstance(c, Tag): s.append(c.decode(indent_level, eventual_encoding, formatter)) if text and indent_level and not self.name == 'pre': text = text.strip() if text: if pretty_print and not self.name == 'pre': s.append(" " * (indent_level - 1)) s.append(text) if pretty_print and not self.name == 'pre': s.append("\n") return ''.join(s) def encode_contents( self, indent_level=None, encoding=DEFAULT_OUTPUT_ENCODING, formatter="minimal"): """Renders the contents of this tag as a bytestring.""" contents = self.decode_contents(indent_level, encoding, formatter) return contents.encode(encoding) # Old method for BS3 compatibility def renderContents(self, encoding=DEFAULT_OUTPUT_ENCODING, prettyPrint=False, indentLevel=0): if not prettyPrint: indentLevel = None return self.encode_contents( indent_level=indentLevel, encoding=encoding) #Soup methods def find(self, name=None, attrs={}, recursive=True, text=None, **kwargs): """Return only the first child of this Tag matching the given criteria.""" r = None l = self.find_all(name, attrs, recursive, text, 1, **kwargs) if l: r = l[0] return r findChild = find def find_all(self, name=None, attrs={}, recursive=True, text=None, limit=None, **kwargs): """Extracts a list of Tag objects that match the given criteria. You can specify the name of the Tag and any attributes you want the Tag to have. The value of a key-value pair in the 'attrs' map can be a string, a list of strings, a regular expression object, or a callable that takes a string and returns whether or not the string matches for some custom definition of 'matches'. The same is true of the tag name.""" generator = self.descendants if not recursive: generator = self.children return self._find_all(name, attrs, text, limit, generator, **kwargs) findAll = find_all # BS3 findChildren = find_all # BS2 #Generator methods @property def children(self): # return iter() to make the purpose of the method clear return iter(self.contents) # XXX This seems to be untested. @property def descendants(self): if not len(self.contents): return stopNode = self._last_descendant().next_element current = self.contents[0] while current is not stopNode: yield current current = current.next_element # CSS selector code _selector_combinators = ['>', '+', '~'] _select_debug = False def select(self, selector, _candidate_generator=None): """Perform a CSS selection operation on the current element.""" tokens = selector.split() current_context = [self] if tokens[-1] in self._selector_combinators: raise ValueError( 'Final combinator "%s" is missing an argument.' % tokens[-1]) if self._select_debug: print 'Running CSS selector "%s"' % selector for index, token in enumerate(tokens): if self._select_debug: print ' Considering token "%s"' % token recursive_candidate_generator = None tag_name = None if tokens[index-1] in self._selector_combinators: # This token was consumed by the previous combinator. Skip it. if self._select_debug: print ' Token was consumed by the previous combinator.' continue # Each operation corresponds to a checker function, a rule # for determining whether a candidate matches the # selector. Candidates are generated by the active # iterator. checker = None m = self.attribselect_re.match(token) if m is not None: # Attribute selector tag_name, attribute, operator, value = m.groups() checker = self._attribute_checker(operator, attribute, value) elif '#' in token: # ID selector tag_name, tag_id = token.split('#', 1) def id_matches(tag): return tag.get('id', None) == tag_id checker = id_matches elif '.' in token: # Class selector tag_name, klass = token.split('.', 1) classes = set(klass.split('.')) def classes_match(candidate): return classes.issubset(candidate.get('class', [])) checker = classes_match elif ':' in token: # Pseudo-class tag_name, pseudo = token.split(':', 1) if tag_name == '': continue raise ValueError( "A pseudo-class must be prefixed with a tag name.") pseudo_attributes = re.match('([a-zA-Z\d-]+)\(([a-zA-Z\d]+)\)', pseudo) found = [] if pseudo_attributes is not None: pseudo_type, pseudo_value = pseudo_attributes.groups() if pseudo_type == 'nth-of-type': try: pseudo_value = int(pseudo_value) except: continue raise NotImplementedError( 'Only numeric values are currently supported for the nth-of-type pseudo-class.') if pseudo_value < 1: continue raise ValueError( 'nth-of-type pseudo-class value must be at least 1.') class Counter(object): def __init__(self, destination): self.count = 0 self.destination = destination def nth_child_of_type(self, tag): self.count += 1 if self.count == self.destination: return True if self.count > self.destination: # Stop the generator that's sending us # these things. raise StopIteration() return False checker = Counter(pseudo_value).nth_child_of_type else: continue raise NotImplementedError( 'Only the following pseudo-classes are implemented: nth-of-type.') elif token == '*': # Star selector -- matches everything pass elif token == '>': # Run the next token as a CSS selector against the # direct children of each tag in the current context. recursive_candidate_generator = lambda tag: tag.children elif token == '~': # Run the next token as a CSS selector against the # siblings of each tag in the current context. recursive_candidate_generator = lambda tag: tag.next_siblings elif token == '+': # For each tag in the current context, run the next # token as a CSS selector against the tag's next # sibling that's a tag. def next_tag_sibling(tag): yield tag.find_next_sibling(True) recursive_candidate_generator = next_tag_sibling elif self.tag_name_re.match(token): # Just a tag name. tag_name = token else: continue raise ValueError( 'Unsupported or invalid CSS selector: "%s"' % token) if recursive_candidate_generator: # This happens when the selector looks like "> foo". # # The generator calls select() recursively on every # member of the current context, passing in a different # candidate generator and a different selector. # # In the case of "> foo", the candidate generator is # one that yields a tag's direct children (">"), and # the selector is "foo". next_token = tokens[index+1] def recursive_select(tag): if self._select_debug: print ' Calling select("%s") recursively on %s %s' % (next_token, tag.name, tag.attrs) print '-' * 40 for i in tag.select(next_token, recursive_candidate_generator): if self._select_debug: print '(Recursive select picked up candidate %s %s)' % (i.name, i.attrs) yield i if self._select_debug: print '-' * 40 _use_candidate_generator = recursive_select elif _candidate_generator is None: # By default, a tag's candidates are all of its # children. If tag_name is defined, only yield tags # with that name. if self._select_debug: if tag_name: check = "[any]" else: check = tag_name print ' Default candidate generator, tag name="%s"' % check if self._select_debug: # This is redundant with later code, but it stops # a bunch of bogus tags from cluttering up the # debug log. def default_candidate_generator(tag): for child in tag.descendants: if not isinstance(child, Tag): continue if tag_name and not child.name == tag_name: continue yield child _use_candidate_generator = default_candidate_generator else: _use_candidate_generator = lambda tag: tag.descendants else: _use_candidate_generator = _candidate_generator new_context = [] new_context_ids = set([]) for tag in current_context: if self._select_debug: print " Running candidate generator on %s %s" % ( tag.name, repr(tag.attrs)) for candidate in _use_candidate_generator(tag): if not isinstance(candidate, Tag): continue if tag_name and candidate.name != tag_name: continue if checker is not None: try: result = checker(candidate) except StopIteration: # The checker has decided we should no longer # run the generator. break if checker is None or result: if self._select_debug: print " SUCCESS %s %s" % (candidate.name, repr(candidate.attrs)) if id(candidate) not in new_context_ids: # If a tag matches a selector more than once, # don't include it in the context more than once. new_context.append(candidate) new_context_ids.add(id(candidate)) elif self._select_debug: print " FAILURE %s %s" % (candidate.name, repr(candidate.attrs)) current_context = new_context if self._select_debug: print "Final verdict:" for i in current_context: print " %s %s" % (i.name, i.attrs) return current_context # Old names for backwards compatibility def childGenerator(self): return self.children def recursiveChildGenerator(self): return self.descendants def has_key(self, key): """This was kind of misleading because has_key() (attributes) was different from __in__ (contents). has_key() is gone in Python 3, anyway.""" warnings.warn('has_key is deprecated. Use has_attr("%s") instead.' % ( key)) return self.has_attr(key) # Next, a couple classes to represent queries and their results. class SoupStrainer(object): """Encapsulates a number of ways of matching a markup element (tag or text).""" def __init__(self, name=None, attrs={}, text=None, **kwargs): self.name = self._normalize_search_value(name) if not isinstance(attrs, dict): # Treat a non-dict value for attrs as a search for the 'class' # attribute. kwargs['class'] = attrs attrs = None if 'class_' in kwargs: # Treat class_="foo" as a search for the 'class' # attribute, overriding any non-dict value for attrs. kwargs['class'] = kwargs['class_'] del kwargs['class_'] if kwargs: if attrs: attrs = attrs.copy() attrs.update(kwargs) else: attrs = kwargs normalized_attrs = {} for key, value in attrs.items(): normalized_attrs[key] = self._normalize_search_value(value) self.attrs = normalized_attrs self.text = self._normalize_search_value(text) def _normalize_search_value(self, value): # Leave it alone if it's a Unicode string, a callable, a # regular expression, a boolean, or None. if (isinstance(value, unicode) or callable(value) or hasattr(value, 'match') or isinstance(value, bool) or value is None): return value # If it's a bytestring, convert it to Unicode, treating it as UTF-8. if isinstance(value, bytes): return value.decode("utf8") # If it's listlike, convert it into a list of strings. if hasattr(value, '__iter__'): new_value = [] for v in value: if (hasattr(v, '__iter__') and not isinstance(v, bytes) and not isinstance(v, unicode)): # This is almost certainly the user's mistake. In the # interests of avoiding infinite loops, we'll let # it through as-is rather than doing a recursive call. new_value.append(v) else: new_value.append(self._normalize_search_value(v)) return new_value # Otherwise, convert it into a Unicode string. # The unicode(str()) thing is so this will do the same thing on Python 2 # and Python 3. return unicode(str(value)) def __str__(self): if self.text: return self.text else: return "%s|%s" % (self.name, self.attrs) def search_tag(self, markup_name=None, markup_attrs={}): found = None markup = None if isinstance(markup_name, Tag): markup = markup_name markup_attrs = markup call_function_with_tag_data = ( isinstance(self.name, collections.Callable) and not isinstance(markup_name, Tag)) if ((not self.name) or call_function_with_tag_data or (markup and self._matches(markup, self.name)) or (not markup and self._matches(markup_name, self.name))): if call_function_with_tag_data: match = self.name(markup_name, markup_attrs) else: match = True markup_attr_map = None for attr, match_against in list(self.attrs.items()): if not markup_attr_map: if hasattr(markup_attrs, 'get'): markup_attr_map = markup_attrs else: markup_attr_map = {} for k, v in markup_attrs: markup_attr_map[k] = v attr_value = markup_attr_map.get(attr) if not self._matches(attr_value, match_against): match = False break if match: if markup: found = markup else: found = markup_name if found and self.text and not self._matches(found.string, self.text): found = None return found searchTag = search_tag def search(self, markup): # print 'looking for %s in %s' % (self, markup) found = None # If given a list of items, scan it for a text element that # matches. if hasattr(markup, '__iter__') and not isinstance(markup, (Tag, basestring)): for element in markup: if isinstance(element, NavigableString) \ and self.search(element): found = element break # If it's a Tag, make sure its name or attributes match. # Don't bother with Tags if we're searching for text. elif isinstance(markup, Tag): if not self.text or self.name or self.attrs: found = self.search_tag(markup) # If it's text, make sure the text matches. elif isinstance(markup, NavigableString) or \ isinstance(markup, basestring): if not self.name and not self.attrs and self._matches(markup, self.text): found = markup else: raise Exception( "I don't know how to match against a %s" % markup.__class__) return found def _matches(self, markup, match_against): # print u"Matching %s against %s" % (markup, match_against) result = False if isinstance(markup, list) or isinstance(markup, tuple): # This should only happen when searching a multi-valued attribute # like 'class'. if (isinstance(match_against, unicode) and ' ' in match_against): # A bit of a special case. If they try to match "foo # bar" on a multivalue attribute's value, only accept # the literal value "foo bar" # # XXX This is going to be pretty slow because we keep # splitting match_against. But it shouldn't come up # too often. return (whitespace_re.split(match_against) == markup) else: for item in markup: if self._matches(item, match_against): return True return False if match_against is True: # True matches any non-None value. return markup is not None if isinstance(match_against, collections.Callable): return match_against(markup) # Custom callables take the tag as an argument, but all # other ways of matching match the tag name as a string. if isinstance(markup, Tag): markup = markup.name # Ensure that `markup` is either a Unicode string, or None. markup = self._normalize_search_value(markup) if markup is None: # None matches None, False, an empty string, an empty list, and so on. return not match_against if isinstance(match_against, unicode): # Exact string match return markup == match_against if hasattr(match_against, 'match'): # Regexp match return match_against.search(markup) if hasattr(match_against, '__iter__'): # The markup must be an exact match against something # in the iterable. return markup in match_against class ResultSet(list): """A ResultSet is just a list that keeps track of the SoupStrainer that created it.""" def __init__(self, source): list.__init__([]) self.source = source
ruuk/script.web.viewer2
lib/webviewer/bs4/element.py
Python
gpl-2.0
61,200
<?php /* Plugin Name: Cactus - Mega Menu Plugin URI: http://www.cactusthemes.com Description: Rewrite menu Author: Cactusthemes Author URI: http://www.cactusthemes.com License: TF Version: 1.0 */ define('MASHMENU_NAV_LOCS', 'wp-mash-menu-nav-locations'); define('MASHMENU_VERSION', '1.6'); require_once 'core/MegaMenuWalker.class.php'; class MashMenuContentHelper{ /* * Get 6 Latest posts in custom category (taxonomy) * * $post_type: post type to return * $tax: type of custom taxonomy * $cat_id: custom taxonomy ID * Return HTML */ function getLatestCustomCategoryItems($cat_id, $tax, $post_type = 'any'){ $term = get_term_by('id',$cat_id,$tax); if($term === false){ return; } $args = array('posts_per_page'=>6,'post_type'=>$post_type,$tax=>$term->slug); $query = new WP_Query($args); $html = ''; ob_start(); $tmp_post = $post; $options = get_option('mashmenu_options'); $sizes = $options['thumbnail_size']; $width = 200;$height = 200; if($sizes != '') { $sizes = explode('x',$sizes); if(count($sizes) == 2){ $width = intval($sizes[0]); $height = intval($sizes[1]); if($width == 0) $width = 200; if($height == 0) $height = 200; } } while($query->have_posts()) : $query->the_post(); ?> <div class="content-item"> <?php $options['image_link'] = 'on'; if($options['image_link'] == 'on'){?> <a href="<?php the_permalink(); ?>" title="<?php the_title();?>"> <?php the_post_thumbnail(array($width,$height));?> </a> <?php } else {?> <?php the_post_thumbnail(array($width,$height));?> <?php }?> <h3 class="title"><a href="<?php the_permalink(); ?>" title="<?php the_title();?>"><?php the_title();?></a></h3> </div> <?php endwhile; $html = ob_get_contents(); ob_end_clean(); wp_reset_postdata(); $post = $temp_post; return $html; } /* * Get 6 Latest posts in category * * Return HTML */ function getLatestCategoryItems($cat_id, $post_type = 'post'){ $args = array('posts_per_page'=>3,'category'=>$cat_id,'post_type'=>$post_type); $posts = get_posts($args); $html = ''; ob_start(); global $post; $tmp_post = $post; $options = get_option('mashmenu_options'); $sizes = $options['thumbnail_size']; $width = 490;$height = 350; if($sizes != '') { $sizes = explode('x',$sizes); if(count($sizes) == 2){ $width = intval($sizes[0]); $height = intval($sizes[1]); if($width == 0) $width = 200; if($height == 0) $height = 200; } } foreach($posts as $post) : setup_postdata($post); ?> <div class="content-item col-md-4"> <div class="img-wrap"> <?php $options['image_link'] = 'on'; if($options['image_link'] == 'on'){?> <a href="<?php the_permalink(); ?>" title="<?php the_title();?>"> <?php the_post_thumbnail('thumb_megamenu');?> </a> <?php } else {?> <?php the_post_thumbnail('thumb_megamenu');?> <?php }?> </div> <h3 class="title"><a href="<?php the_permalink(); ?>" title="<?php the_title();?>"><?php the_title();?></a></h3> </div> <?php endforeach; $html = ob_get_contents(); ob_end_clean(); $temp_post=''; $post = $temp_post; return $html; } /* * Get 6 Latest WooCommerce/JigoShop Products in category * * Return HTML */ function getWProductItems($cat_id){ $html = ''; // get slug by ID $term = get_term_by('id',$cat_id,'product_cat'); if($term){ $args = array('posts_per_page'=>6,'product_cat'=>$term->slug,'post_type'=>'product'); $posts = get_posts($args); ob_start(); global $post; $tmp_post = $post; $options = get_option('mashmenu_options'); $sizes = $options['thumbnail_size']; $width = 200;$height = 200; if($sizes != '') { $sizes = explode('x',$sizes); if(count($sizes) == 2){ $width = intval($sizes[0]); $height = intval($sizes[1]); if($width == 0) $width = 200; if($height == 0) $height = 200; } } foreach($posts as $post) : setup_postdata($post); //$product = WC_Product($post->ID); if (class_exists('WC_Product')) { // WooCommerce Installed global $product; } else if(class_exists('jigoshop_product')){ $product = new jigoshop_product( $post->ID ); // JigoShop } ?> <div class="content-item"> <?php $options['image_link'] = 'on'; if($options['image_link'] == 'on'){?> <a href="<?php the_permalink(); ?>" title="<?php the_title();?>"> <?php the_post_thumbnail(array($width,$height));?> </a> <?php } else {?> <?php the_post_thumbnail(array($width,$height));?> <?php }?> <h3 class="title"><a href="<?php the_permalink(); ?>" title="<?php the_title();?>"><?php if ( ($options['show_price'] == 'left') && $price_html = $product->get_price_html() ) { echo $price_html; } ?> <?php the_title();?> <?php if ( (!isset($options['show_price']) || $options['show_price'] == '') && $price_html = $product->get_price_html() ) { echo $price_html; } ?></a></h3> </div> <?php endforeach; $html = ob_get_contents(); ob_end_clean(); $post = $temp_post; } return $html; } /* * Get page content * * Return HTML */ function getPageContent($page_id){ $page = get_page($page_id); $html = ''; if($page){ ob_start(); ?> <div class="page-item"> <h3 class="title"><a href="<?php echo esc_url(get_permalink($page->ID)); ?>" title="<?php echo esc_attr($page->post_title);?>"><?php echo apply_filters('the_title', $page->post_title);?></a></h3> <?php $morepos = strpos($page->post_content,'<!--more-->'); if($morepos === false){ echo apply_filters('the_content',$page->post_content); } else { echo apply_filters('the_content',substr($page->post_content,0,$morepos)); } ?> </div> <?php } $html = ob_get_contents(); ob_end_clean(); return $html; } /* * Get post content * * Return HTML */ function getPostContent($post_id){ $page = get_post($post_id); $html = ''; $options = get_option('mashmenu_options'); $sizes = $options['thumbnail_size']; $width = 200;$height = 200; if($sizes != '') { $sizes = explode('x',$sizes); if(count($sizes) == 2){ $width = intval($sizes[0]); $height = intval($sizes[1]); if($width == 0) $width = 200; if($height == 0) $height = 200; } } if($page){ ob_start(); ?> <div class="page-item"> <h3 class="title"><a href="<?php echo esc_url(get_permalink($page->ID)); ?>" title="<?php echo esc_attr($page->post_title);?>"><?php echo apply_filters('the_title', $page->post_title);?></a></h3> <div> <div class="thumb"> <?php echo get_the_post_thumbnail( $page->ID, array($width,$height));?> </div> <?php $morepos = strpos($page->post_content,'<!--more-->'); if($morepos === false){ echo apply_filters('the_content',$page->post_content); } else { echo apply_filters('the_content',substr($page->post_content,0,$morepos)); } ?> </div> </div> <?php } $html = ob_get_contents(); ob_end_clean(); return $html; } /* * Get 6 Latest posts that has tag id * * Return HTML */ function getLatestItemsByTag($tag_id, $post_type = 'post'){ $tag = get_term($tag_id,'post_tag'); $args = array('showposts'=>6,'tag'=>$tag->slug,'caller_get_posts'=>1,'post_status'=>'publish','post_type'=>$post_type); $query = new WP_Query($args); $html = ''; ob_start(); $options = get_option('mashmenu_options'); $sizes = $options['thumbnail_size']; $width = 200;$height = 200; if($sizes != '') { $sizes = explode('x',$sizes); if(count($sizes) == 2){ $width = intval($sizes[0]); $height = intval($sizes[1]); if($width == 0) $width = 200; if($height == 0) $height = 200; } } while($query->have_posts()) : $query->the_post(); ?> <div class="content-item"> <?php if($options['image_link'] == 'on'){?> <a href="<?php the_permalink(); ?>" title="<?php the_title();?>"> <?php the_post_thumbnail(array($width,$height));?> </a> <?php } else {?> <?php the_post_thumbnail(array($width,$height));?> <?php }?> <h3 class="title"><a href="<?php the_permalink(); ?>" title="<?php the_title();?>"><?php the_title();?></a></h3> </div> <?php endwhile; $html = ob_get_contents(); ob_end_clean(); $post = $temp_post; wp_reset_query(); return $html; } } class MashMenu{ protected $baseURL; protected $menuItemOptions; protected $optionDefaults; protected $count = 0; function __construct($base_url = ''){ if( $base_url ){ //Integrated theme version $this->baseURL = $base_url; } else{ //Plugin Version $this->baseURL = esc_url(get_template_directory_uri().'/inc/megamenu/'); } $this->menuItemOptions = array(); //ADMIN if( is_admin() ){ add_action( 'admin_menu' , array( $this , 'adminInit' ) ); add_filter( 'wp_edit_nav_menu_walker', array( $this , 'editWalker' ) , 2000); add_action( 'wp_ajax_mashMenu_updateNavLocs', array( $this , 'updateNavLocs_callback' ) ); //For logged in users add_action( 'wp_ajax_mashMenu_addMenuItem', array( $this , 'addMenuItem_callback' ) ); //Appearance > Menus : save custom menu options add_action( 'wp_update_nav_menu_item', array( $this , 'updateNavMenuItem' ), 10, 3); //, $menu_id, $menu_item_db_id, $args; add_action( 'mashmenu_menu_item_options', array( $this , 'menuItemCustomOptions' ), 10, 1); //Must go here for AJAX purposes // front-end Ajax add_action( 'wp_ajax_mashMenu_getChannelContent', array( $this , 'getChannelContent_callback' ) ); add_action( 'wp_ajax_nopriv_mashMenu_getChannelContent', array( $this , 'getChannelContent_callback' )); $this->optionDefaults = array( 'menu-item-isMega' => 'off' ); } else { $this->init(); } add_action( 'init', array($this, 'register_sidebars' ), 500); add_action( 'wp_enqueue_scripts', array ($this, 'add_scripts')); } function register_sidebars(){ $options = get_option('mashmenu_options'); /* if(isset($options['sidebars']) && $options['sidebars'] != ''){ // Compatible with MashMenu 1.5.1. This option is removed since 1.6 $sidebars = explode(PHP_EOL, $options['sidebars']); $i = 1; foreach($sidebars as $sidebar){ register_sidebar( array( 'name' => __( 'Mashmenu Sidebar ' . $i . ' - '. $sidebar, 'mashmenu' ), 'id' => 'mashmenu-sidebar-' . $i, 'description' => __( 'Drag widgets here to add to mashmenu', 'mashmenu' ), 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '', ) ); $i++; } } else { for($i = 1; $i<=5; $i++){ if(isset($options['sidebar'.$i]) && $options['sidebar'.$i] != ''){ register_sidebar( array( 'name' => __( 'Mashmenu Sidebar ' . $i . ' - '. $options['sidebar'.$i], 'mashmenu' ), 'id' => 'mashmenu-sidebar-' . $i, 'description' => __( 'Drag widgets here to add to mashmenu', 'mashmenu' ), 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '', ) ); } } }*/ if(is_admin()){ wp_enqueue_script('jscolor',$this->baseURL.'js/jscolor/jscolor.js'); } } function init(){ //Filters add_filter( 'wp_nav_menu_args' , array( $this , 'megaMenuFilter' ), 2000 ); //filters arguments passed to wp_nav_menu } function adminInit(){ //add_action( 'admin_head', array( $this , 'addActivationMetaBox' ) ); //Appearance > Menus : load additional styles and scripts add_action( 'admin_print_styles-nav-menus.php', array( $this , 'loadAdminNavMenuJS' ) ); add_action( 'admin_print_styles-nav-menus.php', array( $this , 'loadAdminNavMenuCSS' )); } /* * Save the Menu Item Options */ function updateNavMenuItem( $menu_id, $menu_item_db_id, $args ){ $mashmenu_options_string = isset( $_POST['mashmenu_options'][$menu_item_db_id] ) ? $_POST['mashmenu_options'][$menu_item_db_id] : ''; $mashmenu_options = array(); parse_str( $mashmenu_options_string, $mashmenu_options ); $mashmenu_options = wp_parse_args( $mashmenu_options, $this->optionDefaults ); update_post_meta( $menu_item_db_id, '_mashmenu_options', $mashmenu_options ); } /* * Add the Activate Mash Menu Locations Meta Box to the Appearance > Menus Control Panel */ /*function addActivationMetaBox(){ if ( wp_get_nav_menus() ) add_meta_box( 'nav-menu-theme-mashmenus', __( 'Activate Mash Menu Locations' , 'mashmenu' ), array( $this , 'showActivationMetaBox' ) , 'nav-menus', 'side', 'high' ); }*/ /* * Generates the Activate Mash Menu Locations Meta Box */ /*function showActivationMetaBox(){ */ /* This is just in case JS is not working. It'll only save the last checked box */ /*if( isset( $_POST['mashMenu-locations'] ) && $_POST['mashMenu-locations'] == 'Save'){ $data = $_POST['wp-mash-menu-nav-loc']; $data = explode(',', $data); update_option( MASHMENU_NAV_LOCS, $data ); echo 'Saved Changes'; } $active = get_option( MASHMENU_NAV_LOCS, array()); echo '<div class="megaMenu-metaBox">'; echo '<p class="howto">'.__( 'Select the Menu to build MashMenu', 'mashmenu' ).'</p>'; echo '<form>'; //$locs = get_registered_nav_menus(); $menus = get_terms( 'nav_menu', array( 'hide_empty' => true ) ); //echo $menus;exit; foreach($menus as $menu){ $slug = $menu->slug; echo '<label class="menu-item-title" for="megaMenuThemeLoc-'.$slug.'">'. '<input class="menu-item-checkbox" type="radio" value="'.$slug.'" id="megaMenuThemeLoc-'.$slug.'" name="wp-mash-menu-nav-loc" '. checked( in_array( $slug, $active ), true, false).'/>'. $menu->name.'</label>'; } echo '<p class="button-controls">'. '<img class="waiting" src="'.esc_url( admin_url( 'images/wpspin_light.gif' ) ).'" alt="" style="display:none;"/>'. '<input id="wp-mash-menu-navlocs-submit" type="submit" class="button-primary" name="megaMenu-locations" value="'.__( 'Save' , 'mashmenu' ).'" />'. '</p>'; echo '</form>'; echo '</div>'; }*/ function getChannelContent_callback(){ $data = $_POST['data']; // Array(dataType, dataId, postType) $helper = new MashMenuContentHelper(); switch($data[0]){ case 'category': echo $helper->getLatestCategoryItems($data[1]); break; case 'post_tag': echo $helper->getLatestItemsByTag($data[1]); break; case 'page': echo $helper->getPageContent($data[1]); break; case 'post': echo $helper->getPostContent($data[1]); break; /* WooCommerce/JigoShop Product Category */ case 'product_cat': echo $helper->getWProductItems($data[1]); break; /* Custom Taxonomy */ default: echo $helper->getLatestCustomCategoryItems($data[1],$data[0],$data[2]); break; } die(); } /* * Update the Locations when the Activate Mash Menu Locations Meta Box is Submitted */ function updateNavLocs_callback(){ $data = $_POST['data']; $data = explode(',', $data); update_option( MASHMENU_NAV_LOCS, $data); echo $data; die(); } function addMenuItem_callback(){ if ( ! current_user_can( 'edit_theme_options' ) ) die('-1'); check_ajax_referer( 'add-menu_item', 'menu-settings-column-nonce' ); require_once ABSPATH . 'wp-admin/includes/nav-menu.php'; // For performance reasons, we omit some object properties from the checklist. // The following is a hacky way to restore them when adding non-custom items. $menu_items_data = array(); foreach ( (array) $_POST['menu-item'] as $menu_item_data ) { if ( ! empty( $menu_item_data['menu-item-type'] ) && 'custom' != $menu_item_data['menu-item-type'] && ! empty( $menu_item_data['menu-item-object-id'] ) ) { switch( $menu_item_data['menu-item-type'] ) { case 'post_type' : $_object = get_post( $menu_item_data['menu-item-object-id'] ); break; case 'taxonomy' : $_object = get_term( $menu_item_data['menu-item-object-id'], $menu_item_data['menu-item-object'] ); break; } $_menu_items = array_map( 'wp_setup_nav_menu_item', array( $_object ) ); $_menu_item = array_shift( $_menu_items ); // Restore the missing menu item properties $menu_item_data['menu-item-description'] = $_menu_item->description; } $menu_items_data[] = $menu_item_data; } $item_ids = wp_save_nav_menu_items( 0, $menu_items_data ); if ( is_wp_error( $item_ids ) ) die('-1'); foreach ( (array) $item_ids as $menu_item_id ) { $menu_obj = get_post( $menu_item_id ); if ( ! empty( $menu_obj->ID ) ) { $menu_obj = wp_setup_nav_menu_item( $menu_obj ); $menu_obj->label = $menu_obj->title; // don't show "(pending)" in ajax-added items $menu_items[] = $menu_obj; } } if ( ! empty( $menu_items ) ) { $args = array( 'after' => '', 'before' => '', 'link_after' => '', 'link_before' => '', 'walker' => new MashMenuWalkerEdit, //EDIT FOR MASHMENU ); echo walk_nav_menu_tree( $menu_items, 0, (object) $args ); } } function menuItemCustomOptions( $item_id ){ ?> <!-- START MASHMENU ATTS --> <div> <div class="wpmega-atts wpmega-unprocessed" style="display:block"> <input id="mashmenu_options-<?php echo $item_id;?>" class="mashmenu_options_input" name="mashmenu_options[<?php echo $item_id;?>]" type="hidden" value="" /> <?php $this->showMenuOptions( $item_id ); ?> </div> <!-- END MASHMENU ATTS --> </div> <?php } function showMenuOptions( $item_id ){ if(ot_get_option('megamenu')=='on'){ $this->showCustomMenuOption( 'menu_style', $item_id, array( 'level' => '0', 'title' => esc_html__( 'Select style for Menu' , 'mashmenu' ), 'label' => esc_html__( 'Menu Style' , 'mashmenu' ), 'type' => 'select', 'default' => '', 'ops' => array('list'=>'List Style','columns'=>'Columns Style', 'preview'=>'Preview Mode') ) ); } /*$this->showCustomMenuOption( 'isMega', $item_id, array( 'level' => '0', 'title' => __( 'Make this item\'s submenu a MashMenu. Leave unchecked to use a three-level menu.' , 'mashmenu' ), 'label' => __( 'MashMenu - Preview mode' , 'mashmenu' ), 'type' => 'checkbox', 'default' => 'on' ) );*/ /*$this->showCustomMenuOption( 'icon', $item_id, array( 'level' => '0', 'title' => __( 'Add a FontAwesome icon to the left/right of menu item. Enter full name of icon here. Check <a href="http://fortawesome.github.io/Font-Awesome/icons/" target="_blank">Font-Awesome icons</a> for names' , 'mashmenu' ), 'label' => __( 'Menu Icon' , 'mashmenu' ), 'type' => 'text', 'default' => '' ) );*/ /** Get Sidebar **/ global $wp_registered_sidebars; $arr = array("0"=>"No Sidebar"); foreach ( $wp_registered_sidebars as $sidebar ) : $arr = array_merge($arr, array($sidebar['id']=>$sidebar['name'])); endforeach; if(ot_get_option('megamenu')=='on'){ $this->showCustomMenuOption( 'addSidebar', $item_id, array( 'level' => '1', 'title' => esc_html__( 'Select the widget area to display' , 'mashmenu' ), 'label' => esc_html__( 'Display widgets area ' , 'mashmenu' ), 'type' => 'select', 'default' => '0', 'ops' => $arr ) ); } /** Get Sidebar **/ /* $this->showCustomMenuOption( 'iconPos', $item_id, array( 'level' => '0', 'title' => __( 'Position of icon to the menu item' , 'mashmenu' ), 'label' => __( 'Icon position' , 'mashmenu' ), 'type' => 'select', 'default' => '', 'ops' => array('left'=>'Left','right'=>'Right') ) );*/ /*$this->showCustomMenuOption( 'caretDownPos', $item_id, array( 'level' => '0', 'title' => __( 'Position of caret-down icon to the menu item. Caret-down Icon appears when this menu item has sub levels' , 'mashmenu' ), 'label' => __( 'Caret-down position' , 'mashmenu' ), 'type' => 'select', 'default' => '', 'ops' => array('right'=>'Right','left'=>'Left','none'=>'Not shown') ) );*/ if(ot_get_option('megamenu')=='on'){ $this->showCustomMenuOption( 'displayLogic', $item_id, array( 'level' => '0', 'title' => esc_html__( 'Logic to display this menu item' , 'mashmenu' ), 'label' => esc_html__( 'Display Logic' , 'mashmenu' ), 'type' => 'select', 'default' => '', 'ops' => array('both'=>'Always visible','guest'=>'Only Visible to Guests','member'=>'Only Visible to Members') ) ); } } function showCustomMenuOption( $id, $item_id, $args ){ extract( wp_parse_args( $args, array( 'level' => '0-plus', 'title' => '', 'label' => '', 'type' => 'text', 'ops' => array(), 'default'=> '', ) ) ); $_val = $this->getMenuItemOption( $item_id , $id ); $desc = '<span class="ss-desc">'.$label.'<span class="ss-info-container">?<span class="ss-info">'.$title.'</span></span></span>'; ?> <p class="field-description description description-wide wpmega-custom wpmega-l<?php echo $level;?> wpmega-<?php echo $id;?>"> <label for="edit-menu-item-<?php echo $id;?>-<?php echo $item_id;?>"> <?php switch($type) { case 'text': echo wp_kses_post($desc); ?> <input type="text" id="edit-menu-item-<?php echo $id;?>-<?php echo $item_id;?>" class="edit-menu-item-<?php echo $id;?>" name="menu-item-<?php echo $id;?>[<?php echo $item_id;?>]" size="30" value="<?php echo htmlspecialchars( $_val );?>" /> <?php break; case 'checkbox': ?> <input type="checkbox" id="edit-menu-item-<?php echo $id;?>-<?php echo $item_id;?>" class="edit-menu-item-<?php echo $id;?>" name="menu-item-<?php echo $id;?>[<?php echo $item_id;?>]" <?php if ( ( $_val == '' && $default == 'on' ) || $_val == 'on') echo 'checked="checked"'; ?> /> <?php echo wp_kses_post($desc); break; case 'select': echo wp_kses_post($desc); if( empty($_val) ) $_val = $default; ?> <select id="edit-menu-item-<?php echo $id; ?>-<?php echo $item_id; ?>" class="edit-menu-item-<?php echo $id; ?>" name="menu-item-<?php echo $id;?>[<?php echo $item_id;?>]"> <?php foreach( $ops as $opval => $optitle ): ?> <option value="<?php echo esc_attr($opval); ?>" <?php if( $_val == $opval ) echo 'selected="selected"'; ?> ><?php echo $optitle; ?></option> <?php endforeach; ?> </select> <?php break; } ?> </label> </p> <?php } function getMenuItemOption( $item_id , $id ){ $option_id = 'menu-item-'.$id; //We haven't investigated this item yet if( !isset( $this->menuItemOptions[ $item_id ] ) ){ $mashmenu_options = get_post_meta( $item_id , '_mashmenu_options', true ); //If $mashmenu_options are set, use them if( $mashmenu_options ){ //echo '<pre>'; print_r( $mashmenu_options ); echo '</pre>'; $this->menuItemOptions[ $item_id ] = $mashmenu_options; } //Otherwise get the old meta else{ return get_post_meta( $item_id, '_menu_item_'.$id , true ); } } return isset( $this->menuItemOptions[ $item_id ][ $option_id ] ) ? $this->menuItemOptions[ $item_id ][ $option_id ] : ''; } /* * Custom Walker Name - to be overridden by Standard */ function editWalker( $className ){ return 'MashMenuWalkerEdit'; } /* * Default walker, but this can be overridden */ function getWalker(){ return new MashMenuWalkerCore(); } function getMenuArgs( $args ){ $options = get_option('mashmenu_options'); /*$css = $this->getCustomCSS($options);*/ $items_wrap = '<i class="menu-mobile fa fa-list-ul"></i><ul id="%1$s" class="%2$s">%3$s</ul>'; if(isset($options['logo']) && $options['logo'] != ''){ $items_wrap = '<div id="mlogo" class="mod mlogo"> <a href="'.esc_url( home_url( '/' ) ).'"> <img class="mlogo" src="'.$options['logo'].'"/> </a> </div>' . $items_wrap; } $sidebars_html = ''; ob_start(); // for compatible with MashMenu 1.5.1 if(isset($options['sidebars']) && $options['sidebars'] != ''){ $sidebars = explode(PHP_EOL, $options['sidebars']); $i = 1; foreach($sidebars as $sidebar){ ?> <div id="mashmenu-mod-<?php echo $i;?>" class="mod right"> <a href="javascript:void(0)" class="head"><i class="fa fa-<?php echo $sidebar;?>"></i></a> <div class="mod-content"> <?php dynamic_sidebar('mashmenu-sidebar-' . $i);?> </div> </div> <?php $i++; } } else { for($j=1;$j<=5;$j++){ if(isset($options['sidebar'.$j.'_logic'])){ $logic = $options['sidebar'.$j.'_logic']; if(($logic == 'guest' && is_user_logged_in()) || ($logic == 'member' && !is_user_logged_in())){ continue; } } if(isset($options['sidebar'.$j]) && $options['sidebar'.$j] != ''){ $sidebar = $options['sidebar'.$j]; ?> <div id="mashmenu-mod-<?php echo $j;?>" class="mod right"> <a href="javascript:void(0)" class="head"><i class="fa fa-<?php echo $sidebar;?>"></i></a> <div class="mod-content"> <?php dynamic_sidebar('mashmenu-sidebar-' . $j);?> </div> </div> <?php } } } $sidebars_html .= ob_get_contents(); ob_end_clean(); $items_wrap .= $sidebars_html; $args['walker'] = $this->getWalker(); $args['container_id'] = 'MashMenu'; $args['container_class'] = 'mashmenu hidden-mobile'; $args['menu_class'] = 'menu'; $args['depth'] = 0; $args['items_wrap'] = '<ul id="%1$s" class="%2$s main-menu nav navbar-nav navbar-right cactus-mega-menu" data-theme-location="">%3$s</ul>'/*.$css*/; $args['link_before'] = ''; $args['link_after'] = ''; return $args; } /*** Add Megamenu CSS in line to Menubar *** /*function getCustomCSS($options){ $css = '<style type="text/css">'; if($options['disable_css'] != 'on'){ if(isset($options['maincolor']) && $options['maincolor'] != ''){ $css .= ' .mashmenu{background-color:#'.$options['maincolor'].'} .mashmenu .mod .mod-content,.mashmenu .menu .sub-content{border-bottom-color:#'.$options['maincolor'].'} .mashmenu .mod:hover a,.mashmenu .menu li.level0:hover>a,.mashmenu .menu .sub-channel li a,.mashmenu .menu li.level0:hover .sub-channel li.hover a .fa-chevron-right,.mashmenu .columns .list a{color:#'.$options['maincolor'].'}'; } if(isset($options['hovercolor']) && $options['hovercolor'] != ''){ $css .= '.mashmenu .mod .mod-content,.mashmenu .mod:hover,.mashmenu .menu .sub-content,.mashmenu .menu li.level0:hover>a,.mashmenu .menu li.level0:hover .sub-channel li.hover a{background-color:#'.$options['hovercolor'].'}.mashmenu .mlogo:hover{background:none}'; } if(isset($options['channeltitlecolor']) && $options['channeltitlecolor'] != ''){ $css .= '.mashmenu .sub-channel{background-color:#'.$options['channeltitlecolor'].'}'; } if(isset($options['advance_css'])){ $css .= $options['advance_css']; } } if(isset($options['loader']) && $options['loader']){ $css .= '.mashmenu .loading{background-image:url('.$options['loader'].')}'; } // responsive CSS if(isset($options['menu_hidden_limit']) && $options['menu_hidden_limit'] != ''){ $limits = explode(PHP_EOL, $options['menu_hidden_limit']); foreach($limits as $limit){ if($limit != ''){ $arr = explode(',',$limit); $width = $arr[0]; $itemth = $arr[1]; $css .= '@media (max-width: '.$width.'px) {.mashmenu .menu>li:nth-child('.$itemth.'){display:none}}'; } } } $mobile_screen = 480; if(isset($options['menu_mobile_limit']) && $options['menu_mobile_limit'] != ''){ $mobile_screen = $options['menu_mobile_limit']; } if($options['hide_on_mobile'] == 'on'){ $css .= '@media (max-width:'.$mobile_screen.'px){.mashmenu{display:none}}'; } else { $css .= '@media (max-width:'.$mobile_screen.'px){#wpadminbar{display:none}.admin-bar .mashmenu{top:0px}.mashmenu .menu,.mashmenu .mod{display:none}.mashmenu .mlogo{display:inline-block}.mashmenu .menu-mobile{display:inline-block}}'; } if(isset($options['subcontent_height']) && $options['subcontent_height'] != ''){ if($options['subcontent_height'] == '0'){ $css .= '.mashmenu .sub-channel{height:auto}'; } else { $css .= '.mashmenu .sub-channel{height:' . $options['subcontent_height'] . '}'; } } if($options['rtl'] == 'on'){ $css .= '.mashmenu .mlogo,.mashmenu .menu{float:right;text-align:right}.mashmenu .menu>li{float:right}.mashmenu .mod.right{float:left}.mashmenu .mod .mod-content{left:0;}.mashmenu .sub-channel{float:right}.mashmenu .menu .sub-channel li a{text-align:left}.mashmenu .mod .mod-content{text-align:right}'; } if($options['hide_on_mobile'] == 'on'){ //$mobile_screen } $css .= '</style>'; $css .= '<script type="text/javascript">var _mobile_screen = ' . $mobile_screen . ';</script>'; return $css; }*/ /* * Apply options to the Menu via the filter */ function megaMenuFilter( $args ){ //Only print the menu once if( $this->count > 0 ) return $args; if( isset( $args['responsiveSelectMenu'] ) ) return $args; if( isset( $args['filter'] ) && $args['filter'] === false ) return $args; //Check to See if this Menu Should be Megafied if(!isset($args['is_megamenu']) || !$args['is_megamenu']){ return $args; } $this->count++; $items_wrap = '<ul id="%1$s" class="%2$s" data-theme-location="primary-menu">%3$s</ul>'; //This is the default, to override any stupidity $args['items_wrap'] = $items_wrap; $args = $this->getMenuArgs( $args ); return $args; } function add_scripts(){ wp_enqueue_script('jquery'); wp_enqueue_script('mashmenu-js', $this->baseURL.'js/mashmenu.js', array('jquery'), MASHMENU_VERSION, true); $options = get_option('mashmenu_options'); // wp_enqueue_style('mashmenu-css',$this->baseURL.'css/mashmenu.css'); wp_localize_script( 'mashmenu-js', 'mashmenu', array( 'ajax_url' => admin_url( 'admin-ajax.php' ),'ajax_loader'=>'on','ajax_enabled'=>($options['ajax_loading'] == "on" ? 1 : 0)) ); } function loadAdminNavMenuJS(){ wp_enqueue_script('jquery'); wp_enqueue_script('mashmenu-admin-js', $this->baseURL.'js/mashmenu.admin.js', array('jquery'), MASHMENU_VERSION, true); } function loadAdminNavMenuCSS(){ wp_enqueue_style('mashmenu-admin-css',$this->baseURL.'css/mashmenu.admin.css'); } } $mashmenu = new MashMenu(); /* ADMIN - Setting page */ define('_DS_', DIRECTORY_SEPARATOR); require_once dirname(__FILE__) . _DS_ . 'options.php'; if ( is_admin() ){ // admin actions //add_action( 'admin_menu', 'add_mashmenu_menu' ); add_action( 'admin_init', 'register_mashmenu_settings' ); } else { // non-admin enqueues, actions, and filters } /*function add_mashmenu_menu(){ //create new top-level menu add_menu_page('MegaMenu Settings', 'MegaMenu', 'administrator', __FILE__, 'mashmenu_settings_page',get_template_directory_uri().'/inc/megamenu/images/mashmenu24x24.png'); }*/ function register_mashmenu_settings(){ //register our settings register_setting( 'mashmenu_options', 'mashmenu_options', 'mashmenu_validate_setting' ); add_settings_section('mashmenu_settings_group', 'Main Settings', 'mashmenu_section_cb', __FILE__); add_settings_field('logo', 'Logo:', 'mashmenu_logo_setting', __FILE__, 'mashmenu_settings_group'); // LOGO add_settings_field('remove_logo', '', 'mashmenu_remove_logo_setting', __FILE__, 'mashmenu_settings_group'); // LOGO add_settings_field('maincolor', 'Main Color:', 'mashmenu_maincolor_setting', __FILE__, 'mashmenu_settings_group'); // Main color add_settings_field('hovercolor', 'Hover Color:', 'mashmenu_hovercolor_setting', __FILE__, 'mashmenu_settings_group'); // Hover color add_settings_field('channeltitlecolor', 'Channel Title Color:', 'mashmenu_channeltitle_color_setting', __FILE__, 'mashmenu_settings_group'); // Hover color add_settings_field('icon_mainmenu_parent', 'Icon for MainMenu Parent Item:', 'icon_mainmenu_parent_setting', __FILE__, 'mashmenu_settings_group'); add_settings_field('icon_subchannel_item_right', 'Icon for Sub Channel Item (LTR):', 'icon_subchannel_item_right_setting', __FILE__, 'mashmenu_settings_group'); add_settings_field('icon_subchannel_item_left', 'Icon for Sub Channel Item (RTL):', 'icon_subchannel_item_left_setting', __FILE__, 'mashmenu_settings_group'); add_settings_field('image_link', 'Link on preview image:', 'mashmenu_image_link_setting', __FILE__, 'mashmenu_settings_group'); add_settings_field('sidebars', 'Sidebars:', 'mashmenu_sidebars', __FILE__, 'mashmenu_settings_group'); add_settings_section('mashmenu_layout_group', 'Layout Settings', 'mashmenu_section_cb', __FILE__); add_settings_field('thumbnail_size', 'Thumbnail Size:', 'mashmenu_thumbnails_setting', __FILE__, 'mashmenu_layout_group'); add_settings_field('subcontent_height', 'Sub-content Height:', 'mashmenu_subcontentheight_setting', __FILE__, 'mashmenu_layout_group'); add_settings_field('rtl', 'RTL Language:', 'mashmenu_rtl_setting', __FILE__, 'mashmenu_layout_group'); add_settings_section('mashmenu_responsive_group', 'Responsive Settings', 'mashmenu_section_cb', __FILE__); add_settings_field('menu_hidden_limit', 'Width limit to hide menu:', 'mashmenu_menuhiddenlimit_setting', __FILE__, 'mashmenu_responsive_group'); add_settings_field('menu_mobile_limit', 'Width limit for mobile:', 'mashmenu_mobilelimit_setting', __FILE__, 'mashmenu_responsive_group'); add_settings_section('mashmenu_advance_settings_group', 'Advance Settings', 'mashmenu_section_cb', __FILE__); add_settings_field('load_fontawesome', 'Load FontAwesome:', 'mashmenu_loadawesome_setting', __FILE__, 'mashmenu_advance_settings_group'); add_settings_field('ajax_loading', 'Ajax loading:', 'mashmenu_ajax_loading_setting', __FILE__, 'mashmenu_advance_settings_group'); add_settings_field('ajax_loaderimage', 'Ajax loader image:', 'mashmenu_ajax_loaderimage_setting', __FILE__, 'mashmenu_advance_settings_group'); add_settings_field('ajax_loaderimage_default', '', 'mashmenu_ajax_loaderimage_default_setting', __FILE__, 'mashmenu_advance_settings_group'); add_settings_field('disable_css', 'Disable CSS Setting', 'mashmenu_css_setting', __FILE__, 'mashmenu_advance_settings_group'); add_settings_field('advance_css', 'Advance CSS', 'mashmenu_advancecss_setting', __FILE__, 'mashmenu_advance_settings_group'); add_settings_field('hide_on_mobile', 'Hide on mobile', 'mashmenu_hide_on_mobile_setting', __FILE__, 'mashmenu_advance_settings_group'); /*add_settings_field('conditional_logic', 'Conditional Logic', 'mashmenu_condition_setting', __FILE__, 'mashmenu_advance_settings_group'); */ add_settings_section('mashmenu_woocommerce_settings_group', 'WooCommerce/JigoShop Settings', 'mashmenu_section_cb', __FILE__); add_settings_field('show_price', 'Show Price:', 'mashmenu_woo_showprice_setting', __FILE__, 'mashmenu_woocommerce_settings_group'); } function mashmenu_woo_showprice_setting() { $options = get_option('mashmenu_options'); echo "<select name='mashmenu_options[show_price]'> <option ".((isset($options['show_price']) && $options['show_price'] == '')?"selected='selected'":'')." value=''>Right of name</option> <option ".((isset($options['show_price']) && $options['show_price'] == 'left')?"selected='selected'":'')." value='left'>Left of name</option> <option ".((isset($options['show_price']) && $options['show_price'] == 'no')?"selected='selected'":'')." value='no'>Do not show price</option> </select><br/> <i>Whether to show price of product or not</i> "; } function mashmenu_hide_on_mobile_setting() { $options = get_option('mashmenu_options'); echo "<input type='checkbox' name='mashmenu_options[hide_on_mobile]' ". (($options['hide_on_mobile'] == 'on')?"checked='checked'":'')."/><br/> <i>Check if you want to hide menu on mobile. MashMenu will use mobile screen width setting above to detect mobile browser</i> "; } function mashmenu_image_link_setting() { $options = get_option('mashmenu_options'); echo "<input type='checkbox' name='mashmenu_options[image_link]' ". (($options['image_link'] == 'on')?"checked='checked'":'')."/><br/> <i>Check if you want to put link on preview image!</i> "; } function mashmenu_advancecss_setting() { $options = get_option('mashmenu_options'); echo "<textarea cols='100' rows='5' name='mashmenu_options[advance_css]'>{$options['advance_css']}</textarea><br/> <i>Enter your own CSS here</i> "; } function mashmenu_css_setting() { $options = get_option('mashmenu_options'); echo "<input type='checkbox' name='mashmenu_options[disable_css]' ". (($options['disable_css'] == 'on')?"checked='checked'":'')."/><br/> <i>If you want to load custom CSS in this setting, you can disable it. Remember to add your own code somewhere else!</i> "; } function mashmenu_rtl_setting() { $options = get_option('mashmenu_options'); echo "<input type='checkbox' name='mashmenu_options[rtl]' ". (($options['rtl'] == 'on')?"checked='checked'":'')."/><br/> <i>Choose to set the layout of MashMenu to adapt with RTL Language!</i> "; } function icon_mainmenu_parent_setting(){ $options = get_option('mashmenu_options'); echo "<input name='mashmenu_options[icon_mainmenu_parent]' value='{$options['icon_mainmenu_parent']}'/><br/><i>If leave empty, Caret-Down icon will be used. Check <a href='http://fortawesome.github.io/Font-Awesome/icons/'>Font Awesome icons</a> to get icon class</i>. For example, fa-caret-down"; } function icon_subchannel_item_right_setting(){ $options = get_option('mashmenu_options'); echo "<input name='mashmenu_options[icon_subchannel_item_right]' value='{$options['icon_subchannel_item_right']}'/><br/><i>If leave empty, Chevron-Right icon will be used. Check <a href='http://fortawesome.github.io/Font-Awesome/icons/'>Font Awesome icons</a> to get icon class</i>. For example, fa-chevron-right"; } function icon_subchannel_item_left_setting(){ $options = get_option('mashmenu_options'); echo "<input name='mashmenu_options[icon_subchannel_item_left]' value='{$options['icon_subchannel_item_left']}'/><br/><i>If leave empty, Chevron-Left icon will be used. Check <a href='http://fortawesome.github.io/Font-Awesome/icons/'>Font Awesome icons</a> to get icon class</i>. For example, fa-chevron-left"; } function mashmenu_subcontentheight_setting() { $options = get_option('mashmenu_options'); echo "<input name='mashmenu_options[subcontent_height]' value='{$options['subcontent_height']}'/><br/><i>By default, sub-content has the height of 200px. Set the height you want here (includes 'px'), or enter 0 to make it expandable</i>"; } function mashmenu_thumbnails_setting(){ $options = get_option('mashmenu_options'); echo "<input name='mashmenu_options[thumbnail_size]' value='{$options['thumbnail_size']}'/><br/><i>Enter size of thumbnails in format [width]x[height]. For example: 150x120</i>"; } function mashmenu_ajax_loaderimage_setting(){ echo '<input type="file" name="loader" /><br/>'; $options = get_option('mashmenu_options'); if($options['loader'] != ''){ echo '<span style="padding:3px;border:1px solid #CCC;background:#F2F2F2;display:inline-block"><img src="'.$options['loader'].'"/></span> <a href="javascript:void(0)" onclick="jQuery(\'#mashmenu_default_image\').val(\'\');jQuery(this).prev().remove()">Use default loader image</a>'; }; } // hidden field to clear custom loader image function mashmenu_ajax_loaderimage_default_setting() { $options = get_option('mashmenu_options'); echo "<input type='hidden' id='mashmenu_default_image' name='mashmenu_options[ajax_loaderimage_default]' value='{$options['loader']}'/>"; } function mashmenu_ajax_loading_setting() { $options = get_option('mashmenu_options'); echo "<input type='checkbox' name='mashmenu_options[ajax_loading]' ". (($options['ajax_loading'] == 'on')?"checked='checked'":'')."/><br/> <i>Choose to load content in submenu by Ajax (asynchronous) or not. Using Ajax increases the performance, but it would affect your site's SEO. It's you who decides!</i> "; } // Output Load Font Awesome setting function mashmenu_loadawesome_setting() { $options = get_option('mashmenu_options'); echo "<input type='checkbox' name='mashmenu_options[load_fontawesome]' ". (($options['load_fontawesome'] == 'on')?"checked='checked'":'')."/><br/> <i>Choose to load <a href='http://fortawesome.github.io/Font-Awesome/' target='_blank'>Font-Awesome</a> or not. Turn it off if your theme has already loaded this library</i> "; } // Ouput Sidebar settings function mashmenu_sidebars() { $options = get_option('mashmenu_options'); // for compatible with MashMenu 1.5.1. This option is removed since 1.6 $sidebars = array(); if(isset($options['sidebars']) && $options['sidebars'] != ''){ echo "<input type='text' style='display:none' name='mashmenu_options[sidebars]'/>"; // to clear value after saving $sidebars = explode(PHP_EOL, $options['sidebars']); } for($i = 1; $i <= 5; $i++){ echo "<p><input type='text' name='mashmenu_options[sidebar".$i."]' value='".(isset($sidebars[$i-1]) && $sidebars[$i-1] != ''?$sidebars[$i-1]:$options['sidebar'.$i])."'/> <select name='mashmenu_options[sidebar".$i."_logic]'><option value='both' ".($options['sidebar'.$i.'_logic'] == "both"?"selected='selected'":"").">Always visible</option><option value='guest' ".($options['sidebar'.$i.'_logic'] == "guest"?"selected='selected'":"").">Only visible to guest</option><option value='member' ".($options['sidebar'.$i.'_logic'] == "member"?"selected='selected'":"").">Only visible to members</option></select></p>"; } echo "<i>Enter names of awesome icons here, one a line. Each icon will represent a sidebar. For example, if you enter facebook, then the fa-facebook will be used. Check list of <a href='http://fortawesome.github.io/Font-Awesome/icons/'>Font Awesome icons</a></i> "; /* sidebar options will be save in the following format [name of awesome icon],[name of awesome icon] Sidebars will be created with the name "mashmenu-sidebar-iconname" */ } function mashmenu_menuhiddenlimit_setting(){ $options = get_option('mashmenu_options'); echo "<textarea cols='100' rows='5' name='mashmenu_options[menu_hidden_limit]'>{$options['menu_hidden_limit']}</textarea><br/> <i>This will control the visibility of menu items in different browser's sizes. Use the following format:</i><br/> <i>[width],[menu item]<br/> [width],[menu item]<br/> [width],[menu item]<br/> </i><br/> <i>In which, [width] is the width of browser (in pixels); [menu item] is the order of menu item that will be hidden. For example <br/> 1137,7<br/> 1126,6<br/> 946,5<br/> 850,4<br/> 710,3<br/> 610,2<br/> 539,1<br/> </i>"; /* sidebar options will be save in the following format [name of awesome icon],[name of awesome icon] Sidebars will be created with the name "mashmenu-sidebar-iconname" */ } // Output MainColor setting function mashmenu_mobilelimit_setting() { $options = get_option('mashmenu_options'); echo "<input name='mashmenu_options[menu_mobile_limit]' value='{$options['menu_mobile_limit']}'/><br/> <i>Width limit for mobile screen (in pixels). For example: 480</i> "; } // Output Logo setting function mashmenu_logo_setting(){ echo '<input type="file" name="logo" /><br/>'; $options = get_option('mashmenu_options'); if($options['logo'] != ''){ echo '<span style="padding:3px;border:1px solid #CCC;background:#F2F2F2;display:inline-block" id="img_logo"><img src="'.$options['logo'].'"/></span><input type="checkbox" onchange="if(this.checked){jQuery(\'#remove_logo\').val(1);jQuery(\'#img_logo\').hide();} else {jQuery(\'#remove_logo\').val(0);jQuery(\'#img_logo\').show();}"/> Remove Current Logo?'; }; } function mashmenu_remove_logo_setting(){ echo '<input type="hidden" value="0" id="remove_logo" name="mashmenu_options[remove_logo]"/>'; } // Output MainColor setting function mashmenu_maincolor_setting() { $options = get_option('mashmenu_options'); echo "<input name='mashmenu_options[maincolor]' class='color' value='{$options['maincolor']}'/><br/> <i>Hexa color (ex. #2AA4CF).</i> "; } // Output HoverColor setting function mashmenu_hovercolor_setting() { $options = get_option('mashmenu_options'); echo "<input name='mashmenu_options[hovercolor]' class='color' value='{$options['hovercolor']}'/><br/> <i>Hexa color (ex. #DDF0F9).</i> "; } function mashmenu_channeltitle_color_setting(){ $options = get_option('mashmenu_options'); echo "<input name='mashmenu_options[channeltitlecolor]' class='color' value='{$options['channeltitlecolor']}'/><br/> <i>Hexa color (ex. #C7E6F5).</i> "; } function mashmenu_section_cb() {} function mashmenu_validate_setting($plugin_options) { $keys = array_keys($_FILES); $i = 0; $loader_image = false; if($plugin_options['remove_logo'] == '1'){ $plugin_options['logo'] = ''; } else { foreach ( $_FILES as $image ) { // if a files was upload if ($image['size']) { // if it is an image if ( preg_match('/(jpg|jpeg|png|gif)$/', $image['type']) ) { $override = array('test_form' => false); // save the file, and store an array, containing its location in $file $file = wp_handle_upload( $image, $override ); $plugin_options[$keys[$i]] = $file['url']; if($keys[$i] == 'loader') $loader_image = true; } else { // Not an image. $options = get_option('plugin_options'); $plugin_options[$keys[$i]] = $options[$logo]; // Die and let the user know that they made a mistake. wp_die('No image was uploaded.'); } } // Else, the user didn't upload a file. // Retain the image that's already on file. else { $options = get_option('mashmenu_options'); $plugin_options[$keys[$i]] = $options[$keys[$i]]; } $i++; } } if(!$loader_image){ // no image was uploaded, check if users choose to use default loader image if($plugin_options['ajax_loaderimage_default'] == ''){ $plugin_options['loader'] = ''; } } return $plugin_options; } function mashmenu_activate() { // called when mashmenu is activated // set some default values $options = get_option('mashmenu_options'); $options['maincolor'] = '222222'; $options['hovercolor'] = 'dd4c39'; $options['channeltitlecolor'] = 'ffffff'; $options['menu_hidden_limit'] = '1137,7'.PHP_EOL.'1126,6'.PHP_EOL.'946,5'.PHP_EOL.'850,4'.PHP_EOL.'710,3'.PHP_EOL.'610,2'.PHP_EOL.'539,1'; $options['logo'] = esc_url(get_template_directory_uri() .'/inc/megamenu/images/mashmenu.png'); $options['load_fontawesome'] = 'on'; $options['ajax_loading'] = 'on'; $options['menu_mobile_limit'] = 480; $options['sidebars'] = 'search'.PHP_EOL.'facebook'; $options['image_link'] = 'on'; $options['thumbnail_size'] ='490x350'; $options['icon_subchannel_item_left']=''; $options['icon_subchannel_item_right']=''; $options['load_fontawesome'] = 'off'; update_option('mashmenu_options',$options); } add_action('init', 'mashmenu_activate'); function mashmenu_load() { wp_nav_menu(array( 'theme_location' => 'primary','is_megamenu' => true)); } //add_action('wp_footer', 'mashmenu_load');
openfoodfoundation/openfoodnetwork-wp
wp-content/themes/theblog/inc/megamenu/megamenu.php
PHP
gpl-2.0
48,725
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "Spell.h" #include "AccountMgr.h" #include "Battleground.h" #include "CellImpl.h" #include "Common.h" #include "Creature.h" #include "CreatureAI.h" #include "DatabaseEnv.h" #include "DynamicObject.h" #include "Formulas.h" #include "GameObject.h" #include "GameObjectAI.h" #include "GossipDef.h" #include "GridNotifiers.h" #include "InstanceScript.h" #include "Item.h" #include "Language.h" #include "Log.h" #include "LootMgr.h" #include "MiscPackets.h" #include "MotionMaster.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "Opcodes.h" #include "OutdoorPvPMgr.h" #include "PathGenerator.h" #include "Pet.h" #include "Player.h" #include "ReputationMgr.h" #ifdef ELUNA #include "LuaEngine.h" #endif #include "ScriptMgr.h" #include "SkillExtraItems.h" #include "SharedDefines.h" #include "SocialMgr.h" #include "SpellAuraEffects.h" #include "SpellAuras.h" #include "SpellHistory.h" #include "SpellMgr.h" #include "TemporarySummon.h" #include "Totem.h" #include "UpdateMask.h" #include "Unit.h" #include "Util.h" #include "World.h" #include "WorldPacket.h" #include "WorldSession.h" SpellEffectHandlerFn SpellEffectHandlers[TOTAL_SPELL_EFFECTS] = { &Spell::EffectNULL, // 0 &Spell::EffectInstaKill, // 1 SPELL_EFFECT_INSTAKILL &Spell::EffectSchoolDMG, // 2 SPELL_EFFECT_SCHOOL_DAMAGE &Spell::EffectDummy, // 3 SPELL_EFFECT_DUMMY &Spell::EffectUnused, // 4 SPELL_EFFECT_PORTAL_TELEPORT unused &Spell::EffectTeleportUnits, // 5 SPELL_EFFECT_TELEPORT_UNITS &Spell::EffectApplyAura, // 6 SPELL_EFFECT_APPLY_AURA &Spell::EffectEnvironmentalDMG, // 7 SPELL_EFFECT_ENVIRONMENTAL_DAMAGE &Spell::EffectPowerDrain, // 8 SPELL_EFFECT_POWER_DRAIN &Spell::EffectHealthLeech, // 9 SPELL_EFFECT_HEALTH_LEECH &Spell::EffectHeal, // 10 SPELL_EFFECT_HEAL &Spell::EffectBind, // 11 SPELL_EFFECT_BIND &Spell::EffectNULL, // 12 SPELL_EFFECT_PORTAL &Spell::EffectUnused, // 13 SPELL_EFFECT_RITUAL_BASE unused &Spell::EffectUnused, // 14 SPELL_EFFECT_RITUAL_SPECIALIZE unused &Spell::EffectUnused, // 15 SPELL_EFFECT_RITUAL_ACTIVATE_PORTAL unused &Spell::EffectQuestComplete, // 16 SPELL_EFFECT_QUEST_COMPLETE &Spell::EffectWeaponDmg, // 17 SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL &Spell::EffectResurrect, // 18 SPELL_EFFECT_RESURRECT &Spell::EffectAddExtraAttacks, // 19 SPELL_EFFECT_ADD_EXTRA_ATTACKS &Spell::EffectUnused, // 20 SPELL_EFFECT_DODGE one spell: Dodge &Spell::EffectUnused, // 21 SPELL_EFFECT_EVADE one spell: Evade (DND) &Spell::EffectParry, // 22 SPELL_EFFECT_PARRY &Spell::EffectBlock, // 23 SPELL_EFFECT_BLOCK one spell: Block &Spell::EffectCreateItem, // 24 SPELL_EFFECT_CREATE_ITEM &Spell::EffectUnused, // 25 SPELL_EFFECT_WEAPON &Spell::EffectUnused, // 26 SPELL_EFFECT_DEFENSE one spell: Defense &Spell::EffectPersistentAA, // 27 SPELL_EFFECT_PERSISTENT_AREA_AURA &Spell::EffectSummonType, // 28 SPELL_EFFECT_SUMMON &Spell::EffectLeap, // 29 SPELL_EFFECT_LEAP &Spell::EffectEnergize, // 30 SPELL_EFFECT_ENERGIZE &Spell::EffectWeaponDmg, // 31 SPELL_EFFECT_WEAPON_PERCENT_DAMAGE &Spell::EffectTriggerMissileSpell, // 32 SPELL_EFFECT_TRIGGER_MISSILE &Spell::EffectOpenLock, // 33 SPELL_EFFECT_OPEN_LOCK &Spell::EffectSummonChangeItem, // 34 SPELL_EFFECT_SUMMON_CHANGE_ITEM &Spell::EffectUnused, // 35 SPELL_EFFECT_APPLY_AREA_AURA_PARTY &Spell::EffectLearnSpell, // 36 SPELL_EFFECT_LEARN_SPELL &Spell::EffectUnused, // 37 SPELL_EFFECT_SPELL_DEFENSE one spell: SPELLDEFENSE (DND) &Spell::EffectDispel, // 38 SPELL_EFFECT_DISPEL &Spell::EffectUnused, // 39 SPELL_EFFECT_LANGUAGE &Spell::EffectDualWield, // 40 SPELL_EFFECT_DUAL_WIELD &Spell::EffectJump, // 41 SPELL_EFFECT_JUMP &Spell::EffectJumpDest, // 42 SPELL_EFFECT_JUMP_DEST &Spell::EffectTeleUnitsFaceCaster, // 43 SPELL_EFFECT_TELEPORT_UNITS_FACE_CASTER &Spell::EffectLearnSkill, // 44 SPELL_EFFECT_SKILL_STEP &Spell::EffectAddHonor, // 45 SPELL_EFFECT_ADD_HONOR honor/pvp related &Spell::EffectUnused, // 46 SPELL_EFFECT_SPAWN clientside, unit appears as if it was just spawned &Spell::EffectTradeSkill, // 47 SPELL_EFFECT_TRADE_SKILL &Spell::EffectUnused, // 48 SPELL_EFFECT_STEALTH one spell: Base Stealth &Spell::EffectUnused, // 49 SPELL_EFFECT_DETECT one spell: Detect &Spell::EffectTransmitted, // 50 SPELL_EFFECT_TRANS_DOOR &Spell::EffectUnused, // 51 SPELL_EFFECT_FORCE_CRITICAL_HIT unused &Spell::EffectUnused, // 52 SPELL_EFFECT_GUARANTEE_HIT one spell: zzOLDCritical Shot &Spell::EffectEnchantItemPerm, // 53 SPELL_EFFECT_ENCHANT_ITEM &Spell::EffectEnchantItemTmp, // 54 SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY &Spell::EffectTameCreature, // 55 SPELL_EFFECT_TAMECREATURE &Spell::EffectSummonPet, // 56 SPELL_EFFECT_SUMMON_PET &Spell::EffectLearnPetSpell, // 57 SPELL_EFFECT_LEARN_PET_SPELL &Spell::EffectWeaponDmg, // 58 SPELL_EFFECT_WEAPON_DAMAGE &Spell::EffectCreateRandomItem, // 59 SPELL_EFFECT_CREATE_RANDOM_ITEM create item base at spell specific loot &Spell::EffectProficiency, // 60 SPELL_EFFECT_PROFICIENCY &Spell::EffectSendEvent, // 61 SPELL_EFFECT_SEND_EVENT &Spell::EffectPowerBurn, // 62 SPELL_EFFECT_POWER_BURN &Spell::EffectThreat, // 63 SPELL_EFFECT_THREAT &Spell::EffectTriggerSpell, // 64 SPELL_EFFECT_TRIGGER_SPELL &Spell::EffectUnused, // 65 SPELL_EFFECT_APPLY_AREA_AURA_RAID &Spell::EffectRechargeManaGem, // 66 SPELL_EFFECT_CREATE_MANA_GEM (possibly recharge it, misc - is item ID) &Spell::EffectHealMaxHealth, // 67 SPELL_EFFECT_HEAL_MAX_HEALTH &Spell::EffectInterruptCast, // 68 SPELL_EFFECT_INTERRUPT_CAST &Spell::EffectDistract, // 69 SPELL_EFFECT_DISTRACT &Spell::EffectPull, // 70 SPELL_EFFECT_PULL one spell: Distract Move &Spell::EffectPickPocket, // 71 SPELL_EFFECT_PICKPOCKET &Spell::EffectAddFarsight, // 72 SPELL_EFFECT_ADD_FARSIGHT &Spell::EffectUntrainTalents, // 73 SPELL_EFFECT_UNTRAIN_TALENTS &Spell::EffectApplyGlyph, // 74 SPELL_EFFECT_APPLY_GLYPH &Spell::EffectHealMechanical, // 75 SPELL_EFFECT_HEAL_MECHANICAL one spell: Mechanical Patch Kit &Spell::EffectSummonObjectWild, // 76 SPELL_EFFECT_SUMMON_OBJECT_WILD &Spell::EffectScriptEffect, // 77 SPELL_EFFECT_SCRIPT_EFFECT &Spell::EffectUnused, // 78 SPELL_EFFECT_ATTACK &Spell::EffectSanctuary, // 79 SPELL_EFFECT_SANCTUARY &Spell::EffectAddComboPoints, // 80 SPELL_EFFECT_ADD_COMBO_POINTS &Spell::EffectUnused, // 81 SPELL_EFFECT_CREATE_HOUSE one spell: Create House (TEST) &Spell::EffectNULL, // 82 SPELL_EFFECT_BIND_SIGHT &Spell::EffectDuel, // 83 SPELL_EFFECT_DUEL &Spell::EffectStuck, // 84 SPELL_EFFECT_STUCK &Spell::EffectSummonPlayer, // 85 SPELL_EFFECT_SUMMON_PLAYER &Spell::EffectActivateObject, // 86 SPELL_EFFECT_ACTIVATE_OBJECT &Spell::EffectGameObjectDamage, // 87 SPELL_EFFECT_GAMEOBJECT_DAMAGE &Spell::EffectGameObjectRepair, // 88 SPELL_EFFECT_GAMEOBJECT_REPAIR &Spell::EffectGameObjectSetDestructionState, // 89 SPELL_EFFECT_GAMEOBJECT_SET_DESTRUCTION_STATE &Spell::EffectKillCreditPersonal, // 90 SPELL_EFFECT_KILL_CREDIT Kill credit but only for single person &Spell::EffectUnused, // 91 SPELL_EFFECT_THREAT_ALL one spell: zzOLDBrainwash &Spell::EffectEnchantHeldItem, // 92 SPELL_EFFECT_ENCHANT_HELD_ITEM &Spell::EffectForceDeselect, // 93 SPELL_EFFECT_FORCE_DESELECT &Spell::EffectSelfResurrect, // 94 SPELL_EFFECT_SELF_RESURRECT &Spell::EffectSkinning, // 95 SPELL_EFFECT_SKINNING &Spell::EffectCharge, // 96 SPELL_EFFECT_CHARGE &Spell::EffectCastButtons, // 97 SPELL_EFFECT_CAST_BUTTON (totem bar since 3.2.2a) &Spell::EffectKnockBack, // 98 SPELL_EFFECT_KNOCK_BACK &Spell::EffectDisEnchant, // 99 SPELL_EFFECT_DISENCHANT &Spell::EffectInebriate, //100 SPELL_EFFECT_INEBRIATE &Spell::EffectFeedPet, //101 SPELL_EFFECT_FEED_PET &Spell::EffectDismissPet, //102 SPELL_EFFECT_DISMISS_PET &Spell::EffectReputation, //103 SPELL_EFFECT_REPUTATION &Spell::EffectSummonObject, //104 SPELL_EFFECT_SUMMON_OBJECT_SLOT1 &Spell::EffectSummonObject, //105 SPELL_EFFECT_SUMMON_OBJECT_SLOT2 &Spell::EffectSummonObject, //106 SPELL_EFFECT_SUMMON_OBJECT_SLOT3 &Spell::EffectSummonObject, //107 SPELL_EFFECT_SUMMON_OBJECT_SLOT4 &Spell::EffectDispelMechanic, //108 SPELL_EFFECT_DISPEL_MECHANIC &Spell::EffectResurrectPet, //109 SPELL_EFFECT_RESURRECT_PET &Spell::EffectDestroyAllTotems, //110 SPELL_EFFECT_DESTROY_ALL_TOTEMS &Spell::EffectDurabilityDamage, //111 SPELL_EFFECT_DURABILITY_DAMAGE &Spell::EffectUnused, //112 SPELL_EFFECT_112 &Spell::EffectResurrectNew, //113 SPELL_EFFECT_RESURRECT_NEW &Spell::EffectTaunt, //114 SPELL_EFFECT_ATTACK_ME &Spell::EffectDurabilityDamagePCT, //115 SPELL_EFFECT_DURABILITY_DAMAGE_PCT &Spell::EffectSkinPlayerCorpse, //116 SPELL_EFFECT_SKIN_PLAYER_CORPSE one spell: Remove Insignia, bg usage, required special corpse flags... &Spell::EffectSpiritHeal, //117 SPELL_EFFECT_SPIRIT_HEAL one spell: Spirit Heal &Spell::EffectSkill, //118 SPELL_EFFECT_SKILL professions and more &Spell::EffectUnused, //119 SPELL_EFFECT_APPLY_AREA_AURA_PET &Spell::EffectUnused, //120 SPELL_EFFECT_TELEPORT_GRAVEYARD one spell: Graveyard Teleport Test &Spell::EffectWeaponDmg, //121 SPELL_EFFECT_NORMALIZED_WEAPON_DMG &Spell::EffectUnused, //122 SPELL_EFFECT_122 unused &Spell::EffectSendTaxi, //123 SPELL_EFFECT_SEND_TAXI taxi/flight related (misc value is taxi path id) &Spell::EffectPullTowards, //124 SPELL_EFFECT_PULL_TOWARDS &Spell::EffectModifyThreatPercent, //125 SPELL_EFFECT_MODIFY_THREAT_PERCENT &Spell::EffectStealBeneficialBuff, //126 SPELL_EFFECT_STEAL_BENEFICIAL_BUFF spell steal effect? &Spell::EffectProspecting, //127 SPELL_EFFECT_PROSPECTING Prospecting spell &Spell::EffectUnused, //128 SPELL_EFFECT_APPLY_AREA_AURA_FRIEND &Spell::EffectUnused, //129 SPELL_EFFECT_APPLY_AREA_AURA_ENEMY &Spell::EffectRedirectThreat, //130 SPELL_EFFECT_REDIRECT_THREAT &Spell::EffectPlaySound, //131 SPELL_EFFECT_PLAY_SOUND sound id in misc value (SoundEntries.dbc) &Spell::EffectPlayMusic, //132 SPELL_EFFECT_PLAY_MUSIC sound id in misc value (SoundEntries.dbc) &Spell::EffectUnlearnSpecialization, //133 SPELL_EFFECT_UNLEARN_SPECIALIZATION unlearn profession specialization &Spell::EffectKillCredit, //134 SPELL_EFFECT_KILL_CREDIT misc value is creature entry &Spell::EffectNULL, //135 SPELL_EFFECT_CALL_PET &Spell::EffectHealPct, //136 SPELL_EFFECT_HEAL_PCT &Spell::EffectEnergizePct, //137 SPELL_EFFECT_ENERGIZE_PCT &Spell::EffectLeapBack, //138 SPELL_EFFECT_LEAP_BACK Leap back &Spell::EffectQuestClear, //139 SPELL_EFFECT_CLEAR_QUEST Reset quest status (miscValue - quest ID) &Spell::EffectForceCast, //140 SPELL_EFFECT_FORCE_CAST &Spell::EffectForceCast, //141 SPELL_EFFECT_FORCE_CAST_WITH_VALUE &Spell::EffectTriggerSpell, //142 SPELL_EFFECT_TRIGGER_SPELL_WITH_VALUE &Spell::EffectUnused, //143 SPELL_EFFECT_APPLY_AREA_AURA_OWNER &Spell::EffectKnockBack, //144 SPELL_EFFECT_KNOCK_BACK_DEST &Spell::EffectPullTowardsDest, //145 SPELL_EFFECT_PULL_TOWARDS_DEST Black Hole Effect &Spell::EffectActivateRune, //146 SPELL_EFFECT_ACTIVATE_RUNE &Spell::EffectQuestFail, //147 SPELL_EFFECT_QUEST_FAIL quest fail &Spell::EffectTriggerMissileSpell, //148 SPELL_EFFECT_TRIGGER_MISSILE_SPELL_WITH_VALUE &Spell::EffectChargeDest, //149 SPELL_EFFECT_CHARGE_DEST &Spell::EffectQuestStart, //150 SPELL_EFFECT_QUEST_START &Spell::EffectTriggerRitualOfSummoning, //151 SPELL_EFFECT_TRIGGER_SPELL_2 &Spell::EffectSummonRaFFriend, //152 SPELL_EFFECT_SUMMON_RAF_FRIEND summon Refer-a-Friend &Spell::EffectCreateTamedPet, //153 SPELL_EFFECT_CREATE_TAMED_PET misc value is creature entry &Spell::EffectDiscoverTaxi, //154 SPELL_EFFECT_DISCOVER_TAXI &Spell::EffectTitanGrip, //155 SPELL_EFFECT_TITAN_GRIP Allows you to equip two-handed axes, maces and swords in one hand, but you attack $49152s1% slower than normal. &Spell::EffectEnchantItemPrismatic, //156 SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC &Spell::EffectCreateItem2, //157 SPELL_EFFECT_CREATE_ITEM_2 create item or create item template and replace by some randon spell loot item &Spell::EffectMilling, //158 SPELL_EFFECT_MILLING milling &Spell::EffectRenamePet, //159 SPELL_EFFECT_ALLOW_RENAME_PET allow rename pet once again &Spell::EffectForceCast, //160 SPELL_EFFECT_FORCE_CAST_2 &Spell::EffectSpecCount, //161 SPELL_EFFECT_TALENT_SPEC_COUNT second talent spec (learn/revert) &Spell::EffectActivateSpec, //162 SPELL_EFFECT_TALENT_SPEC_SELECT activate primary/secondary spec &Spell::EffectNULL, //163 unused &Spell::EffectRemoveAura, //164 SPELL_EFFECT_REMOVE_AURA }; void Spell::EffectNULL() { TC_LOG_DEBUG("spells", "WORLD: Spell Effect DUMMY"); } void Spell::EffectUnused() { // NOT USED BY ANY SPELL OR USELESS OR IMPLEMENTED IN DIFFERENT WAY IN TRINITY } void Spell::EffectResurrectNew() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!m_corpseTarget && !unitTarget) return; Player* player = nullptr; if (m_corpseTarget) player = ObjectAccessor::FindPlayer(m_corpseTarget->GetOwnerGUID()); else if (unitTarget) player = unitTarget->ToPlayer(); if (!player || player->IsAlive() || !player->IsInWorld()) return; if (player->IsResurrectRequested()) // already have one active request return; uint32 health = damage; uint32 mana = effectInfo->MiscValue; ExecuteLogEffectResurrect(effectInfo->EffectIndex, player); player->SetResurrectRequestData(m_caster, health, mana, 0); SendResurrectRequest(player); } void Spell::EffectInstaKill() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || !unitTarget->IsAlive()) return; if (unitTarget->GetTypeId() == TYPEID_PLAYER) if (unitTarget->ToPlayer()->GetCommandStatus(CHEAT_GOD)) return; if (m_caster == unitTarget) // prevent interrupt message finish(); WorldPacket data(SMSG_SPELLINSTAKILLLOG, 8+8+4); data << uint64(m_caster->GetGUID()); data << uint64(unitTarget->GetGUID()); data << uint32(m_spellInfo->Id); m_caster->SendMessageToSet(&data, true); Unit::DealDamage(GetUnitCasterForEffectHandlers(), unitTarget, unitTarget->GetHealth(), nullptr, NODAMAGE, SPELL_SCHOOL_MASK_NORMAL, nullptr, false); } void Spell::EffectEnvironmentalDMG() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || !unitTarget->IsAlive()) return; // CalcAbsorbResist already in Player::EnvironmentalDamage if (unitTarget->GetTypeId() == TYPEID_PLAYER) unitTarget->ToPlayer()->EnvironmentalDamage(DAMAGE_FIRE, damage); else { Unit* unitCaster = GetUnitCasterForEffectHandlers(); DamageInfo damageInfo(unitCaster, unitTarget, damage, m_spellInfo, m_spellInfo->GetSchoolMask(), SPELL_DIRECT_DAMAGE, BASE_ATTACK); Unit::CalcAbsorbResist(damageInfo); uint32 const absorb = damageInfo.GetAbsorb(); uint32 const resist = damageInfo.GetResist(); if (unitCaster) unitCaster->SendSpellNonMeleeDamageLog(unitTarget, m_spellInfo->Id, damage, m_spellInfo->GetSchoolMask(), absorb, resist, false, 0, false); } } void Spell::EffectSchoolDMG() { if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET) return; if (unitTarget && unitTarget->IsAlive()) { bool apply_direct_bonus = true; Unit* unitCaster = GetUnitCasterForEffectHandlers(); switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: { // Meteor like spells (divided damage to targets) if (m_spellInfo->HasAttribute(SPELL_ATTR0_CU_SHARE_DAMAGE)) { uint32 count = 0; for (auto ihit = m_UniqueTargetInfo.begin(); ihit != m_UniqueTargetInfo.end(); ++ihit) { if (ihit->MissCondition != SPELL_MISS_NONE) continue; if (ihit->EffectMask & (1 << effectInfo->EffectIndex)) ++count; } // divide to all targets if (count) damage /= count; } break; } case SPELLFAMILY_WARRIOR: { if (!unitCaster) break; // Shield Slam if ((m_spellInfo->SpellFamilyFlags[1] & 0x200) && m_spellInfo->GetCategory() == 1209) { uint8 level = unitCaster->GetLevel(); uint32 block_value = unitCaster->GetShieldBlockValue(uint32(float(level) * 24.5f), uint32(float(level) * 34.5f)); damage += int32(unitCaster->ApplyEffectModifiers(m_spellInfo, effectInfo->EffectIndex, float(block_value))); } // Victory Rush else if (m_spellInfo->SpellFamilyFlags[1] & 0x100) ApplyPct(damage, unitCaster->GetTotalAttackPowerValue(BASE_ATTACK)); // Shockwave else if (m_spellInfo->Id == 46968) { int32 pct = unitCaster->CalculateSpellDamage(m_spellInfo->GetEffect(EFFECT_2)); if (pct > 0) damage += int32(CalculatePct(unitCaster->GetTotalAttackPowerValue(BASE_ATTACK), pct)); break; } break; } case SPELLFAMILY_WARLOCK: { if (!unitCaster) break; // Incinerate Rank 1 & 2 if ((m_spellInfo->SpellFamilyFlags[1] & 0x000040) && m_spellInfo->SpellIconID == 2128) { // Incinerate does more dmg (dmg*0.25) if the target have Immolate debuff. // Check aura state for speed but aura state set not only for Immolate spell if (unitTarget->HasAuraState(AURA_STATE_CONFLAGRATE)) { if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_WARLOCK, 0x4, 0, 0)) damage += damage / 4; } } // Conflagrate - consumes Immolate or Shadowflame else if (m_spellInfo->TargetAuraState == AURA_STATE_CONFLAGRATE) { AuraEffect const* aura = nullptr; // found req. aura for damage calculation Unit::AuraEffectList const& mPeriodic = unitTarget->GetAuraEffectsByType(SPELL_AURA_PERIODIC_DAMAGE); for (Unit::AuraEffectList::const_iterator i = mPeriodic.begin(); i != mPeriodic.end(); ++i) { // for caster applied auras only if ((*i)->GetSpellInfo()->SpellFamilyName != SPELLFAMILY_WARLOCK || (*i)->GetCasterGUID() != unitCaster->GetGUID()) continue; // Immolate if ((*i)->GetSpellInfo()->SpellFamilyFlags[0] & 0x4) { aura = *i; // it selected always if exist break; } // Shadowflame if ((*i)->GetSpellInfo()->SpellFamilyFlags[2] & 0x00000002) aura = *i; // remember but wait possible Immolate as primary priority } // found Immolate or Shadowflame if (aura) { // Calculate damage of Immolate/Shadowflame tick int32 pdamage = aura->GetAmount(); pdamage = unitTarget->SpellDamageBonusTaken(unitCaster, aura->GetSpellInfo(), pdamage, DOT); // And multiply by amount of ticks to get damage potential pdamage *= aura->GetSpellInfo()->GetMaxTicks(); int32 pct_dir = unitCaster->CalculateSpellDamage(m_spellInfo->GetEffect(EFFECT_1)); damage += CalculatePct(pdamage, pct_dir); int32 pct_dot = unitCaster->CalculateSpellDamage(m_spellInfo->GetEffect(EFFECT_2)); int32 const dotBasePoints = CalculatePct(pdamage, pct_dot); ASSERT(m_spellInfo->GetMaxTicks() > 0); m_spellValue->EffectBasePoints[EFFECT_1] = dotBasePoints / m_spellInfo->GetMaxTicks(); apply_direct_bonus = false; // Glyph of Conflagrate if (!unitCaster->HasAura(56235)) unitTarget->RemoveAurasDueToSpell(aura->GetId(), unitCaster->GetGUID()); break; } } // Shadow Bite else if (m_spellInfo->SpellFamilyFlags[1] & 0x400000) { if (unitCaster->GetTypeId() == TYPEID_UNIT && unitCaster->IsPet()) { if (Player* owner = unitCaster->GetOwner()->ToPlayer()) { if (AuraEffect* aurEff = owner->GetAuraEffect(SPELL_AURA_ADD_FLAT_MODIFIER, SPELLFAMILY_WARLOCK, 214, 0)) { int32 bp0 = aurEff->GetId() == 54037 ? 4 : 8; CastSpellExtraArgs args(TRIGGERED_FULL_MASK); args.AddSpellMod(SPELLVALUE_BASE_POINT0, bp0); unitCaster->CastSpell(nullptr, 54425, args); } } } } break; } case SPELLFAMILY_PRIEST: { if (!unitCaster) break; // Improved Mind Blast (Mind Blast in shadow form bonus) if (unitCaster->GetShapeshiftForm() == FORM_SHADOW && (m_spellInfo->SpellFamilyFlags[0] & 0x00002000)) { Unit::AuraEffectList const& ImprMindBlast = unitCaster->GetAuraEffectsByType(SPELL_AURA_ADD_FLAT_MODIFIER); for (Unit::AuraEffectList::const_iterator i = ImprMindBlast.begin(); i != ImprMindBlast.end(); ++i) { if ((*i)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_PRIEST && ((*i)->GetSpellInfo()->SpellIconID == 95)) { // Mind Trauma int32 const chance = (*i)->GetSpellInfo()->GetEffect(EFFECT_1).CalcValue(unitCaster); if (roll_chance_i(chance)) unitCaster->CastSpell(unitTarget, 48301, true); break; } } } break; } case SPELLFAMILY_DRUID: { if (!unitCaster) break; // Ferocious Bite if (unitCaster->GetTypeId() == TYPEID_PLAYER && (m_spellInfo->SpellFamilyFlags[0] & 0x000800000) && m_spellInfo->SpellVisual[0] == 6587) { // converts each extra point of energy into ($f1+$AP/410) additional damage float ap = unitCaster->GetTotalAttackPowerValue(BASE_ATTACK); float multiple = ap / 410 + effectInfo->DamageMultiplier; int32 energy = -(unitCaster->ModifyPower(POWER_ENERGY, -30)); damage += int32(energy * multiple); damage += int32(CalculatePct(unitCaster->ToPlayer()->GetComboPoints() * ap, 7)); } // Wrath else if (m_spellInfo->SpellFamilyFlags[0] & 0x00000001) { // Improved Insect Swarm if (AuraEffect const* aurEff = unitCaster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 1771, 0)) if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DRUID, 0x00200000, 0, 0)) AddPct(damage, aurEff->GetAmount()); } break; } case SPELLFAMILY_ROGUE: { if (!unitCaster) break; // Envenom if (m_spellInfo->SpellFamilyFlags[1] & 0x00000008) { if (Player* player = unitCaster->ToPlayer()) { // consume from stack dozes not more that have combo-points if (uint32 combo = player->GetComboPoints()) { // Lookup for Deadly poison (only attacker applied) if (AuraEffect const* aurEff = unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_ROGUE, 0x00010000, 0, 0, unitCaster->GetGUID())) { // count consumed deadly poison doses at target bool needConsume = true; uint32 spellId = aurEff->GetId(); uint32 doses = aurEff->GetBase()->GetStackAmount(); if (doses > combo) doses = combo; // Master Poisoner Unit::AuraEffectList const& auraList = player->GetAuraEffectsByType(SPELL_AURA_MOD_AURA_DURATION_BY_DISPEL_NOT_STACK); for (Unit::AuraEffectList::const_iterator iter = auraList.begin(); iter != auraList.end(); ++iter) { if ((*iter)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_ROGUE && (*iter)->GetSpellInfo()->SpellIconID == 1960) { uint32 chance = (*iter)->GetSpellInfo()->GetEffect(EFFECT_2).CalcValue(unitCaster); if (chance && roll_chance_i(chance)) needConsume = false; break; } } if (needConsume) for (uint32 i = 0; i < doses; ++i) unitTarget->RemoveAuraFromStack(spellId, unitCaster->GetGUID()); damage *= doses; damage += int32(player->GetTotalAttackPowerValue(BASE_ATTACK) * 0.09f * combo); } // Eviscerate and Envenom Bonus Damage (item set effect) if (unitCaster->HasAura(37169)) damage += combo * 40; } } } // Eviscerate else if (m_spellInfo->SpellFamilyFlags[0] & 0x00020000) { if (Player* player = unitCaster->ToPlayer()) { if (uint32 combo = player->GetComboPoints()) { float ap = unitCaster->GetTotalAttackPowerValue(BASE_ATTACK); damage += std::lroundf(ap * combo * 0.07f); // Eviscerate and Envenom Bonus Damage (item set effect) if (unitCaster->HasAura(37169)) damage += combo*40; } } } break; } case SPELLFAMILY_HUNTER: { if (!unitCaster) break; //Gore if (m_spellInfo->SpellIconID == 1578) { if (unitCaster->HasAura(57627)) // Charge 6 sec post-affect damage *= 2; } // Steady Shot else if (m_spellInfo->SpellFamilyFlags[1] & 0x1) { bool found = false; // check dazed affect Unit::AuraEffectList const& decSpeedList = unitTarget->GetAuraEffectsByType(SPELL_AURA_MOD_DECREASE_SPEED); for (Unit::AuraEffectList::const_iterator iter = decSpeedList.begin(); iter != decSpeedList.end(); ++iter) { if ((*iter)->GetSpellInfo()->SpellIconID == 15 && (*iter)->GetSpellInfo()->Dispel == 0) { found = true; break; } } /// @todo should this be put on taken but not done? if (found) damage += m_spellInfo->GetEffect(EFFECT_1).CalcValue(); if (Player* caster = unitCaster->ToPlayer()) { // Add Ammo and Weapon damage plus RAP * 0.1 float dmg_min = 0.f; float dmg_max = 0.f; for (uint8 i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i) { dmg_min += caster->GetWeaponDamageRange(RANGED_ATTACK, MINDAMAGE, i); dmg_max += caster->GetWeaponDamageRange(RANGED_ATTACK, MAXDAMAGE, i); } if (dmg_max == 0.0f && dmg_min > dmg_max) damage += int32(dmg_min); else damage += irand(int32(dmg_min), int32(dmg_max)); damage += int32(caster->GetAmmoDPS() * caster->GetAttackTime(RANGED_ATTACK) * 0.001f); } } break; } case SPELLFAMILY_PALADIN: { if (!unitCaster) break; // Hammer of the Righteous if (m_spellInfo->SpellFamilyFlags[1] & 0x00040000) { float minTotal = 0.f; float maxTotal = 0.f; float tmpMin, tmpMax; for (uint8 i = 0; i < MAX_ITEM_PROTO_DAMAGES; ++i) { unitCaster->CalculateMinMaxDamage(BASE_ATTACK, false, false, tmpMin, tmpMax, i); minTotal += tmpMin; maxTotal += tmpMax; } float average = (minTotal + maxTotal) / 2; // Add main hand dps * effect[2] amount int32 count = unitCaster->CalculateSpellDamage(m_spellInfo->GetEffect(EFFECT_2)); damage += count * int32(average * IN_MILLISECONDS) / unitCaster->GetAttackTime(BASE_ATTACK); break; } // Shield of Righteousness if (m_spellInfo->SpellFamilyFlags[EFFECT_1] & 0x100000) { uint8 level = unitCaster->GetLevel(); uint32 block_value = unitCaster->GetShieldBlockValue(uint32(float(level) * 29.5f), uint32(float(level) * 39.5f)); damage += CalculatePct(block_value, m_spellInfo->GetEffect(EFFECT_1).CalcValue()); break; } break; } case SPELLFAMILY_DEATHKNIGHT: { if (!unitCaster) break; // Blood Boil - bonus for diseased targets if (m_spellInfo->SpellFamilyFlags[0] & 0x00040000) { if (unitTarget->GetAuraEffect(SPELL_AURA_PERIODIC_DAMAGE, SPELLFAMILY_DEATHKNIGHT, 0, 0, 0x00000002, unitCaster->GetGUID())) { damage += m_damage / 2; damage += int32(unitCaster->GetTotalAttackPowerValue(BASE_ATTACK) * 0.035f); } } break; } } if (unitCaster && damage > 0 && apply_direct_bonus) { damage = unitCaster->SpellDamageBonusDone(unitTarget, m_spellInfo, (uint32)damage, SPELL_DIRECT_DAMAGE, *effectInfo, { }); damage = unitTarget->SpellDamageBonusTaken(unitCaster, m_spellInfo, (uint32)damage, SPELL_DIRECT_DAMAGE); } m_damage += damage; } } void Spell::EffectDummy() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget && !gameObjTarget && !itemTarget && !m_corpseTarget) return; // pet auras if (m_caster->GetTypeId() == TYPEID_PLAYER) { if (PetAura const* petSpell = sSpellMgr->GetPetAura(m_spellInfo->Id, effectInfo->EffectIndex)) { m_caster->ToPlayer()->AddPetAura(petSpell); return; } } // normal DB scripted effect TC_LOG_DEBUG("spells", "Spell ScriptStart spellid %u in EffectDummy(%u)", m_spellInfo->Id, uint32(effectInfo->EffectIndex)); m_caster->GetMap()->ScriptsStart(sSpellScripts, uint32(m_spellInfo->Id | (effectInfo->EffectIndex << 24)), m_caster, unitTarget); #ifdef ELUNA if (gameObjTarget) sEluna->OnDummyEffect(m_caster, m_spellInfo->Id, effectInfo->EffectIndex, gameObjTarget); else if (unitTarget && unitTarget->GetTypeId() == TYPEID_UNIT) sEluna->OnDummyEffect(m_caster, m_spellInfo->Id, effectInfo->EffectIndex, unitTarget->ToCreature()); else if (itemTarget) sEluna->OnDummyEffect(m_caster, m_spellInfo->Id, effectInfo->EffectIndex, itemTarget); #endif } void Spell::EffectTriggerSpell() { if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET && effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH) return; uint32 triggered_spell_id = effectInfo->TriggerSpell; /// @todo move those to spell scripts if (effectInfo->Effect == SPELL_EFFECT_TRIGGER_SPELL && effectHandleMode == SPELL_EFFECT_HANDLE_LAUNCH_TARGET) { Unit* unitCaster = GetUnitCasterForEffectHandlers(); // special cases switch (triggered_spell_id) { // Mirror Image case 58832: { if (!unitCaster) break; // Glyph of Mirror Image if (unitCaster->HasAura(63093)) unitCaster->CastSpell(nullptr, 65047, true); // Mirror Image break; } // Demonic Empowerment -- succubus case 54437: { unitTarget->RemoveMovementImpairingAuras(true); unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STALKED); unitTarget->RemoveAurasByType(SPELL_AURA_MOD_STUN); // Cast Lesser Invisibility unitTarget->CastSpell(unitTarget, 7870, true); return; } // Brittle Armor - (need add max stack of 24575 Brittle Armor) case 29284: { // Brittle Armor SpellInfo const* spell = sSpellMgr->GetSpellInfo(24575); if (!spell) return; for (uint32 j = 0; j < spell->StackAmount; ++j) m_caster->CastSpell(unitTarget, spell->Id, true); return; } // Mercurial Shield - (need add max stack of 26464 Mercurial Shield) case 29286: { // Mercurial Shield SpellInfo const* spell = sSpellMgr->GetSpellInfo(26464); if (!spell) return; for (uint32 j = 0; j < spell->StackAmount; ++j) m_caster->CastSpell(unitTarget, spell->Id, true); return; } } } if (triggered_spell_id == 0) { TC_LOG_WARN("spells.effect.nospell", "Spell::EffectTriggerSpell: Spell %u [EffectIndex: %u] does not have triggered spell.", m_spellInfo->Id, uint32(effectInfo->EffectIndex)); return; } // normal case SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(triggered_spell_id); if (!spellInfo) { TC_LOG_ERROR("spells.effect.nospell", "Spell::EffectTriggerSpell spell %u tried to trigger unknown spell %u", m_spellInfo->Id, triggered_spell_id); return; } SpellCastTargets targets; if (effectHandleMode == SPELL_EFFECT_HANDLE_LAUNCH_TARGET) { if (!spellInfo->NeedsToBeTriggeredByCaster(m_spellInfo)) return; targets.SetUnitTarget(unitTarget); } else //if (effectHandleMode == SPELL_EFFECT_HANDLE_LAUNCH) { if (spellInfo->NeedsToBeTriggeredByCaster(m_spellInfo) && (effectInfo->GetProvidedTargetMask() & TARGET_FLAG_UNIT_MASK)) return; if (spellInfo->GetExplicitTargetMask() & TARGET_FLAG_DEST_LOCATION) targets.SetDst(m_targets); if (Unit* target = m_targets.GetUnitTarget()) targets.SetUnitTarget(target); else { if (Unit* unit = m_caster->ToUnit()) targets.SetUnitTarget(unit); else if (GameObject* go = m_caster->ToGameObject()) targets.SetGOTarget(go); } } CastSpellExtraArgs args(m_originalCasterGUID); // set basepoints for trigger with value effect if (effectInfo->Effect == SPELL_EFFECT_TRIGGER_SPELL_WITH_VALUE) for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) args.AddSpellMod(SpellValueMod(SPELLVALUE_BASE_POINT0 + i), damage); // original caster guid only for GO cast m_caster->CastSpell(targets, spellInfo->Id, args); } void Spell::EffectTriggerMissileSpell() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET && effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; uint32 triggered_spell_id = effectInfo->TriggerSpell; if (triggered_spell_id == 0) { TC_LOG_WARN("spells.effect.nospell", "Spell::EffectTriggerMissileSpell: Spell %u [EffectIndex: %u] does not have triggered spell.", m_spellInfo->Id, uint32(effectInfo->EffectIndex)); return; } // normal case SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(triggered_spell_id); if (!spellInfo) { TC_LOG_ERROR("spells.effect.nospell", "Spell::EffectTriggerMissileSpell spell %u tried to trigger unknown spell %u.", m_spellInfo->Id, triggered_spell_id); return; } SpellCastTargets targets; if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT_TARGET) { if (!spellInfo->NeedsToBeTriggeredByCaster(m_spellInfo)) return; targets.SetUnitTarget(unitTarget); } else //if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT) { if (spellInfo->NeedsToBeTriggeredByCaster(m_spellInfo) && (effectInfo->GetProvidedTargetMask() & TARGET_FLAG_UNIT_MASK)) return; if (spellInfo->GetExplicitTargetMask() & TARGET_FLAG_DEST_LOCATION) targets.SetDst(m_targets); if (Unit* unit = m_caster->ToUnit()) targets.SetUnitTarget(unit); else if (GameObject* go = m_caster->ToGameObject()) targets.SetGOTarget(go); } CastSpellExtraArgs args(m_originalCasterGUID); // set basepoints for trigger with value effect if (effectInfo->Effect == SPELL_EFFECT_TRIGGER_MISSILE_SPELL_WITH_VALUE) for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) args.AddSpellMod(SpellValueMod(SPELLVALUE_BASE_POINT0 + i), damage); // original caster guid only for GO cast m_caster->CastSpell(targets, spellInfo->Id, args); } void Spell::EffectForceCast() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; uint32 triggered_spell_id = effectInfo->TriggerSpell; if (triggered_spell_id == 0) { TC_LOG_WARN("spells.effect.nospell", "Spell::EffectForceCast: Spell %u [EffectIndex: %u] does not have triggered spell.", m_spellInfo->Id, uint32(effectInfo->EffectIndex)); return; } // normal case SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(triggered_spell_id); if (!spellInfo) { TC_LOG_ERROR("spells.effect.nospell", "Spell::EffectForceCast of spell %u: triggering unknown spell id %i.", m_spellInfo->Id, triggered_spell_id); return; } if (effectInfo->Effect == SPELL_EFFECT_FORCE_CAST && damage) { switch (m_spellInfo->Id) { case 52588: // Skeletal Gryphon Escape case 48598: // Ride Flamebringer Cue unitTarget->RemoveAura(damage); break; case 52463: // Hide In Mine Car case 52349: // Overtake { CastSpellExtraArgs args(m_originalCasterGUID); args.AddSpellMod(SPELLVALUE_BASE_POINT0, damage); unitTarget->CastSpell(unitTarget, spellInfo->Id, args); return; } } } switch (spellInfo->Id) { case 72298: // Malleable Goo Summon unitTarget->CastSpell(unitTarget, spellInfo->Id, m_originalCasterGUID); return; } CastSpellExtraArgs args(TRIGGERED_FULL_MASK); if (effectInfo->Effect == SPELL_EFFECT_FORCE_CAST_WITH_VALUE) for (uint32 i = 0; i < MAX_SPELL_EFFECTS; ++i) args.AddSpellMod(SpellValueMod(SPELLVALUE_BASE_POINT0 + i), damage); unitTarget->CastSpell(m_caster, spellInfo->Id, args); } void Spell::EffectTriggerRitualOfSummoning() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; uint32 triggered_spell_id = effectInfo->TriggerSpell; if (triggered_spell_id == 0) { TC_LOG_WARN("spells.effect.nospell", "Spell::EffectTriggerRitualOfSummoning: Spell %u [EffectIndex: %u] does not have triggered spell.", m_spellInfo->Id, uint32(effectInfo->EffectIndex)); return; } SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(triggered_spell_id); if (!spellInfo) { TC_LOG_ERROR("spells.effect.nospell", "EffectTriggerRitualOfSummoning of spell %u: triggering unknown spell id %i.", m_spellInfo->Id, triggered_spell_id); return; } finish(); m_caster->CastSpell(nullptr, spellInfo->Id, false); } void Spell::CalculateJumpSpeeds(SpellEffectInfo const& spellEffectInfo, float dist, float& speedXY, float& speedZ) { Unit* unitCaster = GetUnitCasterForEffectHandlers(); ASSERT(unitCaster); float runSpeed = unitCaster->IsControlledByPlayer() ? playerBaseMoveSpeed[MOVE_RUN] : baseMoveSpeed[MOVE_RUN]; if (Creature* creature = unitCaster->ToCreature()) runSpeed *= creature->GetCreatureTemplate()->speed_run; float multiplier = spellEffectInfo.ValueMultiplier; if (multiplier <= 0.0f) multiplier = 1.0f; speedXY = std::min(runSpeed * 3.0f * multiplier, std::max(28.0f, unitCaster->GetSpeed(MOVE_RUN) * 4.0f)); float duration = dist / speedXY; float durationSqr = duration * duration; float minHeight = spellEffectInfo.MiscValue ? spellEffectInfo.MiscValue / 10.0f : 0.5f; // Lower bound is blizzlike float maxHeight = spellEffectInfo.MiscValueB ? spellEffectInfo.MiscValueB / 10.0f : 1000.0f; // Upper bound is unknown float height; if (durationSqr < minHeight * 8 / Movement::gravity) height = minHeight; else if (durationSqr > maxHeight * 8 / Movement::gravity) height = maxHeight; else height = Movement::gravity * durationSqr / 8; speedZ = std::sqrt(2 * Movement::gravity * height); } void Spell::EffectJump() { if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; if (unitCaster->IsInFlight()) return; if (!unitTarget) return; float speedXY, speedZ; CalculateJumpSpeeds(*effectInfo, unitCaster->GetExactDist2d(unitTarget), speedXY, speedZ); unitCaster->GetMotionMaster()->MoveJump(*unitTarget, speedXY, speedZ, EVENT_JUMP, false); } void Spell::EffectJumpDest() { if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; if (unitCaster->IsInFlight()) return; if (!m_targets.HasDst()) return; float speedXY, speedZ; CalculateJumpSpeeds(*effectInfo, unitCaster->GetExactDist2d(destTarget), speedXY, speedZ); unitCaster->GetMotionMaster()->MoveJump(*destTarget, speedXY, speedZ, EVENT_JUMP, !m_targets.GetObjectTargetGUID().IsEmpty()); } void Spell::EffectTeleportUnits() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->IsInFlight()) return; // If not exist data for dest location - return if (!m_targets.HasDst()) { TC_LOG_ERROR("spells", "Spell::EffectTeleportUnits - does not have a destination for spellId %u.", m_spellInfo->Id); return; } // Init dest coordinates WorldLocation targetDest(*destTarget); if (targetDest.GetMapId() == MAPID_INVALID) targetDest.m_mapId = unitTarget->GetMapId(); if (!targetDest.GetOrientation() && m_targets.GetUnitTarget()) targetDest.SetOrientation(m_targets.GetUnitTarget()->GetOrientation()); if (targetDest.GetMapId() == unitTarget->GetMapId()) unitTarget->NearTeleportTo(targetDest, unitTarget == m_caster); else if (unitTarget->GetTypeId() == TYPEID_PLAYER) unitTarget->ToPlayer()->TeleportTo(targetDest, unitTarget == m_caster ? TELE_TO_SPELL : 0); else { TC_LOG_ERROR("spells", "Spell::EffectTeleportUnits - spellId %u attempted to teleport creature to a different map.", m_spellInfo->Id); return; } } void Spell::EffectApplyAura() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!_spellAura || !unitTarget) return; // register target/effect on aura AuraApplication* aurApp = _spellAura->GetApplicationOfTarget(unitTarget->GetGUID()); if (!aurApp) aurApp = unitTarget->_CreateAuraApplication(_spellAura, 1 << effectInfo->EffectIndex); else aurApp->UpdateApplyEffectMask(aurApp->GetEffectsToApply() | 1 << effectInfo->EffectIndex); } void Spell::EffectUnlearnSpecialization() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = unitTarget->ToPlayer(); uint32 spellToUnlearn = effectInfo->TriggerSpell; player->RemoveSpell(spellToUnlearn); TC_LOG_DEBUG("spells", "Spell: Player %s has unlearned spell %u from Npc %s", player->GetGUID().ToString().c_str(), spellToUnlearn, m_caster->GetGUID().ToString().c_str()); } void Spell::EffectPowerDrain() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (effectInfo->MiscValue < 0 || effectInfo->MiscValue >= int8(MAX_POWERS)) return; Powers powerType = Powers(effectInfo->MiscValue); if (!unitTarget || !unitTarget->IsAlive() || unitTarget->GetPowerType() != powerType || damage < 0) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); // add spell damage bonus if (unitCaster) { damage = unitCaster->SpellDamageBonusDone(unitTarget, m_spellInfo, uint32(damage), SPELL_DIRECT_DAMAGE, *effectInfo, { }); damage = unitTarget->SpellDamageBonusTaken(unitCaster, m_spellInfo, uint32(damage), SPELL_DIRECT_DAMAGE); } // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) int32 power = damage; if (powerType == POWER_MANA) power -= unitTarget->GetSpellCritDamageReduction(power); int32 newDamage = -(unitTarget->ModifyPower(powerType, -int32(power))); // Don't restore from self drain float gainMultiplier = 0.f; if (unitCaster && unitCaster != unitTarget) { gainMultiplier = effectInfo->CalcValueMultiplier(unitCaster, this); int32 const gain = int32(newDamage * gainMultiplier); unitCaster->EnergizeBySpell(unitCaster, m_spellInfo, gain, powerType); } ExecuteLogEffectTakeTargetPower(effectInfo->EffectIndex, unitTarget, powerType, newDamage, gainMultiplier); } void Spell::EffectSendEvent() { // we do not handle a flag dropping or clicking on flag in battleground by sendevent system if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET && effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; WorldObject* target = nullptr; // call events for object target if present if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT_TARGET) { if (unitTarget) target = unitTarget; else if (gameObjTarget) target = gameObjTarget; else if (m_corpseTarget) target = m_corpseTarget; } else // if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT) { // let's prevent executing effect handler twice in case when spell effect is capable of targeting an object // this check was requested by scripters, but it has some downsides: // now it's impossible to script (using sEventScripts) a cast which misses all targets // or to have an ability to script the moment spell hits dest (in a case when there are object targets present) if (effectInfo->GetProvidedTargetMask() & (TARGET_FLAG_UNIT_MASK | TARGET_FLAG_GAMEOBJECT_MASK)) return; // some spells have no target entries in dbc and they use focus target if (focusObject) target = focusObject; /// @todo there should be a possibility to pass dest target to event script } TC_LOG_DEBUG("spells", "Spell ScriptStart %u for spellid %u in EffectSendEvent ", effectInfo->MiscValue, m_spellInfo->Id); if (ZoneScript* zoneScript = m_caster->GetZoneScript()) zoneScript->ProcessEvent(target, effectInfo->MiscValue); else if (InstanceScript* instanceScript = m_caster->GetInstanceScript()) // needed in case Player is the caster instanceScript->ProcessEvent(target, effectInfo->MiscValue); m_caster->GetMap()->ScriptsStart(sEventScripts, effectInfo->MiscValue, m_caster, target); } void Spell::EffectPowerBurn() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (effectInfo->MiscValue < 0 || effectInfo->MiscValue >= int8(MAX_POWERS)) return; Powers powerType = Powers(effectInfo->MiscValue); if (!unitTarget || !unitTarget->IsAlive() || unitTarget->GetPowerType() != powerType || damage < 0) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); // burn x% of target's mana, up to maximum of 2x% of caster's mana (Mana Burn) ///@todo: move this to scripts if (unitCaster && m_spellInfo->Id == 8129) { int32 maxDamage = int32(CalculatePct(unitCaster->GetMaxPower(powerType), damage * 2)); damage = int32(CalculatePct(unitTarget->GetMaxPower(powerType), damage)); damage = std::min(damage, maxDamage); } int32 power = damage; // resilience reduce mana draining effect at spell crit damage reduction (added in 2.4) if (powerType == POWER_MANA) power -= unitTarget->GetSpellCritDamageReduction(power); int32 newDamage = -(unitTarget->ModifyPower(powerType, -power)); // NO - Not a typo - EffectPowerBurn uses effect value multiplier - not effect damage multiplier float dmgMultiplier = effectInfo->CalcValueMultiplier(unitCaster, this); // add log data before multiplication (need power amount, not damage) ExecuteLogEffectTakeTargetPower(effectInfo->EffectIndex, unitTarget, powerType, newDamage, 0.0f); newDamage = int32(newDamage * dmgMultiplier); m_damage += newDamage; } void Spell::EffectHeal() { if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET) return; if (!unitTarget || !unitTarget->IsAlive() || damage < 0) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); // Skip if m_originalCaster not available if (!unitCaster) return; int32 addhealth = damage; // Vessel of the Naaru (Vial of the Sunwell trinket) ///@todo: move this to scripts if (m_spellInfo->Id == 45064) { // Amount of heal - depends from stacked Holy Energy int32 damageAmount = 0; if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(45062, 0)) { damageAmount += aurEff->GetAmount(); unitCaster->RemoveAurasDueToSpell(45062); } addhealth += damageAmount; } // Swiftmend - consumes Regrowth or Rejuvenation else if (m_spellInfo->TargetAuraState == AURA_STATE_SWIFTMEND && unitTarget->HasAuraState(AURA_STATE_SWIFTMEND, m_spellInfo, unitCaster)) { Unit::AuraEffectList const& RejorRegr = unitTarget->GetAuraEffectsByType(SPELL_AURA_PERIODIC_HEAL); // find most short by duration AuraEffect* targetAura = nullptr; for (Unit::AuraEffectList::const_iterator i = RejorRegr.begin(); i != RejorRegr.end(); ++i) { if ((*i)->GetSpellInfo()->SpellFamilyName == SPELLFAMILY_DRUID && (*i)->GetSpellInfo()->SpellFamilyFlags[0] & 0x50) { if (!targetAura || (*i)->GetBase()->GetDuration() < targetAura->GetBase()->GetDuration()) targetAura = *i; } } if (!targetAura) { TC_LOG_ERROR("spells", "Target (%s) has the aurastate AURA_STATE_SWIFTMEND, but no matching aura.", unitTarget->GetGUID().ToString().c_str()); return; } int32 tickheal = targetAura->GetAmount(); unitTarget->SpellHealingBonusTaken(unitCaster, targetAura->GetSpellInfo(), tickheal, DOT); int32 tickcount = 0; // Rejuvenation if (targetAura->GetSpellInfo()->SpellFamilyFlags[0] & 0x10) tickcount = 4; // Regrowth else // if (targetAura->GetSpellInfo()->SpellFamilyFlags[0] & 0x40) tickcount = 6; addhealth += tickheal * tickcount; // Glyph of Swiftmend if (!unitCaster->HasAura(54824)) unitTarget->RemoveAura(targetAura->GetId(), targetAura->GetCasterGUID()); } // Death Pact - return pct of max health to caster else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_DEATHKNIGHT && m_spellInfo->SpellFamilyFlags[0] & 0x00080000) addhealth = unitCaster->SpellHealingBonusDone(unitTarget, m_spellInfo, int32(unitCaster->CountPctFromMaxHealth(damage)), HEAL, *effectInfo, { }); else addhealth = unitCaster->SpellHealingBonusDone(unitTarget, m_spellInfo, addhealth, HEAL, *effectInfo, { }); addhealth = unitTarget->SpellHealingBonusTaken(unitCaster, m_spellInfo, addhealth, HEAL); // Remove Grievious bite if fully healed if (unitTarget->HasAura(48920) && (unitTarget->GetHealth() + addhealth >= unitTarget->GetMaxHealth())) unitTarget->RemoveAura(48920); m_healing += addhealth; } void Spell::EffectHealPct() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || !unitTarget->IsAlive() || damage < 0) return; uint32 heal = unitTarget->CountPctFromMaxHealth(damage); if (Unit* unitCaster = GetUnitCasterForEffectHandlers()) { heal = unitCaster->SpellHealingBonusDone(unitTarget, m_spellInfo, heal, HEAL, *effectInfo, { }); heal = unitTarget->SpellHealingBonusTaken(unitCaster, m_spellInfo, heal, HEAL); } m_healing += heal; } void Spell::EffectHealMechanical() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || !unitTarget->IsAlive() || damage < 0) return; uint32 heal = damage; if (Unit* unitCaster = GetUnitCasterForEffectHandlers()) { heal = unitCaster->SpellHealingBonusDone(unitTarget, m_spellInfo, heal, HEAL, *effectInfo, { }); heal = unitTarget->SpellHealingBonusTaken(unitCaster, m_spellInfo, heal, HEAL); } m_healing += heal; } void Spell::EffectHealthLeech() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || !unitTarget->IsAlive() || damage < 0) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (unitCaster) { damage = unitCaster->SpellDamageBonusDone(unitTarget, m_spellInfo, uint32(damage), SPELL_DIRECT_DAMAGE, *effectInfo, { }); damage = unitTarget->SpellDamageBonusTaken(unitCaster, m_spellInfo, uint32(damage), SPELL_DIRECT_DAMAGE); } TC_LOG_DEBUG("spells", "HealthLeech :%i", damage); float healMultiplier = effectInfo->CalcValueMultiplier(unitCaster, this); m_damage += damage; DamageInfo damageInfo(unitCaster, unitTarget, damage, m_spellInfo, m_spellInfo->GetSchoolMask(), SPELL_DIRECT_DAMAGE, BASE_ATTACK); Unit::CalcAbsorbResist(damageInfo); uint32 const absorb = damageInfo.GetAbsorb(); damage -= absorb; // get max possible damage, don't count overkill for heal uint32 healthGain = uint32(-unitTarget->GetHealthGain(-damage) * healMultiplier); if (unitCaster && unitCaster->IsAlive()) { healthGain = unitCaster->SpellHealingBonusDone(unitCaster, m_spellInfo, healthGain, HEAL, *effectInfo, { }); healthGain = unitCaster->SpellHealingBonusTaken(unitCaster, m_spellInfo, healthGain, HEAL); HealInfo healInfo(unitCaster, unitCaster, healthGain, m_spellInfo, m_spellSchoolMask); unitCaster->HealBySpell(healInfo); } } void Spell::DoCreateItem(uint32 itemId) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = unitTarget->ToPlayer(); uint32 newitemid = itemId; ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(newitemid); if (!pProto) { player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } // bg reward have some special in code work uint32 bgType = 0; switch (m_spellInfo->Id) { case SPELL_AV_MARK_WINNER: case SPELL_AV_MARK_LOSER: bgType = BATTLEGROUND_AV; break; case SPELL_WS_MARK_WINNER: case SPELL_WS_MARK_LOSER: bgType = BATTLEGROUND_WS; break; case SPELL_AB_MARK_WINNER: case SPELL_AB_MARK_LOSER: bgType = BATTLEGROUND_AB; break; default: break; } uint32 num_to_add = damage; if (num_to_add < 1) num_to_add = 1; if (num_to_add > pProto->GetMaxStackSize()) num_to_add = pProto->GetMaxStackSize(); /* == gem perfection handling == */ // the chance of getting a perfect result float perfectCreateChance = 0.0f; // the resulting perfect item if successful uint32 perfectItemType = itemId; // get perfection capability and chance if (CanCreatePerfectItem(player, m_spellInfo->Id, perfectCreateChance, perfectItemType)) if (roll_chance_f(perfectCreateChance)) // if the roll succeeds... newitemid = perfectItemType; // the perfect item replaces the regular one /* == gem perfection handling over == */ /* == profession specialization handling == */ // init items_count to 1, since 1 item will be created regardless of specialization int items_count=1; // the chance to create additional items float additionalCreateChance=0.0f; // the maximum number of created additional items uint8 additionalMaxNum=0; // get the chance and maximum number for creating extra items if (CanCreateExtraItems(player, m_spellInfo->Id, additionalCreateChance, additionalMaxNum)) // roll with this chance till we roll not to create or we create the max num while (roll_chance_f(additionalCreateChance) && items_count <= additionalMaxNum) ++items_count; // really will be created more items num_to_add *= items_count; /* == profession specialization handling over == */ // can the player store the new item? ItemPosCountVec dest; uint32 no_space = 0; InventoryResult msg = player->CanStoreNewItem(NULL_BAG, NULL_SLOT, dest, newitemid, num_to_add, &no_space); if (msg != EQUIP_ERR_OK) { // convert to possible store amount if (msg == EQUIP_ERR_INVENTORY_FULL || msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS) num_to_add -= no_space; else { // if not created by another reason from full inventory or unique items amount limitation player->SendEquipError(msg, nullptr, nullptr, newitemid); return; } } if (num_to_add) { // create the new item and store it Item* pItem = player->StoreNewItem(dest, newitemid, true, GenerateItemRandomPropertyId(newitemid)); // was it successful? return error if not if (!pItem) { player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } // set the "Crafted by ..." property of the item if (pItem->GetTemplate()->HasSignature()) pItem->SetGuidValue(ITEM_FIELD_CREATOR, player->GetGUID()); // send info to the client player->SendNewItem(pItem, num_to_add, true, bgType == 0); // we succeeded in creating at least one item, so a levelup is possible if (bgType == 0) player->UpdateCraftSkill(m_spellInfo->Id); } /* // for battleground marks send by mail if not add all expected if (no_space > 0 && bgType) { if (Battleground* bg = sBattlegroundMgr->GetBattlegroundTemplate(BattlegroundTypeId(bgType))) bg->SendRewardMarkByMail(player, newitemid, no_space); } */ } void Spell::EffectCreateItem() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; DoCreateItem(effectInfo->ItemType); ExecuteLogEffectCreateItem(effectInfo->EffectIndex, effectInfo->ItemType); } void Spell::EffectCreateItem2() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = unitTarget->ToPlayer(); // Pick a random item from spell_loot_template if (m_spellInfo->IsLootCrafting()) { player->AutoStoreLoot(m_spellInfo->Id, LootTemplates_Spell, false, true); player->UpdateCraftSkill(m_spellInfo->Id); } else // If there's no random loot entries for this spell, pick the item associated with this spell { uint32 item_id = effectInfo->ItemType; if (item_id) DoCreateItem(item_id); } /// @todo ExecuteLogEffectCreateItem(effectInfo->EffectIndex, effectInfo->ItemType); } void Spell::EffectCreateRandomItem() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = unitTarget->ToPlayer(); // create some random items player->AutoStoreLoot(m_spellInfo->Id, LootTemplates_Spell); /// @todo ExecuteLogEffectCreateItem(effectInfo->EffectIndex, effectInfo->ItemType); } void Spell::EffectPersistentAA() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; // only handle at last effect for (size_t i = effectInfo->EffectIndex + 1; i < m_spellInfo->GetEffects().size(); ++i) if (m_spellInfo->GetEffect(SpellEffIndex(i)).IsEffect(SPELL_EFFECT_PERSISTENT_AREA_AURA)) return; ASSERT(!_dynObjAura); float radius = effectInfo->CalcRadius(unitCaster); // Caster not in world, might be spell triggered from aura removal if (!unitCaster->IsInWorld()) return; DynamicObject* dynObj = new DynamicObject(false); if (!dynObj->CreateDynamicObject(unitCaster->GetMap()->GenerateLowGuid<HighGuid::DynamicObject>(), unitCaster, m_spellInfo->Id, *destTarget, radius, DYNAMIC_OBJECT_AREA_SPELL)) { delete dynObj; return; } AuraCreateInfo createInfo(m_spellInfo, MAX_EFFECT_MASK, dynObj); createInfo .SetCaster(unitCaster) .SetBaseAmount(m_spellValue->EffectBasePoints); if (Aura* aura = Aura::TryCreate(createInfo)) { _dynObjAura = aura->ToDynObjAura(); _dynObjAura->_RegisterForTargets(); } else return; ASSERT(_dynObjAura->GetDynobjOwner()); _dynObjAura->_ApplyEffectForTargets(effectInfo->EffectIndex); } void Spell::EffectEnergize() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster || !unitTarget) return; if (!unitTarget->IsAlive()) return; if (effectInfo->MiscValue < 0 || effectInfo->MiscValue >= int8(MAX_POWERS)) return; Powers power = Powers(effectInfo->MiscValue); if (unitTarget->GetTypeId() == TYPEID_PLAYER && unitTarget->GetPowerType() != power && m_spellInfo->SpellFamilyName != SPELLFAMILY_POTION && !m_spellInfo->HasAttribute(SPELL_ATTR7_CAN_RESTORE_SECONDARY_POWER)) return; if (unitTarget->GetMaxPower(power) == 0) return; // Some level depends spells ///@todo: move this to scripts int32 level_multiplier = 0; int32 level_diff = 0; switch (m_spellInfo->Id) { case 9512: // Restore Energy level_diff = unitCaster->GetLevel() - 40; level_multiplier = 2; break; case 24571: // Blood Fury level_diff = unitCaster->GetLevel() - 60; level_multiplier = 10; break; case 24532: // Burst of Energy level_diff = unitCaster->GetLevel() - 60; level_multiplier = 4; break; case 31930: // Judgements of the Wise case 63375: // Improved Stormstrike case 68082: // Glyph of Seal of Command damage = int32(CalculatePct(unitTarget->GetCreateMana(), damage)); break; case 48542: // Revitalize damage = int32(CalculatePct(unitTarget->GetMaxPower(power), damage)); break; case 67490: // Runic Mana Injector (mana gain increased by 25% for engineers - 3.2.0 patch change) { if (Player* player = unitCaster->ToPlayer()) if (player->HasSkill(SKILL_ENGINEERING)) AddPct(damage, 25); break; } case 71132: // Glyph of Shadow Word: Pain damage = int32(CalculatePct(unitTarget->GetCreateMana(), 1)); // set 1 as value, missing in dbc break; default: break; } if (level_diff > 0) damage -= level_multiplier * level_diff; if (damage < 0) return; unitCaster->EnergizeBySpell(unitTarget, m_spellInfo, damage, power); } void Spell::EffectEnergizePct() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster || !unitTarget) return; if (!unitTarget->IsAlive()) return; if (effectInfo->MiscValue < 0 || effectInfo->MiscValue >= int8(MAX_POWERS)) return; Powers power = Powers(effectInfo->MiscValue); if (unitTarget->GetTypeId() == TYPEID_PLAYER && unitTarget->GetPowerType() != power && !m_spellInfo->HasAttribute(SPELL_ATTR7_CAN_RESTORE_SECONDARY_POWER)) return; uint32 maxPower = unitTarget->GetMaxPower(power); if (!maxPower) return; uint32 const gain = CalculatePct(maxPower, damage); unitCaster->EnergizeBySpell(unitTarget, m_spellInfo, gain, power); } void Spell::SendLoot(ObjectGuid guid, LootType loottype) { Player* player = m_caster->ToPlayer(); if (!player) return; if (gameObjTarget) { // Players shouldn't be able to loot gameobjects that are currently despawned if (!gameObjTarget->isSpawned() && !player->IsGameMaster()) { TC_LOG_ERROR("entities.player.cheat", "Possible hacking attempt: Player %s %s tried to loot a gameobject %s which is on respawn timer without being in GM mode!", player->GetName().c_str(), player->GetGUID().ToString().c_str(), gameObjTarget->GetGUID().ToString().c_str()); return; } // special case, already has GossipHello inside so return and avoid calling twice if (gameObjTarget->GetGoType() == GAMEOBJECT_TYPE_GOOBER) { gameObjTarget->Use(player); return; } player->PlayerTalkClass->ClearMenus(); #ifdef ELUNA if (sEluna->OnGossipHello(player, gameObjTarget)) return; if (sEluna->OnGameObjectUse(player, gameObjTarget)) return; #endif if (gameObjTarget->AI()->OnGossipHello(player)) return; switch (gameObjTarget->GetGoType()) { case GAMEOBJECT_TYPE_DOOR: case GAMEOBJECT_TYPE_BUTTON: gameObjTarget->UseDoorOrButton(0, false, player); return; case GAMEOBJECT_TYPE_QUESTGIVER: player->PrepareGossipMenu(gameObjTarget, gameObjTarget->GetGOInfo()->questgiver.gossipID, true); player->SendPreparedGossip(gameObjTarget); return; case GAMEOBJECT_TYPE_SPELL_FOCUS: // triggering linked GO if (uint32 trapEntry = gameObjTarget->GetGOInfo()->spellFocus.linkedTrapId) gameObjTarget->TriggeringLinkedGameObject(trapEntry, player); return; case GAMEOBJECT_TYPE_CHEST: /// @todo possible must be moved to loot release (in different from linked triggering) if (gameObjTarget->GetGOInfo()->chest.eventId) { TC_LOG_DEBUG("spells", "Chest ScriptStart id %u for GO %u", gameObjTarget->GetGOInfo()->chest.eventId, gameObjTarget->GetSpawnId()); player->GetMap()->ScriptsStart(sEventScripts, gameObjTarget->GetGOInfo()->chest.eventId, player, gameObjTarget); } // triggering linked GO if (uint32 trapEntry = gameObjTarget->GetGOInfo()->chest.linkedTrapId) gameObjTarget->TriggeringLinkedGameObject(trapEntry, player); // Don't return, let loots been taken break; default: break; } } // Send loot player->SendLoot(guid, loottype); } void Spell::EffectOpenLock() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (m_caster->GetTypeId() != TYPEID_PLAYER) { TC_LOG_DEBUG("spells", "WORLD: Open Lock - No Player Caster!"); return; } Player* player = m_caster->ToPlayer(); uint32 lockId = 0; ObjectGuid guid; // Get lockId if (gameObjTarget) { GameObjectTemplate const* goInfo = gameObjTarget->GetGOInfo(); if (goInfo->CannotBeUsedUnderImmunity() && m_caster->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE)) return; // Arathi Basin banner opening. /// @todo Verify correctness of this check if ((goInfo->type == GAMEOBJECT_TYPE_BUTTON && goInfo->button.noDamageImmune) || (goInfo->type == GAMEOBJECT_TYPE_GOOBER && goInfo->goober.losOK)) { //CanUseBattlegroundObject() already called in CheckCast() // in battleground check if (Battleground* bg = player->GetBattleground()) { bg->EventPlayerClickedOnFlag(player, gameObjTarget); return; } } else if (goInfo->type == GAMEOBJECT_TYPE_FLAGSTAND) { //CanUseBattlegroundObject() already called in CheckCast() // in battleground check if (Battleground* bg = player->GetBattleground()) { if (bg->GetTypeID(true) == BATTLEGROUND_EY) bg->EventPlayerClickedOnFlag(player, gameObjTarget); return; } } else if (m_spellInfo->Id == 1842 && gameObjTarget->GetGOInfo()->type == GAMEOBJECT_TYPE_TRAP && gameObjTarget->GetOwner()) { gameObjTarget->SetLootState(GO_JUST_DEACTIVATED); return; } /// @todo Add script for spell 41920 - Filling, becouse server it freze when use this spell // handle outdoor pvp object opening, return true if go was registered for handling // these objects must have been spawned by outdoorpvp! else if (gameObjTarget->GetGOInfo()->type == GAMEOBJECT_TYPE_GOOBER && sOutdoorPvPMgr->HandleOpenGo(player, gameObjTarget)) return; lockId = goInfo->GetLockId(); guid = gameObjTarget->GetGUID(); } else if (itemTarget) { lockId = itemTarget->GetTemplate()->LockID; guid = itemTarget->GetGUID(); } else { TC_LOG_DEBUG("spells", "WORLD: Open Lock - No GameObject/Item Target!"); return; } SkillType skillId = SKILL_NONE; int32 reqSkillValue = 0; int32 skillValue; SpellCastResult res = CanOpenLock(*effectInfo, lockId, skillId, reqSkillValue, skillValue); if (res != SPELL_CAST_OK) { SendCastResult(res); return; } if (gameObjTarget) SendLoot(guid, LOOT_SKINNING); else if (itemTarget) { itemTarget->SetFlag(ITEM_FIELD_FLAGS, ITEM_FIELD_FLAG_UNLOCKED); itemTarget->SetState(ITEM_CHANGED, itemTarget->GetOwner()); } // not allow use skill grow at item base open if (!m_CastItem && skillId != SKILL_NONE) { // update skill if really known if (uint32 pureSkillValue = player->GetPureSkillValue(skillId)) { if (gameObjTarget) { // Allow one skill-up until respawned if (!gameObjTarget->IsInSkillupList(player->GetGUID().GetCounter()) && player->UpdateGatherSkill(skillId, pureSkillValue, reqSkillValue)) gameObjTarget->AddToSkillupList(player->GetGUID().GetCounter()); } else if (itemTarget) { // Do one skill-up player->UpdateGatherSkill(skillId, pureSkillValue, reqSkillValue); } } } ExecuteLogEffectOpenLock(effectInfo->EffectIndex, gameObjTarget ? (Object*)gameObjTarget : (Object*)itemTarget); } void Spell::EffectSummonChangeItem() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player* player = m_caster->ToPlayer(); // applied only to using item if (!m_CastItem) return; // ... only to item in own inventory/bank/equip_slot if (m_CastItem->GetOwnerGUID() != player->GetGUID()) return; uint32 newitemid = effectInfo->ItemType; if (!newitemid) return; uint16 pos = m_CastItem->GetPos(); Item* pNewItem = Item::CreateItem(newitemid, 1, player); if (!pNewItem) return; for (uint8 j = PERM_ENCHANTMENT_SLOT; j <= TEMP_ENCHANTMENT_SLOT; ++j) if (m_CastItem->GetEnchantmentId(EnchantmentSlot(j))) pNewItem->SetEnchantment(EnchantmentSlot(j), m_CastItem->GetEnchantmentId(EnchantmentSlot(j)), m_CastItem->GetEnchantmentDuration(EnchantmentSlot(j)), m_CastItem->GetEnchantmentCharges(EnchantmentSlot(j))); if (m_CastItem->GetUInt32Value(ITEM_FIELD_DURABILITY) < m_CastItem->GetUInt32Value(ITEM_FIELD_MAXDURABILITY)) { double lossPercent = 1 - m_CastItem->GetUInt32Value(ITEM_FIELD_DURABILITY) / double(m_CastItem->GetUInt32Value(ITEM_FIELD_MAXDURABILITY)); player->DurabilityLoss(pNewItem, lossPercent); } if (player->IsInventoryPos(pos)) { ItemPosCountVec dest; InventoryResult msg = player->CanStoreItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), dest, pNewItem, true); if (msg == EQUIP_ERR_OK) { player->DestroyItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), true); // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.GetItemTarget()) m_targets.SetItemTarget(nullptr); m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; player->StoreItem(dest, pNewItem, true); player->SendNewItem(pNewItem, 1, true, false); player->ItemAddedQuestCheck(newitemid, 1); return; } } else if (player->IsBankPos(pos)) { ItemPosCountVec dest; if (player->CanBankItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), dest, pNewItem, true) == EQUIP_ERR_OK) { player->DestroyItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), true); // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.GetItemTarget()) m_targets.SetItemTarget(nullptr); m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; player->BankItem(dest, pNewItem, true); return; } } else if (player->IsEquipmentPos(pos)) { uint16 dest; player->DestroyItem(m_CastItem->GetBagSlot(), m_CastItem->GetSlot(), true); InventoryResult msg = player->CanEquipItem(m_CastItem->GetSlot(), dest, pNewItem, true); if (msg == EQUIP_ERR_OK || msg == EQUIP_ERR_CANT_DO_RIGHT_NOW) { if (msg == EQUIP_ERR_CANT_DO_RIGHT_NOW) dest = EQUIPMENT_SLOT_MAINHAND; // prevent crash at access and unexpected charges counting with item update queue corrupt if (m_CastItem == m_targets.GetItemTarget()) m_targets.SetItemTarget(nullptr); m_CastItem = nullptr; m_castItemGUID.Clear(); m_castItemEntry = 0; player->EquipItem(dest, pNewItem, true); player->AutoUnequipOffhandIfNeed(); player->SendNewItem(pNewItem, 1, true, false); player->ItemAddedQuestCheck(newitemid, 1); return; } } // fail delete pNewItem; } void Spell::EffectProficiency() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player* p_target = m_caster->ToPlayer(); uint32 subClassMask = m_spellInfo->EquippedItemSubClassMask; if (m_spellInfo->EquippedItemClass == ITEM_CLASS_WEAPON && !(p_target->GetWeaponProficiency() & subClassMask)) { p_target->AddWeaponProficiency(subClassMask); p_target->SendProficiency(ITEM_CLASS_WEAPON, p_target->GetWeaponProficiency()); } if (m_spellInfo->EquippedItemClass == ITEM_CLASS_ARMOR && !(p_target->GetArmorProficiency() & subClassMask)) { p_target->AddArmorProficiency(subClassMask); p_target->SendProficiency(ITEM_CLASS_ARMOR, p_target->GetArmorProficiency()); } } void Spell::EffectSummonType() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; uint32 entry = effectInfo->MiscValue; if (!entry) return; SummonPropertiesEntry const* properties = sSummonPropertiesStore.LookupEntry(effectInfo->MiscValueB); if (!properties) { TC_LOG_ERROR("spells", "EffectSummonType: Unhandled summon type %u.", effectInfo->MiscValueB); return; } WorldObject* caster = m_caster; if (m_originalCaster) caster = m_originalCaster; bool personalSpawn = (properties->Flags & SUMMON_PROP_FLAG_PERSONAL_SPAWN) != 0; int32 duration = m_spellInfo->GetDuration(); if (Player* modOwner = caster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); Unit* unitCaster = GetUnitCasterForEffectHandlers(); TempSummon* summon = nullptr; // determine how many units should be summoned uint32 numSummons; // some spells need to summon many units, for those spells number of summons is stored in effect value // however so far noone found a generic check to find all of those (there's no related data in summonproperties.dbc // and in spell attributes, possibly we need to add a table for those) // so here's a list of MiscValueB values, which is currently most generic check switch (properties->ID) { case 64: case 61: case 1101: case 66: case 648: case 2301: case 1061: case 1261: case 629: case 181: case 715: case 1562: case 833: case 1161: case 713: numSummons = (damage > 0) ? damage : 1; break; default: numSummons = 1; break; } switch (properties->Control) { case SUMMON_CATEGORY_WILD: case SUMMON_CATEGORY_ALLY: case SUMMON_CATEGORY_UNK: { if (properties->Flags & 512) { SummonGuardian(*effectInfo, entry, properties, numSummons); break; } switch (properties->Title) { case SUMMON_TYPE_PET: case SUMMON_TYPE_GUARDIAN: case SUMMON_TYPE_GUARDIAN2: case SUMMON_TYPE_MINION: SummonGuardian(*effectInfo, entry, properties, numSummons); break; // Summons a vehicle, but doesn't force anyone to enter it (see SUMMON_CATEGORY_VEHICLE) case SUMMON_TYPE_VEHICLE: case SUMMON_TYPE_VEHICLE2: { if (!unitCaster) return; summon = unitCaster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, unitCaster, m_spellInfo->Id); break; } case SUMMON_TYPE_LIGHTWELL: case SUMMON_TYPE_TOTEM: { if (!unitCaster) return; summon = unitCaster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, unitCaster, m_spellInfo->Id, 0, personalSpawn); if (!summon || !summon->IsTotem()) return; // Mana Tide Totem if (m_spellInfo->Id == 16190) damage = unitCaster->CountPctFromMaxHealth(10); if (damage) // if not spell info, DB values used { summon->SetMaxHealth(damage); summon->SetHealth(damage); } break; } case SUMMON_TYPE_MINIPET: { if (!unitCaster) return; summon = unitCaster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, unitCaster, m_spellInfo->Id, 0, personalSpawn); if (!summon || !summon->HasUnitTypeMask(UNIT_MASK_MINION)) return; summon->SelectLevel(); // some summoned creaters have different from 1 DB data for level/hp summon->SetUInt32Value(UNIT_NPC_FLAGS, summon->GetCreatureTemplate()->npcflag); summon->SetImmuneToAll(true); break; } default: { float radius = effectInfo->CalcRadius(); TempSummonType summonType = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN; for (uint32 count = 0; count < numSummons; ++count) { Position pos; if (count == 0) pos = *destTarget; else // randomize position for multiple summons pos = caster->GetRandomPoint(*destTarget, radius); summon = caster->SummonCreature(entry, pos, summonType, Milliseconds(duration), 0, m_spellInfo->Id, personalSpawn); if (!summon) continue; if (properties->Control == SUMMON_CATEGORY_ALLY) { summon->SetOwnerGUID(caster->GetGUID()); summon->SetFaction(caster->GetFaction()); } ExecuteLogEffectSummonObject(effectInfo->EffectIndex, summon); } return; } } break; } case SUMMON_CATEGORY_PET: SummonGuardian(*effectInfo, entry, properties, numSummons); break; case SUMMON_CATEGORY_PUPPET: { if (!unitCaster) return; summon = unitCaster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, unitCaster, m_spellInfo->Id, 0, personalSpawn); break; } case SUMMON_CATEGORY_VEHICLE: { if (!unitCaster) return; // Summoning spells (usually triggered by npc_spellclick) that spawn a vehicle and that cause the clicker // to cast a ride vehicle spell on the summoned unit. summon = unitCaster->GetMap()->SummonCreature(entry, *destTarget, properties, duration, unitCaster, m_spellInfo->Id); if (!summon || !summon->IsVehicle()) return; // The spell that this effect will trigger. It has SPELL_AURA_CONTROL_VEHICLE uint32 spellId = VEHICLE_SPELL_RIDE_HARDCODED; int32 basePoints = effectInfo->CalcValue(); if (basePoints > MAX_VEHICLE_SEATS) { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(basePoints); if (spellInfo && spellInfo->HasAura(SPELL_AURA_CONTROL_VEHICLE)) spellId = spellInfo->Id; } CastSpellExtraArgs args(TRIGGERED_FULL_MASK); // if we have small value, it indicates seat position if (basePoints > 0 && basePoints < MAX_VEHICLE_SEATS) args.AddSpellMod(SPELLVALUE_BASE_POINT0, basePoints); unitCaster->CastSpell(summon, spellId, args); uint32 faction = properties->Faction; if (!faction) faction = unitCaster->GetFaction(); summon->SetFaction(faction); break; } } if (summon) { summon->SetCreatorGUID(caster->GetGUID()); ExecuteLogEffectSummonObject(effectInfo->EffectIndex, summon); } } void Spell::EffectLearnSpell() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; if (unitTarget->GetTypeId() != TYPEID_PLAYER) { if (unitTarget->ToPet()) EffectLearnPetSpell(); return; } Player* player = unitTarget->ToPlayer(); uint32 spellToLearn = (m_spellInfo->Id == 483 || m_spellInfo->Id == 55884) ? damage : effectInfo->TriggerSpell; player->LearnSpell(spellToLearn, false); TC_LOG_DEBUG("spells", "Spell: Player %s has learned spell %u from Npc %s", player->GetGUID().ToString().c_str(), spellToLearn, m_caster->GetGUID().ToString().c_str()); } void Spell::EffectDispel() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; // Create dispel mask by dispel type uint32 dispel_type = effectInfo->MiscValue; uint32 dispelMask = SpellInfo::GetDispelMask(DispelType(dispel_type)); DispelChargesList dispelList; unitTarget->GetDispellableAuraList(m_caster, dispelMask, dispelList, targetMissInfo == SPELL_MISS_REFLECT); if (dispelList.empty()) return; size_t remaining = dispelList.size(); // Ok if exist some buffs for dispel try dispel it uint32 failCount = 0; DispelChargesList successList; successList.reserve(damage); WorldPacket dataFail(SMSG_DISPEL_FAILED, 8 + 8 + 4 + 4 + damage * 4); // dispel N = damage buffs (or while exist buffs for dispel) for (int32 count = 0; count < damage && remaining > 0;) { // Random select buff for dispel auto itr = dispelList.begin(); std::advance(itr, urand(0, remaining - 1)); if (itr->RollDispel()) { auto successItr = std::find_if(successList.begin(), successList.end(), [&itr](DispelableAura& dispelAura) -> bool { if (dispelAura.GetAura()->GetId() == itr->GetAura()->GetId() && dispelAura.GetAura()->GetCaster() == itr->GetAura()->GetCaster()) return true; return false; }); if (successItr == successList.end()) successList.emplace_back(itr->GetAura(), 0, 1); else successItr->IncrementCharges(); if (!itr->DecrementCharge()) { --remaining; std::swap(*itr, dispelList[remaining]); } } else { if (!failCount) { // Failed to dispell dataFail << uint64(m_caster->GetGUID()); // Caster GUID dataFail << uint64(unitTarget->GetGUID()); // Victim GUID dataFail << uint32(m_spellInfo->Id); // dispel spell id } ++failCount; dataFail << uint32(itr->GetAura()->GetId()); // Spell Id } ++count; } if (failCount) m_caster->SendMessageToSet(&dataFail, true); if (successList.empty()) return; WorldPacket dataSuccess(SMSG_SPELLDISPELLOG, 8 + 8 + 4 + 1 + 4 + successList.size() * 5); // Send packet header dataSuccess << unitTarget->GetPackGUID(); // Victim GUID dataSuccess << m_caster->GetPackGUID(); // Caster GUID dataSuccess << uint32(m_spellInfo->Id); // dispel spell id dataSuccess << uint8(0); // not used dataSuccess << uint32(successList.size()); // count for (DispelChargesList::iterator itr = successList.begin(); itr != successList.end(); ++itr) { // Send dispelled spell info dataSuccess << uint32(itr->GetAura()->GetId()); // Spell Id dataSuccess << uint8(0); // 0 - dispelled !=0 cleansed unitTarget->RemoveAurasDueToSpellByDispel(itr->GetAura()->GetId(), m_spellInfo->Id, itr->GetAura()->GetCasterGUID(), m_caster, itr->GetDispelCharges()); } m_caster->SendMessageToSet(&dataSuccess, true); // On success dispel // Devour Magic if (m_spellInfo->SpellFamilyName == SPELLFAMILY_WARLOCK && m_spellInfo->GetCategory() == SPELLCATEGORY_DEVOUR_MAGIC) { CastSpellExtraArgs args(TRIGGERED_FULL_MASK); args.AddSpellMod(SPELLVALUE_BASE_POINT0, m_spellInfo->GetEffect(EFFECT_1).CalcValue()); m_caster->CastSpell(m_caster, 19658, args); // Glyph of Felhunter if (Unit* owner = m_caster->GetOwner()) if (owner->GetAura(56249)) owner->CastSpell(owner, 19658, args); } } void Spell::EffectDualWield() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; unitTarget->SetCanDualWield(true); } void Spell::EffectPull() { /// @todo create a proper pull towards distract spell center for distract EffectNULL(); } void Spell::EffectDistract() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; // Check for possible target if (!unitTarget || unitTarget->IsEngaged()) return; // target must be OK to do this if (unitTarget->HasUnitState(UNIT_STATE_CONFUSED | UNIT_STATE_STUNNED | UNIT_STATE_FLEEING)) return; unitTarget->GetMotionMaster()->MoveDistract(damage * IN_MILLISECONDS, unitTarget->GetAbsoluteAngle(destTarget)); } void Spell::EffectPickPocket() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (m_caster->GetTypeId() != TYPEID_PLAYER) return; // victim must be creature and attackable if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT || m_caster->IsFriendlyTo(unitTarget)) return; // victim have to be alive and humanoid or undead if (unitTarget->IsAlive() && (unitTarget->GetCreatureTypeMask() &CREATURE_TYPEMASK_HUMANOID_OR_UNDEAD) != 0) m_caster->ToPlayer()->SendLoot(unitTarget->GetGUID(), LOOT_PICKPOCKETING); } void Spell::EffectAddFarsight() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; Player* player = m_caster->ToPlayer(); if (!player) return; float radius = effectInfo->CalcRadius(); int32 duration = m_spellInfo->GetDuration(); // Caster not in world, might be spell triggered from aura removal if (!player->IsInWorld()) return; DynamicObject* dynObj = new DynamicObject(true); if (!dynObj->CreateDynamicObject(player->GetMap()->GenerateLowGuid<HighGuid::DynamicObject>(), player, m_spellInfo->Id, *destTarget, radius, DYNAMIC_OBJECT_FARSIGHT_FOCUS)) { delete dynObj; return; } dynObj->SetDuration(duration); dynObj->SetCasterViewpoint(); } void Spell::EffectUntrainTalents() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || m_caster->GetTypeId() == TYPEID_PLAYER) return; if (ObjectGuid guid = m_caster->GetGUID()) // the trainer is the caster unitTarget->ToPlayer()->SendTalentWipeConfirm(guid); } void Spell::EffectTeleUnitsFaceCaster() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; if (unitTarget->IsInFlight()) return; if (m_targets.HasDst()) unitTarget->NearTeleportTo(destTarget->GetPositionX(), destTarget->GetPositionY(), destTarget->GetPositionZ(), destTarget->GetAbsoluteAngle(m_caster), unitTarget == m_caster); } void Spell::EffectLearnSkill() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; if (damage < 0) return; uint32 skillid = effectInfo->MiscValue; SkillRaceClassInfoEntry const* rcEntry = GetSkillRaceClassInfo(skillid, unitTarget->GetRace(), unitTarget->GetClass()); if (!rcEntry) return; SkillTiersEntry const* tier = sSkillTiersStore.LookupEntry(rcEntry->SkillTierID); if (!tier) return; uint16 skillval = unitTarget->ToPlayer()->GetPureSkillValue(skillid); unitTarget->ToPlayer()->SetSkill(skillid, effectInfo->CalcValue(), std::max<uint16>(skillval, 1), tier->Value[damage - 1]); } void Spell::EffectAddHonor() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; // not scale value for item based reward (/10 value expected) if (m_CastItem) { unitTarget->ToPlayer()->RewardHonor(nullptr, 1, damage/10); TC_LOG_DEBUG("spells", "SpellEffect::AddHonor (spell_id %u) rewards %d honor points (item %u) for player %s", m_spellInfo->Id, damage/10, m_CastItem->GetEntry(), unitTarget->ToPlayer()->GetGUID().ToString().c_str()); return; } // do not allow to add too many honor for player (50 * 21) = 1040 at level 70, or (50 * 31) = 1550 at level 80 if (damage <= 50) { uint32 honor_reward = Trinity::Honor::hk_honor_at_level(unitTarget->GetLevel(), float(damage)); unitTarget->ToPlayer()->RewardHonor(nullptr, 1, honor_reward); TC_LOG_DEBUG("spells", "SpellEffect::AddHonor (spell_id %u) rewards %u honor points (scale) to player %s", m_spellInfo->Id, honor_reward, unitTarget->ToPlayer()->GetGUID().ToString().c_str()); } else { //maybe we have correct honor_gain in damage already unitTarget->ToPlayer()->RewardHonor(nullptr, 1, damage); TC_LOG_DEBUG("spells", "SpellEffect::AddHonor (spell_id %u) rewards %u honor points (non scale) for player %s", m_spellInfo->Id, damage, unitTarget->ToPlayer()->GetGUID().ToString().c_str()); } } void Spell::EffectTradeSkill() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; if (m_caster->GetTypeId() != TYPEID_PLAYER) return; // uint32 skillid = effectInfo->MiscValue; // uint16 skillmax = unitTarget->ToPlayer()->(skillid); // m_caster->ToPlayer()->SetSkill(skillid, skillval?skillval:1, skillmax+75); } void Spell::EffectEnchantItemPerm() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!itemTarget) return; Player* player = m_caster->ToPlayer(); if (!player) return; // Handle vellums if (itemTarget->IsWeaponVellum() || itemTarget->IsArmorVellum()) { // destroy one vellum from stack uint32 count = 1; player->DestroyItemCount(itemTarget, count, true); unitTarget = player; // and add a scroll DoCreateItem(effectInfo->ItemType); itemTarget = nullptr; m_targets.SetItemTarget(nullptr); } else { // do not increase skill if vellum used if (!(m_CastItem && m_CastItem->GetTemplate()->HasFlag(ITEM_FLAG_NO_REAGENT_COST))) player->UpdateCraftSkill(m_spellInfo->Id); uint32 enchant_id = effectInfo->MiscValue; if (!enchant_id) return; SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) return; // item can be in trade slot and have owner diff. from caster Player* item_owner = itemTarget->GetOwner(); if (!item_owner) return; if (item_owner != player && player->GetSession()->HasPermission(rbac::RBAC_PERM_LOG_GM_TRADE)) { sLog->outCommand(player->GetSession()->GetAccountId(), "GM %s (Account: %u) enchanting(perm): %s (Entry: %d) for player: %s (Account: %u)", player->GetName().c_str(), player->GetSession()->GetAccountId(), itemTarget->GetTemplate()->Name1.c_str(), itemTarget->GetEntry(), item_owner->GetName().c_str(), item_owner->GetSession()->GetAccountId()); } // remove old enchanting before applying new if equipped item_owner->ApplyEnchantment(itemTarget, PERM_ENCHANTMENT_SLOT, false); itemTarget->SetEnchantment(PERM_ENCHANTMENT_SLOT, enchant_id, 0, 0, m_caster->GetGUID()); // add new enchanting if equipped item_owner->ApplyEnchantment(itemTarget, PERM_ENCHANTMENT_SLOT, true); item_owner->RemoveTradeableItem(itemTarget); itemTarget->ClearSoulboundTradeable(item_owner); } } void Spell::EffectEnchantItemPrismatic() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!itemTarget) return; Player* player = m_caster->ToPlayer(); if (!player) return; uint32 enchantId = effectInfo->MiscValue; if (!enchantId) return; SpellItemEnchantmentEntry const* enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId); if (!enchant) return; // support only enchantings with add socket in this slot { bool add_socket = false; for (uint8 i = 0; i < MAX_ITEM_ENCHANTMENT_EFFECTS; ++i) { if (enchant->Effect[i] == ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET) { add_socket = true; break; } } if (!add_socket) { TC_LOG_ERROR("spells", "Spell::EffectEnchantItemPrismatic: attempt to apply the enchant spell %u with SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC (%u), but without ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET (%u), not supported yet.", m_spellInfo->Id, SPELL_EFFECT_ENCHANT_ITEM_PRISMATIC, ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET); return; } } // item can be in trade slot and have owner diff. from caster Player* item_owner = itemTarget->GetOwner(); if (!item_owner) return; if (item_owner != player && player->GetSession()->HasPermission(rbac::RBAC_PERM_LOG_GM_TRADE)) { sLog->outCommand(player->GetSession()->GetAccountId(), "GM %s (Account: %u) enchanting(perm): %s (Entry: %d) for player: %s (Account: %u)", player->GetName().c_str(), player->GetSession()->GetAccountId(), itemTarget->GetTemplate()->Name1.c_str(), itemTarget->GetEntry(), item_owner->GetName().c_str(), item_owner->GetSession()->GetAccountId()); } // remove old enchanting before applying new if equipped item_owner->ApplyEnchantment(itemTarget, PRISMATIC_ENCHANTMENT_SLOT, false); itemTarget->SetEnchantment(PRISMATIC_ENCHANTMENT_SLOT, enchantId, 0, 0, m_caster->GetGUID()); // add new enchanting if equipped item_owner->ApplyEnchantment(itemTarget, PRISMATIC_ENCHANTMENT_SLOT, true); item_owner->RemoveTradeableItem(itemTarget); itemTarget->ClearSoulboundTradeable(item_owner); } void Spell::EffectEnchantItemTmp() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Player* player = m_caster->ToPlayer(); if (!player) return; // Rockbiter Weapon apply to both weapon if (!itemTarget) return; if (m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN && m_spellInfo->SpellFamilyFlags[0] & 0x400000) { uint32 spell_id = 0; // enchanting spell selected by calculated damage-per-sec stored in Effect[1] base value // Note: damage calculated (correctly) with rounding int32(float(v)) but // RW enchantments applied damage int32(float(v)+0.5), this create 0..1 difference sometime switch (damage) { // Rank 1 case 2: spell_id = 36744; break; // 0% [ 7% == 2, 14% == 2, 20% == 2] // Rank 2 case 4: spell_id = 36753; break; // 0% [ 7% == 4, 14% == 4] case 5: spell_id = 36751; break; // 20% // Rank 3 case 6: spell_id = 36754; break; // 0% [ 7% == 6, 14% == 6] case 7: spell_id = 36755; break; // 20% // Rank 4 case 9: spell_id = 36761; break; // 0% [ 7% == 6] case 10: spell_id = 36758; break; // 14% case 11: spell_id = 36760; break; // 20% default: TC_LOG_ERROR("spells", "Spell::EffectEnchantItemTmp: Damage %u not handled in S'RW.", damage); return; } SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id); if (!spellInfo) { TC_LOG_ERROR("spells", "Spell::EffectEnchantItemTmp: unknown spell id %i", spell_id); return; } for (int j = BASE_ATTACK; j <= OFF_ATTACK; ++j) { if (Item* item = player->GetWeaponForAttack(WeaponAttackType(j))) { if (item->IsFitToSpellRequirements(m_spellInfo)) { Spell* spell = new Spell(m_caster, spellInfo, TRIGGERED_FULL_MASK); SpellCastTargets targets; targets.SetItemTarget(item); spell->prepare(targets); } } } return; } uint32 enchant_id = effectInfo->MiscValue; if (!enchant_id) { TC_LOG_ERROR("spells", "Spell %u Effect %u (SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY) has enchanting id 0.", m_spellInfo->Id, uint32(effectInfo->EffectIndex)); return; } SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) { TC_LOG_ERROR("spells", "Spell %u Effect %u (SPELL_EFFECT_ENCHANT_ITEM_TEMPORARY) has a non-existing enchanting id %u ", m_spellInfo->Id, uint32(effectInfo->EffectIndex), enchant_id); return; } // select enchantment duration uint32 duration; // rogue family enchantments exception by duration if (m_spellInfo->Id == 38615) duration = 1800; // 30 mins // other rogue family enchantments always 1 hour (some have spell damage=0, but some have wrong data in EffBasePoints) else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_ROGUE) duration = 3600; // 1 hour // shaman family enchantments else if (m_spellInfo->SpellFamilyName == SPELLFAMILY_SHAMAN) duration = 1800; // 30 mins // other cases with this SpellVisual already selected else if (m_spellInfo->SpellVisual[0] == 215) duration = 1800; // 30 mins // some fishing pole bonuses except Glow Worm which lasts full hour else if (m_spellInfo->SpellVisual[0] == 563 && m_spellInfo->Id != 64401) duration = 600; // 10 mins // shaman rockbiter enchantments else if (m_spellInfo->SpellVisual[0] == 0) duration = 1800; // 30 mins else if (m_spellInfo->Id == 29702) duration = 300; // 5 mins else if (m_spellInfo->Id == 37360) duration = 300; // 5 mins // default case else duration = 3600; // 1 hour // item can be in trade slot and have owner diff. from caster Player* item_owner = itemTarget->GetOwner(); if (!item_owner) return; if (item_owner != player && player->GetSession()->HasPermission(rbac::RBAC_PERM_LOG_GM_TRADE)) { sLog->outCommand(player->GetSession()->GetAccountId(), "GM %s (Account: %u) enchanting(temp): %s (Entry: %d) for player: %s (Account: %u)", player->GetName().c_str(), player->GetSession()->GetAccountId(), itemTarget->GetTemplate()->Name1.c_str(), itemTarget->GetEntry(), item_owner->GetName().c_str(), item_owner->GetSession()->GetAccountId()); } // remove old enchanting before applying new if equipped item_owner->ApplyEnchantment(itemTarget, TEMP_ENCHANTMENT_SLOT, false); itemTarget->SetEnchantment(TEMP_ENCHANTMENT_SLOT, enchant_id, duration * 1000, 0, m_caster->GetGUID()); // add new enchanting if equipped item_owner->ApplyEnchantment(itemTarget, TEMP_ENCHANTMENT_SLOT, true); } void Spell::EffectTameCreature() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster || unitCaster->GetPetGUID()) return; if (!unitTarget) return; if (unitTarget->GetTypeId() != TYPEID_UNIT) return; Creature* creatureTarget = unitTarget->ToCreature(); if (creatureTarget->IsPet()) return; if (unitCaster->GetClass() != CLASS_HUNTER) return; // cast finish successfully //SendChannelUpdate(0); finish(); Pet* pet = unitCaster->CreateTamedPetFrom(creatureTarget, m_spellInfo->Id); if (!pet) // in very specific state like near world end/etc. return; // "kill" original creature creatureTarget->DespawnOrUnsummon(); uint8 level = (creatureTarget->GetLevel() < (unitCaster->GetLevel() - 5)) ? (unitCaster->GetLevel() - 5) : creatureTarget->GetLevel(); // prepare visual effect for levelup pet->SetUInt32Value(UNIT_FIELD_LEVEL, level - 1); // add to world pet->GetMap()->AddToMap(pet->ToCreature()); // visual effect for levelup pet->SetUInt32Value(UNIT_FIELD_LEVEL, level); // caster have pet now unitCaster->SetMinion(pet, true); pet->InitTalentForLevel(); if (unitCaster->GetTypeId() == TYPEID_PLAYER) { pet->SavePetToDB(PET_SAVE_AS_CURRENT); unitCaster->ToPlayer()->PetSpellInitialize(); } } void Spell::EffectSummonPet() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; Player* owner = nullptr; if (Unit* unitCaster = GetUnitCasterForEffectHandlers()) { owner = unitCaster->ToPlayer(); if (!owner && unitCaster->IsTotem()) owner = unitCaster->GetCharmerOrOwnerPlayerOrPlayerItself(); } uint32 petentry = effectInfo->MiscValue; if (!owner) { SummonPropertiesEntry const* properties = sSummonPropertiesStore.LookupEntry(67); if (properties) SummonGuardian(*effectInfo, petentry, properties, 1); return; } Pet* OldSummon = owner->GetPet(); // if pet requested type already exist if (OldSummon) { if (petentry == 0 || OldSummon->GetEntry() == petentry) { // pet in corpse state can't be summoned if (OldSummon->isDead()) return; ASSERT(OldSummon->GetMap() == owner->GetMap()); //OldSummon->GetMap()->Remove(OldSummon->ToCreature(), false); float px, py, pz; owner->GetClosePoint(px, py, pz, OldSummon->GetCombatReach()); OldSummon->NearTeleportTo(px, py, pz, OldSummon->GetOrientation()); //OldSummon->Relocate(px, py, pz, OldSummon->GetOrientation()); //OldSummon->SetMap(owner->GetMap()); //owner->GetMap()->Add(OldSummon->ToCreature()); if (OldSummon->getPetType() == SUMMON_PET) { OldSummon->SetHealth(OldSummon->GetMaxHealth()); OldSummon->SetPower(OldSummon->GetPowerType(), OldSummon->GetMaxPower(OldSummon->GetPowerType())); OldSummon->GetSpellHistory()->ResetAllCooldowns(); } if (owner->GetTypeId() == TYPEID_PLAYER && OldSummon->isControlled()) owner->ToPlayer()->PetSpellInitialize(); return; } if (owner->GetTypeId() == TYPEID_PLAYER) owner->ToPlayer()->RemovePet(OldSummon, PET_SAVE_NOT_IN_SLOT, false); else return; } float x, y, z; owner->GetClosePoint(x, y, z, owner->GetCombatReach()); Pet* pet = owner->SummonPet(petentry, x, y, z, owner->GetOrientation(), SUMMON_PET, 0); if (!pet) return; if (m_caster->GetTypeId() == TYPEID_UNIT) { if (m_caster->ToCreature()->IsTotem()) pet->SetReactState(REACT_AGGRESSIVE); else pet->SetReactState(REACT_DEFENSIVE); } pet->SetUInt32Value(UNIT_CREATED_BY_SPELL, m_spellInfo->Id); // generate new name for summon pet std::string new_name = sObjectMgr->GeneratePetName(petentry); if (!new_name.empty()) pet->SetName(new_name); ExecuteLogEffectSummonObject(effectInfo->EffectIndex, pet); } void Spell::EffectLearnPetSpell() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; if (unitTarget->ToPlayer()) { EffectLearnSpell(); return; } Pet* pet = unitTarget->ToPet(); if (!pet) return; SpellInfo const* learn_spellproto = sSpellMgr->GetSpellInfo(effectInfo->TriggerSpell); if (!learn_spellproto) return; pet->learnSpell(learn_spellproto->Id); pet->SavePetToDB(PET_SAVE_AS_CURRENT); pet->GetOwner()->PetSpellInitialize(); } void Spell::EffectTaunt() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; // this effect use before aura Taunt apply for prevent taunt already attacking target // for spell as marked "non effective at already attacking target" if (!unitTarget || unitTarget->IsTotem()) { SendCastResult(SPELL_FAILED_DONT_REPORT); return; } // Hand of Reckoning can hit some entities that can't have a threat list (including players' pets) if (m_spellInfo->Id == 62124) if (unitTarget->GetTypeId() != TYPEID_PLAYER && unitTarget->GetTarget() != unitCaster->GetGUID()) unitCaster->CastSpell(unitTarget, 67485, true); if (!unitTarget->CanHaveThreatList()) { SendCastResult(SPELL_FAILED_DONT_REPORT); return; } ThreatManager& mgr = unitTarget->GetThreatManager(); if (mgr.GetCurrentVictim() == unitCaster) { SendCastResult(SPELL_FAILED_DONT_REPORT); return; } if (!mgr.IsThreatListEmpty()) // Set threat equal to highest threat currently on target mgr.MatchUnitThreatToHighestThreat(unitCaster); } void Spell::EffectWeaponDmg() { if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; if (!unitTarget || !unitTarget->IsAlive()) return; // multiple weapon dmg effect workaround // execute only the last weapon damage // and handle all effects at once for (size_t j = effectInfo->EffectIndex + 1; j < m_spellInfo->GetEffects().size(); ++j) { switch (m_spellInfo->GetEffect(SpellEffIndex(j)).Effect) { case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: case SPELL_EFFECT_NORMALIZED_WEAPON_DMG: case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE: return; // we must calculate only at last weapon effect default: break; } } // some spell specific modifiers float totalDamagePercentMod = 1.0f; // applied to final bonus+weapon damage int32 fixed_bonus = 0; int32 spell_bonus = 0; // bonus specific for spell switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_WARRIOR: { // Devastate (player ones) if (m_spellInfo->SpellFamilyFlags[1] & 0x40) { unitCaster->CastSpell(unitTarget, 58567, true); // 58388 - Glyph of Devastate dummy aura. if (unitCaster->HasAura(58388)) unitCaster->CastSpell(unitTarget, 58567, true); if (Aura* aur = unitTarget->GetAura(58567, unitCaster->GetGUID())) fixed_bonus += (aur->GetStackAmount() - 1) * CalculateDamage(m_spellInfo->GetEffect(EFFECT_2)); // subtract 1 so fixed bonus is not applied twice } else if (m_spellInfo->SpellFamilyFlags[0] & 0x8000000) // Mocking Blow { if (unitTarget->IsImmunedToSpellEffect(m_spellInfo, m_spellInfo->GetEffect(EFFECT_1), unitCaster) || unitTarget->GetTypeId() == TYPEID_PLAYER) { m_damage = 0; return; } } break; } case SPELLFAMILY_ROGUE: { // Fan of Knives, Hemorrhage, Ghostly Strike if ((m_spellInfo->SpellFamilyFlags[1] & 0x40000) || (m_spellInfo->SpellFamilyFlags[0] & 0x6000000)) { // Hemorrhage if (m_spellInfo->SpellFamilyFlags[0] & 0x2000000) AddComboPointGain(unitTarget, 1); // 50% more damage with daggers if (unitCaster->GetTypeId() == TYPEID_PLAYER) if (Item* item = unitCaster->ToPlayer()->GetWeaponForAttack(m_attackType, true)) if (item->GetTemplate()->SubClass == ITEM_SUBCLASS_WEAPON_DAGGER) totalDamagePercentMod *= 1.5f; } // Mutilate (for each hand) else if (m_spellInfo->SpellFamilyFlags[1] & 0x6) { bool found = false; // fast check if (unitTarget->HasAuraState(AURA_STATE_DEADLY_POISON, m_spellInfo, unitCaster)) found = true; // full aura scan else { Unit::AuraApplicationMap const& auras = unitTarget->GetAppliedAuras(); for (Unit::AuraApplicationMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { if (itr->second->GetBase()->GetSpellInfo()->Dispel == DISPEL_POISON) { found = true; break; } } } if (found) totalDamagePercentMod *= 1.2f; // 120% if poisoned } break; } case SPELLFAMILY_PALADIN: { // Seal of Command Unleashed if (m_spellInfo->Id == 20467) { spell_bonus += int32(0.08f * unitCaster->GetTotalAttackPowerValue(BASE_ATTACK)); spell_bonus += int32(0.13f * unitCaster->SpellBaseDamageBonusDone(m_spellInfo->GetSchoolMask())); } break; } case SPELLFAMILY_SHAMAN: { // Skyshatter Harness item set bonus // Stormstrike if (AuraEffect* aurEff = unitCaster->IsScriptOverriden(m_spellInfo, 5634)) unitCaster->CastSpell(nullptr, 38430, aurEff); break; } case SPELLFAMILY_DRUID: { // Mangle (Cat): CP if (m_spellInfo->SpellFamilyFlags[1] & 0x400) AddComboPointGain(unitTarget, 1); // Shred, Maul - Rend and Tear else if (m_spellInfo->SpellFamilyFlags[0] & 0x00008800 && unitTarget->HasAuraState(AURA_STATE_BLEEDING)) { if (AuraEffect const* rendAndTear = unitCaster->GetDummyAuraEffect(SPELLFAMILY_DRUID, 2859, 0)) AddPct(totalDamagePercentMod, rendAndTear->GetAmount()); } break; } case SPELLFAMILY_HUNTER: { // Kill Shot - bonus damage from Ranged Attack Power if (m_spellInfo->SpellFamilyFlags[1] & 0x800000) spell_bonus += int32(0.4f * unitCaster->GetTotalAttackPowerValue(RANGED_ATTACK)); break; } case SPELLFAMILY_DEATHKNIGHT: { // Plague Strike if (m_spellInfo->SpellFamilyFlags[0] & 0x1) { // Glyph of Plague Strike if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(58657, EFFECT_0)) AddPct(totalDamagePercentMod, aurEff->GetAmount()); break; } // Blood Strike if (m_spellInfo->SpellFamilyFlags[0] & 0x400000) { float bonusPct = m_spellInfo->GetEffect(EFFECT_2).CalcValue() * unitTarget->GetDiseasesByCaster(unitCaster->GetGUID()) / 2.0f; // Death Knight T8 Melee 4P Bonus if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(64736, EFFECT_0)) AddPct(bonusPct, aurEff->GetAmount()); AddPct(totalDamagePercentMod, bonusPct); // Glyph of Blood Strike if (unitCaster->GetAuraEffect(59332, EFFECT_0)) if (unitTarget->HasAuraType(SPELL_AURA_MOD_DECREASE_SPEED)) AddPct(totalDamagePercentMod, 20); break; } // Death Strike if (m_spellInfo->SpellFamilyFlags[0] & 0x10) { // Glyph of Death Strike if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(59336, EFFECT_0)) if (uint32 runic = std::min<uint32>(unitCaster->GetPower(POWER_RUNIC_POWER), aurEff->GetSpellInfo()->GetEffect(EFFECT_1).CalcValue())) AddPct(totalDamagePercentMod, runic); break; } // Obliterate (12.5% more damage per disease) if (m_spellInfo->SpellFamilyFlags[1] & 0x20000) { bool consumeDiseases = true; // Annihilation if (AuraEffect const* aurEff = unitCaster->GetDummyAuraEffect(SPELLFAMILY_DEATHKNIGHT, 2710, EFFECT_0)) // Do not consume diseases if roll sucesses if (roll_chance_i(aurEff->GetAmount())) consumeDiseases = false; float bonusPct = m_spellInfo->GetEffect(EFFECT_2).CalcValue() * unitTarget->GetDiseasesByCaster(unitCaster->GetGUID(), consumeDiseases) / 2.0f; // Death Knight T8 Melee 4P Bonus if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(64736, EFFECT_0)) AddPct(bonusPct, aurEff->GetAmount()); AddPct(totalDamagePercentMod, bonusPct); break; } // Blood-Caked Strike - Blood-Caked Blade if (m_spellInfo->SpellIconID == 1736) { AddPct(totalDamagePercentMod, unitTarget->GetDiseasesByCaster(unitCaster->GetGUID()) * 50.0f); break; } // Heart Strike if (m_spellInfo->SpellFamilyFlags[0] & 0x1000000) { float bonusPct = m_spellInfo->GetEffect(EFFECT_2).CalcValue() * unitTarget->GetDiseasesByCaster(unitCaster->GetGUID()); // Death Knight T8 Melee 4P Bonus if (AuraEffect const* aurEff = unitCaster->GetAuraEffect(64736, EFFECT_0)) AddPct(bonusPct, aurEff->GetAmount()); AddPct(totalDamagePercentMod, bonusPct); break; } break; } } bool normalized = false; float weaponDamagePercentMod = 1.0f; for (SpellEffectInfo const& spellEffectInfo : m_spellInfo->GetEffects()) { switch (spellEffectInfo.Effect) { case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: fixed_bonus += CalculateDamage(spellEffectInfo); break; case SPELL_EFFECT_NORMALIZED_WEAPON_DMG: fixed_bonus += CalculateDamage(spellEffectInfo); normalized = true; break; case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE: ApplyPct(weaponDamagePercentMod, CalculateDamage(spellEffectInfo)); break; default: break; // not weapon damage effect, just skip } } // if (addPctMods) { percent mods are added in Unit::CalculateDamage } else { percent mods are added in Unit::MeleeDamageBonusDone } // this distinction is neccessary to properly inform the client about his autoattack damage values from Script_UnitDamage bool const addPctMods = !m_spellInfo->HasAttribute(SPELL_ATTR6_LIMIT_PCT_DAMAGE_MODS) && (m_spellSchoolMask & SPELL_SCHOOL_MASK_NORMAL); if (addPctMods) { UnitMods unitMod; switch (m_attackType) { default: case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break; case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break; case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break; } float weapon_total_pct = unitCaster->GetPctModifierValue(unitMod, TOTAL_PCT); if (fixed_bonus) fixed_bonus = int32(fixed_bonus * weapon_total_pct); if (spell_bonus) spell_bonus = int32(spell_bonus * weapon_total_pct); } int32 weaponDamage = unitCaster->CalculateDamage(m_attackType, normalized, addPctMods); // Sequence is important for (SpellEffectInfo const& spellEffectInfo : m_spellInfo->GetEffects()) { // We assume that a spell have at most one fixed_bonus // and at most one weaponDamagePercentMod switch (spellEffectInfo.Effect) { case SPELL_EFFECT_WEAPON_DAMAGE: case SPELL_EFFECT_WEAPON_DAMAGE_NOSCHOOL: case SPELL_EFFECT_NORMALIZED_WEAPON_DMG: weaponDamage += fixed_bonus; break; case SPELL_EFFECT_WEAPON_PERCENT_DAMAGE: weaponDamage = int32(weaponDamage * weaponDamagePercentMod); break; default: break; // not weapon damage effect, just skip } } weaponDamage += spell_bonus; weaponDamage = int32(weaponDamage * totalDamagePercentMod); // apply spellmod to Done damage if (Player* modOwner = unitCaster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DAMAGE, weaponDamage); // prevent negative damage weaponDamage = std::max(weaponDamage, 0); // Add melee damage bonuses (also check for negative) weaponDamage = unitCaster->MeleeDamageBonusDone(unitTarget, weaponDamage, m_attackType, m_spellInfo); m_damage += unitTarget->MeleeDamageBonusTaken(unitCaster, weaponDamage, m_attackType, m_spellInfo); } void Spell::EffectThreat() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster || !unitCaster->IsAlive()) return; if (!unitTarget) return; if (!unitTarget->CanHaveThreatList()) return; unitTarget->GetThreatManager().AddThreat(unitCaster, float(damage), m_spellInfo, true); } void Spell::EffectHealMaxHealth() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; if (!unitTarget || !unitTarget->IsAlive()) return; int32 addhealth = 0; // damage == 0 - heal for caster max health if (damage == 0) addhealth = unitCaster->GetMaxHealth(); else addhealth = unitTarget->GetMaxHealth() - unitTarget->GetHealth(); m_healing += addhealth; } void Spell::EffectInterruptCast() { if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET) return; if (!unitTarget || !unitTarget->IsAlive()) return; /// @todo not all spells that used this effect apply cooldown at school spells // also exist case: apply cooldown to interrupted cast only and to all spells // there is no CURRENT_AUTOREPEAT_SPELL spells that can be interrupted for (uint32 i = CURRENT_FIRST_NON_MELEE_SPELL; i < CURRENT_AUTOREPEAT_SPELL; ++i) { if (Spell* spell = unitTarget->GetCurrentSpell(CurrentSpellTypes(i))) { SpellInfo const* curSpellInfo = spell->m_spellInfo; // check if we can interrupt spell if ((spell->getState() == SPELL_STATE_CASTING || (spell->getState() == SPELL_STATE_PREPARING && spell->GetCastTime() > 0.0f)) && curSpellInfo->PreventionType == SPELL_PREVENTION_TYPE_SILENCE && ((i == CURRENT_GENERIC_SPELL && curSpellInfo->InterruptFlags & SPELL_INTERRUPT_FLAG_INTERRUPT) || (i == CURRENT_CHANNELED_SPELL && curSpellInfo->ChannelInterruptFlags & CHANNEL_INTERRUPT_FLAG_INTERRUPT))) { if (Unit* unitCaster = GetUnitCasterForEffectHandlers()) { int32 duration = m_spellInfo->GetDuration(); unitTarget->GetSpellHistory()->LockSpellSchool(curSpellInfo->GetSchoolMask(), unitTarget->ModSpellDuration(m_spellInfo, unitTarget, duration, false, 1 << effectInfo->EffectIndex)); if (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MAGIC) Unit::ProcSkillsAndAuras(unitCaster, unitTarget, PROC_FLAG_DONE_SPELL_MAGIC_DMG_CLASS_NEG, PROC_FLAG_TAKEN_SPELL_MAGIC_DMG_CLASS_NEG, PROC_SPELL_TYPE_MASK_ALL, PROC_SPELL_PHASE_HIT, PROC_HIT_INTERRUPT, nullptr, nullptr, nullptr); else if (m_spellInfo->DmgClass == SPELL_DAMAGE_CLASS_MELEE) Unit::ProcSkillsAndAuras(unitCaster, unitTarget, PROC_FLAG_DONE_SPELL_MELEE_DMG_CLASS, PROC_FLAG_TAKEN_SPELL_MELEE_DMG_CLASS, PROC_SPELL_TYPE_MASK_ALL, PROC_SPELL_PHASE_HIT, PROC_HIT_INTERRUPT, nullptr, nullptr, nullptr); } ExecuteLogEffectInterruptCast(effectInfo->EffectIndex, unitTarget, curSpellInfo->Id); unitTarget->InterruptSpell(CurrentSpellTypes(i), false); } } } } void Spell::EffectSummonObjectWild() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; uint32 gameobject_id = effectInfo->MiscValue; GameObject* pGameObj = new GameObject(); WorldObject* target = focusObject; if (!target) target = m_caster; float x, y, z; if (m_targets.HasDst()) destTarget->GetPosition(x, y, z); else m_caster->GetClosePoint(x, y, z, DEFAULT_PLAYER_BOUNDING_RADIUS); Map* map = target->GetMap(); QuaternionData rot = QuaternionData::fromEulerAnglesZYX(target->GetOrientation(), 0.f, 0.f); if (!pGameObj->Create(map->GenerateLowGuid<HighGuid::GameObject>(), gameobject_id, map, m_caster->GetPhaseMask(), Position(x, y, z, target->GetOrientation()), rot, 255, GO_STATE_READY)) { delete pGameObj; return; } int32 duration = m_spellInfo->GetDuration(); pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); pGameObj->SetSpellId(m_spellInfo->Id); ExecuteLogEffectSummonObject(effectInfo->EffectIndex, pGameObj); // Wild object not have owner and check clickable by players map->AddToMap(pGameObj); if (pGameObj->GetGoType() == GAMEOBJECT_TYPE_FLAGDROP) if (Player* player = m_caster->ToPlayer()) if (Battleground* bg = player->GetBattleground()) bg->SetDroppedFlagGUID(pGameObj->GetGUID(), player->GetTeam() == ALLIANCE ? TEAM_HORDE: TEAM_ALLIANCE); if (GameObject* linkedTrap = pGameObj->GetLinkedTrap()) { linkedTrap->SetRespawnTime(duration > 0 ? duration / IN_MILLISECONDS : 0); linkedTrap->SetSpellId(m_spellInfo->Id); ExecuteLogEffectSummonObject(effectInfo->EffectIndex, linkedTrap); } } void Spell::EffectScriptEffect() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); /// @todo we must implement hunter pet summon at login there (spell 6962) /// @todo: move this to scripts switch (m_spellInfo->SpellFamilyName) { case SPELLFAMILY_GENERIC: { switch (m_spellInfo->Id) { // Shadow Flame (All script effects, not just end ones to prevent player from dodging the last triggered spell) case 22539: case 22972: case 22975: case 22976: case 22977: case 22978: case 22979: case 22980: case 22981: case 22982: case 22983: case 22984: case 22985: { if (!unitTarget || !unitTarget->IsAlive()) return; // Onyxia Scale Cloak if (unitTarget->HasAura(22683)) return; // Shadow Flame m_caster->CastSpell(unitTarget, 22682, true); return; } // Mug Transformation case 41931: { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; uint8 bag = 19; uint8 slot = 0; Item* item = nullptr; while (bag) // 256 = 0 due to var type { item = m_caster->ToPlayer()->GetItemByPos(bag, slot); if (item && item->GetEntry() == 38587) break; ++slot; if (slot == 39) { slot = 0; ++bag; } } if (bag) { if (m_caster->ToPlayer()->GetItemByPos(bag, slot)->GetCount() == 1) m_caster->ToPlayer()->RemoveItem(bag, slot, true); else m_caster->ToPlayer()->GetItemByPos(bag, slot)->SetCount(m_caster->ToPlayer()->GetItemByPos(bag, slot)->GetCount()-1); // Spell 42518 (Braufest - Gratisprobe des Braufest herstellen) m_caster->CastSpell(m_caster, 42518, true); return; } break; } // Brutallus - Burn case 45141: case 45151: { //Workaround for Range ... should be global for every ScriptEffect float radius = effectInfo->CalcRadius(); if (unitTarget && unitTarget->GetTypeId() == TYPEID_PLAYER && unitTarget->GetDistance(m_caster) >= radius && !unitTarget->HasAura(46394) && unitTarget != m_caster) unitTarget->CastSpell(unitTarget, 46394, true); break; } // Summon Ghouls On Scarlet Crusade case 51904: { if (!m_targets.HasDst()) return; float x, y, z; float radius = effectInfo->CalcRadius(); for (uint8 i = 0; i < 15; ++i) { m_caster->GetRandomPoint(*destTarget, radius, x, y, z); m_caster->CastSpell({x, y, z}, 54522, true); } break; } case 52173: // Coyote Spirit Despawn case 60243: // Blood Parrot Despawn if (unitTarget->GetTypeId() == TYPEID_UNIT && unitTarget->IsSummon()) unitTarget->ToTempSummon()->UnSummon(); return; case 57347: // Retrieving (Wintergrasp RP-GG pickup spell) { if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT || m_caster->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToCreature()->DespawnOrUnsummon(); return; } case 57349: // Drop RP-GG (Wintergrasp RP-GG at death drop spell) { if (m_caster->GetTypeId() != TYPEID_PLAYER) return; // Delete item from inventory at death m_caster->ToPlayer()->DestroyItemCount(damage, 5, true); return; } case 62482: // Grab Crate { if (!unitCaster) return; if (unitTarget) { if (Unit* seat = unitCaster->GetVehicleBase()) { if (Unit* parent = seat->GetVehicleBase()) { /// @todo a hack, range = 11, should after some time cast, otherwise too far unitCaster->CastSpell(parent, 62496, true); unitTarget->CastSpell(parent, m_spellInfo->GetEffect(EFFECT_0).CalcValue()); } } } return; } } break; } } // normal DB scripted effect TC_LOG_DEBUG("spells", "Spell ScriptStart spellid %u in EffectScriptEffect(%u)", m_spellInfo->Id, uint32(effectInfo->EffectIndex)); m_caster->GetMap()->ScriptsStart(sSpellScripts, uint32(m_spellInfo->Id | (effectInfo->EffectIndex << 24)), m_caster, unitTarget); } void Spell::EffectSanctuary() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; if (unitTarget->GetTypeId() == TYPEID_PLAYER && !unitTarget->GetMap()->IsDungeon()) { // stop all pve combat for players outside dungeons, suppress pvp combat unitTarget->CombatStop(false, false); } else { // in dungeons (or for nonplayers), reset this unit on all enemies' threat lists for (auto const& pair : unitTarget->GetThreatManager().GetThreatenedByMeList()) pair.second->ScaleThreat(0.0f); } // makes spells cast before this time fizzle unitTarget->m_lastSanctuaryTime = GameTime::GetGameTimeMS(); } void Spell::EffectAddComboPoints() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; if (damage <= 0) return; AddComboPointGain(unitTarget, damage); } void Spell::EffectDuel() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || m_caster->GetTypeId() != TYPEID_PLAYER || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* caster = m_caster->ToPlayer(); Player* target = unitTarget->ToPlayer(); // caster or target already have requested duel if (caster->duel || target->duel || !target->GetSocial() || target->GetSocial()->HasIgnore(caster->GetGUID())) return; // Players can only fight a duel in zones with this flag AreaTableEntry const* casterAreaEntry = sAreaTableStore.LookupEntry(caster->GetAreaId()); if (casterAreaEntry && !(casterAreaEntry->Flags & AREA_FLAG_ALLOW_DUELS)) { SendCastResult(SPELL_FAILED_NO_DUELING); // Dueling isn't allowed here return; } AreaTableEntry const* targetAreaEntry = sAreaTableStore.LookupEntry(target->GetAreaId()); if (targetAreaEntry && !(targetAreaEntry->Flags & AREA_FLAG_ALLOW_DUELS)) { SendCastResult(SPELL_FAILED_NO_DUELING); // Dueling isn't allowed here return; } //CREATE DUEL FLAG OBJECT GameObject* pGameObj = new GameObject; uint32 gameobject_id = effectInfo->MiscValue; Position const pos = { caster->GetPositionX() + (unitTarget->GetPositionX() - caster->GetPositionX()) / 2, caster->GetPositionY() + (unitTarget->GetPositionY() - caster->GetPositionY()) / 2, caster->GetPositionZ(), caster->GetOrientation() }; Map* map = caster->GetMap(); QuaternionData rot = QuaternionData::fromEulerAnglesZYX(pos.GetOrientation(), 0.f, 0.f); if (!pGameObj->Create(map->GenerateLowGuid<HighGuid::GameObject>(), gameobject_id, map, caster->GetPhaseMask(), pos, rot, 0, GO_STATE_READY)) { delete pGameObj; return; } pGameObj->SetFaction(caster->GetFaction()); pGameObj->SetUInt32Value(GAMEOBJECT_LEVEL, caster->GetLevel() + 1); int32 duration = m_spellInfo->GetDuration(); pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); pGameObj->SetSpellId(m_spellInfo->Id); ExecuteLogEffectSummonObject(effectInfo->EffectIndex, pGameObj); caster->AddGameObject(pGameObj); map->AddToMap(pGameObj); //END // Send request WorldPacket data(SMSG_DUEL_REQUESTED, 8 + 8); data << uint64(pGameObj->GetGUID()); data << uint64(caster->GetGUID()); caster->SendDirectMessage(&data); target->SendDirectMessage(&data); // create duel-info bool isMounted = (GetSpellInfo()->Id == 62875); caster->duel = std::make_unique<DuelInfo>(target, caster, isMounted); target->duel = std::make_unique<DuelInfo>(caster, caster, isMounted); caster->SetGuidValue(PLAYER_DUEL_ARBITER, pGameObj->GetGUID()); target->SetGuidValue(PLAYER_DUEL_ARBITER, pGameObj->GetGUID()); sScriptMgr->OnPlayerDuelRequest(target, caster); } void Spell::EffectStuck() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; if (!sWorld->getBoolConfig(CONFIG_CAST_UNSTUCK)) return; Player* player = m_caster->ToPlayer(); if (!player) return; TC_LOG_DEBUG("spells", "Spell Effect: Stuck"); TC_LOG_DEBUG("spells", "Player %s %s used the auto-unstuck feature at map %u (%f, %f, %f).", player->GetName().c_str(), player->GetGUID().ToString().c_str(), player->GetMapId(), player->GetPositionX(), player->GetPositionY(), player->GetPositionZ()); if (player->IsInFlight()) return; // if player is dead - teleport to graveyard if (!player->IsAlive()) { if (player->HasAuraType(SPELL_AURA_PREVENT_RESURRECTION)) return; // player is in corpse if (!player->HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST)) player->BuildPlayerRepop(); player->RepopAtGraveyard(); return; } // no hearthstone in bag or on cooldown Item* hearthStone = player->GetItemByEntry(6948 /*Hearthstone*/); if (!hearthStone || player->GetSpellHistory()->HasCooldown(8690 /*Spell Hearthstone*/)) { float o = rand_norm() * 2 * M_PI; Position pos = *player; player->MovePositionToFirstCollision(pos, 5.0f, o); player->NearTeleportTo(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), player->GetOrientation()); return; } // we have hearthstone not on cooldown, just use it player->CastSpell(player, 8690, TriggerCastFlags(TRIGGERED_FULL_MASK&~TRIGGERED_IGNORE_SPELL_AND_CATEGORY_CD)); } void Spell::EffectSummonPlayer() { // workaround - this effect should not use target map if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->SendSummonRequestFrom(unitCaster); } void Spell::EffectActivateObject() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!gameObjTarget) return; GameObjectActions action = GameObjectActions(effectInfo->MiscValue); gameObjTarget->ActivateObject(action, m_caster, m_spellInfo->Id, int32(effectInfo->EffectIndex)); } void Spell::EffectApplyGlyph() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; if (m_glyphIndex >= MAX_GLYPH_SLOT_INDEX) return; Player* player = m_caster->ToPlayer(); if (!player) return; // glyph sockets level requirement uint8 minLevel = 0; switch (m_glyphIndex) { case 0: case 1: minLevel = 15; break; case 2: minLevel = 50; break; case 3: minLevel = 30; break; case 4: minLevel = 70; break; case 5: minLevel = 80; break; } if (minLevel && player->GetLevel() < minLevel) { SendCastResult(SPELL_FAILED_GLYPH_SOCKET_LOCKED); return; } // apply new one if (uint32 glyph = effectInfo->MiscValue) { if (GlyphPropertiesEntry const* gp = sGlyphPropertiesStore.LookupEntry(glyph)) { if (GlyphSlotEntry const* gs = sGlyphSlotStore.LookupEntry(player->GetGlyphSlot(m_glyphIndex))) { if (gp->GlyphSlotFlags != gs->Type) { SendCastResult(SPELL_FAILED_INVALID_GLYPH); return; // glyph slot mismatch } } // remove old glyph if (uint32 oldglyph = player->GetGlyph(m_glyphIndex)) { if (GlyphPropertiesEntry const* old_gp = sGlyphPropertiesStore.LookupEntry(oldglyph)) { player->RemoveAurasDueToSpell(old_gp->SpellID); player->SetGlyph(m_glyphIndex, 0); } } player->CastSpell(player, gp->SpellID, true); player->SetGlyph(m_glyphIndex, glyph); player->SendTalentsInfoData(false); } } } void Spell::EffectEnchantHeldItem() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; // this is only item spell effect applied to main-hand weapon of target player (players in area) if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* item_owner = unitTarget->ToPlayer(); Item* item = item_owner->GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND); if (!item) return; // must be equipped if (!item->IsEquipped()) return; if (effectInfo->MiscValue) { uint32 enchant_id = effectInfo->MiscValue; int32 duration = m_spellInfo->GetDuration(); // Try duration index first .. if (!duration) duration = damage;//+1; // Base points after .. if (!duration) duration = 10 * IN_MILLISECONDS; // 10 seconds for enchants which don't have listed duration if (m_spellInfo->Id == 14792) // Venomhide Poison duration = 5 * MINUTE * IN_MILLISECONDS; SpellItemEnchantmentEntry const* pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id); if (!pEnchant) return; // Always go to temp enchantment slot EnchantmentSlot slot = TEMP_ENCHANTMENT_SLOT; // Enchantment will not be applied if a different one already exists if (item->GetEnchantmentId(slot) && item->GetEnchantmentId(slot) != enchant_id) return; // Apply the temporary enchantment item->SetEnchantment(slot, enchant_id, duration, 0, m_caster->GetGUID()); item_owner->ApplyEnchantment(item, slot, true); } } void Spell::EffectDisEnchant() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!itemTarget || !itemTarget->GetTemplate()->DisenchantID) return; if (Player* caster = m_caster->ToPlayer()) { caster->UpdateCraftSkill(m_spellInfo->Id); caster->SendLoot(itemTarget->GetGUID(), LOOT_DISENCHANTING); } // item will be removed at disenchanting end } void Spell::EffectInebriate() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = unitTarget->ToPlayer(); uint8 currentDrunk = player->GetDrunkValue(); uint8 drunkMod = damage; if (currentDrunk + drunkMod > 100) { currentDrunk = 100; if (rand_chance() < 25.0f) player->CastSpell(player, 67468, false); // Drunken Vomit } else currentDrunk += drunkMod; player->SetDrunkValue(currentDrunk, m_CastItem ? m_CastItem->GetEntry() : 0); } void Spell::EffectFeedPet() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Player* player = m_caster->ToPlayer(); if (!player) return; Item* foodItem = itemTarget; if (!foodItem) return; Pet* pet = player->GetPet(); if (!pet) return; if (!pet->IsAlive()) return; int32 benefit = pet->GetCurrentFoodBenefitLevel(foodItem->GetTemplate()->ItemLevel); if (benefit <= 0) return; ExecuteLogEffectDestroyItem(effectInfo->EffectIndex, foodItem->GetEntry()); uint32 count = 1; player->DestroyItemCount(foodItem, count, true); /// @todo fix crash when a spell has two effects, both pointed at the same item target CastSpellExtraArgs args(TRIGGERED_FULL_MASK); args.AddSpellMod(SPELLVALUE_BASE_POINT0, benefit); m_caster->CastSpell(pet, effectInfo->TriggerSpell, args); } void Spell::EffectDismissPet() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || !unitTarget->IsPet()) return; Pet* pet = unitTarget->ToPet(); ExecuteLogEffectUnsummonObject(effectInfo->EffectIndex, pet); pet->Remove(PET_SAVE_NOT_IN_SLOT); } void Spell::EffectSummonObject() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; uint32 go_id = effectInfo->MiscValue; uint8 slot = effectInfo->Effect - SPELL_EFFECT_SUMMON_OBJECT_SLOT1; if (ObjectGuid guid = unitCaster->m_ObjectSlot[slot]) { if (GameObject* obj = unitCaster->GetMap()->GetGameObject(guid)) { // Recast case - null spell id to make auras not be removed on object remove from world if (m_spellInfo->Id == obj->GetSpellId()) obj->SetSpellId(0); unitCaster->RemoveGameObject(obj, true); } unitCaster->m_ObjectSlot[slot].Clear(); } GameObject* go = new GameObject(); float x, y, z; // If dest location if present if (m_targets.HasDst()) destTarget->GetPosition(x, y, z); // Summon in random point all other units if location present else unitCaster->GetClosePoint(x, y, z, DEFAULT_PLAYER_BOUNDING_RADIUS); Map* map = unitCaster->GetMap(); QuaternionData rot = QuaternionData::fromEulerAnglesZYX(unitCaster->GetOrientation(), 0.f, 0.f); if (!go->Create(map->GenerateLowGuid<HighGuid::GameObject>(), go_id, map, unitCaster->GetPhaseMask(), Position(x, y, z, unitCaster->GetOrientation()), rot, 255, GO_STATE_READY)) { delete go; return; } go->SetFaction(unitCaster->GetFaction()); go->SetUInt32Value(GAMEOBJECT_LEVEL, unitCaster->GetLevel()); int32 duration = m_spellInfo->GetDuration(); go->SetRespawnTime(duration > 0 ? duration / IN_MILLISECONDS : 0); go->SetSpellId(m_spellInfo->Id); unitCaster->AddGameObject(go); ExecuteLogEffectSummonObject(effectInfo->EffectIndex, go); map->AddToMap(go); unitCaster->m_ObjectSlot[slot] = go->GetGUID(); } void Spell::EffectResurrect() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!m_corpseTarget && !unitTarget) return; Player* player = nullptr; if (m_corpseTarget) player = ObjectAccessor::FindPlayer(m_corpseTarget->GetOwnerGUID()); else if (unitTarget) player = unitTarget->ToPlayer(); if (!player || player->IsAlive() || !player->IsInWorld()) return; if (player->IsResurrectRequested()) // already have one active request return; uint32 health = player->CountPctFromMaxHealth(damage); uint32 mana = CalculatePct(player->GetMaxPower(POWER_MANA), damage); ExecuteLogEffectResurrect(effectInfo->EffectIndex, player); player->SetResurrectRequestData(m_caster, health, mana, 0); SendResurrectRequest(player); } void Spell::EffectAddExtraAttacks() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || !unitTarget->IsAlive()) return; unitTarget->AddExtraAttacks(damage); ExecuteLogEffectExtraAttacks(effectInfo->EffectIndex, unitTarget, damage); } void Spell::EffectParry() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetCanParry(true); } void Spell::EffectBlock() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetCanBlock(true); } void Spell::EffectLeap() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->IsInFlight()) return; if (!m_targets.HasDst()) return; Position pos = destTarget->GetPosition(); unitTarget->NearTeleportTo(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ(), pos.GetOrientation(), unitTarget == m_caster); } void Spell::EffectReputation() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = unitTarget->ToPlayer(); int32 repChange = damage; uint32 factionId = effectInfo->MiscValue; FactionEntry const* factionEntry = sFactionStore.LookupEntry(factionId); if (!factionEntry) return; repChange = player->CalculateReputationGain(REPUTATION_SOURCE_SPELL, 0, repChange, factionId); player->GetReputationMgr().ModifyReputation(factionEntry, repChange); } void Spell::EffectQuestComplete() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = unitTarget->ToPlayer(); uint32 questId = effectInfo->MiscValue; if (questId) { Quest const* quest = sObjectMgr->GetQuestTemplate(questId); if (!quest) return; uint16 logSlot = player->FindQuestSlot(questId); if (logSlot < MAX_QUEST_LOG_SIZE) player->AreaExploredOrEventHappens(questId); else if (quest->HasFlag(QUEST_FLAGS_TRACKING)) // Check if the quest is used as a serverside flag. player->SetRewardedQuest(questId); // If so, set status to rewarded without broadcasting it to client. } } void Spell::EffectForceDeselect() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; float dist = unitCaster->GetVisibilityRange(); // clear focus WorldPacket data(SMSG_BREAK_TARGET, unitCaster->GetPackGUID().size()); data << unitCaster->GetPackGUID(); Trinity::MessageDistDelivererToHostile notifierBreak(unitCaster, &data, dist); Cell::VisitWorldObjects(unitCaster, notifierBreak, dist); // and selection data.Initialize(SMSG_CLEAR_TARGET, 8); data << uint64(unitCaster->GetGUID()); Trinity::MessageDistDelivererToHostile notifierClear(unitCaster, &data, dist); Cell::VisitWorldObjects(unitCaster, notifierClear, dist); // we should also force pets to remove us from current target Unit::AttackerSet attackerSet; for (Unit::AttackerSet::const_iterator itr = unitCaster->getAttackers().begin(); itr != unitCaster->getAttackers().end(); ++itr) if ((*itr)->GetTypeId() == TYPEID_UNIT && !(*itr)->CanHaveThreatList()) attackerSet.insert(*itr); for (Unit::AttackerSet::const_iterator itr = attackerSet.begin(); itr != attackerSet.end(); ++itr) (*itr)->AttackStop(); } void Spell::EffectSelfResurrect() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; Player* player = m_caster->ToPlayer(); if (!player || !player->IsInWorld() || player->IsAlive()) return; uint32 health = 0; uint32 mana = 0; // flat case if (damage < 0) { health = uint32(-damage); mana = effectInfo->MiscValue; } // percent case else { health = player->CountPctFromMaxHealth(damage); if (player->GetMaxPower(POWER_MANA) > 0) mana = CalculatePct(player->GetMaxPower(POWER_MANA), damage); } player->ResurrectPlayer(0.0f); player->SetHealth(health); player->SetPower(POWER_MANA, mana); player->SetPower(POWER_RAGE, 0); player->SetPower(POWER_ENERGY, player->GetMaxPower(POWER_ENERGY)); player->SpawnCorpseBones(); } void Spell::EffectSkinning() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (unitTarget->GetTypeId() != TYPEID_UNIT) return; Player* player = m_caster->ToPlayer(); if (!player) return; Creature* creature = unitTarget->ToCreature(); int32 targetLevel = creature->GetLevel(); uint32 skill = creature->GetCreatureTemplate()->GetRequiredLootSkill(); creature->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); creature->SetFlag(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_LOOTABLE); player->SendLoot(creature->GetGUID(), LOOT_SKINNING); int32 const reqValue = targetLevel < 10 ? 0 : (targetLevel < 20 ? (targetLevel - 10) * 10 : targetLevel * 5); int32 const skillValue = player->GetPureSkillValue(skill); // Double chances for elites player->UpdateGatherSkill(skill, skillValue, reqValue, creature->isElite() ? 2 : 1); } void Spell::EffectCharge() { if (!unitTarget) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; if (effectHandleMode == SPELL_EFFECT_HANDLE_LAUNCH_TARGET) { // charge changes fall time if (unitCaster->GetTypeId() == TYPEID_PLAYER) unitCaster->ToPlayer()->SetFallInformation(0, unitCaster->GetPositionZ()); float speed = G3D::fuzzyGt(m_spellInfo->Speed, 0.0f) ? m_spellInfo->Speed : SPEED_CHARGE; // Spell is not using explicit target - no generated path if (!m_preGeneratedPath) { //unitTarget->GetContactPoint(m_caster, pos.m_positionX, pos.m_positionY, pos.m_positionZ); Position pos = unitTarget->GetFirstCollisionPosition(unitTarget->GetCombatReach(), unitTarget->GetRelativeAngle(m_caster)); unitCaster->GetMotionMaster()->MoveCharge(pos.m_positionX, pos.m_positionY, pos.m_positionZ, speed); } else unitCaster->GetMotionMaster()->MoveCharge(*m_preGeneratedPath, speed); } if (effectHandleMode == SPELL_EFFECT_HANDLE_HIT_TARGET) { // not all charge effects used in negative spells if (!m_spellInfo->IsPositive() && m_caster->GetTypeId() == TYPEID_PLAYER) unitCaster->Attack(unitTarget, true); } } void Spell::EffectChargeDest() { if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; if (m_targets.HasDst()) { Position pos = destTarget->GetPosition(); if (!unitCaster->IsWithinLOS(pos.GetPositionX(), pos.GetPositionY(), pos.GetPositionZ())) { float angle = unitCaster->GetRelativeAngle(pos.GetPositionX(), pos.GetPositionY()); float dist = unitCaster->GetDistance(pos); pos = unitCaster->GetFirstCollisionPosition(dist, angle); } unitCaster->GetMotionMaster()->MoveCharge(pos.m_positionX, pos.m_positionY, pos.m_positionZ); } } void Spell::EffectKnockBack() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; if (m_caster->GetAffectingPlayer()) if (Creature* creatureTarget = unitTarget->ToCreature()) if (creatureTarget->isWorldBoss() || creatureTarget->IsDungeonBoss()) return; // Spells with SPELL_EFFECT_KNOCK_BACK (like Thunderstorm) can't knockback target if target has ROOT/STUN if (unitTarget->HasUnitState(UNIT_STATE_ROOT | UNIT_STATE_STUNNED)) return; // Instantly interrupt non melee spells being cast if (unitTarget->IsNonMeleeSpellCast(true)) unitTarget->InterruptNonMeleeSpells(true); float ratio = 0.1f; float speedxy = float(effectInfo->MiscValue) * ratio; float speedz = float(damage) * ratio; if (speedxy < 0.01f && speedz < 0.01f) return; float x, y; if (effectInfo->Effect == SPELL_EFFECT_KNOCK_BACK_DEST) { if (m_targets.HasDst()) destTarget->GetPosition(x, y); else return; } else //if (m_spellInfo->Effects[i].Effect == SPELL_EFFECT_KNOCK_BACK) m_caster->GetPosition(x, y); unitTarget->KnockbackFrom(x, y, speedxy, speedz); } void Spell::EffectLeapBack() { if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH_TARGET) return; if (!unitTarget) return; float speedxy = effectInfo->MiscValue / 10.f; float speedz = damage/ 10.f; //1891: Disengage unitTarget->JumpTo(speedxy, speedz, m_spellInfo->SpellIconID != 1891); // changes fall time if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetFallInformation(0, m_caster->GetPositionZ()); } void Spell::EffectQuestClear() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = unitTarget->ToPlayer(); uint32 quest_id = effectInfo->MiscValue; Quest const* quest = sObjectMgr->GetQuestTemplate(quest_id); if (!quest) return; // Player has never done this quest if (player->GetQuestStatus(quest_id) == QUEST_STATUS_NONE) return; // remove all quest entries for 'entry' from quest log for (uint8 slot = 0; slot < MAX_QUEST_LOG_SIZE; ++slot) { uint32 logQuest = player->GetQuestSlotQuestId(slot); if (logQuest == quest_id) { player->SetQuestSlot(slot, 0); // we ignore unequippable quest items in this case, it's still be equipped player->TakeQuestSourceItem(logQuest, false); if (quest->HasFlag(QUEST_FLAGS_FLAGS_PVP)) { player->pvpInfo.IsHostile = player->pvpInfo.IsInHostileArea || player->HasPvPForcingQuest(); player->UpdatePvPState(); } } } player->RemoveActiveQuest(quest_id, false); player->RemoveRewardedQuest(quest_id); sScriptMgr->OnQuestStatusChange(player, quest_id); } void Spell::EffectSendTaxi() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->ActivateTaxiPathTo(effectInfo->MiscValue, m_spellInfo->Id); } void Spell::EffectPullTowards() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; Position pos = m_caster->GetFirstCollisionPosition(m_caster->GetCombatReach(), m_caster->GetRelativeAngle(unitTarget)); // This is a blizzlike mistake: this should be 2D distance according to projectile motion formulas, but Blizzard erroneously used 3D distance. float distXY = unitTarget->GetExactDist(pos); // Avoid division by 0 if (distXY < 0.001) return; float distZ = pos.GetPositionZ() - unitTarget->GetPositionZ(); float speedXY = effectInfo->MiscValue ? effectInfo->MiscValue / 10.0f : 30.0f; float speedZ = (2 * speedXY * speedXY * distZ + Movement::gravity * distXY * distXY) / (2 * speedXY * distXY); if (!std::isfinite(speedZ)) { TC_LOG_ERROR("spells", "Spell %u with SPELL_EFFECT_PULL_TOWARDS called with invalid speedZ. %s", m_spellInfo->Id, GetDebugInfo().c_str()); return; } unitTarget->JumpTo(speedXY, speedZ, true, pos); } void Spell::EffectPullTowardsDest() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; if (!m_targets.HasDst()) { TC_LOG_ERROR("spells", "Spell %u with SPELL_EFFECT_PULL_TOWARDS_DEST has no dest target", m_spellInfo->Id); return; } Position const* pos = m_targets.GetDstPos(); // This is a blizzlike mistake: this should be 2D distance according to projectile motion formulas, but Blizzard erroneously used 3D distance float distXY = unitTarget->GetExactDist(pos); // Avoid division by 0 if (distXY < 0.001) return; float distZ = pos->GetPositionZ() - unitTarget->GetPositionZ(); float speedXY = effectInfo->MiscValue ? effectInfo->MiscValue / 10.0f : 30.0f; float speedZ = (2 * speedXY * speedXY * distZ + Movement::gravity * distXY * distXY) / (2 * speedXY * distXY); if (!std::isfinite(speedZ)) { TC_LOG_ERROR("spells", "Spell %u with SPELL_EFFECT_PULL_TOWARDS_DEST called with invalid speedZ. %s", m_spellInfo->Id, GetDebugInfo().c_str()); return; } unitTarget->JumpTo(speedXY, speedZ, true, *pos); } void Spell::EffectDispelMechanic() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; uint32 mechanic = effectInfo->MiscValue; DispelList dispel_list; Unit::AuraMap const& auras = unitTarget->GetOwnedAuras(); for (Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { Aura* aura = itr->second; if (!aura->GetApplicationOfTarget(unitTarget->GetGUID())) continue; if (roll_chance_i(aura->CalcDispelChance(unitTarget, !unitTarget->IsFriendlyTo(m_caster)))) if ((aura->GetSpellInfo()->GetAllEffectsMechanicMask() & (1 << mechanic))) dispel_list.emplace_back(aura->GetId(), aura->GetCasterGUID()); } for (auto itr = dispel_list.begin(); itr != dispel_list.end(); ++itr) unitTarget->RemoveAura(itr->first, itr->second, 0, AURA_REMOVE_BY_ENEMY_SPELL); } void Spell::EffectResurrectPet() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; if (damage < 0) return; Player* player = m_caster->ToPlayer(); if (!player) return; // Maybe player dismissed dead pet or pet despawned? bool hadPet = true; if (!player->GetPet()) { // Position passed to SummonPet is irrelevant with current implementation, // pet will be relocated without using these coords in Pet::LoadPetFromDB player->SummonPet(0, 0.0f, 0.0f, 0.0f, 0.0f, SUMMON_PET, 0); hadPet = false; } // TODO: Better to fail Hunter's "Revive Pet" at cast instead of here when casting ends Pet* pet = player->GetPet(); // Attempt to get current pet if (!pet || pet->IsAlive()) return; // If player did have a pet before reviving, teleport it if (hadPet) { // Reposition the pet's corpse before reviving so as not to grab aggro // We can use a different, more accurate version of GetClosePoint() since we have a pet float x, y, z; // Will be used later to reposition the pet if we have one player->GetClosePoint(x, y, z, pet->GetCombatReach(), PET_FOLLOW_DIST, pet->GetFollowAngle()); pet->NearTeleportTo(x, y, z, player->GetOrientation()); pet->Relocate(x, y, z, player->GetOrientation()); // This is needed so SaveStayPosition() will get the proper coords. } pet->SetUInt32Value(UNIT_DYNAMIC_FLAGS, UNIT_DYNFLAG_NONE); pet->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE); pet->setDeathState(ALIVE); pet->ClearUnitState(UNIT_STATE_ALL_ERASABLE); pet->SetHealth(pet->CountPctFromMaxHealth(damage)); // Reset things for when the AI to takes over CharmInfo *ci = pet->GetCharmInfo(); if (ci) { // In case the pet was at stay, we don't want it running back ci->SaveStayPosition(); ci->SetIsAtStay(ci->HasCommandState(COMMAND_STAY)); ci->SetIsFollowing(false); ci->SetIsCommandAttack(false); ci->SetIsCommandFollow(false); ci->SetIsReturning(false); } pet->SavePetToDB(PET_SAVE_AS_CURRENT); } void Spell::EffectDestroyAllTotems() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; int32 mana = 0; for (uint8 slot = SUMMON_SLOT_TOTEM_FIRE; slot < MAX_TOTEM_SLOT; ++slot) { if (!unitCaster->m_SummonSlot[slot]) continue; Creature* totem = unitCaster->GetMap()->GetCreature(unitCaster->m_SummonSlot[slot]); if (totem && totem->IsTotem()) { uint32 spell_id = totem->GetUInt32Value(UNIT_CREATED_BY_SPELL); SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id); if (spellInfo) { mana += spellInfo->ManaCost; mana += int32(CalculatePct(unitCaster->GetCreateMana(), spellInfo->ManaCostPercentage)); } totem->ToTotem()->UnSummon(); } } ApplyPct(mana, damage); if (mana) { CastSpellExtraArgs args(TRIGGERED_FULL_MASK); args.AddSpellMod(SPELLVALUE_BASE_POINT0, mana); unitCaster->CastSpell(unitCaster, 39104, args); } } void Spell::EffectDurabilityDamage() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; int32 slot = effectInfo->MiscValue; // -1 means all player equipped items and -2 all items if (slot < 0) { unitTarget->ToPlayer()->DurabilityPointsLossAll(damage, (slot < -1)); ExecuteLogEffectDurabilityDamage(effectInfo->EffectIndex, unitTarget, -1, -1); return; } // invalid slot value if (slot >= INVENTORY_SLOT_BAG_END) return; if (Item* item = unitTarget->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) { unitTarget->ToPlayer()->DurabilityPointsLoss(item, damage); ExecuteLogEffectDurabilityDamage(effectInfo->EffectIndex, unitTarget, item->GetEntry(), slot); } } void Spell::EffectDurabilityDamagePCT() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; int32 slot = effectInfo->MiscValue; // FIXME: some spells effects have value -1/-2 // Possibly its mean -1 all player equipped items and -2 all items if (slot < 0) { unitTarget->ToPlayer()->DurabilityLossAll(float(damage) / 100.0f, (slot < -1)); return; } // invalid slot value if (slot >= INVENTORY_SLOT_BAG_END) return; if (damage <= 0) return; if (Item* item = unitTarget->ToPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) unitTarget->ToPlayer()->DurabilityLoss(item, float(damage) / 100.0f); } void Spell::EffectModifyThreatPercent() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster || !unitTarget) return; unitTarget->GetThreatManager().ModifyThreatByPercent(unitCaster, damage); } void Spell::EffectTransmitted() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; uint32 name_id = effectInfo->MiscValue; GameObjectTemplate const* goinfo = sObjectMgr->GetGameObjectTemplate(name_id); if (!goinfo) { TC_LOG_ERROR("sql.sql", "Gameobject (Entry: %u) does not exist and is not created by spell (ID: %u) cast.", name_id, m_spellInfo->Id); return; } float fx, fy, fz; if (m_targets.HasDst()) destTarget->GetPosition(fx, fy, fz); //FIXME: this can be better check for most objects but still hack else if (effectInfo->HasRadius() && m_spellInfo->Speed == 0) { float dis = effectInfo->CalcRadius(unitCaster); unitCaster->GetClosePoint(fx, fy, fz, DEFAULT_PLAYER_BOUNDING_RADIUS, dis); } else { //GO is always friendly to it's creator, get range for friends float min_dis = m_spellInfo->GetMinRange(true); float max_dis = m_spellInfo->GetMaxRange(true); float dis = (float)rand_norm() * (max_dis - min_dis) + min_dis; unitCaster->GetClosePoint(fx, fy, fz, DEFAULT_PLAYER_BOUNDING_RADIUS, dis); } Map* cMap = unitCaster->GetMap(); // if gameobject is summoning object, it should be spawned right on caster's position if (goinfo->type == GAMEOBJECT_TYPE_SUMMONING_RITUAL) unitCaster->GetPosition(fx, fy, fz); GameObject* pGameObj = new GameObject; Position pos = { fx, fy, fz, unitCaster->GetOrientation() }; QuaternionData rot = QuaternionData::fromEulerAnglesZYX(unitCaster->GetOrientation(), 0.f, 0.f); if (!pGameObj->Create(cMap->GenerateLowGuid<HighGuid::GameObject>(), name_id, cMap, unitCaster->GetPhaseMask(), pos, rot, 255, GO_STATE_READY)) { delete pGameObj; return; } int32 duration = m_spellInfo->GetDuration(); switch (goinfo->type) { case GAMEOBJECT_TYPE_FISHINGNODE: { unitCaster->SetChannelObjectGuid(pGameObj->GetGUID()); unitCaster->AddGameObject(pGameObj); // will removed at spell cancel // end time of range when possible catch fish (FISHING_BOBBER_READY_TIME..GetDuration(m_spellInfo)) // start time == fish-FISHING_BOBBER_READY_TIME (0..GetDuration(m_spellInfo)-FISHING_BOBBER_READY_TIME) int32 lastSec = 0; switch (urand(0, 2)) { case 0: lastSec = 3; break; case 1: lastSec = 7; break; case 2: lastSec = 13; break; } // Duration of the fishing bobber can't be higher than the Fishing channeling duration duration = std::min(duration, duration - lastSec*IN_MILLISECONDS + FISHING_BOBBER_READY_TIME*IN_MILLISECONDS); break; } case GAMEOBJECT_TYPE_SUMMONING_RITUAL: { if (unitCaster->GetTypeId() == TYPEID_PLAYER) { pGameObj->AddUniqueUse(unitCaster->ToPlayer()); unitCaster->AddGameObject(pGameObj); // will be removed at spell cancel } break; } case GAMEOBJECT_TYPE_DUEL_ARBITER: // 52991 unitCaster->AddGameObject(pGameObj); break; case GAMEOBJECT_TYPE_FISHINGHOLE: case GAMEOBJECT_TYPE_CHEST: default: break; } pGameObj->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); pGameObj->SetOwnerGUID(unitCaster->GetGUID()); //pGameObj->SetUInt32Value(GAMEOBJECT_LEVEL, unitCaster->GetLevel()); pGameObj->SetSpellId(m_spellInfo->Id); ExecuteLogEffectSummonObject(effectInfo->EffectIndex, pGameObj); TC_LOG_DEBUG("spells", "AddObject at SpellEfects.cpp EffectTransmitted"); //unitCaster->AddGameObject(pGameObj); //m_ObjToDel.push_back(pGameObj); cMap->AddToMap(pGameObj); if (GameObject* linkedTrap = pGameObj->GetLinkedTrap()) { linkedTrap->SetRespawnTime(duration > 0 ? duration/IN_MILLISECONDS : 0); //linkedTrap->SetUInt32Value(GAMEOBJECT_LEVEL, unitCaster->GetLevel()); linkedTrap->SetSpellId(m_spellInfo->Id); linkedTrap->SetOwnerGUID(unitCaster->GetGUID()); ExecuteLogEffectSummonObject(effectInfo->EffectIndex, linkedTrap); } } void Spell::EffectProspecting() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Player* player = m_caster->ToPlayer(); if (!player) return; if (!itemTarget || !itemTarget->GetTemplate()->HasFlag(ITEM_FLAG_IS_PROSPECTABLE)) return; if (itemTarget->GetCount() < 5) return; if (sWorld->getBoolConfig(CONFIG_SKILL_PROSPECTING)) { uint32 SkillValue = player->GetPureSkillValue(SKILL_JEWELCRAFTING); uint32 reqSkillValue = itemTarget->GetTemplate()->RequiredSkillRank; player->UpdateGatherSkill(SKILL_JEWELCRAFTING, SkillValue, reqSkillValue); } player->SendLoot(itemTarget->GetGUID(), LOOT_PROSPECTING); } void Spell::EffectMilling() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Player* player = m_caster->ToPlayer(); if (!player) return; if (!itemTarget || !itemTarget->GetTemplate()->HasFlag(ITEM_FLAG_IS_MILLABLE)) return; if (itemTarget->GetCount() < 5) return; if (sWorld->getBoolConfig(CONFIG_SKILL_MILLING)) { uint32 SkillValue = player->GetPureSkillValue(SKILL_INSCRIPTION); uint32 reqSkillValue = itemTarget->GetTemplate()->RequiredSkillRank; player->UpdateGatherSkill(SKILL_INSCRIPTION, SkillValue, reqSkillValue); } player->SendLoot(itemTarget->GetGUID(), LOOT_MILLING); } void Spell::EffectSkill() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; TC_LOG_DEBUG("spells", "WORLD: SkillEFFECT"); } /* There is currently no need for this effect. We handle it in Battleground.cpp If we would handle the resurrection here, the spiritguide would instantly disappear as the player revives, and so we wouldn't see the spirit heal visual effect on the npc. This is why we use a half sec delay between the visual effect and the resurrection itself */ void Spell::EffectSpiritHeal() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; /* if (unitTarget->GetTypeId() != TYPEID_PLAYER) return; if (!unitTarget->IsInWorld()) return; //m_spellInfo->Effects[i].BasePoints; == 99 (percent?) //unitTarget->ToPlayer()->setResurrect(m_caster->GetGUID(), unitTarget->GetPositionX(), unitTarget->GetPositionY(), unitTarget->GetPositionZ(), unitTarget->GetMaxHealth(), unitTarget->GetMaxPower(POWER_MANA)); unitTarget->ToPlayer()->ResurrectPlayer(1.0f); unitTarget->ToPlayer()->SpawnCorpseBones(); */ } // remove insignia spell effect void Spell::EffectSkinPlayerCorpse() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; TC_LOG_DEBUG("spells", "Effect: SkinPlayerCorpse"); Player* player = m_caster->ToPlayer(); Player* target = nullptr; if (unitTarget) target = unitTarget->ToPlayer(); else if (m_corpseTarget) target = ObjectAccessor::FindPlayer(m_corpseTarget->GetOwnerGUID()); if (!player || !target || target->IsAlive()) return; target->RemovedInsignia(player); } void Spell::EffectStealBeneficialBuff() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; TC_LOG_DEBUG("spells", "Effect: StealBeneficialBuff"); if (!unitTarget || unitTarget == m_caster) // can't steal from self return; DispelChargesList stealList; // Create dispel mask by dispel type uint32 dispelMask = SpellInfo::GetDispelMask(DispelType(effectInfo->MiscValue)); Unit::AuraMap const& auras = unitTarget->GetOwnedAuras(); for (Unit::AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr) { Aura* aura = itr->second; AuraApplication const* aurApp = aura->GetApplicationOfTarget(unitTarget->GetGUID()); if (!aurApp) continue; if ((aura->GetSpellInfo()->GetDispelMask()) & dispelMask) { // Need check for passive? this if (!aurApp->IsPositive() || aura->IsPassive() || aura->GetSpellInfo()->HasAttribute(SPELL_ATTR4_NOT_STEALABLE)) continue; // 2.4.3 Patch Notes: "Dispel effects will no longer attempt to remove effects that have 100% dispel resistance." int32 chance = aura->CalcDispelChance(unitTarget, !unitTarget->IsFriendlyTo(m_caster)); if (!chance) continue; // The charges / stack amounts don't count towards the total number of auras that can be dispelled. // Ie: A dispel on a target with 5 stacks of Winters Chill and a Polymorph has 1 / (1 + 1) -> 50% chance to dispell // Polymorph instead of 1 / (5 + 1) -> 16%. bool dispelCharges = aura->GetSpellInfo()->HasAttribute(SPELL_ATTR7_DISPEL_CHARGES); uint8 charges = dispelCharges ? aura->GetCharges() : aura->GetStackAmount(); if (charges > 0) stealList.emplace_back(aura, chance, charges); } } if (stealList.empty()) return; size_t remaining = stealList.size(); // Ok if exist some buffs for dispel try dispel it uint32 failCount = 0; DispelList successList; successList.reserve(damage); WorldPacket dataFail(SMSG_DISPEL_FAILED, 8 + 8 + 4 + 4 + damage * 4); // dispel N = damage buffs (or while exist buffs for dispel) for (int32 count = 0; count < damage && remaining > 0;) { // Random select buff for dispel DispelChargesList::iterator itr = stealList.begin(); std::advance(itr, urand(0, remaining - 1)); if (itr->RollDispel()) { successList.emplace_back(itr->GetAura()->GetId(), itr->GetAura()->GetCasterGUID()); if (!itr->DecrementCharge()) { --remaining; std::swap(*itr, stealList[remaining]); } } else { if (!failCount) { // Failed to dispell dataFail << uint64(m_caster->GetGUID()); // Caster GUID dataFail << uint64(unitTarget->GetGUID()); // Victim GUID dataFail << uint32(m_spellInfo->Id); // dispel spell id } ++failCount; dataFail << uint32(itr->GetAura()->GetId()); // Spell Id } ++count; } if (failCount) m_caster->SendMessageToSet(&dataFail, true); if (successList.empty()) return; WorldPacket dataSuccess(SMSG_SPELLSTEALLOG, 8 + 8 + 4 + 1 + 4 + damage * 5); dataSuccess << unitTarget->GetPackGUID(); // Victim GUID dataSuccess << m_caster->GetPackGUID(); // Caster GUID dataSuccess << uint32(m_spellInfo->Id); // dispel spell id dataSuccess << uint8(0); // not used dataSuccess << uint32(successList.size()); // count for (auto itr = successList.begin(); itr != successList.end(); ++itr) { dataSuccess << uint32(itr->first); // Spell Id dataSuccess << uint8(0); // 0 - steals !=0 transfers unitTarget->RemoveAurasDueToSpellBySteal(itr->first, itr->second, m_caster); } m_caster->SendMessageToSet(&dataSuccess, true); } void Spell::EffectKillCreditPersonal() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->KilledMonsterCredit(effectInfo->MiscValue); } void Spell::EffectKillCredit() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; int32 creatureEntry = effectInfo->MiscValue; if (!creatureEntry) { if (m_spellInfo->Id == 42793) // Burn Body creatureEntry = 24008; // Fallen Combatant } if (creatureEntry) unitTarget->ToPlayer()->RewardPlayerAndGroupAtEvent(creatureEntry, unitTarget); } void Spell::EffectQuestFail() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->FailQuest(effectInfo->MiscValue); } void Spell::EffectQuestStart() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; Player* player = unitTarget->ToPlayer(); if (!player) return; if (Quest const* quest = sObjectMgr->GetQuestTemplate(effectInfo->MiscValue)) { if (!player->CanTakeQuest(quest, false)) return; if (quest->IsAutoAccept() && player->CanAddQuest(quest, false)) player->AddQuestAndCheckCompletion(quest, player); player->PlayerTalkClass->SendQuestGiverQuestDetails(quest, player->GetGUID(), true); } } void Spell::EffectActivateRune() { if (effectHandleMode != SPELL_EFFECT_HANDLE_LAUNCH) return; if (m_caster->GetTypeId() != TYPEID_PLAYER) return; Player* player = m_caster->ToPlayer(); if (player->GetClass() != CLASS_DEATH_KNIGHT) return; // needed later m_runesState = m_caster->ToPlayer()->GetRunesState(); uint32 count = damage; if (count == 0) count = 1; for (uint32 j = 0; j < MAX_RUNES && count > 0; ++j) { if (player->GetRuneCooldown(j) && player->GetCurrentRune(j) == RuneType(effectInfo->MiscValue)) { player->SetRuneCooldown(j, 0); --count; } } // Empower rune weapon if (m_spellInfo->Id == 47568) { // Need to do this just once if (effectInfo->EffectIndex != EFFECT_0) return; for (uint32 i = 0; i < MAX_RUNES; ++i) { if (player->GetRuneCooldown(i) && (player->GetBaseRune(i) == RUNE_FROST)) player->SetRuneCooldown(i, 0); } } } void Spell::EffectCreateTamedPet() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER || unitTarget->GetPetGUID() || unitTarget->GetClass() != CLASS_HUNTER) return; uint32 creatureEntry = effectInfo->MiscValue; Pet* pet = unitTarget->CreateTamedPetFrom(creatureEntry, m_spellInfo->Id); if (!pet) return; // add to world pet->GetMap()->AddToMap(pet->ToCreature()); // unitTarget has pet now unitTarget->SetMinion(pet, true); pet->InitTalentForLevel(); if (unitTarget->GetTypeId() == TYPEID_PLAYER) { pet->SavePetToDB(PET_SAVE_AS_CURRENT); unitTarget->ToPlayer()->PetSpellInitialize(); } } void Spell::EffectDiscoverTaxi() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; uint32 nodeid = effectInfo->MiscValue; if (sTaxiNodesStore.LookupEntry(nodeid)) unitTarget->ToPlayer()->GetSession()->SendDiscoverNewTaxiNode(nodeid); } void Spell::EffectTitanGrip() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; if (m_caster->GetTypeId() == TYPEID_PLAYER) m_caster->ToPlayer()->SetCanTitanGrip(true, effectInfo->MiscValue); } void Spell::EffectRedirectThreat() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; if (unitTarget) unitCaster->GetThreatManager().RegisterRedirectThreat(m_spellInfo->Id, unitTarget->GetGUID(), uint32(damage)); } void Spell::EffectGameObjectDamage() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!gameObjTarget) return; FactionTemplateEntry const* casterFaction = m_caster->GetFactionTemplateEntry(); FactionTemplateEntry const* targetFaction = sFactionTemplateStore.LookupEntry(gameObjTarget->GetFaction()); // Do not allow to damage GO's of friendly factions (ie: Wintergrasp Walls/Ulduar Storm Beacons) if (!targetFaction || (casterFaction && !casterFaction->IsFriendlyTo(*targetFaction))) gameObjTarget->ModifyHealth(-damage, m_caster, GetSpellInfo()->Id); } void Spell::EffectGameObjectRepair() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!gameObjTarget) return; gameObjTarget->ModifyHealth(damage, m_caster); } void Spell::EffectGameObjectSetDestructionState() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!gameObjTarget) return; gameObjTarget->SetDestructibleState(GameObjectDestructibleState(effectInfo->MiscValue), m_caster, true); } void Spell::SummonGuardian(SpellEffectInfo const& spellEffectInfo, uint32 entry, SummonPropertiesEntry const* properties, uint32 numGuardians) { Unit* unitCaster = GetUnitCasterForEffectHandlers(); if (!unitCaster) return; if (unitCaster->IsTotem()) unitCaster = unitCaster->ToTotem()->GetOwner(); // in another case summon new uint8 level = unitCaster->GetLevel(); // level of pet summoned using engineering item based at engineering skill level if (m_CastItem && unitCaster->GetTypeId() == TYPEID_PLAYER) if (ItemTemplate const* proto = m_CastItem->GetTemplate()) if (proto->RequiredSkill == SKILL_ENGINEERING) if (uint16 skill202 = unitCaster->ToPlayer()->GetSkillValue(SKILL_ENGINEERING)) level = skill202 / 5; float radius = 5.0f; int32 duration = m_spellInfo->GetDuration(); if (Player* modOwner = unitCaster->GetSpellModOwner()) modOwner->ApplySpellMod(m_spellInfo->Id, SPELLMOD_DURATION, duration); //TempSummonType summonType = (duration == 0) ? TEMPSUMMON_DEAD_DESPAWN : TEMPSUMMON_TIMED_DESPAWN; Map* map = unitCaster->GetMap(); for (uint32 count = 0; count < numGuardians; ++count) { Position pos; if (count == 0) pos = *destTarget; else // randomize position for multiple summons pos = unitCaster->GetRandomPoint(*destTarget, radius); TempSummon* summon = map->SummonCreature(entry, pos, properties, duration, unitCaster, m_spellInfo->Id); if (!summon) return; if (summon->HasUnitTypeMask(UNIT_MASK_GUARDIAN)) ((Guardian*)summon)->InitStatsForLevel(level); if (properties && properties->Control == SUMMON_CATEGORY_ALLY) summon->SetFaction(unitCaster->GetFaction()); if (summon->HasUnitTypeMask(UNIT_MASK_MINION) && m_targets.HasDst()) ((Minion*)summon)->SetFollowAngle(unitCaster->GetAbsoluteAngle(summon)); if (summon->GetEntry() == 27893) { if (uint32 weapon = unitCaster->GetUInt32Value(PLAYER_VISIBLE_ITEM_16_ENTRYID)) { summon->SetDisplayId(11686); // modelid2 summon->SetUInt32Value(UNIT_VIRTUAL_ITEM_SLOT_ID, weapon); } else summon->SetDisplayId(1126); // modelid1 } ExecuteLogEffectSummonObject(spellEffectInfo.EffectIndex, summon); } } void Spell::EffectRenamePet() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_UNIT || !unitTarget->IsPet() || ((Pet*)unitTarget)->getPetType() != HUNTER_PET) return; unitTarget->SetByteFlag(UNIT_FIELD_BYTES_2, UNIT_BYTES_2_OFFSET_PET_FLAGS, UNIT_CAN_BE_RENAMED); } void Spell::EffectPlayMusic() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; uint32 soundid = effectInfo->MiscValue; if (!sSoundEntriesStore.LookupEntry(soundid)) { TC_LOG_ERROR("spells", "EffectPlayMusic: Sound (Id: %u) does not exist in spell %u.", soundid, m_spellInfo->Id); return; } unitTarget->ToPlayer()->SendDirectMessage(WorldPackets::Misc::PlayMusic(soundid).Write()); } void Spell::EffectSpecCount() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->UpdateSpecCount(damage); } void Spell::EffectActivateSpec() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; unitTarget->ToPlayer()->ActivateSpec(damage-1); // damage is 1 or 2, spec is 0 or 1 } void Spell::EffectPlaySound() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; Player* player = unitTarget->ToPlayer(); if (!player) return; switch (m_spellInfo->Id) { case 58730: // Restricted Flight Area case 58600: // Restricted Flight Area player->GetSession()->SendNotification(LANG_ZONE_NOFLYZONE); break; default: break; } uint32 soundId = effectInfo->MiscValue; if (!sSoundEntriesStore.LookupEntry(soundId)) { TC_LOG_ERROR("spells", "EffectPlaySound: Sound (Id: %u) does not exist in spell %u.", soundId, m_spellInfo->Id); return; } player->PlayDirectSound(soundId, player); } void Spell::EffectRemoveAura() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget) return; // there may be need of specifying casterguid of removed auras unitTarget->RemoveAurasDueToSpell(effectInfo->TriggerSpell); } void Spell::EffectCastButtons() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT) return; Player* player = m_caster->ToPlayer(); if (!player) return; uint32 button_id = effectInfo->MiscValue + 132; uint32 n_buttons = effectInfo->MiscValueB; for (; n_buttons; --n_buttons, ++button_id) { ActionButton const* ab = player->GetActionButton(button_id); if (!ab || ab->GetType() != ACTION_BUTTON_SPELL) continue; //! Action button data is unverified when it's set so it can be "hacked" //! to contain invalid spells, so filter here. uint32 spell_id = ab->GetAction(); if (!spell_id) continue; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(spell_id); if (!spellInfo) continue; if (!player->HasSpell(spell_id) || player->GetSpellHistory()->HasCooldown(spell_id)) continue; if (!spellInfo->HasAttribute(SPELL_ATTR7_SUMMON_PLAYER_TOTEM)) continue; uint32 cost = spellInfo->CalcPowerCost(player, spellInfo->GetSchoolMask()); if (player->GetPower(POWER_MANA) < cost) continue; TriggerCastFlags triggerFlags = TriggerCastFlags(TRIGGERED_IGNORE_GCD | TRIGGERED_IGNORE_CAST_IN_PROGRESS | TRIGGERED_CAST_DIRECTLY); player->CastSpell(player, spell_id, triggerFlags); } } void Spell::EffectRechargeManaGem() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = m_caster->ToPlayer(); if (!player) return; uint32 item_id = effectInfo->ItemType; ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(item_id); if (!pProto) { player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (Item* pItem = player->GetItemByEntry(item_id)) { for (int x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) pItem->SetSpellCharges(x, pProto->Spells[x].SpellCharges); pItem->SetState(ITEM_CHANGED, player); } } void Spell::EffectBind() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (!unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; Player* player = unitTarget->ToPlayer(); WorldLocation homeLoc; uint32 areaId = player->GetAreaId(); if (effectInfo->MiscValue) areaId = effectInfo->MiscValue; if (m_targets.HasDst()) homeLoc.WorldRelocate(*destTarget); else homeLoc = player->GetWorldLocation(); player->SetHomebind(homeLoc, areaId); player->SendBindPointUpdate(); TC_LOG_DEBUG("spells", "EffectBind: New homebind X: %f, Y: %f, Z: %f, MapId: %u, AreaId: %u", homeLoc.GetPositionX(), homeLoc.GetPositionY(), homeLoc.GetPositionZ(), homeLoc.GetMapId(), areaId); // zone update WorldPackets::Misc::PlayerBound packet(m_caster->GetGUID(), areaId); player->SendDirectMessage(packet.Write()); } void Spell::EffectSummonRaFFriend() { if (effectHandleMode != SPELL_EFFECT_HANDLE_HIT_TARGET) return; if (m_caster->GetTypeId() != TYPEID_PLAYER || !unitTarget || unitTarget->GetTypeId() != TYPEID_PLAYER) return; m_caster->CastSpell(unitTarget, effectInfo->TriggerSpell, true); }
ElunaLuaEngine/ElunaTrinityWotlk
src/server/game/Spells/SpellEffects.cpp
C++
gpl-2.0
204,972
/* * Copyright (C) 2006 Gérard Milmeister * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * */ package org.rubato.logeo.reform; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.rubato.base.RubatoException; import org.rubato.math.module.Module; import org.rubato.math.yoneda.*; class RecursiveLimitReformer extends LimitReformer { public static RecursiveLimitReformer make(LimitForm from, LimitForm to) { RecursiveLimitReformer reformer = null; List<Form> fromForms = new LinkedList<Form>(); collectForms(from, fromForms); List<Form> toForms = new LinkedList<Form>(); collectForms(to, toForms); if (fromForms.size() == toForms.size()) { Reformer[] reformers = new Reformer[fromForms.size()]; Iterator<Form> from_iter = fromForms.iterator(); Iterator<Form> to_iter = toForms.iterator(); for (int i = 0; i < reformers.length; i++) { reformers[i] = Reformer._make(from_iter.next(), to_iter.next()); if (reformers[i] == null) { return null; } } reformer = new RecursiveLimitReformer(to, reformers); } return reformer; } private static void collectForms(LimitForm form, List<Form> forms) { for (Form f : form.getForms()) { if (f instanceof LimitForm) { collectForms((LimitForm)f, forms); } else { forms.add(f); } } } public Denotator reform(Denotator d) throws RubatoException { LimitDenotator ld = (LimitDenotator)d; List<Denotator> fromList = new LinkedList<Denotator>(); collectDenotators(ld, fromList); List<Denotator> toList = new LinkedList<Denotator>(); int i = 0; for (Denotator from : fromList) { toList.add(reformers[i++].reform(from)); } return distributeDenotators(toList, d.getAddress(), to); } private void collectDenotators(LimitDenotator deno, List<Denotator> denos) { for (Denotator d : deno.getFactors()) { if (d instanceof LimitDenotator) { collectDenotators((LimitDenotator)d, denos); } else { denos.add(d); } } } private Denotator distributeDenotators(List<Denotator> denos, Module address, LimitForm toForm) { List<Denotator> list = new LinkedList<Denotator>(); for (Form f : toForm.getForms()) { if (f instanceof LimitForm) { list.add(distributeDenotators(denos, address, (LimitForm)f)); } else { list.add(denos.remove(0)); } } return LimitDenotator._make_unsafe(null, address, toForm, list); } private RecursiveLimitReformer(LimitForm to, Reformer[] reformers) { this.to = to; this.reformers = reformers; } private LimitForm to; private Reformer[] reformers; }
wells369/Rubato
java/src/org/rubato/logeo/reform/RecursiveLimitReformer.java
Java
gpl-2.0
3,764
/* Copyright 2005-2007 Adobe Systems Incorporated Distributed under the MIT License (see accompanying file LICENSE_1_0_0.txt or a copy at http://opensource.adobe.com/licenses.html) */ /*************************************************************************************************/ #ifndef GIL_CHANNEL_NUMERIC_OPERATIONS_HPP #define GIL_CHANNEL_NUMERIC_OPERATIONS_HPP /*! /// \file /// \brief Structures for channel-wise numeric operations /// \author Hailin Jin and Lubomir Bourdev \n /// Adobe Systems Incorporated /// \date 2005-2007 \n Last updated on September 30, 2006 /// Currently defined structures: /// channel_plus_t (+), channel_minus_t (-), /// channel_multiplies_t (*), channel_divides_t (/), /// channel_plus_scalar_t (+s), channel_minus_scalar_t (-s), /// channel_multiplies_scalar_t (*s), channel_divides_scalar_t (/s), /// channel_halves_t (/=2), channel_zeros_t (=0), channel_assigns_t (=) */ #include <functional> #include <boost/version.hpp> #if BOOST_VERSION < 106900 #include <boost/gil/gil_config.hpp> #else #include <boost/gil.hpp> #endif #include <boost/gil/channel.hpp> namespace boost { namespace gil { /// \ingroup ChannelNumericOperations /// structure for adding one channel to another /// this is a generic implementation; user should specialize it for better performance template <typename Channel1,typename Channel2,typename ChannelR> struct channel_plus_t : public std::binary_function<Channel1,Channel2,ChannelR> { ChannelR operator()(typename channel_traits<Channel1>::const_reference ch1, typename channel_traits<Channel2>::const_reference ch2) const { return ChannelR(ch1)+ChannelR(ch2); } }; /// \ingroup ChannelNumericOperations /// structure for subtracting one channel from another /// this is a generic implementation; user should specialize it for better performance template <typename Channel1,typename Channel2,typename ChannelR> struct channel_minus_t : public std::binary_function<Channel1,Channel2,ChannelR> { ChannelR operator()(typename channel_traits<Channel1>::const_reference ch1, typename channel_traits<Channel2>::const_reference ch2) const { return ChannelR(ch1)-ChannelR(ch2); } }; /// \ingroup ChannelNumericOperations /// structure for multiplying one channel to another /// this is a generic implementation; user should specialize it for better performance template <typename Channel1,typename Channel2,typename ChannelR> struct channel_multiplies_t : public std::binary_function<Channel1,Channel2,ChannelR> { ChannelR operator()(typename channel_traits<Channel1>::const_reference ch1, typename channel_traits<Channel2>::const_reference ch2) const { return ChannelR(ch1)*ChannelR(ch2); } }; /// \ingroup ChannelNumericOperations /// structure for dividing channels /// this is a generic implementation; user should specialize it for better performance template <typename Channel1,typename Channel2,typename ChannelR> struct channel_divides_t : public std::binary_function<Channel1,Channel2,ChannelR> { ChannelR operator()(typename channel_traits<Channel1>::const_reference ch1, typename channel_traits<Channel2>::const_reference ch2) const { return ChannelR(ch1)/ChannelR(ch2); } }; /// \ingroup ChannelNumericOperations /// structure for adding a scalar to a channel /// this is a generic implementation; user should specialize it for better performance template <typename Channel,typename Scalar,typename ChannelR> struct channel_plus_scalar_t : public std::binary_function<Channel,Scalar,ChannelR> { ChannelR operator()(typename channel_traits<Channel>::const_reference ch, const Scalar& s) const { return ChannelR(ch)+ChannelR(s); } }; /// \ingroup ChannelNumericOperations /// structure for subtracting a scalar from a channel /// this is a generic implementation; user should specialize it for better performance template <typename Channel,typename Scalar,typename ChannelR> struct channel_minus_scalar_t : public std::binary_function<Channel,Scalar,ChannelR> { ChannelR operator()(typename channel_traits<Channel>::const_reference ch, const Scalar& s) const { return ChannelR(ch-s); } }; /// \ingroup ChannelNumericOperations /// structure for multiplying a scalar to one channel /// this is a generic implementation; user should specialize it for better performance template <typename Channel,typename Scalar,typename ChannelR> struct channel_multiplies_scalar_t : public std::binary_function<Channel,Scalar,ChannelR> { ChannelR operator()(typename channel_traits<Channel>::const_reference ch, const Scalar& s) const { return ChannelR(ch)*ChannelR(s); } }; /// \ingroup ChannelNumericOperations /// structure for dividing a channel by a scalar /// this is a generic implementation; user should specialize it for better performance template <typename Channel,typename Scalar,typename ChannelR> struct channel_divides_scalar_t : public std::binary_function<Channel,Scalar,ChannelR> { ChannelR operator()(typename channel_traits<Channel>::const_reference ch, const Scalar& s) const { return ChannelR(ch)/ChannelR(s); } }; /// \ingroup ChannelNumericOperations /// structure for halving a channel /// this is a generic implementation; user should specialize it for better performance template <typename Channel> struct channel_halves_t : public std::unary_function<Channel,Channel> { typename channel_traits<Channel>::reference operator()(typename channel_traits<Channel>::reference ch) const { return ch/=2.0; } }; /// \ingroup ChannelNumericOperations /// structure for setting a channel to zero /// this is a generic implementation; user should specialize it for better performance template <typename Channel> struct channel_zeros_t : public std::unary_function<Channel,Channel> { typename channel_traits<Channel>::reference operator()(typename channel_traits<Channel>::reference ch) const { return ch=Channel(0); } }; /// \ingroup ChannelNumericOperations /// structure for assigning one channel to another /// this is a generic implementation; user should specialize it for better performance template <typename Channel1,typename Channel2> struct channel_assigns_t : public std::binary_function<Channel1,Channel2,Channel2> { typename channel_traits<Channel2>::reference operator()(typename channel_traits<Channel1>::const_reference ch1, typename channel_traits<Channel2>::reference ch2) const { return ch2=Channel2(ch1); } }; } } // namespace boost::gil #endif
K-3D/k3d
k3dsdk/gil/boost/gil/extension/numeric/channel_numeric_operations.hpp
C++
gpl-2.0
6,955
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 1.8 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2007 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the Affero General Public License Version 1, | | March 2002. | | | | CiviCRM is distributed in the hope that it will be useful, but | | WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | See the Affero General Public License for more details. | | | | You should have received a copy of the Affero General Public | | License along with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2007 * $Id$ * */ require_once 'CRM/Core/DAO/CustomGroup.php'; /** * Business object for managing custom data groups * */ class CRM_Core_BAO_CustomGroup extends CRM_Core_DAO_CustomGroup { /** * class constructor */ function __construct( ) { parent::__construct( ); } /** * takes an associative array and creates a custom group object * * @param array $params (reference) an assoc array of name/value pairs * * @return object CRM_Core_DAO_CustomGroup object * @access public * @static */ static function create(&$params) { $customGroupBAO =& new CRM_Core_BAO_CustomGroup(); $customGroupBAO->copyValues($params); return $customGroupBAO->save(); } /** * Takes a bunch of params that are needed to match certain criteria and * retrieves the relevant objects. Typically the valid params are only * contact_id. We'll tweak this function to be more full featured over a period * of time. This is the inverse function of create. It also stores all the retrieved * values in the default array * * @param array $params (reference ) an assoc array of name/value pairs * @param array $defaults (reference ) an assoc array to hold the flattened values * * @return object CRM_Core_DAO_CustomGroup object * @access public * @static */ static function retrieve(&$params, &$defaults) { return CRM_Core_DAO::commonRetrieve( 'CRM_Core_DAO_CustomGroup', $params, $defaults ); } /** * update the is_active flag in the db * * @param int $id id of the database record * @param boolean $is_active value we want to set the is_active field * * @return Object DAO object on sucess, null otherwise * @static * @access public */ static function setIsActive($id, $is_active) { return CRM_Core_DAO::setFieldValue( 'CRM_Core_DAO_CustomGroup', $id, 'is_active', $is_active ); } /** * Get custom groups/fields for type of entity. * * An array containing all custom groups and their custom fields is returned. * * @param string $entityType - of the contact whose contact type is needed * @param int $entityId - optional - id of entity if we need to populate the tree with custom values. * @param int $groupId - optional group id (if we need it for a single group only) * - if groupId is 0 it gets for inline groups only * - if groupId is -1 we get for all groups * * @return array $groupTree - array consisting of all groups and fields and optionally populated with custom data values. * * @access public * * @static * */ public static function &getTree($entityType, $entityId=null, $groupId=0, $subType = null) { // create a new tree $groupTree = array(); $strSelect = $strFrom = $strWhere = $orderBy = ''; $tableData = array(); // using tableData to build the queryString $tableData = array( 'civicrm_custom_field' => array('id', 'name', 'label', 'data_type', 'html_type', 'default_value', 'attributes', 'is_required', 'help_post', 'options_per_line', 'start_date_years', 'end_date_years', 'date_parts'), 'civicrm_custom_group' => array('id', 'name', 'title', 'help_pre', 'help_post', 'collapse_display'), ); // since we have an entity id, lets get it's custom values too. if ($entityId) { $tableData['civicrm_custom_value'] = array('id', 'int_data', 'float_data', 'decimal_data', 'char_data', 'date_data', 'memo_data', 'file_id'); } // create select $strSelect = "SELECT"; foreach ($tableData as $tableName => $tableColumn) { foreach ($tableColumn as $columnName) { $alias = $tableName . "_" . $columnName; $strSelect .= " $tableName.$columnName as $alias,"; } } $strSelect = rtrim($strSelect, ','); // from, where, order by $strFrom = " FROM civicrm_custom_group LEFT JOIN civicrm_custom_field ON (civicrm_custom_field.custom_group_id = civicrm_custom_group.id) "; if ($entityId) { if ($entityType == "Activity") { if ( $subType == 1) { $activityType = "Meeting"; } else if($subType == 2) { $activityType = "Phonecall"; } else { $activityType = "Activity"; } $tableName = self::_getTableName($activityType); } else { $tableName = self::_getTableName($entityType); } $strFrom .= " LEFT JOIN civicrm_custom_value ON ( civicrm_custom_value.custom_field_id = civicrm_custom_field.id AND civicrm_custom_value.entity_table = '$tableName' AND civicrm_custom_value.entity_id = $entityId ) "; } // if entity is either individual, organization or household pls get custom groups for 'contact' too. if ($entityType == "Individual" || $entityType == 'Organization' || $entityType == 'Household') { $in = "'$entityType', 'Contact'"; } else { $in = "'$entityType'"; } $domainID = CRM_Core_Config::domainID( ); if ( $subType ) { $strWhere = " WHERE civicrm_custom_group.domain_id = $domainID AND civicrm_custom_group.is_active = 1 AND civicrm_custom_field.is_active = 1 AND civicrm_custom_group.extends IN ($in) AND ( civicrm_custom_group.extends_entity_column_value = '$subType' OR civicrm_custom_group.extends_entity_column_value IS NULL ) "; } else { $strWhere = " WHERE civicrm_custom_group.domain_id = $domainID AND civicrm_custom_group.is_active = 1 AND civicrm_custom_field.is_active = 1 AND civicrm_custom_group.extends IN ($in) AND civicrm_custom_group.extends_entity_column_value IS NULL "; } $params = array( ); if ($groupId > 0) { // since we want a specific group id we add it to the where clause $strWhere .= " AND civicrm_custom_group.style = 'Tab' AND civicrm_custom_group.id = %1"; $params[1] = array( $groupId, 'Integer' ); } else if ($groupId == 0){ // since groupId is 0 we need to show all Inline groups $strWhere .= " AND civicrm_custom_group.style = 'Inline'"; } require_once 'CRM/Core/Permission.php'; // ensure that the user has access to these custom groups $strWhere .= " AND " . CRM_Core_Permission::customGroupClause( CRM_Core_Permission::VIEW, 'civicrm_custom_group.' ); $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_group.title, civicrm_custom_field.weight, civicrm_custom_field.label "; // final query string $queryString = $strSelect . $strFrom . $strWhere . $orderBy; // dummy dao needed $crmDAO =& CRM_Core_DAO::executeQuery( $queryString, $params ); // process records while($crmDAO->fetch()) { // get the id's $groupId = $crmDAO->civicrm_custom_group_id; $fieldId = $crmDAO->civicrm_custom_field_id; // create an array for groups if it does not exist if (!array_key_exists($groupId, $groupTree)) { $groupTree[$groupId] = array(); $groupTree[$groupId]['id'] = $groupId; // populate the group information foreach ($tableData['civicrm_custom_group'] as $fieldName) { $fullFieldName = 'civicrm_custom_group_' . $fieldName; if ($fieldName == 'id' || is_null($crmDAO->$fullFieldName)) { continue; } $groupTree[$groupId][$fieldName] = $crmDAO->$fullFieldName; } $groupTree[$groupId]['fields'] = array(); } // add the fields now (note - the query row will always contain a field) // we only reset this once, since multiple values come is as multiple rows if ( ! array_key_exists( $fieldId, $groupTree[$groupId]['fields'] ) ) { $groupTree[$groupId]['fields'][$fieldId] = array(); } $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId; // populate information for a custom field foreach ($tableData['civicrm_custom_field'] as $fieldName) { $fullFieldName = "civicrm_custom_field_" . $fieldName; if ($fieldName == 'id' || is_null($crmDAO->$fullFieldName)) { continue; } $groupTree[$groupId]['fields'][$fieldId][$fieldName] = $crmDAO->$fullFieldName; } // check for custom values please if ( isset( $crmDAO->civicrm_custom_value_id ) && $crmDAO->civicrm_custom_value_id ) { $valueId = $crmDAO->civicrm_custom_value_id; // create an array for storing custom values for that field $customValue = array(); $customValue['id'] = $valueId; $dataType = $groupTree[$groupId]['fields'][$fieldId]['data_type']; switch ($dataType) { case 'String': $customValue['data'] = $crmDAO->civicrm_custom_value_char_data; break; case 'Int': case 'Boolean': case 'StateProvince': case 'Country': $customValue['data'] = $crmDAO->civicrm_custom_value_int_data; break; case 'Float': $customValue['data'] = $crmDAO->civicrm_custom_value_float_data; break; case 'Money': $customValue['data'] = $crmDAO->civicrm_custom_value_decimal_data; break; case 'Memo': $customValue['data'] = $crmDAO->civicrm_custom_value_memo_data; break; case 'Date': $customValue['data'] = $crmDAO->civicrm_custom_value_date_data; break; case 'File': require_once 'CRM/Core/DAO/File.php'; $config =& CRM_Core_Config::singleton( ); $fileDAO =& new CRM_Core_DAO_File(); $fileDAO->id = $crmDAO->civicrm_custom_value_file_id; if ( $fileDAO->find(true) ) { $customValue['data'] = $fileDAO->uri; $customValue['fid'] = $fileDAO->id; $customValue['fileURL'] = CRM_Utils_System::url( 'civicrm/file', "reset=1&id={$fileDAO->id}&eid=$entityId" ); $customValue['displayURL'] = null; $deleteExtra = ts('Are you sure you want to delete attached file.'); $deleteURL = array(CRM_Core_Action::DELETE => array( 'name' => ts('Delete Attached File'), 'url' => 'civicrm/file', 'qs' => 'reset=1&id=%%id%%&eid=%%eid%%&action=delete', 'extra' => 'onclick = "if (confirm( \''. $deleteExtra .'\' ) ) this.href+=\'&amp;confirmed=1\'; else return false;"' ) ); $customValue['deleteURL'] = CRM_Core_Action::formLink($deleteURL, CRM_Core_Action::DELETE, array('id' => $fileDAO->id,'eid' => $entityId )); $customValue['fileName'] = basename( $fileDAO->uri ); if ( $fileDAO->mime_type =="image/jpeg" || $fileDAO->mime_type =="image/gif" || $fileDAO->mime_type =="image/png" ) { $customValue['displayURL'] = $customValue['fileURL']; } } break; case 'Link': $customValue['data'] = $crmDAO->civicrm_custom_value_char_data; break; } if ( ! empty( $customValue ) ) { $groupTree[$groupId]['fields'][$fieldId]['customValue'] = $customValue; } } } $uploadNames = array(); foreach ($groupTree as $key1 => $group) { foreach ($group['fields'] as $key2 => $field) { if ( $field['data_type'] == 'File' ) { $fieldId = $field['id']; $elementName = 'custom_' . $fieldId; $uploadNames[] = $elementName; } } } //hack for field type File $session = & CRM_Core_Session::singleton( ); $session->set('uploadNames', $uploadNames); return $groupTree; } /** * Update custom data. * * - custom data is modified as follows * - if custom data is changed it's updated. * - if custom data is newly entered in field, it's inserted into db, finally * - if existing custom data is cleared, it is deleted from the table. * * @param array &$groupTree - array of all custom groups, fields and values. * @param string $entityType - type of entity being extended * @param int $entityId - id of the contact whose custom data is to be updated * @return void * * @access public * @static * */ public static function updateCustomData(&$groupTree, $entityType, $entityId) { $tableName = self::_getTableName($entityType); // traverse the group tree foreach ($groupTree as $group) { $groupId = $group['id']; // traverse fields foreach ($group['fields'] as $field) { $fieldId = $field['id']; /** * $field['customValue'] is set in the tree in the following cases * - data existed in db for that field * - new data was entered in the "form" for that field */ if (isset($field['customValue'])) { // customValue exists hence we need a DAO. require_once "CRM/Core/DAO/CustomValue.php"; $customValueDAO =& new CRM_Core_DAO_CustomValue(); $customValueDAO->entity_table = $tableName; $customValueDAO->custom_field_id = $fieldId; $customValueDAO->entity_id = $entityId; // check if it's an update or new one if (isset($field['customValue']['id'])) { // get the id of row in civicrm_custom_value $customValueDAO->id = $field['customValue']['id']; } $data = $field['customValue']['data']; // since custom data is empty, delete it from db. // note we cannot use a plain if($data) since data could have a value "0" // which will result in a !false expression // and accidental deletion of data. // especially true in the case of radio buttons where we are using the values // 1 - true and 0 for false. if (! strlen(trim($data) ) ) { if($field['data_type'] != 'File') { $customValueDAO->delete(); } continue; } // data is not empty switch ($field['data_type']) { case 'String': $customValueDAO->char_data = $data; break; case 'Int': case 'Boolean': case 'StateProvince': case 'Country': $customValueDAO->int_data = $data; break; case 'Float': $customValueDAO->float_data = $data; break; case 'Money': $customValueDAO->decimal_data = CRM_Utils_Rule::cleanMoney( $data ); //$customValueDAO->decimal_data = number_format( $data, 2, '.', '' ); break; case 'Memo': $customValueDAO->memo_data = $data; break; case 'Date': $customValueDAO->date_data = $data; break; case 'File': require_once 'CRM/Core/DAO/File.php'; $config = & CRM_Core_Config::singleton(); $path = explode( '/', $data ); $filename = $path[count($path) - 1]; // rename this file to go into the secure directory if ( ! rename( $data, $config->customFileUploadDir . $filename ) ) { CRM_Core_Error::statusBounce( ts( 'Could not move custom file to custom upload directory' ) ); break; } //$customValueDAO->char_data = $config->customFileUploadDir . $filename; $customValueDAO->char_data = $filename; $mimeType = $_FILES['custom_'.$field['id']]['type']; $fileDAO =& new CRM_Core_DAO_File(); if (isset($field['customValue']['fid'])) { $fileDAO->id = $field['customValue']['fid']; } $fileDAO->uri = $filename; $fileDAO->mime_type = $mimeType; $fileDAO->upload_date = date('Ymdhis'); $fileDAO->save(); $customValueDAO->file_id = $fileDAO->id; // need to add/update civicrm_entity_file require_once 'CRM/Core/DAO/EntityFile.php'; $entityFileDAO =& new CRM_Core_DAO_EntityFile(); if ( isset($field['customValue']['fid'] )) { $entityFileDAO->file_id = $field['customValue']['fid']; $entityFileDAO->find(true); } $entityFileDAO->entity_table = $tableName; $entityFileDAO->entity_id = $entityId; $entityFileDAO->file_id = $fileDAO->id; $entityFileDAO->save(); break; case 'Link': $customValueDAO->char_data = $data; break; } // insert/update of custom value $customValueDAO->save(); } } } } /** * Get number of elements for a particular group. * * This method returns the number of entries in the civicrm_custom_value table for this particular group. * * @param int $groupId - id of group. * @return int $numValue - number of custom data values for this group. * * @access public * @static * */ public static function getNumValue($groupId) { $query = "SELECT count(*) FROM civicrm_custom_value, civicrm_custom_field WHERE civicrm_custom_value.custom_field_id = civicrm_custom_field.id AND civicrm_custom_field.custom_group_id = %1"; $params = array( 1 => array( $groupId, 'Integer' ) ); return CRM_Core_DAO::singleValueQuery( $query, $params ); } /** * Get the group title. * * @param int $id id of group. * @return string title * * @access public * @static * */ public static function getTitle( $id ) { return CRM_Core_DAO::getFieldValue( 'CRM_Core_DAO_CustomGroup', $id, 'title' ); } /** * Get custom group details for a group. * * An array containing custom group details (including their custom field) is returned. * * @param int $groupId - group id whose details are needed * @param boolean $searchable - is this field searchable * @param extends $extends - which table does it extend if any * @return array $groupTree - array consisting of all group and field details * * @access public * * @static * */ public static function getGroupDetail($groupId = null, $searchable = null, $extends = null) { // create a new tree $groupTree = array(); $select = $from = $where = $orderBy = ''; $tableData = array(); // using tableData to build the queryString $tableData = array( 'civicrm_custom_field' => array('id', 'name', 'label', 'data_type', 'html_type', 'default_value', 'attributes', 'is_required', 'help_post', 'options_per_line', 'is_searchable', 'start_date_years', 'end_date_years', 'is_search_range', 'date_parts', 'note_columns', 'note_rows'), 'civicrm_custom_group' => array('id', 'name', 'title', 'help_pre', 'help_post', 'collapse_display', 'extends', 'extends_entity_column_value' ), ); // create select $select = "SELECT"; $s = array( ); foreach ($tableData as $tableName => $tableColumn) { foreach ($tableColumn as $columnName) { $s[] = "{$tableName}.{$columnName} as {$tableName}_{$columnName}"; } } $select = 'SELECT ' . implode( ', ', $s ); $params = array( ); // from, where, order by $from = " FROM civicrm_custom_field, civicrm_custom_group"; $where = " WHERE civicrm_custom_field.custom_group_id = civicrm_custom_group.id AND civicrm_custom_group.is_active = 1 AND civicrm_custom_field.is_active = 1 "; if ( $groupId ) { $params[1] = array( $groupId, 'Integer' ); $where .= " AND civicrm_custom_group.id = %1"; } if ( $searchable ) { $where .= " AND civicrm_custom_field.is_searchable = 1"; } if ( $extends ) { $clause = array( ); foreach ( $extends as $e ) { $clause[] = "civicrm_custom_group.extends = '$e'"; } $where .= " AND ( " . implode( ' OR ', $clause ) . " ) "; } $orderBy = " ORDER BY civicrm_custom_group.weight, civicrm_custom_field.weight"; // final query string $queryString = $select . $from . $where . $orderBy; // dummy dao needed $crmDAO =& CRM_Core_DAO::executeQuery( $queryString, $params ); // process records while($crmDAO->fetch()) { $groupId = $crmDAO->civicrm_custom_group_id; $fieldId = $crmDAO->civicrm_custom_field_id; // create an array for groups if it does not exist if (!array_key_exists($groupId, $groupTree)) { $groupTree[$groupId] = array(); $groupTree[$groupId]['id'] = $groupId; $groupTree[$groupId]['name'] = $crmDAO->civicrm_custom_group_name; $groupTree[$groupId]['title'] = $crmDAO->civicrm_custom_group_title; $groupTree[$groupId]['help_pre'] = $crmDAO->civicrm_custom_group_help_pre; $groupTree[$groupId]['help_post'] = $crmDAO->civicrm_custom_group_help_post; $groupTree[$groupId]['collapse_display'] = $crmDAO->civicrm_custom_group_collapse_display; $groupTree[$groupId]['extends'] = $crmDAO->civicrm_custom_group_extends; $groupTree[$groupId]['extends_entity_column_value'] = $crmDAO->civicrm_custom_group_extends_entity_column_value; $groupTree[$groupId]['fields'] = array(); } // add the fields now (note - the query row will always contain a field) $groupTree[$groupId]['fields'][$fieldId] = array(); $groupTree[$groupId]['fields'][$fieldId]['id'] = $fieldId; foreach ($tableData['civicrm_custom_field'] as $v) { $fullField = "civicrm_custom_field_" . $v; if ($v == 'id' || is_null($crmDAO->$fullField)) { continue; } $groupTree[$groupId]['fields'][$fieldId][$v] = $crmDAO->$fullField; } } return $groupTree; } /** * * This function does 2 things - * 1 - Create menu tabs for all custom groups with style 'Tab' * 2 - Updates tab for custom groups with style 'Inline'. If there * are no inline groups it removes the 'Custom Data' tab * * * @param string $entityType - what entity are we extending here ? * @param string $path - what should be the starting path for the new menus ? * @param int $startWeight - weight to start the local menu tabs * * @return void * * @access public * @static * */ public static function addMenuTabs($entityType, $path, $startWeight) { $groups =& self::getActiveGroups( $entityType, $path ); foreach( $groups as $group ) { $group['weight'] = $startWeight++; CRM_Core_Menu::add( $group ); } } public static function &getActiveGroups( $entityType, $path, $cidToken = '%%cid%%' ) { // for Group's $customGroupDAO =& new CRM_Core_DAO_CustomGroup(); // get only 'Tab' groups $customGroupDAO->whereAdd("style = 'Tab'"); $customGroupDAO->whereAdd("is_active = 1"); $customGroupDAO->whereAdd("domain_id =" . CRM_Core_Config::domainID() ); // add whereAdd for entity type self::_addWhereAdd($customGroupDAO, $entityType); $groups = array( ); $permissionClause = CRM_Core_Permission::customGroupClause( ); $customGroupDAO->whereAdd( $permissionClause ); // order by weight $customGroupDAO->orderBy('weight'); $customGroupDAO->find(); // process each group with menu tab while ($customGroupDAO->fetch( ) ) { $group = array(); $group['id'] = $customGroupDAO->id; $group['path'] = $path; $group['title'] = "$customGroupDAO->title"; $group['query'] = "reset=1&gid={$customGroupDAO->id}&cid={$cidToken}"; $group['type'] = CRM_Core_Menu::CALLBACK; $group['crmType'] = CRM_Core_Menu::LOCAL_TASK; $group['extra' ] = array( 'gid' => $customGroupDAO->id ); $groups[] = $group; } return $groups; } /** * Get the table name for the entity type * currently if entity type is 'Contact', 'Individual', 'Household', 'Organization' * tableName is 'civicrm_contact' * * @param string $entityType what entity are we extending here ? * * @return string $tableName * * @access private * @static * */ private static function _getTableName($entityType) { $tableName = ''; switch($entityType) { case 'Contact': case 'Individual': case 'Household': case 'Organization': $tableName = 'civicrm_contact'; break; case 'Contribution': $tableName = 'civicrm_contribution'; break; case 'Group': $tableName = 'civicrm_group'; break; case 'Activity': $tableName = 'civicrm_activity'; break; case 'Relationship': $tableName = 'civicrm_relationship'; break; case 'Phonecall': $tableName = 'civicrm_phonecall'; break; case 'Meeting': $tableName = 'civicrm_meeting'; break; case 'Membership': $tableName = 'civicrm_membership'; break; case 'Participant': $tableName = 'civicrm_participant'; break; case 'Event': $tableName = 'civicrm_event'; break; // need to add cases for Location, Address } return $tableName; } /** * Add the whereAdd clause for the DAO depending on the type of entity * the custom group is extending. * * @param object CRM_Core_DAO_CustomGroup (reference) - Custom Group DAO. * @param string $entityType - what entity are we extending here ? * * @return void * * @access private * @static * */ private static function _addWhereAdd(&$customGroupDAO, $entityType) { switch($entityType) { case 'Contact': // if contact, get all related to contact $customGroupDAO->whereAdd("extends IN ('Contact', 'Individual', 'Household', 'Organization')"); break; case 'Individual': case 'Household': case 'Organization': // is I/H/O then get I/H/O and contact $customGroupDAO->whereAdd("extends IN ('Contact', '$entityType')"); break; case 'Location': case 'Address': $customGroupDAO->whereAdd("extends IN ('$entityType')"); break; } } /** * Delete the Custom Group. * * @param int $id Group Id * * @return boolean false if field exists for this group, true if group gets deleted. * * @access public * @static * */ public static function deleteGroup($id) { require_once 'CRM/Core/DAO/CustomField.php'; //check wheter this contain any custom fields $custonField = & new CRM_Core_DAO_CustomField(); $custonField->custom_group_id = $id; $custonField->find(); while($custonField->fetch()) { return false; } //delete custom group $group = & new CRM_Core_DAO_CustomGroup(); $group->id = $id; $group->delete(); return true; } static function setDefaults( &$groupTree, &$defaults, $viewMode, $inactiveNeeded ) { foreach ( $groupTree as $group ) { $groupId = $group['id']; foreach ($group['fields'] as $field) { if ( CRM_Utils_Array::value( 'customValue', $field ) !== null ) { $value = $field['customValue']['data']; } else if ( CRM_Utils_Array::value( 'default_value', $field ) !== null ) { $value = $viewMode ? null : $field['default_value']; } else { continue; } $fieldId = $field['id']; $elementName = 'custom_' . $fieldId; switch($field['html_type']) { case 'CheckBox': if ($viewMode) { $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded); $customValues = CRM_Core_BAO_CustomOption::getCustomValues($field['id']); $checkedData = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, substr($value,1,-1)); $defaults[$elementName] = array(); if(isset($value)) { foreach($customOption as $val) { if (is_array($customValues)) { if (in_array($val['value'], $checkedData)) { $defaults[$elementName][$val['value']] = 1; } else { $defaults[$elementName][$val['value']] = 0; } } } } } else { $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded); $defaults[$elementName] = array(); if (isset($field['customValue']['data'])) { $checkedData = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR,substr($field['customValue']['data'],1,-1)); foreach($customOption as $val) { if (in_array($val['value'], $checkedData)) { $defaults[$elementName][$val['value']] = 1; } else { $defaults[$elementName][$val['value']] = 0; } } } else { $checkedValue = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, substr($value,1,-1)); foreach($customOption as $val) { if ( in_array($val['value'], $checkedValue) ) { $defaults[$elementName][$val['value']] = 1; } else { $defaults[$elementName][$val['value']] = 0; } } } } break; //added a case for Multi-Select option case 'Multi-Select': if ($viewMode) { $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded); $customValues = CRM_Core_BAO_CustomOption::getCustomValues($field['id']); $checkedData = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, substr($value,1,-1)); $defaults[$elementName] = array(); if(isset($value)) { foreach($customOption as $val) { if (is_array($customValues)) { if (in_array($val['value'], $checkedData)) { $defaults[$elementName][$val['value']] = $val['value']; } } } } } else { $customOption = CRM_Core_BAO_CustomOption::getCustomOption($field['id'], $inactiveNeeded); $defaults[$elementName] = array(); if (isset($field['customValue']['data'])) { $checkedData = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, substr($field['customValue']['data'],1,-1)); foreach($customOption as $val) { if (in_array($val['value'], $checkedData)) { //$defaults[$elementName][$val['value']] = 1; $defaults[$elementName][$val['value']] = $val['value']; } } } else { $checkedValue = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, substr($value,1,-1)); foreach($customOption as $val) { if ( in_array($val['value'], $checkedValue) ) { $defaults[$elementName][$val['value']] = $val['value']; } } } } break; case 'Select Date': if (isset($value)) { $defaults[$elementName] = CRM_Utils_Date::unformat( $value, '-' ); } break; case 'Select Country': if ( $value ) { $defaults[$elementName] = $value; } else { $config =& CRM_Core_Config::singleton( ); $defaults[$elementName] = $config->defaultContactCountry; } break; default: if ($field['data_type'] == "Float") { $defaults[$elementName] = (float)$value; } else { $defaults[$elementName] = $value; } } } } } static function postProcess( &$groupTree, &$params ) { // CRM_Core_Error::debug( 'g', $groupTree ); // CRM_Core_Error::debug( 'p', $params ); // Get the Custom form values and groupTree // first reset all checkbox and radio data foreach ($groupTree as $group) { foreach ($group['fields'] as $field) { $groupId = $group['id']; $fieldId = $field['id']; //added Multi-Select option in the below if-statement if ( $field['html_type'] == 'CheckBox' || $field['html_type'] == 'Radio' || $field['html_type'] == 'Multi-Select' ) { $groupTree[$groupId]['fields'][$fieldId]['customValue']['data'] = 'NULL'; } $v = CRM_Utils_Array::value( 'custom_' . $field['id'], $params ); if ( ! isset($groupTree[$groupId]['fields'][$fieldId]['customValue'] ) ) { // field exists in db so populate value from "form". $groupTree[$groupId]['fields'][$fieldId]['customValue'] = array(); } switch ( $groupTree[$groupId]['fields'][$fieldId]['html_type'] ) { case 'CheckBox': $optionDAO =& new CRM_Core_DAO_CustomOption(); $optionDAO->custom_field_id = $fieldId; $optionDAO->find(); $optionValue = array(); while($optionDAO->fetch() ) { $optionValue[$optionDAO->label] = $optionDAO->value; } if ( ! empty( $v ) ) { $customValue = array_keys( $v ); $groupTree[$groupId]['fields'][$fieldId]['customValue']['data'] = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR.implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $customValue).CRM_Core_BAO_CustomOption::VALUE_SEPERATOR; } else { $groupTree[$groupId]['fields'][$fieldId]['customValue']['data'] = null; } break; //added for Multi-Select case 'Multi-Select': $optionDAO =& new CRM_Core_DAO_CustomOption(); $optionDAO->custom_field_id = $fieldId; $optionDAO->find(); $optionValue = array(); while($optionDAO->fetch() ) { $optionValue[$optionDAO->label] = $optionDAO->value; } if ( ! empty( $v ) ) { $groupTree[$groupId]['fields'][$fieldId]['customValue']['data'] = CRM_Core_BAO_CustomOption::VALUE_SEPERATOR.implode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $v).CRM_Core_BAO_CustomOption::VALUE_SEPERATOR; } else { $groupTree[$groupId]['fields'][$fieldId]['customValue']['data'] = null; } break; case 'Select Date': //print_r($v); $date = CRM_Utils_Date::format( $v ); /*if ( ! $date ) { $date = ''; }*/ $groupTree[$groupId]['fields'][$fieldId]['customValue']['data'] = $date; break; default: $groupTree[$groupId]['fields'][$fieldId]['customValue']['data'] = $v; break; } } } } /** * generic function to build all the form elements for a specific group tree * * @param CRM_Core_Form $form the form object * @param array $groupTree the group tree object * @param string $showName * @param string $hideName * * @return void * @access public * @static */ static function buildQuickForm( &$form, &$groupTree, $showName = 'showBlocks', $hideName = 'hideBlocks', $inactiveNeeded = false ) { require_once 'CRM/Core/BAO/CustomField.php'; require_once 'CRM/Core/BAO/CustomOption.php'; //this is fix for calendar for date field foreach ($groupTree as $key1 => $group) { foreach ($group['fields'] as $key2 => $field) { if ($field['data_type'] == 'Date' && $field['date_parts'] ) { $datePart = explode( CRM_Core_BAO_CustomOption::VALUE_SEPERATOR , $field['date_parts']); if ( count( $datePart ) < 3) { $groupTree[$key1]['fields'][$key2]['skip_calendar'] = true; } } } } $form->assign_by_ref( 'groupTree', $groupTree ); $sBlocks = array( ); $hBlocks = array( ); // this is fix for date field $form->assign('currentYear',date('Y')); require_once 'CRM/Core/ShowHideBlocks.php'; foreach ($groupTree as $group) { CRM_Core_ShowHideBlocks::links( $form, $group['title'], '', ''); $groupId = $group['id']; foreach ($group['fields'] as $field) { $required = $field['is_required']; //fix for CRM-1620 if ( $field['data_type'] == 'File') { if ( isset($field['customValue']['data']) ) { $required = 0; } } $fieldId = $field['id']; $elementName = 'custom_' . $fieldId; require_once "CRM/Core/BAO/CustomField.php"; CRM_Core_BAO_CustomField::addQuickFormElement($form, $elementName, $fieldId, $inactiveNeeded, $required); } if ( $group['collapse_display'] ) { $sBlocks[] = "'". $group['name'] . "_show'" ; $hBlocks[] = "'". $group['name'] ."'"; } else { $hBlocks[] = "'". $group['name'] . "_show'" ; $sBlocks[] = "'". $group['name'] ."'"; } } $showBlocks = implode(",",$sBlocks); $hideBlocks = implode(",",$hBlocks); $form->assign( $showName, $showBlocks ); $form->assign( $hideName, $hideBlocks ); } /** * generic function to build all the view form elements for a specific group tree * * @param CRM_Core_Form $page the page object * @param array $groupTree the group tree object * @param string $viewName what name should all the values be stored under * @param string $showName * @param string $hideName * * @return void * @access public * @static */ static function buildViewHTML( &$page, &$groupTree, $viewName = 'viewForm', $showName = 'showBlocks1', $hideName = 'hideBlocks1' ) { //showhide blocks for Custom Fields inline $sBlocks = array(); $hBlocks = array(); $form = array(); foreach ($groupTree as $group) { $groupId = $group['id']; foreach ($group['fields'] as $field) { $fieldId = $field['id']; $elementName = 'custom_' . $fieldId; $form[$elementName] = array( ); $form[$elementName]['name'] = $elementName; $form[$elementName]['html'] = null; if ( $field['data_type'] == 'String' || $field['data_type'] == 'Int' || $field['data_type'] == 'Float' || $field['data_type'] == 'Money') { //added check for Multi-Select in the below if-statement if ($field['html_type'] == 'Radio' || $field['html_type'] == 'CheckBox' || $field['html_type'] == 'Multi-Select') { $freezeString = ""; $freezeStringChecked = ""; $customData = array(); if ( isset( $field['customValue'] ) ) { //added check for Multi-Select in the below if-statement if ( $field['html_type'] == 'CheckBox' || $field['html_type'] == 'Multi-Select') { $customData = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR, $field['customValue']['data']); } else { $customData[] = $field['customValue']['data']; } } $coDAO =& new CRM_Core_DAO_CustomOption(); $coDAO->entity_id = $field['id']; $coDAO->entity_table = 'civicrm_custom_field'; $coDAO->orderBy('weight ASC, label ASC'); $coDAO->find( ); $counter = 1; while($coDAO->fetch()) { //to show only values that are checked if(in_array($coDAO->value, $customData)){ $checked = in_array($coDAO->value, $customData) ? $freezeStringChecked : $freezeString; if ($counter!=1) { $form[$elementName]['html'] .= $checked .",&nbsp;".$coDAO->label; } else { $form[$elementName]['html'] .= $checked .$coDAO->label; } $form[$elementName][$counter]['html'] = $checked .$coDAO->label."\n"; $counter++; } } } else { if ( $field['html_type'] == 'Select' ) { $coDAO =& new CRM_Core_DAO_CustomOption(); $coDAO->entity_id = $field['id']; $coDAO->entity_table = 'civicrm_custom_field'; $coDAO->orderBy('weight ASC, label ASC'); $coDAO->find( ); while($coDAO->fetch()) { if ( isset( $field['customValue'] ) && $coDAO->value == $field['customValue']['data'] ) { $form[$elementName]['html'] = $coDAO->label; } } } else { if ($field['data_type'] == "Float") { $form[$elementName]['html'] = (float)$field['customValue']['data']; } else { if ( isset ($field['customValue']['data'] ) ) { $form[$elementName]['html'] = $field['customValue']['data']; } } } } } else { if ( isset($field['customValue']['data']) ) { switch ($field['data_type']) { case 'Boolean': $freezeString = ""; $freezeStringChecked = ""; if ( isset($field['customValue']['data']) ) { if ( $field['customValue']['data'] == '1' ) { $form[$elementName]['html'] = $freezeStringChecked."Yes\n"; } else { $form[$elementName]['html'] = $freezeStringChecked."No\n"; } } else { $form[$elementName]['html'] = "\n"; } break; case 'StateProvince': $form[$elementName]['html'] = CRM_Core_PseudoConstant::stateProvince( $field['customValue']['data'] ); break; case 'Country': $form[$elementName]['html'] = CRM_Core_PseudoConstant::country( $field['customValue']['data'] ); break; case 'Date': $format = null; if($field['date_parts']) { $parts = explode(CRM_Core_BAO_CustomOption::VALUE_SEPERATOR,$field['date_parts']); foreach($parts as $v ) { $format = $format." %".$v ; } $format = str_replace('M','B',$format); } $form[$elementName]['html'] = CRM_Utils_Date::customFormat($field['customValue']['data'],$format); break; case 'Link': $form[$elementName]['html'] = CRM_Utils_System::formatWikiURL( $field['customValue']['data'] ); break; default: $form[$elementName]['html'] = $field['customValue']['data']; } } } } //showhide group if ( $group['collapse_display'] ) { $sBlocks[] = "'". $group['name'] . "_show'" ; $hBlocks[] = "'". $group['name'] ."'"; } else { $hBlocks[] = "'". $group['name'] . "_show'" ; $sBlocks[] = "'". $group['name'] ."'"; } } $showBlocks = implode(",",$sBlocks); $hideBlocks = implode(",",$hBlocks); $page->assign( $viewName, $form ); $page->assign( $showName, $showBlocks ); $page->assign( $hideName, $hideBlocks ); $page->assign_by_ref('groupTree', $groupTree); } /** * Function to extract the get params from the url, validate * and store it in session * * @param CRM_Core_Form $form the form object * @param string $type the type of custom group we are using * @return void * @access public * @static */ static function extractGetParams( &$form, $type ) { // if not GET params return if ( empty( $_GET ) ) { return; } $groupTree =& CRM_Core_BAO_CustomGroup::getTree( $type ); $customFields =& CRM_Core_BAO_CustomField::getFields( $type ); $customValue = array(); $htmlType = array('CheckBox','Multi-Select','Select','Radio'); foreach ($groupTree as $group) { foreach( $group['fields'] as $key => $field) { $fieldName = 'custom_' . $key; $value = CRM_Utils_Request::retrieve( $fieldName, 'String', $form ); if ( $value ) { if ( ! in_array( $customFields[$key][3], $htmlType ) || $customFields[$key][2] =='Boolean' ) { $valid = CRM_Core_BAO_CustomValue::typecheck( $customFields[$key][2], $value); } if ( $customFields[$key][3] == 'CheckBox' || $customFields[$key][3] =='Multi-Select' ) { $value = str_replace("|",",",$value); $mulValues = explode( ',' , $value ); $customOption = CRM_Core_BAO_CustomOption::getCustomOption( $key, true ); $val = array (); foreach( $mulValues as $v1 ) { foreach( $customOption as $v2 ) { if ( strtolower(trim($v2['label'])) == strtolower(trim($v1)) ) { $val[$v2['value']] = 1; } } } if (! empty ($val) ) { $value = $val; $valid = true; } else { $value = null; } } else if ($customFields[$key][3] == 'Select' || ( $customFields[$key][3] =='Radio' && $customFields[$key][2] !='Boolean' ) ) { $customOption = CRM_Core_BAO_CustomOption::getCustomOption($key, true ); foreach( $customOption as $v2 ) { if ( strtolower(trim($v2['label'])) == strtolower(trim($value)) ) { $value = $v2['value']; $valid = true; } } } else if ( $customFields[$key][2] == 'Date' ) { require_once 'CRM/Utils/Date.php'; if( is_numeric( $value ) ){ $value = CRM_Utils_Date::unformat( $value , null ); } else { $value = CRM_Utils_Date::unformat( $value , $separator = '-' ); } $valid = true; } if ( $valid ) { $customValue[$fieldName] = $value; } } } } $form->set( 'customGetValues', $customValue ); $form->set( 'groupTree', $groupTree ); } /** * Function to check the type of custom field type (eg: Used for Individual, Contribution, etc) * this function is used to get the custom fields of a type (eg: Used for Individual, Contribution, etc ) * * @param int $customFieldId custom field id * @param array $removeCustomFieldTypes remove custom fields of a type eg: array("Individual") ; * * * @return boolean false if it matches else true * @static * @access public */ static function checkCustomField($customFieldId, &$removeCustomFieldTypes ) { $query = "SELECT cg.extends as extends FROM civicrm_custom_group as cg, civicrm_custom_field as cf WHERE cg.id = cf.custom_group_id AND cf.id =" . CRM_Utils_Type::escape($customFieldId, 'Integer'); $extends = CRM_Core_DAO::singleValueQuery( $query, CRM_Core_DAO::$_nullArray ); if ( in_array( $extends, $removeCustomFieldTypes ) ) { return false; } return true; } } ?>
zakiya/Peoples-History
sites/all/modules/civicrm/CRM/Core/BAO/CustomGroup.php
PHP
gpl-2.0
60,540
/* * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_VM_GC_IMPLEMENTATION_G1_G1REMSET_HPP #define SHARE_VM_GC_IMPLEMENTATION_G1_G1REMSET_HPP #include "gc_implementation/g1/g1RemSetSummary.hpp" // A G1RemSet provides ways of iterating over pointers into a selected // collection set. class G1CollectedHeap; class ConcurrentG1Refine; class G1ParPushHeapRSClosure; // A G1RemSet in which each heap region has a rem set that records the // external heap references into it. Uses a mod ref bs to track updates, // so that they can be used to update the individual region remsets. class G1RemSet: public CHeapObj<mtGC> { private: G1RemSetSummary _prev_period_summary; protected: G1CollectedHeap* _g1; size_t _conc_refine_cards; uint n_workers(); protected: enum SomePrivateConstants { UpdateRStoMergeSync = 0, MergeRStoDoDirtySync = 1, DoDirtySync = 2, LastSync = 3, SeqTask = 0, NumSeqTasks = 1 }; CardTableModRefBS* _ct_bs; SubTasksDone* _seq_task; G1CollectorPolicy* _g1p; ConcurrentG1Refine* _cg1r; size_t* _cards_scanned; size_t _total_cards_scanned; // Used for caching the closure that is responsible for scanning // references into the collection set. G1ParPushHeapRSClosure** _cset_rs_update_cl; // Print the given summary info virtual void print_summary_info(G1RemSetSummary * summary, const char * header = NULL); public: // This is called to reset dual hash tables after the gc pause // is finished and the initial hash table is no longer being // scanned. void cleanupHRRS(); G1RemSet(G1CollectedHeap* g1, CardTableModRefBS* ct_bs); ~G1RemSet(); // Invoke "blk->do_oop" on all pointers into the collection set // from objects in regions outside the collection set (having // invoked "blk->set_region" to set the "from" region correctly // beforehand.) // // Invoke code_root_cl->do_code_blob on the unmarked nmethods // on the strong code roots list for each region in the // collection set. // // The "worker_i" param is for the parallel case where the id // of the worker thread calling this function can be helpful in // partitioning the work to be done. It should be the same as // the "i" passed to the calling thread's work(i) function. // In the sequential case this param will be ignored. void oops_into_collection_set_do(G1ParPushHeapRSClosure* blk, CodeBlobClosure* code_root_cl, uint worker_i); // Prepare for and cleanup after an oops_into_collection_set_do // call. Must call each of these once before and after (in sequential // code) any threads call oops_into_collection_set_do. (This offers an // opportunity to sequential setup and teardown of structures needed by a // parallel iteration over the CS's RS.) void prepare_for_oops_into_collection_set_do(); void cleanup_after_oops_into_collection_set_do(); void scanRS(G1ParPushHeapRSClosure* oc, CodeBlobClosure* code_root_cl, uint worker_i); void updateRS(DirtyCardQueue* into_cset_dcq, uint worker_i); CardTableModRefBS* ct_bs() { return _ct_bs; } size_t cardsScanned() { return _total_cards_scanned; } // Record, if necessary, the fact that *p (where "p" is in region "from", // which is required to be non-NULL) has changed to a new non-NULL value. template <class T> void write_ref(HeapRegion* from, T* p); template <class T> void par_write_ref(HeapRegion* from, T* p, uint tid); // Requires "region_bm" and "card_bm" to be bitmaps with 1 bit per region // or card, respectively, such that a region or card with a corresponding // 0 bit contains no part of any live object. Eliminates any remembered // set entries that correspond to dead heap ranges. "worker_num" is the // parallel thread id of the current thread, and "hrclaimer" is the // HeapRegionClaimer that should be used. void scrub(BitMap* region_bm, BitMap* card_bm, uint worker_num, HeapRegionClaimer* hrclaimer); // Refine the card corresponding to "card_ptr". // If check_for_refs_into_cset is true, a true result is returned // if the given card contains oops that have references into the // current collection set. virtual bool refine_card(jbyte* card_ptr, uint worker_i, bool check_for_refs_into_cset); // Print accumulated summary info from the start of the VM. virtual void print_summary_info(); // Print accumulated summary info from the last time called. virtual void print_periodic_summary_info(const char* header); // Prepare remembered set for verification. virtual void prepare_for_verify(); size_t conc_refine_cards() const { return _conc_refine_cards; } }; class UpdateRSOopClosure: public ExtendedOopClosure { HeapRegion* _from; G1RemSet* _rs; uint _worker_i; template <class T> void do_oop_work(T* p); public: UpdateRSOopClosure(G1RemSet* rs, uint worker_i = 0) : _from(NULL), _rs(rs), _worker_i(worker_i) {} void set_from(HeapRegion* from) { assert(from != NULL, "from region must be non-NULL"); _from = from; } virtual void do_oop(narrowOop* p) { do_oop_work(p); } virtual void do_oop(oop* p) { do_oop_work(p); } // Override: this closure is idempotent. // bool idempotent() { return true; } bool apply_to_weak_ref_discovered_field() { return true; } }; #endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1REMSET_HPP
netroby/jdk9-shenandoah-hotspot
src/share/vm/gc_implementation/g1/g1RemSet.hpp
C++
gpl-2.0
6,594
/* * $RCSfile$ * * Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. * * $Revision: 892 $ * $Date: 2008-02-28 20:18:01 +0000 (Thu, 28 Feb 2008) $ * $State$ */ package javax.media.j3d; import javax.vecmath.*; /** * The ShaderAttributeBinding object encapsulates a uniform attribute * whose value is bound to a Java&nbsp;3D system attribute. The * shader variable <code>attrName</code> is implicitly set to the * value of the corresponding Java&nbsp;3D system attribute * <code>j3dAttrName</code> during rendering. <code>attrName</code> * must be the name of a valid uniform attribute in the shader in * which it is used. Otherwise, the attribute name will be ignored and * a runtime error may be generated. <code>j3dAttrName</code> must be * the name of a predefined Java&nbsp;3D system attribute. An * IllegalArgumentException will be thrown if the specified * <code>j3dAttrName</code> is not one of the predefined system * attributes. Further, the type of the <code>j3dAttrName</code> * attribute must match the type of the corresponding * <code>attrName</code> variable in the shader in which it is * used. Otherwise, the shader will not be able to use the attribute * and a runtime error may be generated. */ class ShaderAttributeBindingRetained extends ShaderAttributeRetained { String j3dAttrName; ShaderAttributeBindingRetained() { } void initJ3dAttrName(String j3dAttrName) { this.j3dAttrName = j3dAttrName; } /** * Retrieves the name of the Java 3D system attribute that is bound to this * shader attribute. * * @return the name of the Java 3D system attribute that is bound to this * shader attribute */ String getJ3DAttributeName() { return j3dAttrName; } }
philipwhiuk/j3d-core
src/classes/share/javax/media/j3d/ShaderAttributeBindingRetained.java
Java
gpl-2.0
2,911
<?php function theme_setup(){ add_theme_support( 'html5', array( 'comment-list', 'comment-form', 'search-form', 'gallery', 'caption' ) ); add_theme_support( 'post-formats', array( 'aside', 'gallery' ) ); add_theme_support( 'post-thumbnails', array( 'post', 'page' ) ); add_theme_support('title-tag'); } add_action( 'after_setup_theme', 'theme_setup' ); function enqueue_theme_styles_and_scripts(){ //Styles wp_enqueue_style('reset-styles', get_stylesheet_directory_uri()."/css/reset.css"); wp_enqueue_style('bootstrap.css', get_stylesheet_directory_uri()."/css/bootstrap/css/bootstrap.min.css", array('reset-styles')); wp_enqueue_style('style', get_stylesheet_uri(), array('reset-styles', 'bootstrap.css')); //Scripts wp_enqueue_script('boostrap.js', get_stylesheet_directory_uri()."/css/bootstrap/js/bootstrap.min.js"); } add_action('wp_enqueue_scripts', 'enqueue_theme_styles_and_scripts'); ?>
volpster2100/wordpress
wp-content/themes/Custom Theme/functions.php
PHP
gpl-2.0
909
package org.safehaus.penrose.jdbc; /** * @author Endi Sukma Dewata */ public class StatementSource { private String alias; private String partitionName; private String sourceName; public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public String getPartitionName() { return partitionName; } public void setPartitionName(String partitionName) { this.partitionName = partitionName; } public String getSourceName() { return sourceName; } public void setSourceName(String sourceName) { this.sourceName = sourceName; } }
identityxx/penrose-server
core/src/java/org/safehaus/penrose/jdbc/StatementSource.java
Java
gpl-2.0
719
/* Mango - Open Source M2M - http://mango.serotoninsoftware.com Copyright (C) 2006-2011 Serotonin Software Technologies Inc. @author Matthew Lohbihler This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.serotonin.mango.rt.event.detectors; import com.serotonin.mango.rt.dataImage.PointValueTime; import com.serotonin.mango.util.PointEventDetectorUtils; import com.serotonin.mango.view.event.NoneEventRenderer; import com.serotonin.mango.view.text.TextRenderer; import com.serotonin.mango.vo.event.PointEventDetectorVO; import com.serotonin.web.i18n.LocalizableMessage; public class BinaryStateDetectorRT extends StateDetectorRT { public BinaryStateDetectorRT(PointEventDetectorVO vo) { this.vo = vo; } @Override public LocalizableMessage getMessage() { String name = vo.njbGetDataPoint().getName(); String prettyText = vo.njbGetDataPoint().getTextRenderer().getText(vo.isBinaryState(), TextRenderer.HINT_SPECIFIC); LocalizableMessage durationDescription = getDurationDescription(); String description = PointEventDetectorUtils.getDescription(vo); String eventRendererText = (vo.njbGetDataPoint().getEventTextRenderer() == null) ? "" : vo.njbGetDataPoint().getEventTextRenderer().getText(vo.isBinaryState()); if (durationDescription == null) return new LocalizableMessage("event.detector.state", name, prettyText, description, eventRendererText); return new LocalizableMessage("event.detector.periodState", name, prettyText, durationDescription, description, eventRendererText); } @Override protected LocalizableMessage getShortMessage() { if (vo.njbGetDataPoint().getEventTextRenderer() != null && !vo.njbGetDataPoint().getEventTextRenderer().getTypeName().equals(NoneEventRenderer.TYPE_NAME) && vo.njbGetDataPoint().getEventTextRenderer().getText(vo.isBinaryState()) != null && (!vo.njbGetDataPoint().getEventTextRenderer().getText(vo.isBinaryState()).equals(""))) { String eventRendererText = vo.njbGetDataPoint().getEventTextRenderer().getText(vo.isBinaryState()); return new LocalizableMessage("event.detector.shortMessage", vo.njbGetDataPoint().getName(), eventRendererText); } else { return getMessage(); } } @Override protected boolean stateDetected(PointValueTime newValue) { boolean newBinary = newValue.getBooleanValue(); return newBinary == vo.isBinaryState(); } }
SCADA-LTS/Scada-LTS
src/com/serotonin/mango/rt/event/detectors/BinaryStateDetectorRT.java
Java
gpl-2.0
3,230
/* * Copyright (C) 2014 University of Dundee & Open Microscopy Environment. * All rights reserved. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * *------------------------------------------------------------------------------ */ package org.openmicroscopy.shoola.env.data.views.calls; import java.util.List; import org.openmicroscopy.shoola.agents.metadata.FileAnnotationCheckResult; import org.openmicroscopy.shoola.env.data.OmeroMetadataService; import omero.gateway.SecurityContext; import org.openmicroscopy.shoola.env.data.views.BatchCall; import org.openmicroscopy.shoola.env.data.views.BatchCallTree; import pojos.DataObject; import pojos.FileAnnotationData; /** * Loads the parents ({@link DataObject}) of the specified {@link FileAnnotationData} objects, * wrapped in a {@link FileAnnotationCheckResult} * * @author Dominik Lindner &nbsp;&nbsp;&nbsp;&nbsp; <a * href="mailto:d.lindner@dundee.ac.uk">d.lindner@dundee.ac.uk</a> * @since 5.0 */ public class FileAnnotationCheckLoader extends BatchCallTree { /** The result of the call. */ private FileAnnotationCheckResult result; /** The call */ private BatchCall loadCall; /** * Creates a {@link BatchCall} to load the parents of the annotations. * * @param ctx The security context. * @param annotations The @link FileAnnotationData} objects * @param referenceObjects The DataObjects from which the FileAnnotation should be removed * @return The {@link BatchCall}. */ private BatchCall makeCall(final SecurityContext ctx, final List<FileAnnotationData> annotations, final List<DataObject> referenceObjects) { return new BatchCall("Load Parents of annotations") { public void doCall() throws Exception { result = new FileAnnotationCheckResult(referenceObjects); for(FileAnnotationData fd : annotations) { OmeroMetadataService svc = context.getMetadataService(); List<DataObject> parents = svc.loadParentsOfAnnotations(ctx, fd.getId(), -1); result.addLinks(fd, parents); } } }; } /** * Adds the {@link #loadCall} to the computation tree. * * @see BatchCallTree#buildTree() */ protected void buildTree() { add(loadCall); } /** * Returns {@link FileAnnotationCheckResult}, which holds a <code>Map</code> * of {@link FileAnnotationData} objects mapped to {@link DataObject}s * * @see BatchCallTree#getResult() */ protected Object getResult() { return result; } /** * Creates a new instance. * * @param ctx The security context. * @param annotations The {@link FileAnnotationData} objects */ public FileAnnotationCheckLoader(SecurityContext ctx, List<FileAnnotationData> annotations, List<DataObject> referenceObjects) { loadCall = makeCall(ctx, annotations, referenceObjects); } }
stelfrich/openmicroscopy
components/insight/SRC/org/openmicroscopy/shoola/env/data/views/calls/FileAnnotationCheckLoader.java
Java
gpl-2.0
3,769
<?php namespace TYPO3\CMS\Extbase\Persistence\Generic; /* * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ use TYPO3\CMS\Extbase\DomainObject\DomainObjectInterface; /** * A proxy that can replace any object and replaces itself in it's parent on * first access (call, get, set, isset, unset). */ class LazyLoadingProxy implements \Iterator, \TYPO3\CMS\Extbase\Persistence\Generic\LoadingStrategyInterface { /** * @var \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper */ protected $dataMapper; /** * The object this property is contained in. * * @var DomainObjectInterface */ private $parentObject; /** * The name of the property represented by this proxy. * * @var string */ private $propertyName; /** * The raw field value. * * @var mixed */ private $fieldValue; /** * @param \TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper $dataMapper */ public function injectDataMapper(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper $dataMapper) { $this->dataMapper = $dataMapper; } /** * Constructs this proxy instance. * * @param DomainObjectInterface $parentObject The object instance this proxy is part of * @param string $propertyName The name of the proxied property in it's parent * @param mixed $fieldValue The raw field value. */ public function __construct($parentObject, $propertyName, $fieldValue) { $this->parentObject = $parentObject; $this->propertyName = $propertyName; $this->fieldValue = $fieldValue; } /** * Populate this proxy by asking the $population closure. * * @return object The instance (hopefully) returned */ public function _loadRealInstance() { // this check safeguards against a proxy being activated multiple times // usually that does not happen, but if the proxy is held from outside // its parent ... the result would be weird. if ($this->parentObject->_getProperty($this->propertyName) instanceof \TYPO3\CMS\Extbase\Persistence\Generic\LazyLoadingProxy) { $objects = $this->dataMapper->fetchRelated($this->parentObject, $this->propertyName, $this->fieldValue, false, false); $propertyValue = $this->dataMapper->mapResultToPropertyValue($this->parentObject, $this->propertyName, $objects); $this->parentObject->_setProperty($this->propertyName, $propertyValue); $this->parentObject->_memorizeCleanState($this->propertyName); return $propertyValue; } return $this->parentObject->_getProperty($this->propertyName); } /** * Magic method call implementation. * * @param string $methodName The name of the property to get * @param array $arguments The arguments given to the call * @return mixed */ public function __call($methodName, $arguments) { $realInstance = $this->_loadRealInstance(); if (!is_object($realInstance)) { return null; } return call_user_func_array([$realInstance, $methodName], $arguments); } /** * Magic get call implementation. * * @param string $propertyName The name of the property to get * @return mixed */ public function __get($propertyName) { $realInstance = $this->_loadRealInstance(); return $realInstance->{$propertyName}; } /** * Magic set call implementation. * * @param string $propertyName The name of the property to set * @param mixed $value The value for the property to set */ public function __set($propertyName, $value) { $realInstance = $this->_loadRealInstance(); $realInstance->{$propertyName} = $value; } /** * Magic isset call implementation. * * @param string $propertyName The name of the property to check * @return bool */ public function __isset($propertyName) { $realInstance = $this->_loadRealInstance(); return isset($realInstance->{$propertyName}); } /** * Magic unset call implementation. * * @param string $propertyName The name of the property to unset */ public function __unset($propertyName) { $realInstance = $this->_loadRealInstance(); unset($realInstance->{$propertyName}); } /** * Magic toString call implementation. * * @return string */ public function __toString() { $realInstance = $this->_loadRealInstance(); return $realInstance->__toString(); } /** * Returns the current value of the storage array * * @return mixed */ public function current() { $realInstance = $this->_loadRealInstance(); return current($realInstance); } /** * Returns the current key storage array * * @return int */ public function key() { $realInstance = $this->_loadRealInstance(); return key($realInstance); } /** * Returns the next position of the storage array */ public function next() { $realInstance = $this->_loadRealInstance(); next($realInstance); } /** * Resets the array pointer of the storage */ public function rewind() { $realInstance = $this->_loadRealInstance(); reset($realInstance); } /** * Checks if the array pointer of the storage points to a valid position * * @return bool */ public function valid() { return $this->current() !== false; } }
morinfa/TYPO3.CMS
typo3/sysext/extbase/Classes/Persistence/Generic/LazyLoadingProxy.php
PHP
gpl-2.0
6,094
@extends('site.layouts.default') {{-- Web site Title --}} @section('title') Login @parent @stop {{-- Content --}} @section('content') <div class="page-header"> <h1>Ingresar al administrador</h1> </div> <?php echo Form::open(array('url' => '/login', 'class' => 'form-horizontal')); ?> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <fieldset> <div class="form-group"> <label class="col-md-2 control-label" for="email">Usuario</label> <div class="col-md-10"> <input class="form-control" tabindex="1" placeholder="usuario" type="text" name="username" id="email"> </div> </div> <div class="form-group"> <label class="col-md-2 control-label" for="password"> Clave </label> <div class="col-md-10"> <input class="form-control" tabindex="2" placeholder="clave" type="password" name="password" id="password"> </div> </div> @if ( Session::get('error') ) <div class="alert alert-danger">{{ Session::get('error') }}</div> @endif @if ( Session::get('notice') ) <div class="alert">{{ Session::get('notice') }}</div> @endif <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button tabindex="3" type="submit" class="btn btn-primary">Ingresar</button> </div> </div> </fieldset> </form> @stop
palamago/shared-links-ranking
app/views/site/user/login.blade.php
PHP
gpl-2.0
1,634
(function ($) { Drupal.ychenikSearch = {}; /** * jQuery plugin. */ $.fn.ychenikSearch = function (stars) { stars = stars || 0; this.each(function () { $(this).addClass('ychenik-search').find('label').each(function () { var context = this.form; var $label = $(this); if (!$label.attr('for')) { return; } var $field = $('#' + $label.attr('for'), context); if (!$field.length || !$field.is('input:text,input:password,textarea')) { return; } // Store the initial field value, in case the browser is going to // automatically fill it in upon focus. var initial_value = $field.val(); if (initial_value != '') { // Firefox doesn't like .hide() here for some reason. $label.css('display', 'none'); } $label.parent().addClass('ychenik-search-wrapper'); $label.addClass('ychenik-search-label'); $field.addClass('ychenik-search-field'); if (stars === 0) { $label.find('.form-required').hide(); } else if (stars === 2) { $label.find('.form-required').insertAfter($field).prepend('&nbsp;'); } $field.focus(function () { // Some browsers (e.g., Firefox) are automatically inserting a stored // username and password into login forms. In case the password field is // manually emptied afterwards, and the user jumps back to the username // field (without changing it), and forth to the password field, then // the browser automatically re-inserts the password again. Therefore, // we also need to test against the initial field value. if ($field.val() === initial_value || $field.val() === '') { $label.fadeOut('fast'); } }); $field.blur(function () { if ($field.val() === '') { $label.fadeIn('slow'); } }); // Chrome adds passwords after page load, so we need to track changes. $field.change(function () { if ($field.get(0) != document.activeElement) { if ($field.val() === '') { $label.fadeIn('fast'); } else { $label.css('display', 'none'); } } }); }); }); }; /** * Attach compact forms behavior to all enabled forms upon page load. */ Drupal.behaviors.ychenikSearch = { attach: function (context, settings) { if (!settings || !settings.ychenikSearch) { return; } $('#' + settings.ychenikSearch.forms.join(',#'), context).ychenikSearch(settings.ychenikSearch.stars); // Safari adds passwords without triggering any event after page load. // We therefore need to wait a bit and then check for field values. if ($.browser.safari) { setTimeout(Drupal.ychenikSearch.fixSafari, 200); } } }; /** * Checks for field values and hides the corresponding label if non-empty. * * @todo Convert $.fn.compactForm to always use a function like this. */ Drupal.ychenikSearch.fixSafari = function () { $('label.ychenik-search-label').each(function () { var $label = $(this); var context = this.form; if ($('#' + $label.attr('for'), context).val() != '') { $label.css('display', 'none'); } }); } })(jQuery);
borisay/ychenik
sites/all/modules/custom/ychenik_search/ychenik_search.js
JavaScript
gpl-2.0
3,267
#ifndef BOX_H #define BOX_H class MyBox: public Gtk::Frame { public: MyBox(const Glib::ustring& label, Gtk::Orientation orientation); void pack_start(Widget& child); private: Gtk::Box* p_child; }; #endif
blablack/ams-lv2
src/my_box.hpp
C++
gpl-2.0
215
<?php /** * @copyright Copyright (C) 2005 - 2008 Open Source Matters. All rights reserved. * @license GNU/GPL, see LICENSE.php * Joomla! is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>" id="minwidth" > <head> <jdoc:include type="head" /> <link rel="stylesheet" href="templates/system/css/system.css" type="text/css" /> <link href="templates/<?php echo $this->template ?>/css/template.css" rel="stylesheet" type="text/css" /> <?php if($this->direction == 'rtl') : ?> <link href="templates/<?php echo $this->template ?>/css/template_rtl.css" rel="stylesheet" type="text/css" /> <?php endif; ?> <!--[if IE 7]> <link href="templates/<?php echo $this->template ?>/css/ie7.css" rel="stylesheet" type="text/css" /> <![endif]--> <!--[if lte IE 6]> <link href="templates/<?php echo $this->template ?>/css/ie6.css" rel="stylesheet" type="text/css" /> <![endif]--> <?php if($this->params->get('useRoundedCorners')) : ?> <link rel="stylesheet" type="text/css" href="templates/<?php echo $this->template ?>/css/rounded.css" /> <?php else : ?> <link rel="stylesheet" type="text/css" href="templates/<?php echo $this->template ?>/css/norounded.css" /> <?php endif; ?> <?php if(JModuleHelper::isEnabled('menu')) : ?> <script type="text/javascript" src="templates/<?php echo $this->template ?>/js/menu.js"></script> <script type="text/javascript" src="templates/<?php echo $this->template ?>/js/index.js"></script> <?php endif; ?> </head> <body id="minwidth-body"> <div id="border-top" class="<?php echo $this->params->get('headerColor','green');?>"> <div> <div> <span class="version"><?php echo JText::_('Version') ?> <?php echo JVERSION; ?></span> <span class="title"><?php echo $this->params->get('showSiteName') ? $mainframe->getCfg( 'sitename' ) : JText::_('Administration'); ?></span> </div> </div> </div> <div id="header-box"> <div id="module-status"> <jdoc:include type="modules" name="status" /> </div> <div id="module-menu"> <jdoc:include type="modules" name="menu" /> </div> <div class="clr"></div> </div> <div id="content-box"> <div class="border"> <div class="padding"> <div id="toolbar-box"> <div class="t"> <div class="t"> <div class="t"></div> </div> </div> <div class="m"> <jdoc:include type="modules" name="toolbar" /> <jdoc:include type="modules" name="title" /> <div class="clr"></div> </div> <div class="b"> <div class="b"> <div class="b"></div> </div> </div> </div> <div class="clr"></div> <?php if (!JRequest::getInt('hidemainmenu')): ?> <jdoc:include type="modules" name="submenu" style="rounded" id="submenu-box" /> <?php endif; ?> <jdoc:include type="message" /> <div id="element-box"> <div class="t"> <div class="t"> <div class="t"></div> </div> </div> <div class="m"> <jdoc:include type="component" /> <div class="clr"></div> </div> <div class="b"> <div class="b"> <div class="b"></div> </div> </div> </div> <noscript> <?php echo JText::_('WARNJAVASCRIPT') ?> </noscript> <div class="clr"></div> </div> <div class="clr"></div> </div> </div> <div id="border-bottom"><div><div></div></div></div> <div id="footer"> <p class="copyright"> <a href="http://mywebcreations.dk/" target="_blank">My Web Creations</a> & Version 1.5.15 <?php //echo JText::_('ISFREESOFTWARE') ?> </p> </div> </body> </html>
naka211/daekcenter_old
administrator/templates/khepri/index.php
PHP
gpl-2.0
4,074
class Project include Mongoid::Document include Mongoid::Timestamps include ParamReader embeds_one :building accepts_nested_attributes_for :building embeds_one :non_building accepts_nested_attributes_for :non_building embeds_many :related_projects accepts_nested_attributes_for :related_projects field :project_number, type: String field :img, type: String field :value, type: String after_initialize if: :new_record? do |doc| doc.non_building = NonBuilding.new doc.building = Building.new doc.related_projects = [RelatedProject.new] end end
notionparallax/ShadowWolf
server/app/models/project.rb
Ruby
gpl-2.0
589
<?php /* * * Copyright 2001-2014 Thomas Belliard, Laurent Delineau, Edouard Hue, Eric Lebrun * * This file is part of GEPI. * * GEPI is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GEPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GEPI; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Initialisations files require_once("../lib/initialisations.inc.php"); // Resume session $resultat_session = $session_gepi->security_check(); if ($resultat_session == 'c') { header("Location: ../utilisateurs/mon_compte.php?change_mdp=yes"); die(); } else if ($resultat_session == '0') { header("Location: ../logout.php?auto=1"); die(); } if (!checkAccess()) { header("Location: ../logout.php?auto=1"); die(); } // Initialisation du répertoire actuel de sauvegarde $dirname = getSettingValue("backup_directory"); //$fileid=isset($_POST['fileid']) ? $_POST['fileid'] : (isset($_GET['fileid']) ? $_GET['fileid'] : NULL); $fileid=isset($_GET['fileid']) ? $_GET['fileid'] : NULL; if((isset($_GET['sous_dossier']))&&($_GET['sous_dossier']=='absences')) { $tab_file=get_tab_fichiers_du_dossier_de_sauvegarde("../backup/".$dirname."/absences", "y"); $n=count($tab_file); $filepath = null; $filename = null; if ($n > 0) { $m = 0; foreach($tab_file as $value) { if ($m == $fileid) { $filepath = "../backup/".$dirname."/absences/".$value; $filename = $value; } $m++; } clearstatcache(); } send_file_download_headers('text/x-csv',$filename); readfile($filepath); } else { $tab_file=get_tab_fichiers_du_dossier_de_sauvegarde(); $n=count($tab_file); $filepath = null; $filename = null; if ($n > 0) { $m = 0; foreach($tab_file as $value) { if ($m == $fileid) { $filepath = "../backup/".$dirname."/".$value; $filename = $value; } $m++; } clearstatcache(); } send_file_download_headers('text/x-sql',$filename); readfile($filepath); } ?>
Regis85/gepi
gestion/savebackup.php
PHP
gpl-2.0
2,450
<?php //Attendee functions function add_attendee_questions($questions, $registration_id, $attendee_id=0, $extra=array()) { if (array_key_exists('session_vars', $extra)) { $response_source = $extra['session_vars']; } else $response_source = $_POST; /* echo 'Debug: <br />'; print_r( $questions ); echo '<br>'; echo $registration_id; echo '<br>'; echo $attendee_id; echo '<br>'; */ $question_groups = $questions; //unserialize($questions->question_groups); global $wpdb, $org_options; $wpdb->show_errors(); //print_r($question_groups); /** * Added this check because in some cases question groups are being sent as serialized */ if ( !is_array($question_groups) && !empty($question_groups)) { $question_groups = unserialize($question_groups); } if (count($question_groups) > 0) { $questions_in = ''; //Debug //echo "<pre question_groups - >".print_r($question_groups,true)."</pre>"; foreach ($question_groups as $g_id) $questions_in .= $g_id . ','; $questions_in = substr($questions_in, 0, -1); $group_name = ''; $counter = 0; $questions = $wpdb->get_results("SELECT q.*, qg.group_name FROM " . EVENTS_QUESTION_TABLE . " q JOIN " . EVENTS_QST_GROUP_REL_TABLE . " qgr on q.id = qgr.question_id JOIN " . EVENTS_QST_GROUP_TABLE . " qg on qg.id = qgr.group_id WHERE qgr.group_id in (" . $questions_in . ") ORDER BY q.id ASC"); //. ") AND q.system_name IS NULL ORDER BY id ASC"); $num_rows = $wpdb->num_rows; if ($num_rows > 0) { $question_displayed = array(); global $email_questions; //Make a global variable to hold the answers to the questions to be sent in the admin email. $email_questions = '<p>' . __('Form Questions:', 'event_espresso') . '<br />'; foreach ($questions as $question) { if (!in_array($question->id, $question_displayed)) { $question_displayed[] = $question->id; switch ($question->question_type) { case "TEXT" : case "TEXTAREA" : case "DROPDOWN" : $post_val = ($question->system_name != '') ? $response_source[$question->system_name] : $response_source[$question->question_type . '_' . $question->id]; $wpdb->query("INSERT into " . EVENTS_ANSWER_TABLE . " (registration_id, attendee_id, question_id, answer) values ('" . $registration_id . "', '" . $attendee_id . "', '" . $question->id . "', '" . $post_val . "')"); $email_questions .= $question->question . ': ' . $post_val . '<br />'; break; case "SINGLE" : $post_val = ($question->system_name != '') ? $response_source[$question->system_name] : $response_source[$question->question_type . '_' . $question->id]; $wpdb->query("INSERT into " . EVENTS_ANSWER_TABLE . " (registration_id, attendee_id, question_id, answer) values ('" . $registration_id . "', '" . $attendee_id . "', '" . $question->id . "', '" . $post_val . "')"); $email_questions .= $question->question . ': ' . $post_val . '<br />'; break; case "MULTIPLE" : $value_string = ''; for ($i = 0; $i < count($response_source[$question->question_type . '_' . $question->id]); $i++) { $value_string .= trim($response_source[$question->question_type . '_' . $question->id][$i]) . ","; } $wpdb->query("INSERT INTO " . EVENTS_ANSWER_TABLE . " (registration_id, attendee_id, question_id, answer) VALUES ('" . $registration_id . "', '" . $attendee_id . "', '" . $question->id . "', '" . $value_string . "')"); $email_questions .= $question->question . ': ' . $value_string . '<br />'; break; } } } $email_questions .= '</p>'; } } } function is_attendee_approved($event_id, $attendee_id) { global $wpdb, $org_options; $result = true; if (isset($org_options["use_attendee_pre_approval"])&&$org_options["use_attendee_pre_approval"] == "Y") { $result = false; $require_pre_approval = 0; $tmp_events = $wpdb->get_results("SELECT * FROM " . EVENTS_DETAIL_TABLE . " WHERE id = " . $event_id); foreach ($tmp_events as $tmp_event) { $require_pre_approval = $tmp_event->require_pre_approval; } if ($require_pre_approval == 1) { $tmp_attendees = $wpdb->get_results("SELECT * FROM " . EVENTS_ATTENDEE_TABLE . " WHERE id = " . $attendee_id); foreach ($tmp_attendees as $tmp_attendee) { $pre_approve = $tmp_attendee->pre_approve; } if ($pre_approve == 0) { $result = true; } } else { $result = true; } } return $result; }
TheOrchardSolutions/WordPress
wp-content/plugins/event-disabled/event-espresso-bak/espress-old/event-espresso.3.1.17.P/includes/functions/attendee_functions.php
PHP
gpl-2.0
5,379
package edu.utep.cybershare.elseweb.build.edac.services.source.edac.fgdc.theme; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Themes { private static final String THEMEKT_ISO_19115_Topic_Categories = "ISO 19115 Topic Categories"; private static final String THEMEKY_GCMD_Science = "GCMD Science"; private static final String THEMEKY_EDAC = "None"; private static final String THEME_CF = "CF"; private Theme theme_ISO_19115_Topic_Categories; private Theme theme_GCMD_Science; private Theme theme_EDAC_Prism; private Theme theme_EDAC_MODIS; private Theme theme_CF; public Themes(Document fgdcDoc){ NodeList themes = fgdcDoc.getElementsByTagName("theme"); for(int i = 0; i < themes.getLength(); i ++) setTheme(getTheme(themes.item(i))); } private Theme getTheme(Node aThemeNode){ NodeList themeParts = aThemeNode.getChildNodes(); Node themePart; String tagName; String tagValue; Theme aTheme = new Theme(); for(int i = 0; i < themeParts.getLength(); i ++){ themePart = themeParts.item(i); tagName = themePart.getNodeName(); tagValue = themePart.getTextContent(); if(tagName.equals("themekt")) aTheme.setThemekt(tagValue); else if(tagName.equals("themekey")) aTheme.addThemekey(tagValue); } return aTheme; } private void setTheme(Theme aTheme){ if(aTheme.getThemekt().equals(Themes.THEMEKT_ISO_19115_Topic_Categories)) this.theme_ISO_19115_Topic_Categories = aTheme; else if(aTheme.getThemekt().equals(Themes.THEMEKY_GCMD_Science)) this.theme_GCMD_Science = aTheme; else if(aTheme.getThemekt().equals(Themes.THEMEKY_EDAC)) setSourceTheme(aTheme); else if(aTheme.getThemekt().equals(Themes.THEME_CF)) this.theme_CF = aTheme; } private void setSourceTheme(Theme sourceTheme){ if(sourceTheme.getNumberOfThemeKeys() == 2) this.theme_EDAC_Prism = sourceTheme; else this.theme_EDAC_MODIS = sourceTheme; } public Theme getTheme_ISO_19115_Topic_Categories(){ return this.theme_ISO_19115_Topic_Categories; } public Theme getTheme_GCMD_Science(){ return this.theme_GCMD_Science; } public Theme getTheme_CF(){ return this.theme_CF; } public Theme getTheme_EDAC_Prism(){ return this.theme_EDAC_Prism; } public Theme getTheme_EDAC_MODIS(){ return this.theme_EDAC_MODIS; } }
cybershare/elseweb-v2
harvester/src/main/java/edu/utep/cybershare/elseweb/build/edac/services/source/edac/fgdc/theme/Themes.java
Java
gpl-2.0
2,344
/* id3ted: mp3file.cpp * Copyright (c) 2011 Bert Muennich <be.muennich at googlemail.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <iostream> #include <sstream> #include <cctype> #include <cstdio> #include <cstring> #include <taglib/id3v1tag.h> #include <taglib/id3v1genres.h> #include <taglib/id3v2tag.h> #include <taglib/attachedpictureframe.h> #include <taglib/commentsframe.h> #include <taglib/textidentificationframe.h> #include <taglib/unsynchronizedlyricsframe.h> #include <taglib/urllinkframe.h> #include "mp3file.h" #include "fileio.h" #include "frametable.h" MP3File::MP3File(const char *filename, int _tags, bool lame) : file(filename), id3Tag(NULL), id3v1Tag(NULL), id3v2Tag(NULL), lameTag(NULL), tags(_tags) { if (file.isValid()) { id3v1Tag = file.ID3v1Tag(tags & 1); id3v2Tag = file.ID3v2Tag(tags & 2); id3Tag = file.tag(); if (tags == 0) { // tag version to write not given on command line // -> write only the tags already in the file if (id3v1Tag != NULL && !id3v1Tag->isEmpty()) tags |= 1; if (id3v2Tag != NULL && !id3v2Tag->isEmpty()) tags |= 2; if (tags == 0) { // no tags found -> use version 2 as default tags = 2; id3v2Tag = file.ID3v2Tag(true); } } if (lame) { long frameOffset, frameLength; if (id3v2Tag != NULL && !id3v2Tag->isEmpty()) frameOffset = file.firstFrameOffset(); else frameOffset = file.nextFrameOffset(0); frameLength = file.nextFrameOffset(frameOffset + 1) - frameOffset; lameTag = new LameTag(filename, frameOffset, frameLength); } } } MP3File::~MP3File() { if (lameTag != NULL) delete lameTag; } bool MP3File::hasLameTag() const { return lameTag != NULL && lameTag->isValid(); } bool MP3File::hasID3v1Tag() const { return id3v1Tag != NULL && !id3v1Tag->isEmpty(); } bool MP3File::hasID3v2Tag() const { return id3v1Tag != NULL && !id3v2Tag->isEmpty(); } void MP3File::apply(GenericInfo *info) { if (info == NULL) return; if (!file.isValid() || file.readOnly()) return; if (id3Tag == NULL) { id3Tag = file.tag(); if (id3Tag == NULL) return; } switch(info->id()) { case 'a': { id3Tag->setArtist(info->value()); break; } case 'A': { id3Tag->setAlbum(info->value()); break; } case 't': { id3Tag->setTitle(info->value()); break; } case 'c': { id3Tag->setComment(info->value()); break; } case 'g': { id3Tag->setGenre(info->value()); break; } case 'T': { if (tags & 1) { int slash = info->value().find('/', 0); if (slash < 0) slash = info->value().length(); id3Tag->setTrack(info->value().substr(0, slash).toInt()); } if (tags & 2) { FrameInfo trackInfo(FrameTable::textFrameID(FID3_TRCK), FID3_TRCK, info->value().toCString(USE_UTF8)); apply(&trackInfo); } break; } case 'y': { id3Tag->setYear(info->value().toInt()); break; } } } void MP3File::apply(FrameInfo *info) { if (!file.isValid() || file.readOnly()) return; if (id3v2Tag == NULL || info == NULL) return; vector<ID3v2::Frame*> frameList = find(info); vector<ID3v2::Frame*>::iterator eachFrame = frameList.begin(); if (info->text().isEmpty() && info->fid() != FID3_APIC) { if (!frameList.empty()) { for (; eachFrame != frameList.end(); ++eachFrame) id3v2Tag->removeFrame(*eachFrame); } } else { if (frameList.empty() || info->fid() == FID3_APIC) { switch (info->fid()) { case FID3_APIC: { ID3v2::AttachedPictureFrame *apic; for (; eachFrame != frameList.end(); ++eachFrame) { apic = dynamic_cast<ID3v2::AttachedPictureFrame*>(*eachFrame); if (apic != NULL && apic->picture() == info->data()) return; } apic = new ID3v2::AttachedPictureFrame(); apic->setMimeType(info->description()); apic->setType(ID3v2::AttachedPictureFrame::FrontCover); apic->setPicture(info->data()); id3v2Tag->addFrame(apic); break; } case FID3_COMM: { if (info->text().isEmpty()) return; ID3v2::CommentsFrame *comment = new ID3v2::CommentsFrame(DEF_TSTR_ENC); comment->setText(info->text()); comment->setDescription(info->description()); comment->setLanguage(info->language()); id3v2Tag->addFrame(comment); break; } case FID3_TXXX: { ID3v2::UserTextIdentificationFrame *userText = new ID3v2::UserTextIdentificationFrame(DEF_TSTR_ENC); userText->setText(info->text()); userText->setDescription(info->description()); id3v2Tag->addFrame(userText); break; } case FID3_USLT: { ID3v2::UnsynchronizedLyricsFrame *lyrics = new ID3v2::UnsynchronizedLyricsFrame(DEF_TSTR_ENC); lyrics->setText(info->text()); lyrics->setDescription(info->description()); lyrics->setLanguage(info->language()); id3v2Tag->addFrame(lyrics); break; } case FID3_WCOM: case FID3_WCOP: case FID3_WOAF: case FID3_WOAR: case FID3_WOAS: case FID3_WORS: case FID3_WPAY: case FID3_WPUB: { ID3v2::UrlLinkFrame *urlLink = new ID3v2::UrlLinkFrame(info->id()); urlLink->setUrl(info->text()); id3v2Tag->addFrame(urlLink); break; } case FID3_WXXX: { ID3v2::UserUrlLinkFrame *userUrl = new ID3v2::UserUrlLinkFrame(DEF_TSTR_ENC); userUrl->setUrl(info->text()); userUrl->setDescription(info->description()); id3v2Tag->addFrame(userUrl); break; } default: { ID3v2::TextIdentificationFrame *textFrame = new ID3v2::TextIdentificationFrame(info->id(), DEF_TSTR_ENC); textFrame->setText(info->text()); id3v2Tag->addFrame(textFrame); break; } } } else { frameList.front()->setText(info->text()); } } } void MP3File::apply(const MatchInfo &info) { if (!file.isValid() || file.readOnly()) return; if (info.id == 0 || info.text.length() == 0) return; switch (info.id) { case 'a': case 'A': case 't': case 'c': case 'g': case 'T': case 'y': { GenericInfo genInfo(info.id, info.text.c_str()); apply(&genInfo); break; } case 'd': { if (id3v2Tag != NULL) { FrameInfo frameInfo("TPOS", FID3_TPOS, info.text.c_str()); apply(&frameInfo); } break; } } } void MP3File::fill(MatchInfo &info) { string &text = info.text; ostringstream tmp; tmp.fill('0'); if (!file.isValid()) return; if (info.id == 0) return; switch (info.id) { case 'a': text = id3Tag->artist().toCString(USE_UTF8); if (text.empty()) text = "Unknown Artist"; break; case 'A': text = id3Tag->album().toCString(USE_UTF8); if (text.empty()) text = "Unknown Album"; break; case 't': text = id3Tag->title().toCString(USE_UTF8); if (text.empty()) text = "Unknown Title"; break; case 'g': text = id3Tag->genre().toCString(USE_UTF8); break; case 'y': { uint year = id3Tag->year(); if (year) { tmp << year; text = tmp.str(); } break; } case 'T': { uint track = id3Tag->track(); if (track) { tmp.width(2); tmp << track; text = tmp.str(); } break; } case 'd': { if (id3v2Tag != NULL) { ID3v2::FrameList list = id3v2Tag->frameListMap()["TPOS"]; if (!list.isEmpty()) { uint disc = list.front()->toString().toInt(); if (disc) { tmp << disc; text = tmp.str(); } } } break; } } } void MP3File::removeFrames(const char *textFID) { if (textFID == NULL) return; if (!file.isValid() || file.readOnly()) return; if (id3v2Tag != NULL) id3v2Tag->removeFrames(textFID); } bool MP3File::save() { if (!file.isValid() || file.readOnly()) return false; // bug in TagLib 1.5.0?: deleting solely frame in id3v2 tag and // then saving file causes the recovery of the last deleted frame. // solution: strip the whole tag if it is empty before writing file! if (tags & 2 && id3v2Tag != NULL && id3v2Tag->isEmpty()) strip(2); return file.save(tags, false); } bool MP3File::strip(int tags) { if (!file.isValid() || file.readOnly()) return false; return file.strip(tags); } void MP3File::showInfo() const { MPEG::Properties *properties; const char *version; const char *channelMode; if (!file.isValid()) return; if ((properties = file.audioProperties()) == NULL) return; switch (properties->version()) { case 1: version = "2"; break; case 2: version = "2.5"; break; default: version = "1"; break; } switch (properties->channelMode()) { case 0: channelMode = "Stereo"; break; case 1: channelMode = "JointStereo"; break; case 2: channelMode = "DualChannel"; break; default: channelMode = "SingleChannel"; break; } int length = properties->length(); printf("MPEG %s Layer %d %s\n", version, properties->layer(), channelMode); printf("bitrate: %d kBit/s, sample rate: %d Hz, length: %02d:%02d:%02d\n", properties->bitrate(), properties->sampleRate(), length / 3600, length / 60, length % 60); } void MP3File::printLameTag(bool checkCRC) const { if (!file.isValid()) return; if (lameTag != NULL) lameTag->print(checkCRC); } void MP3File::listID3v1Tag() const { if (!file.isValid()) return; if (id3v1Tag == NULL || id3v1Tag->isEmpty()) return; int year = id3v1Tag->year(); TagLib::String genreStr = id3v1Tag->genre(); int genre = ID3v1::genreIndex(genreStr); printf("ID3v1:\n"); printf("Title : %-30s Track: %d\n", id3v1Tag->title().toCString(USE_UTF8), id3v1Tag->track()); printf("Artist : %-30s Year : %-4s\n", id3v1Tag->artist().toCString(USE_UTF8), (year != 0 ? TagLib::String::number(year).toCString() : "")); printf("Album : %-30s Genre: %s (%d)\n", id3v1Tag->album().toCString(USE_UTF8), (genre == 255 ? "Unknown" : genreStr.toCString()), genre); printf("Comment: %s\n", id3v1Tag->comment().toCString(USE_UTF8)); } void MP3File::listID3v2Tag(bool withDesc) const { if (!file.isValid()) return; if (id3v2Tag == NULL || id3v2Tag->isEmpty()) return; int frameCount = id3v2Tag->frameList().size(); cout << "ID3v2." << id3v2Tag->header()->majorVersion() << " - " << frameCount << (frameCount != 1 ? " frames:" : " frame:") << endl; ID3v2::FrameList::ConstIterator frame = id3v2Tag->frameList().begin(); for (; frame != id3v2Tag->frameList().end(); ++frame) { String textFID((*frame)->frameID(), DEF_TSTR_ENC); cout << textFID; if (withDesc) cout << " (" << FrameTable::frameDescription(textFID) << ")"; cout << ": "; switch (FrameTable::frameID(textFID)) { case FID3_APIC: { ID3v2::AttachedPictureFrame *apic = dynamic_cast<ID3v2::AttachedPictureFrame*>(*frame); if (apic != NULL) { int size = apic->picture().size(); cout << apic->mimeType() << ", " << FileIO::sizeHumanReadable(size); } break; } case FID3_COMM: { ID3v2::CommentsFrame *comment = dynamic_cast<ID3v2::CommentsFrame*>(*frame); if (comment != NULL) { TagLib::ByteVector lang = comment->language(); bool showLanguage = lang.size() == 3 && isalpha(lang[0]) && isalpha(lang[1]) && isalpha(lang[2]); cout << "[" << comment->description().toCString(USE_UTF8) << "]"; if (showLanguage) cout << "(" << lang[0] << lang[1] << lang[2]; else cout << "(XXX"; cout << "): " << comment->toString().toCString(USE_UTF8); } break; } case FID3_TCON: { String genreStr = (*frame)->toString(); int genre = 255; sscanf(genreStr.toCString(), "(%d)", &genre); if (genre == 255) sscanf(genreStr.toCString(), "%d", &genre); if (genre != 255) genreStr = ID3v1::genre(genre); cout << genreStr; break; } case FID3_USLT: { ID3v2::UnsynchronizedLyricsFrame *lyrics = dynamic_cast<ID3v2::UnsynchronizedLyricsFrame*>(*frame); if (lyrics != NULL) { const char *text = lyrics->text().toCString(USE_UTF8); const char *indent = " "; TagLib::ByteVector lang = lyrics->language(); bool showLanguage = lang.size() == 3 && isalpha(lang[0]) && isalpha(lang[1]) && isalpha(lang[2]); cout << "[" << lyrics->description().toCString(USE_UTF8) << "]"; if (showLanguage) cout << "(" << lang[0] << lang[1] << lang[2]; else cout << "(XXX"; cout << "):\n" << indent; while (*text != '\0') { if (*text == (char) 10 || *text == (char) 13) cout << "\n" << indent; else putchar(*text); ++text; } } break; } case FID3_TXXX: { ID3v2::UserTextIdentificationFrame *userText = dynamic_cast<ID3v2::UserTextIdentificationFrame*>(*frame); if (userText != NULL) { StringList textList = userText->fieldList(); cout << "[" << userText->description().toCString(USE_UTF8) << "]: "; if (textList.size() > 1) cout << textList[1].toCString(USE_UTF8); } break; } case FID3_WXXX: { ID3v2::UserUrlLinkFrame *userUrl = dynamic_cast<ID3v2::UserUrlLinkFrame*>(*frame); if (userUrl != NULL) cout << "[" << userUrl->description().toCString(USE_UTF8) << "]: " << userUrl->url().toCString(USE_UTF8); break; } case FID3_XXXX: { break; } default: cout << (*frame)->toString().toCString(USE_UTF8); break; } cout << endl; } } void MP3File::extractAPICs(bool overwrite) const { if (!file.isValid() || id3v2Tag == NULL) return; int num = 0; const char *mimetype, *filetype; ostringstream filename; ID3v2::FrameList apicList = id3v2Tag->frameListMap()["APIC"]; ID3v2::FrameList::ConstIterator each = apicList.begin(); for (; each != apicList.end(); ++each) { ID3v2::AttachedPictureFrame *apic = dynamic_cast<ID3v2::AttachedPictureFrame*>(*each); if (apic == NULL) continue; mimetype = apic->mimeType().toCString(); if (mimetype != NULL && strlen(mimetype) > 0) { filetype = strrchr(mimetype, '/'); if (filetype != NULL && strlen(filetype+1) > 0) ++filetype; else filetype = mimetype; } else { filetype = "bin"; } filename.str(""); filename << file.name() << ".apic-" << (++num < 10 ? "0" : ""); filename << num << "." << filetype; if (FileIO::exists(filename.str().c_str())) { if (!overwrite && !FileIO::confirmOverwrite(filename.str().c_str())) continue; } OFile outFile(filename.str().c_str()); if (!outFile.isOpen()) continue; outFile.write(apic->picture()); if (outFile.error()) warn("%s: Could not write file", filename.str().c_str()); outFile.close(); } } vector<ID3v2::Frame*> MP3File::find(FrameInfo *info) { vector<ID3v2::Frame*> list; if (id3v2Tag == NULL || info == NULL) return list; ID3v2::FrameList frameList = id3v2Tag->frameListMap()[info->id()]; ID3v2::FrameList::ConstIterator each = frameList.begin(); for (; each != frameList.end(); ++each) { switch (FrameTable::frameID((*each)->frameID())) { case FID3_APIC: { ID3v2::AttachedPictureFrame *apic = dynamic_cast<ID3v2::AttachedPictureFrame*>(*each); if (apic == NULL) continue; if (info->data() == apic->picture() && info->description() == apic->mimeType()) list.push_back(*each); break; } case FID3_COMM: { ID3v2::CommentsFrame *comment = dynamic_cast<ID3v2::CommentsFrame*>(*each); if (comment == NULL) continue; if (comment->language().isEmpty()) comment->setLanguage("XXX"); if (info->description() == comment->description() && info->language() == comment->language()) list.push_back(*each); break; } case FID3_TXXX: { ID3v2::UserTextIdentificationFrame *userText = dynamic_cast<ID3v2::UserTextIdentificationFrame*>(*each); if (userText == NULL) continue; if (info->description() == userText->description()) list.push_back(*each); break; } case FID3_USLT: { ID3v2::UnsynchronizedLyricsFrame *lyrics = dynamic_cast<ID3v2::UnsynchronizedLyricsFrame*>(*each); if (lyrics == NULL) continue; if (lyrics->language().isEmpty()) lyrics->setLanguage("XXX"); if (info->description() == lyrics->description() && info->language() == lyrics->language()) list.push_back(*each); break; } case FID3_WXXX: { ID3v2::UserUrlLinkFrame *userUrl = dynamic_cast<ID3v2::UserUrlLinkFrame*>(*each); if (userUrl == NULL) continue; if (info->description() == userUrl->description()) list.push_back(*each); break; } default: list.push_back(*each); break; } } return list; }
muennich/id3ted
mp3file.cpp
C++
gpl-2.0
17,248
/* Copyright (c) 2012-2014, The Linux Foundataion. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of The Linux Foundation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #define LOG_TAG "QCamera2HWI" #include <cutils/properties.h> #include <hardware/camera.h> #include <stdlib.h> #include <utils/Errors.h> #include <gralloc_priv.h> #include <gui/Surface.h> #include "QCamera2HWI.h" #include "QCameraMem.h" #define MAP_TO_DRIVER_COORDINATE(val, base, scale, offset) (val * scale / base + offset) #define CAMERA_MIN_STREAMING_BUFFERS 3 #define EXTRA_ZSL_PREVIEW_STREAM_BUF 2 #define CAMERA_MIN_JPEG_ENCODING_BUFFERS 2 #define CAMERA_MIN_VIDEO_BUFFERS 9 #define CAMERA_LONGSHOT_STAGES 4 #define HDR_CONFIDENCE_THRESHOLD 0.4 namespace qcamera { cam_capability_t *gCamCapability[MM_CAMERA_MAX_NUM_SENSORS]; qcamera_saved_sizes_list savedSizes[MM_CAMERA_MAX_NUM_SENSORS]; static pthread_mutex_t g_camlock = PTHREAD_MUTEX_INITIALIZER; volatile uint32_t gCamHalLogLevel = 0; camera_device_ops_t QCamera2HardwareInterface::mCameraOps = { set_preview_window: QCamera2HardwareInterface::set_preview_window, set_callbacks: QCamera2HardwareInterface::set_CallBacks, enable_msg_type: QCamera2HardwareInterface::enable_msg_type, disable_msg_type: QCamera2HardwareInterface::disable_msg_type, msg_type_enabled: QCamera2HardwareInterface::msg_type_enabled, start_preview: QCamera2HardwareInterface::start_preview, stop_preview: QCamera2HardwareInterface::stop_preview, preview_enabled: QCamera2HardwareInterface::preview_enabled, store_meta_data_in_buffers: QCamera2HardwareInterface::store_meta_data_in_buffers, start_recording: QCamera2HardwareInterface::start_recording, stop_recording: QCamera2HardwareInterface::stop_recording, recording_enabled: QCamera2HardwareInterface::recording_enabled, release_recording_frame: QCamera2HardwareInterface::release_recording_frame, auto_focus: QCamera2HardwareInterface::auto_focus, cancel_auto_focus: QCamera2HardwareInterface::cancel_auto_focus, take_picture: QCamera2HardwareInterface::take_picture, cancel_picture: QCamera2HardwareInterface::cancel_picture, set_parameters: QCamera2HardwareInterface::set_parameters, get_parameters: QCamera2HardwareInterface::get_parameters, put_parameters: QCamera2HardwareInterface::put_parameters, send_command: QCamera2HardwareInterface::send_command, release: QCamera2HardwareInterface::release, dump: QCamera2HardwareInterface::dump, }; int32_t QCamera2HardwareInterface::getEffectValue(const char *effect) { uint32_t cnt = 0; while(NULL != QCameraParameters::EFFECT_MODES_MAP[cnt].desc) { if(!strcmp(QCameraParameters::EFFECT_MODES_MAP[cnt].desc, effect)) { return QCameraParameters::EFFECT_MODES_MAP[cnt].val; } cnt++; } return 0; } /*=========================================================================== * FUNCTION : set_preview_window * * DESCRIPTION: set preview window. * * PARAMETERS : * @device : ptr to camera device struct * @window : window ops table * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::set_preview_window(struct camera_device *device, struct preview_stream_ops *window) { int rc = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("%s: NULL camera device", __func__); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; rc = hw->processAPI(QCAMERA_SM_EVT_SET_PREVIEW_WINDOW, (void *)window); if (rc == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_SET_PREVIEW_WINDOW, &apiResult); rc = apiResult.status; } hw->unlockAPI(); return rc; } /*=========================================================================== * FUNCTION : set_CallBacks * * DESCRIPTION: set callbacks for notify and data * * PARAMETERS : * @device : ptr to camera device struct * @notify_cb : notify cb * @data_cb : data cb * @data_cb_timestamp : video data cd with timestamp * @get_memory : ops table for request gralloc memory * @user : user data ptr * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::set_CallBacks(struct camera_device *device, camera_notify_callback notify_cb, camera_data_callback data_cb, camera_data_timestamp_callback data_cb_timestamp, camera_request_memory get_memory, void *user) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } qcamera_sm_evt_setcb_payload_t payload; payload.notify_cb = notify_cb; payload.data_cb = data_cb; payload.data_cb_timestamp = data_cb_timestamp; payload.get_memory = get_memory; payload.user = user; hw->lockAPI(); qcamera_api_result_t apiResult; int32_t rc = hw->processAPI(QCAMERA_SM_EVT_SET_CALLBACKS, (void *)&payload); if (rc == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_SET_CALLBACKS, &apiResult); } hw->unlockAPI(); } /*=========================================================================== * FUNCTION : enable_msg_type * * DESCRIPTION: enable certain msg type * * PARAMETERS : * @device : ptr to camera device struct * @msg_type : msg type mask * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::enable_msg_type(struct camera_device *device, int32_t msg_type) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } hw->lockAPI(); qcamera_api_result_t apiResult; int32_t rc = hw->processAPI(QCAMERA_SM_EVT_ENABLE_MSG_TYPE, (void *)msg_type); if (rc == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_ENABLE_MSG_TYPE, &apiResult); } hw->unlockAPI(); } /*=========================================================================== * FUNCTION : disable_msg_type * * DESCRIPTION: disable certain msg type * * PARAMETERS : * @device : ptr to camera device struct * @msg_type : msg type mask * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::disable_msg_type(struct camera_device *device, int32_t msg_type) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } hw->lockAPI(); qcamera_api_result_t apiResult; int32_t rc = hw->processAPI(QCAMERA_SM_EVT_DISABLE_MSG_TYPE, (void *)msg_type); if (rc == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_DISABLE_MSG_TYPE, &apiResult); } hw->unlockAPI(); } /*=========================================================================== * FUNCTION : msg_type_enabled * * DESCRIPTION: if certain msg type is enabled * * PARAMETERS : * @device : ptr to camera device struct * @msg_type : msg type mask * * RETURN : 1 -- enabled * 0 -- not enabled *==========================================================================*/ int QCamera2HardwareInterface::msg_type_enabled(struct camera_device *device, int32_t msg_type) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_MSG_TYPE_ENABLED, (void *)msg_type); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_MSG_TYPE_ENABLED, &apiResult); ret = apiResult.enabled; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : start_preview * * DESCRIPTION: start preview * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::start_preview(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_START_PREVIEW", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; qcamera_sm_evt_enum_t evt = QCAMERA_SM_EVT_START_PREVIEW; if (hw->isNoDisplayMode()) { evt = QCAMERA_SM_EVT_START_NODISPLAY_PREVIEW; } ret = hw->processAPI(evt, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(evt, &apiResult); ret = apiResult.status; } hw->unlockAPI(); hw->m_bPreviewStarted = true; CDBG_HIGH("[KPI Perf] %s: X", __func__); #ifdef ARCSOFT_FB_SUPPORT if(hw->mArcsoftEnabled==true)hw->beautyshot.Init(); #endif return ret; } /*=========================================================================== * FUNCTION : stop_preview * * DESCRIPTION: stop preview * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::stop_preview(struct camera_device *device) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_STOP_PREVIEW", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; int32_t ret = hw->processAPI(QCAMERA_SM_EVT_STOP_PREVIEW, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_STOP_PREVIEW, &apiResult); } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s: X", __func__); #ifdef ARCSOFT_FB_SUPPORT hw->beautyshot.Uninit(); #endif } /*=========================================================================== * FUNCTION : preview_enabled * * DESCRIPTION: if preview is running * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : 1 -- running * 0 -- not running *==========================================================================*/ int QCamera2HardwareInterface::preview_enabled(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_PREVIEW_ENABLED, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_PREVIEW_ENABLED, &apiResult); ret = apiResult.enabled; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : store_meta_data_in_buffers * * DESCRIPTION: if need to store meta data in buffers for video frame * * PARAMETERS : * @device : ptr to camera device struct * @enable : flag if enable * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::store_meta_data_in_buffers( struct camera_device *device, int enable) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_STORE_METADATA_IN_BUFS, (void *)enable); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_STORE_METADATA_IN_BUFS, &apiResult); ret = apiResult.status; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : start_recording * * DESCRIPTION: start recording * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::start_recording(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_START_RECORDING", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_START_RECORDING, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_START_RECORDING, &apiResult); ret = apiResult.status; } hw->unlockAPI(); hw->m_bRecordStarted = true; CDBG_HIGH("[KPI Perf] %s: X", __func__); return ret; } /*=========================================================================== * FUNCTION : stop_recording * * DESCRIPTION: stop recording * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::stop_recording(struct camera_device *device) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_STOP_RECORDING", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; int32_t ret = hw->processAPI(QCAMERA_SM_EVT_STOP_RECORDING, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_STOP_RECORDING, &apiResult); } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s: X", __func__); } /*=========================================================================== * FUNCTION : recording_enabled * * DESCRIPTION: if recording is running * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : 1 -- running * 0 -- not running *==========================================================================*/ int QCamera2HardwareInterface::recording_enabled(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_RECORDING_ENABLED, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_RECORDING_ENABLED, &apiResult); ret = apiResult.enabled; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : release_recording_frame * * DESCRIPTION: return recording frame back * * PARAMETERS : * @device : ptr to camera device struct * @opaque : ptr to frame to be returned * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::release_recording_frame( struct camera_device *device, const void *opaque) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } CDBG_HIGH("%s: E", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; int32_t ret = hw->processAPI(QCAMERA_SM_EVT_RELEASE_RECORIDNG_FRAME, (void *)opaque); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_RELEASE_RECORIDNG_FRAME, &apiResult); } hw->unlockAPI(); CDBG_HIGH("%s: X", __func__); } /*=========================================================================== * FUNCTION : auto_focus * * DESCRIPTION: start auto focus * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::auto_focus(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s : E PROFILE_AUTO_FOCUS", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_START_AUTO_FOCUS, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_START_AUTO_FOCUS, &apiResult); ret = apiResult.status; } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s : X", __func__); return ret; } /*=========================================================================== * FUNCTION : cancel_auto_focus * * DESCRIPTION: cancel auto focus * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::cancel_auto_focus(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s : E PROFILE_CANCEL_AUTO_FOCUS", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_STOP_AUTO_FOCUS, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_STOP_AUTO_FOCUS, &apiResult); ret = apiResult.status; } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s : X", __func__); return ret; } /*=========================================================================== * FUNCTION : take_picture * * DESCRIPTION: take picture * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::take_picture(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_TAKE_PICTURE", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; /* Prepare snapshot in case LED needs to be flashed */ if (hw->mFlashNeeded == 1 || hw->mParameters.isChromaFlashEnabled()) { ret = hw->processAPI(QCAMERA_SM_EVT_PREPARE_SNAPSHOT, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_PREPARE_SNAPSHOT, &apiResult); ret = apiResult.status; } hw->mPrepSnapRun = true; } /* Regardless what the result value for prepare_snapshot, * go ahead with capture anyway. Just like the way autofocus * is handled in capture case. */ /* capture */ ret = hw->processAPI(QCAMERA_SM_EVT_TAKE_PICTURE, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_TAKE_PICTURE, &apiResult); ret = apiResult.status; } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s: X", __func__); return ret; } /*=========================================================================== * FUNCTION : cancel_picture * * DESCRIPTION: cancel current take picture request * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::cancel_picture(struct camera_device *device) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_CANCEL_PICTURE", __func__); hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_CANCEL_PICTURE, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_CANCEL_PICTURE, &apiResult); ret = apiResult.status; } hw->unlockAPI(); CDBG_HIGH("[KPI Perf] %s: X", __func__); return ret; } /*=========================================================================== * FUNCTION : set_parameters * * DESCRIPTION: set camera parameters * * PARAMETERS : * @device : ptr to camera device struct * @parms : string of packed parameters * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::set_parameters(struct camera_device *device, const char *parms) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); #if 0 // BEGIN<><2014.12.17><3ndPart Camera unlike local one>Jiangde char s[100], *pcStart = NULL, *pcEnd = NULL; ALOGE("%s parms begin", __func__); pcStart = (char *)parms; while((pcEnd = strchr(pcStart, ';')) != NULL) { if (pcEnd - pcStart <= 100 - 1) { strncpy(s, pcStart, pcEnd - pcStart); s[pcEnd - pcStart] = '\0'; ALOGE("%s %s", __func__, s); } else { ALOGE("%s out of boundary, print all begin", __func__); ALOGE("%s %s", __func__, pcStart); ALOGE("%s out of boundary, print all end", __func__); } pcStart = pcEnd + 1; } if(pcStart != NULL && pcStart[0] != '\0') { ALOGE("%s %s", __func__, pcStart); } ALOGE("%s parms end", __func__); #endif // END<><2014.12.17><3ndPart Camera unlike local one>Jiangde if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_SET_PARAMS, (void *)parms); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_SET_PARAMS, &apiResult); ret = apiResult.status; } hw->unlockAPI(); #ifdef ARCSOFT_FB_SUPPORT //ALOGE("parms===========================%s",parms); //QCameraParameters *qparam = new QCameraParameters((const String8)parms); //qparam->dump(); //hw->mParameters.dump(); int value = hw->mParameters.getInt(hw->mParameters.KEY_FACE_BEAUTY_ENABLED); if(value == 1){ if(hw->mArcsoftEnabled==false)hw->beautyshot.Init(); hw->mArcsoftEnabled = true; }else if(value == 0){ //if(hw->mArcsoftEnabled==true)hw->beautyshot.Uninit();//when prosessing uninit,cos crash hw->mArcsoftEnabled = false; } value = hw->mParameters.getInt(hw->mParameters.KEY_SKIN_SOFTEN_LEVEL); if(value != -1)hw->skinsoften = value; value = hw->mParameters.getInt(hw->mParameters.KEY_SLENDER_FACE_LEVEL); if(value != -1)hw->slenderface = value; value = hw->mParameters.getInt(hw->mParameters.KEY_EYE_ENLARGEMENT_LEVEL); if(value != -1)hw->eyeenlargement = value; ALOGE("mArcsoftEnabled=%d,skinsoften=%d,slenderface=%d,eyeenlargement=%d",hw->mArcsoftEnabled,hw->skinsoften,hw->slenderface,hw->eyeenlargement); #endif return ret; } /*=========================================================================== * FUNCTION : get_parameters * * DESCRIPTION: query camera parameters * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : packed parameters in a string *==========================================================================*/ char* QCamera2HardwareInterface::get_parameters(struct camera_device *device) { char *ret = NULL; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return NULL; } hw->lockAPI(); qcamera_api_result_t apiResult; int32_t rc = hw->processAPI(QCAMERA_SM_EVT_GET_PARAMS, NULL); if (rc == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_GET_PARAMS, &apiResult); ret = apiResult.params; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : put_parameters * * DESCRIPTION: return camera parameters string back to HAL * * PARAMETERS : * @device : ptr to camera device struct * @parm : ptr to parameter string to be returned * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::put_parameters(struct camera_device *device, char *parm) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } hw->lockAPI(); qcamera_api_result_t apiResult; int32_t ret = hw->processAPI(QCAMERA_SM_EVT_PUT_PARAMS, (void *)parm); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_PUT_PARAMS, &apiResult); } hw->unlockAPI(); } /*=========================================================================== * FUNCTION : send_command * * DESCRIPTION: command to be executed * * PARAMETERS : * @device : ptr to camera device struct * @cmd : cmd to be executed * @arg1 : ptr to optional argument1 * @arg2 : ptr to optional argument2 * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::send_command(struct camera_device *device, int32_t cmd, int32_t arg1, int32_t arg2) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } qcamera_sm_evt_command_payload_t payload; memset(&payload, 0, sizeof(qcamera_sm_evt_command_payload_t)); payload.cmd = cmd; payload.arg1 = arg1; payload.arg2 = arg2; hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_SEND_COMMAND, (void *)&payload); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_SEND_COMMAND, &apiResult); ret = apiResult.status; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : release * * DESCRIPTION: release camera resource * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::release(struct camera_device *device) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return; } hw->lockAPI(); qcamera_api_result_t apiResult; int32_t ret = hw->processAPI(QCAMERA_SM_EVT_RELEASE, NULL); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_RELEASE, &apiResult); } hw->unlockAPI(); } /*=========================================================================== * FUNCTION : dump * * DESCRIPTION: dump camera status * * PARAMETERS : * @device : ptr to camera device struct * @fd : fd for status to be dumped to * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::dump(struct camera_device *device, int fd) { int ret = NO_ERROR; //Log level property is read when "adb shell dumpsys media.camera" is //called so that the log level can be controlled without restarting //media server getLogLevel(); QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_DUMP, (void *)fd); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_DUMP, &apiResult); ret = apiResult.status; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : close_camera_device * * DESCRIPTION: close camera device * * PARAMETERS : * @device : ptr to camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::close_camera_device(hw_device_t *hw_dev) { int ret = NO_ERROR; CDBG_HIGH("[KPI Perf] %s: E",__func__); QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>( reinterpret_cast<camera_device_t *>(hw_dev)->priv); if (!hw) { ALOGE("%s: NULL camera device", __func__); return BAD_VALUE; } delete hw; CDBG_HIGH("[KPI Perf] %s: X",__func__); return ret; } /*=========================================================================== * FUNCTION : register_face_image * * DESCRIPTION: register a face image into imaging lib for face authenticatio/ * face recognition * * PARAMETERS : * @device : ptr to camera device struct * @img_ptr : ptr to image buffer * @config : ptr to config about input image, i.e., format, dimension, and etc. * * RETURN : >=0 unique ID of face registerd. * <0 failure. *==========================================================================*/ int QCamera2HardwareInterface::register_face_image(struct camera_device *device, void *img_ptr, cam_pp_offline_src_config_t *config) { int ret = NO_ERROR; QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(device->priv); if (!hw) { ALOGE("NULL camera device"); return BAD_VALUE; } qcamera_sm_evt_reg_face_payload_t payload; memset(&payload, 0, sizeof(qcamera_sm_evt_reg_face_payload_t)); payload.img_ptr = img_ptr; payload.config = config; hw->lockAPI(); qcamera_api_result_t apiResult; ret = hw->processAPI(QCAMERA_SM_EVT_REG_FACE_IMAGE, (void *)&payload); if (ret == NO_ERROR) { hw->waitAPIResult(QCAMERA_SM_EVT_REG_FACE_IMAGE, &apiResult); ret = apiResult.handle; } hw->unlockAPI(); return ret; } /*=========================================================================== * FUNCTION : QCamera2HardwareInterface * * DESCRIPTION: constructor of QCamera2HardwareInterface * * PARAMETERS : * @cameraId : camera ID * * RETURN : none *==========================================================================*/ QCamera2HardwareInterface::QCamera2HardwareInterface(int cameraId) : mCameraId(cameraId), mCameraHandle(NULL), mCameraOpened(false), mPreviewWindow(NULL), mMsgEnabled(0), mStoreMetaDataInFrame(0), m_stateMachine(this), m_postprocessor(this), m_thermalAdapter(QCameraThermalAdapter::getInstance()), m_cbNotifier(this), m_bShutterSoundPlayed(false), m_bPreviewStarted(false), m_bRecordStarted(false), m_currentFocusState(CAM_AF_SCANNING), m_pPowerModule(NULL), mDumpFrmCnt(0), mDumpSkipCnt(0), mThermalLevel(QCAMERA_THERMAL_NO_ADJUSTMENT), mCancelAutoFocus(false), m_HDRSceneEnabled(false), mLongshotEnabled(false), m_max_pic_width(0), m_max_pic_height(0), mLiveSnapshotThread(0), mIntPicThread(0), mFlashNeeded(false), mCaptureRotation(0), mIs3ALocked(false), mPrepSnapRun(false), mZoomLevel(0), m_bIntEvtPending(false), mSnapshotJob(-1), mPostviewJob(-1), mMetadataJob(-1), mReprocJob(-1), mRawdataJob(-1), mPreviewFrameSkipValid(0) { getLogLevel(); mCameraDevice.common.tag = HARDWARE_DEVICE_TAG; mCameraDevice.common.version = HARDWARE_DEVICE_API_VERSION(1, 0); mCameraDevice.common.close = close_camera_device; mCameraDevice.ops = &mCameraOps; mCameraDevice.priv = this; pthread_mutex_init(&m_lock, NULL); pthread_cond_init(&m_cond, NULL); m_apiResultList = NULL; pthread_mutex_init(&m_evtLock, NULL); pthread_cond_init(&m_evtCond, NULL); memset(&m_evtResult, 0, sizeof(qcamera_api_result_t)); pthread_mutex_init(&m_parm_lock, NULL); pthread_mutex_init(&m_int_lock, NULL); pthread_cond_init(&m_int_cond, NULL); memset(m_channels, 0, sizeof(m_channels)); #ifdef HAS_MULTIMEDIA_HINTS if (hw_get_module(POWER_HARDWARE_MODULE_ID, (const hw_module_t **)&m_pPowerModule)) { ALOGE("%s: %s module not found", __func__, POWER_HARDWARE_MODULE_ID); } #endif memset(mDeffOngoingJobs, 0, sizeof(mDeffOngoingJobs)); //reset preview frame skip memset(&mPreviewFrameSkipIdxRange, 0, sizeof(cam_frame_idx_range_t)); mDefferedWorkThread.launch(defferedWorkRoutine, this); mDefferedWorkThread.sendCmd(CAMERA_CMD_TYPE_START_DATA_PROC, FALSE, FALSE); #ifdef ARCSOFT_FB_SUPPORT mArcsoftEnabled = false; #endif } /*=========================================================================== * FUNCTION : ~QCamera2HardwareInterface * * DESCRIPTION: destructor of QCamera2HardwareInterface * * PARAMETERS : none * * RETURN : none *==========================================================================*/ QCamera2HardwareInterface::~QCamera2HardwareInterface() { CDBG_HIGH("%s: E", __func__); mDefferedWorkThread.sendCmd(CAMERA_CMD_TYPE_STOP_DATA_PROC, TRUE, TRUE); mDefferedWorkThread.exit(); closeCamera(); pthread_mutex_destroy(&m_lock); pthread_cond_destroy(&m_cond); pthread_mutex_destroy(&m_evtLock); pthread_cond_destroy(&m_evtCond); pthread_mutex_destroy(&m_parm_lock); CDBG_HIGH("%s: X", __func__); } /*=========================================================================== * FUNCTION : openCamera * * DESCRIPTION: open camera * * PARAMETERS : * @hw_device : double ptr for camera device struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::openCamera(struct hw_device_t **hw_device) { int rc = NO_ERROR; if (mCameraOpened) { *hw_device = NULL; return PERMISSION_DENIED; } CDBG_HIGH("[KPI Perf] %s: E PROFILE_OPEN_CAMERA camera id %d", __func__,mCameraId); rc = openCamera(); if (rc == NO_ERROR){ *hw_device = &mCameraDevice.common; if (m_thermalAdapter.init(this) != 0) { ALOGE("Init thermal adapter failed"); } } else *hw_device = NULL; return rc; } /*=========================================================================== * FUNCTION : openCamera * * DESCRIPTION: open camera * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::openCamera() { int32_t l_curr_width = 0; int32_t l_curr_height = 0; m_max_pic_width = 0; m_max_pic_height = 0; char value[PROPERTY_VALUE_MAX]; int enable_4k2k; int i; if (mCameraHandle) { ALOGE("Failure: Camera already opened"); return ALREADY_EXISTS; } mCameraHandle = camera_open(mCameraId); if (!mCameraHandle) { ALOGE("camera_open failed."); return UNKNOWN_ERROR; } if (NULL == gCamCapability[mCameraId]) initCapabilities(mCameraId,mCameraHandle); mCameraHandle->ops->register_event_notify(mCameraHandle->camera_handle, camEvtHandle, (void *) this); /* get max pic size for jpeg work buf calculation*/ for(i = 0; i < gCamCapability[mCameraId]->picture_sizes_tbl_cnt - 1; i++) { l_curr_width = gCamCapability[mCameraId]->picture_sizes_tbl[i].width; l_curr_height = gCamCapability[mCameraId]->picture_sizes_tbl[i].height; if ((l_curr_width * l_curr_height) > (m_max_pic_width * m_max_pic_height)) { m_max_pic_width = l_curr_width; m_max_pic_height = l_curr_height; } } //reset the preview and video sizes tables in case they were changed earlier copyList(savedSizes[mCameraId].all_preview_sizes, gCamCapability[mCameraId]->preview_sizes_tbl, savedSizes[mCameraId].all_preview_sizes_cnt); gCamCapability[mCameraId]->preview_sizes_tbl_cnt = savedSizes[mCameraId].all_preview_sizes_cnt; copyList(savedSizes[mCameraId].all_video_sizes, gCamCapability[mCameraId]->video_sizes_tbl, savedSizes[mCameraId].all_video_sizes_cnt); gCamCapability[mCameraId]->video_sizes_tbl_cnt = savedSizes[mCameraId].all_video_sizes_cnt; //check if video size 4k x 2k support is enabled property_get("persist.camera.4k2k.enable", value, "0"); enable_4k2k = atoi(value) > 0 ? 1 : 0; ALOGD("%s: enable_4k2k is %d", __func__, enable_4k2k); if (!enable_4k2k) { //if the 4kx2k size exists in the supported preview size or //supported video size remove it bool found; cam_dimension_t true_size_4k_2k; cam_dimension_t size_4k_2k; true_size_4k_2k.width = 4096; true_size_4k_2k.height = 2160; size_4k_2k.width = 3840; size_4k_2k.height = 2160; found = removeSizeFromList(gCamCapability[mCameraId]->preview_sizes_tbl, gCamCapability[mCameraId]->preview_sizes_tbl_cnt, true_size_4k_2k); if (found) { gCamCapability[mCameraId]->preview_sizes_tbl_cnt--; } found = removeSizeFromList(gCamCapability[mCameraId]->preview_sizes_tbl, gCamCapability[mCameraId]->preview_sizes_tbl_cnt, size_4k_2k); if (found) { gCamCapability[mCameraId]->preview_sizes_tbl_cnt--; } found = removeSizeFromList(gCamCapability[mCameraId]->video_sizes_tbl, gCamCapability[mCameraId]->video_sizes_tbl_cnt, true_size_4k_2k); if (found) { gCamCapability[mCameraId]->video_sizes_tbl_cnt--; } found = removeSizeFromList(gCamCapability[mCameraId]->video_sizes_tbl, gCamCapability[mCameraId]->video_sizes_tbl_cnt, size_4k_2k); if (found) { gCamCapability[mCameraId]->video_sizes_tbl_cnt--; } } int32_t rc = m_postprocessor.init(jpegEvtHandle, this); if (rc != 0) { ALOGE("Init Postprocessor failed"); mCameraHandle->ops->close_camera(mCameraHandle->camera_handle); mCameraHandle = NULL; return UNKNOWN_ERROR; } // update padding info from jpeg cam_padding_info_t padding_info; m_postprocessor.getJpegPaddingReq(padding_info); if (gCamCapability[mCameraId]->padding_info.width_padding < padding_info.width_padding) { gCamCapability[mCameraId]->padding_info.width_padding = padding_info.width_padding; } if (gCamCapability[mCameraId]->padding_info.height_padding < padding_info.height_padding) { gCamCapability[mCameraId]->padding_info.height_padding = padding_info.height_padding; } if (gCamCapability[mCameraId]->padding_info.plane_padding < padding_info.plane_padding) { gCamCapability[mCameraId]->padding_info.plane_padding = padding_info.plane_padding; } mParameters.init(gCamCapability[mCameraId], mCameraHandle, this, this); mCameraOpened = true; return NO_ERROR; } /*=========================================================================== * FUNCTION : closeCamera * * DESCRIPTION: close camera * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::closeCamera() { int rc = NO_ERROR; int i; CDBG_HIGH("%s: E", __func__); if (!mCameraOpened) { return NO_ERROR; } pthread_mutex_lock(&m_parm_lock); // set open flag to false mCameraOpened = false; // deinit Parameters mParameters.deinit(); pthread_mutex_unlock(&m_parm_lock); // exit notifier m_cbNotifier.exit(); // stop and deinit postprocessor m_postprocessor.stop(); m_postprocessor.deinit(); //free all pending api results here if(m_apiResultList != NULL) { api_result_list *apiResultList = m_apiResultList; api_result_list *apiResultListNext; while (apiResultList != NULL) { apiResultListNext = apiResultList->next; free(apiResultList); apiResultList = apiResultListNext; } } m_thermalAdapter.deinit(); // delete all channels if not already deleted for (i = 0; i < QCAMERA_CH_TYPE_MAX; i++) { if (m_channels[i] != NULL) { m_channels[i]->stop(); delete m_channels[i]; m_channels[i] = NULL; } } rc = mCameraHandle->ops->close_camera(mCameraHandle->camera_handle); mCameraHandle = NULL; CDBG_HIGH("%s: X", __func__); return rc; } #define DATA_PTR(MEM_OBJ,INDEX) MEM_OBJ->getPtr( INDEX ) /*=========================================================================== * FUNCTION : initCapabilities * * DESCRIPTION: initialize camera capabilities in static data struct * * PARAMETERS : * @cameraId : camera Id * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::initCapabilities(int cameraId,mm_camera_vtbl_t *cameraHandle) { int rc = NO_ERROR; QCameraHeapMemory *capabilityHeap = NULL; /* Allocate memory for capability buffer */ capabilityHeap = new QCameraHeapMemory(QCAMERA_ION_USE_CACHE); rc = capabilityHeap->allocate(1, sizeof(cam_capability_t)); if(rc != OK) { ALOGE("%s: No memory for cappability", __func__); goto allocate_failed; } /* Map memory for capability buffer */ memset(DATA_PTR(capabilityHeap,0), 0, sizeof(cam_capability_t)); rc = cameraHandle->ops->map_buf(cameraHandle->camera_handle, CAM_MAPPING_BUF_TYPE_CAPABILITY, capabilityHeap->getFd(0), sizeof(cam_capability_t)); if(rc < 0) { ALOGE("%s: failed to map capability buffer", __func__); goto map_failed; } /* Query Capability */ rc = cameraHandle->ops->query_capability(cameraHandle->camera_handle); if(rc < 0) { ALOGE("%s: failed to query capability",__func__); goto query_failed; } gCamCapability[cameraId] = (cam_capability_t *)malloc(sizeof(cam_capability_t)); if (!gCamCapability[cameraId]) { ALOGE("%s: out of memory", __func__); goto query_failed; } memcpy(gCamCapability[cameraId], DATA_PTR(capabilityHeap,0), sizeof(cam_capability_t)); //copy the preview sizes and video sizes lists because they //might be changed later copyList(gCamCapability[cameraId]->preview_sizes_tbl, savedSizes[cameraId].all_preview_sizes, gCamCapability[cameraId]->preview_sizes_tbl_cnt); savedSizes[cameraId].all_preview_sizes_cnt = gCamCapability[cameraId]->preview_sizes_tbl_cnt; copyList(gCamCapability[cameraId]->video_sizes_tbl, savedSizes[cameraId].all_video_sizes, gCamCapability[cameraId]->video_sizes_tbl_cnt); savedSizes[cameraId].all_video_sizes_cnt = gCamCapability[cameraId]->video_sizes_tbl_cnt; rc = NO_ERROR; query_failed: cameraHandle->ops->unmap_buf(cameraHandle->camera_handle, CAM_MAPPING_BUF_TYPE_CAPABILITY); map_failed: capabilityHeap->deallocate(); delete capabilityHeap; allocate_failed: return rc; } /*=========================================================================== * FUNCTION : getCapabilities * * DESCRIPTION: query camera capabilities * * PARAMETERS : * @cameraId : camera Id * @info : camera info struct to be filled in with camera capabilities * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::getCapabilities(int cameraId, struct camera_info *info) { int rc = NO_ERROR; struct camera_info *p_info; pthread_mutex_lock(&g_camlock); p_info = get_cam_info(cameraId); memcpy(info, p_info, sizeof (struct camera_info)); pthread_mutex_unlock(&g_camlock); return rc; } /*=========================================================================== * FUNCTION : prepareTorchCamera * * DESCRIPTION: initializes the camera ( if needed ) * so torch can be configured. * * PARAMETERS : * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::prepareTorchCamera() { int rc = NO_ERROR; if ( ( !m_stateMachine.isPreviewRunning() ) && ( m_channels[QCAMERA_CH_TYPE_PREVIEW] == NULL ) ) { rc = addChannel(QCAMERA_CH_TYPE_PREVIEW); } return rc; } /*=========================================================================== * FUNCTION : releaseTorchCamera * * DESCRIPTION: releases all previously acquired camera resources ( if any ) * needed for torch configuration. * * PARAMETERS : * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::releaseTorchCamera() { if ( !m_stateMachine.isPreviewRunning() && ( m_channels[QCAMERA_CH_TYPE_PREVIEW] != NULL ) ) { delete m_channels[QCAMERA_CH_TYPE_PREVIEW]; m_channels[QCAMERA_CH_TYPE_PREVIEW] = NULL; } return NO_ERROR; } /*=========================================================================== * FUNCTION : getBufNumRequired * * DESCRIPTION: return number of stream buffers needed for given stream type * * PARAMETERS : * @stream_type : type of stream * * RETURN : number of buffers needed *==========================================================================*/ uint8_t QCamera2HardwareInterface::getBufNumRequired(cam_stream_type_t stream_type) { int bufferCnt = 0; int minCaptureBuffers = mParameters.getNumOfSnapshots(); int zslQBuffers = mParameters.getZSLQueueDepth(); int minCircularBufNum = mParameters.getMaxUnmatchedFramesInQueue() + CAMERA_MIN_JPEG_ENCODING_BUFFERS; int minUndequeCount = 0; int minPPBufs = mParameters.getMinPPBufs(); int maxStreamBuf = zslQBuffers + minCircularBufNum + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + mParameters.getNumOfExtraBuffersForImageProc() + EXTRA_ZSL_PREVIEW_STREAM_BUF; if (!isNoDisplayMode()) { if(mPreviewWindow != NULL) { if (mPreviewWindow->get_min_undequeued_buffer_count(mPreviewWindow,&minUndequeCount) != 0) { ALOGE("get_min_undequeued_buffer_count failed"); } } else { //preview window might not be set at this point. So, query directly //from BufferQueue implementation of gralloc buffers. minUndequeCount = BufferQueue::MIN_UNDEQUEUED_BUFFERS; } } // Get buffer count for the particular stream type switch (stream_type) { case CAM_STREAM_TYPE_PREVIEW: { if (mParameters.isZSLMode()) { /* We need to add two extra streming buffers to add flexibility in forming matched super buf in ZSL queue. with number being 'zslQBuffers + minCircularBufNum' we see preview buffers sometimes get dropped at CPP and super buf is not forming in ZSL Q for long time. */ bufferCnt = zslQBuffers + minCircularBufNum + mParameters.getNumOfExtraBuffersForImageProc() + EXTRA_ZSL_PREVIEW_STREAM_BUF; } else { bufferCnt = CAMERA_MIN_STREAMING_BUFFERS + mParameters.getMaxUnmatchedFramesInQueue(); } bufferCnt += minUndequeCount; } break; case CAM_STREAM_TYPE_POSTVIEW: { bufferCnt = minCaptureBuffers + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + minPPBufs + mParameters.getNumOfExtraBuffersForImageProc(); if (bufferCnt > maxStreamBuf) { bufferCnt = maxStreamBuf; } bufferCnt += minUndequeCount; /* TODO: This is Temporary change to overcome the two BufDone/Buf Diverts coming consecutively without SOF in HDR/AE bracketing use case */ if (mParameters.isHDREnabled() || mParameters.isAEBracketEnabled() ) bufferCnt += 2; } break; case CAM_STREAM_TYPE_SNAPSHOT: { if (mParameters.isZSLMode() || mLongshotEnabled) { if (minCaptureBuffers == 1 && !mLongshotEnabled) { // Single ZSL snapshot case bufferCnt = zslQBuffers + CAMERA_MIN_STREAMING_BUFFERS + mParameters.getNumOfExtraBuffersForImageProc(); } else { // ZSL Burst or Longshot case bufferCnt = zslQBuffers + minCircularBufNum + mParameters.getNumOfExtraBuffersForImageProc(); } } else { bufferCnt = minCaptureBuffers + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + minPPBufs + mParameters.getNumOfExtraBuffersForImageProc(); if (bufferCnt > maxStreamBuf) { bufferCnt = maxStreamBuf; } } } break; case CAM_STREAM_TYPE_RAW: if (mParameters.isZSLMode()) { bufferCnt = zslQBuffers + minCircularBufNum; } else { bufferCnt = minCaptureBuffers + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + minPPBufs + mParameters.getNumOfExtraBuffersForImageProc(); if (bufferCnt > maxStreamBuf) { bufferCnt = maxStreamBuf; } } break; case CAM_STREAM_TYPE_VIDEO: { bufferCnt = CAMERA_MIN_VIDEO_BUFFERS; } break; case CAM_STREAM_TYPE_METADATA: { if (mParameters.isZSLMode()) { // MetaData buffers should be >= (Preview buffers-minUndequeCount) bufferCnt = zslQBuffers + minCircularBufNum + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + mParameters.getNumOfExtraBuffersForImageProc() + EXTRA_ZSL_PREVIEW_STREAM_BUF; } else { bufferCnt = minCaptureBuffers + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + mParameters.getMaxUnmatchedFramesInQueue() + CAMERA_MIN_STREAMING_BUFFERS + mParameters.getNumOfExtraBuffersForImageProc(); } if (bufferCnt > maxStreamBuf) { bufferCnt = maxStreamBuf; } bufferCnt += minUndequeCount; } break; case CAM_STREAM_TYPE_OFFLINE_PROC: { bufferCnt = minCaptureBuffers; if (mLongshotEnabled) { bufferCnt = CAMERA_LONGSHOT_STAGES; } if (bufferCnt > maxStreamBuf) { bufferCnt = maxStreamBuf; } } break; case CAM_STREAM_TYPE_DEFAULT: case CAM_STREAM_TYPE_MAX: default: bufferCnt = 0; break; } ALOGD("%s: Allocating %d buffers for streamtype %d",__func__,bufferCnt,stream_type); return bufferCnt; } /*=========================================================================== * FUNCTION : allocateStreamBuf * * DESCRIPTION: alocate stream buffers * * PARAMETERS : * @stream_type : type of stream * @size : size of buffer * @stride : stride of buffer * @scanline : scanline of buffer * @bufferCnt : [IN/OUT] minimum num of buffers to be allocated. * could be modified during allocation if more buffers needed * * RETURN : ptr to a memory obj that holds stream buffers. * NULL if failed *==========================================================================*/ QCameraMemory *QCamera2HardwareInterface::allocateStreamBuf(cam_stream_type_t stream_type, int size, int stride, int scanline, uint8_t &bufferCnt) { int rc = NO_ERROR; QCameraMemory *mem = NULL; bool bCachedMem = QCAMERA_ION_USE_CACHE; bool bPoolMem = false; char value[PROPERTY_VALUE_MAX]; property_get("persist.camera.mem.usepool", value, "1"); if (atoi(value) == 1) { bPoolMem = true; } // Allocate stream buffer memory object switch (stream_type) { case CAM_STREAM_TYPE_PREVIEW: { if (isNoDisplayMode()) { mem = new QCameraStreamMemory(mGetMemory, bCachedMem, (bPoolMem) ? &m_memoryPool : NULL, stream_type); } else { cam_dimension_t dim; QCameraGrallocMemory *grallocMemory = new QCameraGrallocMemory(mGetMemory); mParameters.getStreamDimension(stream_type, dim); if (grallocMemory) grallocMemory->setWindowInfo(mPreviewWindow, dim.width, dim.height, stride, scanline, mParameters.getPreviewHalPixelFormat()); mem = grallocMemory; } } break; case CAM_STREAM_TYPE_POSTVIEW: { if (isPreviewRestartEnabled() || isNoDisplayMode()) { mem = new QCameraStreamMemory(mGetMemory, bCachedMem); } else { cam_dimension_t dim; QCameraGrallocMemory *grallocMemory = new QCameraGrallocMemory(mGetMemory); mParameters.getStreamDimension(stream_type, dim); if (grallocMemory) { grallocMemory->setWindowInfo(mPreviewWindow, dim.width, dim.height, stride, scanline, mParameters.getPreviewHalPixelFormat()); } mem = grallocMemory; } } break; case CAM_STREAM_TYPE_SNAPSHOT: case CAM_STREAM_TYPE_RAW: case CAM_STREAM_TYPE_METADATA: case CAM_STREAM_TYPE_OFFLINE_PROC: mem = new QCameraStreamMemory(mGetMemory, bCachedMem, (bPoolMem) ? &m_memoryPool : NULL, stream_type); break; case CAM_STREAM_TYPE_VIDEO: { char value[PROPERTY_VALUE_MAX]; property_get("persist.camera.mem.usecache", value, "1"); if (atoi(value) == 0) { bCachedMem = QCAMERA_ION_USE_NOCACHE; } ALOGD("%s: vidoe buf using cached memory = %d", __func__, bCachedMem); mem = new QCameraVideoMemory(mGetMemory, bCachedMem); } break; case CAM_STREAM_TYPE_DEFAULT: case CAM_STREAM_TYPE_MAX: default: break; } if (!mem) { return NULL; } if (bufferCnt > 0) { rc = mem->allocate(bufferCnt, size); if (rc < 0) { delete mem; return NULL; } bufferCnt = mem->getCnt(); } return mem; } /*=========================================================================== * FUNCTION : allocateMoreStreamBuf * * DESCRIPTION: alocate more stream buffers from the memory object * * PARAMETERS : * @mem_obj : memory object ptr * @size : size of buffer * @bufferCnt : [IN/OUT] additional number of buffers to be allocated. * output will be the number of total buffers * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::allocateMoreStreamBuf(QCameraMemory *mem_obj, int size, uint8_t &bufferCnt) { int rc = NO_ERROR; if (bufferCnt > 0) { rc = mem_obj->allocateMore(bufferCnt, size); bufferCnt = mem_obj->getCnt(); } return rc; } /*=========================================================================== * FUNCTION : allocateStreamInfoBuf * * DESCRIPTION: alocate stream info buffer * * PARAMETERS : * @stream_type : type of stream * * RETURN : ptr to a memory obj that holds stream info buffer. * NULL if failed *==========================================================================*/ QCameraHeapMemory *QCamera2HardwareInterface::allocateStreamInfoBuf( cam_stream_type_t stream_type) { int rc = NO_ERROR; QCameraHeapMemory *streamInfoBuf = new QCameraHeapMemory(QCAMERA_ION_USE_CACHE); if (!streamInfoBuf) { ALOGE("allocateStreamInfoBuf: Unable to allocate streamInfo object"); return NULL; } rc = streamInfoBuf->allocate(1, sizeof(cam_stream_info_t)); if (rc < 0) { ALOGE("allocateStreamInfoBuf: Failed to allocate stream info memory"); delete streamInfoBuf; return NULL; } cam_stream_info_t *streamInfo = (cam_stream_info_t *)streamInfoBuf->getPtr(0); memset(streamInfo, 0, sizeof(cam_stream_info_t)); streamInfo->stream_type = stream_type; rc = mParameters.getStreamFormat(stream_type, streamInfo->fmt); rc = mParameters.getStreamDimension(stream_type, streamInfo->dim); rc = mParameters.getStreamRotation(stream_type, streamInfo->pp_config, streamInfo->dim); streamInfo->num_bufs = getBufNumRequired(stream_type); streamInfo->streaming_mode = CAM_STREAMING_MODE_CONTINUOUS; ALOGD("%s: stream_type %d, stream format %d,stream dimension %dx%d, num_bufs %d\n", __func__, stream_type, streamInfo->fmt, streamInfo->dim.width, streamInfo->dim.height, streamInfo->num_bufs); switch (stream_type) { case CAM_STREAM_TYPE_SNAPSHOT: case CAM_STREAM_TYPE_RAW: if ((mParameters.isZSLMode() && mParameters.getRecordingHintValue() != true) || mLongshotEnabled) { streamInfo->streaming_mode = CAM_STREAMING_MODE_CONTINUOUS; } else { streamInfo->streaming_mode = CAM_STREAMING_MODE_BURST; streamInfo->num_of_burst = mParameters.getNumOfSnapshots() + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + mParameters.getNumOfExtraBuffersForImageProc(); } break; case CAM_STREAM_TYPE_POSTVIEW: if (mLongshotEnabled) { streamInfo->streaming_mode = CAM_STREAMING_MODE_CONTINUOUS; } else { streamInfo->streaming_mode = CAM_STREAMING_MODE_BURST; streamInfo->num_of_burst = mParameters.getNumOfSnapshots() + mParameters.getNumOfExtraHDRInBufsIfNeeded() - mParameters.getNumOfExtraHDROutBufsIfNeeded() + mParameters.getNumOfExtraBuffersForImageProc(); } break; case CAM_STREAM_TYPE_VIDEO: streamInfo->useAVTimer = mParameters.isAVTimerEnabled(); case CAM_STREAM_TYPE_PREVIEW: if (mParameters.getRecordingHintValue()) { const char* dis_param = mParameters.get(QCameraParameters::KEY_QC_DIS); bool disEnabled = (dis_param != NULL) && !strcmp(dis_param,QCameraParameters::VALUE_ENABLE); if(disEnabled) { char value[PROPERTY_VALUE_MAX]; property_get("persist.camera.is_type", value, "0"); streamInfo->is_type = static_cast<cam_is_type_t>(atoi(value)); } else { streamInfo->is_type = IS_TYPE_NONE; } } break; default: break; } if ((!isZSLMode() || (isZSLMode() && (stream_type != CAM_STREAM_TYPE_SNAPSHOT))) && !mParameters.isHDREnabled()) { //set flip mode based on Stream type; int flipMode = mParameters.getFlipMode(stream_type); if (flipMode > 0) { streamInfo->pp_config.feature_mask |= CAM_QCOM_FEATURE_FLIP; streamInfo->pp_config.flip = flipMode; } } return streamInfoBuf; } /*=========================================================================== * FUNCTION : setPreviewWindow * * DESCRIPTION: set preview window impl * * PARAMETERS : * @window : ptr to window ops table struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::setPreviewWindow( struct preview_stream_ops *window) { mPreviewWindow = window; return NO_ERROR; } /*=========================================================================== * FUNCTION : setCallBacks * * DESCRIPTION: set callbacks impl * * PARAMETERS : * @notify_cb : notify cb * @data_cb : data cb * @data_cb_timestamp : data cb with time stamp * @get_memory : request memory ops table * @user : user data ptr * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::setCallBacks(camera_notify_callback notify_cb, camera_data_callback data_cb, camera_data_timestamp_callback data_cb_timestamp, camera_request_memory get_memory, void *user) { mNotifyCb = notify_cb; mDataCb = data_cb; mDataCbTimestamp = data_cb_timestamp; mGetMemory = get_memory; mCallbackCookie = user; m_cbNotifier.setCallbacks(notify_cb, data_cb, data_cb_timestamp, user); return NO_ERROR; } /*=========================================================================== * FUNCTION : enableMsgType * * DESCRIPTION: enable msg type impl * * PARAMETERS : * @msg_type : msg type mask to be enabled * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::enableMsgType(int32_t msg_type) { mMsgEnabled |= msg_type; CDBG_HIGH("%s (0x%x) : mMsgEnabled = 0x%x", __func__, msg_type , mMsgEnabled ); return NO_ERROR; } /*=========================================================================== * FUNCTION : disableMsgType * * DESCRIPTION: disable msg type impl * * PARAMETERS : * @msg_type : msg type mask to be disabled * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::disableMsgType(int32_t msg_type) { mMsgEnabled &= ~msg_type; CDBG_HIGH("%s (0x%x) : mMsgEnabled = 0x%x", __func__, msg_type , mMsgEnabled ); return NO_ERROR; } /*=========================================================================== * FUNCTION : msgTypeEnabled * * DESCRIPTION: impl to determine if certain msg_type is enabled * * PARAMETERS : * @msg_type : msg type mask * * RETURN : 0 -- not enabled * none 0 -- enabled *==========================================================================*/ int QCamera2HardwareInterface::msgTypeEnabled(int32_t msg_type) { return (mMsgEnabled & msg_type); } /*=========================================================================== * FUNCTION : msgTypeEnabledWithLock * * DESCRIPTION: impl to determine if certain msg_type is enabled with lock * * PARAMETERS : * @msg_type : msg type mask * * RETURN : 0 -- not enabled * none 0 -- enabled *==========================================================================*/ int QCamera2HardwareInterface::msgTypeEnabledWithLock(int32_t msg_type) { int enabled = 0; lockAPI(); enabled = mMsgEnabled & msg_type; unlockAPI(); return enabled; } /*=========================================================================== * FUNCTION : startPreview * * DESCRIPTION: start preview impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::startPreview() { int32_t rc = NO_ERROR; CDBG_HIGH("%s: E", __func__); // start preview stream if (mParameters.isZSLMode() && mParameters.getRecordingHintValue() !=true) { rc = startChannel(QCAMERA_CH_TYPE_ZSL); } else { rc = startChannel(QCAMERA_CH_TYPE_PREVIEW); /* CAF needs cancel auto focus to resume after snapshot. Focus should be locked till take picture is done. In Non-zsl case if focus mode is CAF then calling cancel auto focus to resume CAF. */ cam_focus_mode_type focusMode = mParameters.getFocusMode(); if (focusMode == CAM_FOCUS_MODE_CONTINOUS_PICTURE) mCameraHandle->ops->cancel_auto_focus(mCameraHandle->camera_handle); } CDBG_HIGH("%s: X", __func__); //#ifdef ARCSOFT_FB_SUPPORT // beautyshot.Init(); //flf.Init(); //#endif return rc; } /*=========================================================================== * FUNCTION : stopPreview * * DESCRIPTION: stop preview impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::stopPreview() { CDBG_HIGH("%s: E", __func__); // stop preview stream stopChannel(QCAMERA_CH_TYPE_ZSL); stopChannel(QCAMERA_CH_TYPE_PREVIEW); //reset preview frame skip mPreviewFrameSkipValid = 0; memset(&mPreviewFrameSkipIdxRange, 0, sizeof(cam_frame_idx_range_t)); // delete all channels from preparePreview unpreparePreview(); CDBG_HIGH("%s: X", __func__); //#ifdef ARCSOFT_FB_SUPPORT // beautyshot.Uninit(); //flf.Uninit(); //#endif return NO_ERROR; } /*=========================================================================== * FUNCTION : storeMetaDataInBuffers * * DESCRIPTION: enable store meta data in buffers for video frames impl * * PARAMETERS : * @enable : flag if need enable * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::storeMetaDataInBuffers(int enable) { mStoreMetaDataInFrame = enable; return NO_ERROR; } /*=========================================================================== * FUNCTION : startRecording * * DESCRIPTION: start recording impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::startRecording() { int32_t rc = NO_ERROR; CDBG_HIGH("%s: E", __func__); if (mParameters.getRecordingHintValue() == false) { CDBG_HIGH("%s: start recording when hint is false, stop preview first", __func__); stopPreview(); // Set recording hint to TRUE mParameters.updateRecordingHintValue(TRUE); rc = preparePreview(); if (rc == NO_ERROR) { rc = startChannel(QCAMERA_CH_TYPE_PREVIEW); } } if (rc == NO_ERROR) { rc = startChannel(QCAMERA_CH_TYPE_VIDEO); } #ifdef HAS_MULTIMEDIA_HINTS if (rc == NO_ERROR) { if (m_pPowerModule) { if (m_pPowerModule->powerHint) { m_pPowerModule->powerHint(m_pPowerModule, POWER_HINT_VIDEO_ENCODE, (void *)"state=1"); } } } #endif CDBG_HIGH("%s: X", __func__); return rc; } /*=========================================================================== * FUNCTION : stopRecording * * DESCRIPTION: stop recording impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::stopRecording() { CDBG_HIGH("%s: E", __func__); int rc = stopChannel(QCAMERA_CH_TYPE_VIDEO); #ifdef HAS_MULTIMEDIA_HINTS if (m_pPowerModule) { if (m_pPowerModule->powerHint) { m_pPowerModule->powerHint(m_pPowerModule, POWER_HINT_VIDEO_ENCODE, (void *)"state=0"); } } #endif CDBG_HIGH("%s: X", __func__); return rc; } /*=========================================================================== * FUNCTION : releaseRecordingFrame * * DESCRIPTION: return video frame impl * * PARAMETERS : * @opaque : ptr to video frame to be returned * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::releaseRecordingFrame(const void * opaque) { int32_t rc = UNKNOWN_ERROR; QCameraVideoChannel *pChannel = (QCameraVideoChannel *)m_channels[QCAMERA_CH_TYPE_VIDEO]; CDBG_HIGH("%s: opaque data = %p", __func__,opaque); if(pChannel != NULL) { rc = pChannel->releaseFrame(opaque, mStoreMetaDataInFrame > 0); } return rc; } /*=========================================================================== * FUNCTION : autoFocus * * DESCRIPTION: start auto focus impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::autoFocus() { int rc = NO_ERROR; setCancelAutoFocus(false); cam_focus_mode_type focusMode = mParameters.getFocusMode(); CDBG_HIGH("[AF_DBG] %s: focusMode=%d, m_currentFocusState=%d, m_bAFRunning=%d", __func__, focusMode, m_currentFocusState, isAFRunning()); switch (focusMode) { case CAM_FOCUS_MODE_AUTO: case CAM_FOCUS_MODE_MACRO: case CAM_FOCUS_MODE_CONTINOUS_VIDEO: case CAM_FOCUS_MODE_CONTINOUS_PICTURE: rc = mCameraHandle->ops->do_auto_focus(mCameraHandle->camera_handle); break; case CAM_FOCUS_MODE_INFINITY: case CAM_FOCUS_MODE_FIXED: case CAM_FOCUS_MODE_EDOF: default: ALOGE("%s: No ops in focusMode (%d)", __func__, focusMode); rc = sendEvtNotify(CAMERA_MSG_FOCUS, true, 0); break; } return rc; } /*=========================================================================== * FUNCTION : cancelAutoFocus * * DESCRIPTION: cancel auto focus impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::cancelAutoFocus() { int rc = NO_ERROR; setCancelAutoFocus(true); cam_focus_mode_type focusMode = mParameters.getFocusMode(); switch (focusMode) { case CAM_FOCUS_MODE_AUTO: case CAM_FOCUS_MODE_MACRO: case CAM_FOCUS_MODE_CONTINOUS_VIDEO: case CAM_FOCUS_MODE_CONTINOUS_PICTURE: rc = mCameraHandle->ops->cancel_auto_focus(mCameraHandle->camera_handle); break; case CAM_FOCUS_MODE_INFINITY: case CAM_FOCUS_MODE_FIXED: case CAM_FOCUS_MODE_EDOF: default: CDBG("%s: No ops in focusMode (%d)", __func__, focusMode); break; } return rc; } /*=========================================================================== * FUNCTION : processUFDumps * * DESCRIPTION: process UF jpeg dumps for refocus support * * PARAMETERS : * @evt : payload of jpeg event, including information about jpeg encoding * status, jpeg size and so on. * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code * * NOTE : none *==========================================================================*/ bool QCamera2HardwareInterface::processUFDumps(qcamera_jpeg_evt_payload_t *evt) { bool ret = true; if (mParameters.isUbiRefocus()) { int index = getOutputImageCount(); bool allFocusImage = (index == ((int)mParameters.UfOutputCount()-1)); char name[CAM_FN_CNT]; camera_memory_t *jpeg_mem = NULL; omx_jpeg_ouput_buf_t *jpeg_out = NULL; uint32_t dataLen; uint8_t *dataPtr; if (!m_postprocessor.getJpegMemOpt()) { dataLen = evt->out_data.buf_filled_len; dataPtr = evt->out_data.buf_vaddr; } else { jpeg_out = (omx_jpeg_ouput_buf_t*) evt->out_data.buf_vaddr; jpeg_mem = (camera_memory_t *)jpeg_out->mem_hdl; dataPtr = (uint8_t *)jpeg_mem->data; dataLen = jpeg_mem->size; } if (allFocusImage) { strncpy(name, "AllFocusImage", CAM_FN_CNT - 1); index = -1; } else { strncpy(name, "0", CAM_FN_CNT - 1); } CAM_DUMP_TO_FILE("/data/local/ubifocus", name, index, "jpg", dataPtr, dataLen); CDBG_HIGH("%s:%d] Dump the image %d %d allFocusImage %d", __func__, __LINE__, getOutputImageCount(), index, allFocusImage); setOutputImageCount(getOutputImageCount() + 1); if (!allFocusImage) { ret = false; } } return ret; } /*=========================================================================== * FUNCTION : configureAdvancedCapture * * DESCRIPTION: configure Advanced Capture. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureAdvancedCapture() { CDBG_HIGH("%s: E",__func__); int32_t rc = NO_ERROR; setOutputImageCount(0); mParameters.setDisplayFrame(FALSE); if (mParameters.isUbiFocusEnabled()) { rc = configureAFBracketing(); } else if (mParameters.isOptiZoomEnabled()) { rc = configureOptiZoom(); } else if (mParameters.isChromaFlashEnabled()) { rc = configureFlashBracketing(); } else if (mParameters.isHDREnabled()) { rc = configureZSLHDRBracketing(); } else if (mParameters.isAEBracketEnabled()) { rc = configureAEBracketing(); } else { ALOGE("%s: No Advanced Capture feature enabled!! ", __func__); rc = BAD_VALUE; } CDBG_HIGH("%s: X",__func__); return rc; } /*=========================================================================== * FUNCTION : configureAFBracketing * * DESCRIPTION: configure AF Bracketing. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureAFBracketing(bool enable) { CDBG_HIGH("%s: E",__func__); int32_t rc = NO_ERROR; cam_af_bracketing_t *af_bracketing_need; af_bracketing_need = &gCamCapability[mCameraId]->ubifocus_af_bracketing_need; //Enable AF Bracketing. cam_af_bracketing_t afBracket; memset(&afBracket, 0, sizeof(cam_af_bracketing_t)); afBracket.enable = enable; afBracket.burst_count = af_bracketing_need->burst_count; for(int8_t i = 0; i < MAX_AF_BRACKETING_VALUES; i++) { afBracket.focus_steps[i] = af_bracketing_need->focus_steps[i]; CDBG_HIGH("%s: focus_step[%d] = %d", __func__, i, afBracket.focus_steps[i]); } //Send cmd to backend to set AF Bracketing for Ubi Focus. rc = mParameters.commitAFBracket(afBracket); if ( NO_ERROR != rc ) { ALOGE("%s: cannot configure AF bracketing", __func__); return rc; } if (enable) { mParameters.set3ALock(QCameraParameters::VALUE_TRUE); mIs3ALocked = true; } CDBG_HIGH("%s: X",__func__); return rc; } /*=========================================================================== * FUNCTION : configureFlashBracketing * * DESCRIPTION: configure Flash Bracketing. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureFlashBracketing() { CDBG_HIGH("%s: E",__func__); int32_t rc = NO_ERROR; cam_flash_bracketing_t flashBracket; memset(&flashBracket, 0, sizeof(cam_flash_bracketing_t)); flashBracket.enable = 1; //TODO: Hardcoded value. flashBracket.burst_count = 2; //Send cmd to backend to set Flash Bracketing for chroma flash. rc = mParameters.commitFlashBracket(flashBracket); if ( NO_ERROR != rc ) { ALOGE("%s: cannot configure AF bracketing", __func__); } CDBG_HIGH("%s: X",__func__); return rc; } /*=========================================================================== * FUNCTION : configureZSLHDRBracketing * * DESCRIPTION: configure HDR Bracketing. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureZSLHDRBracketing() { CDBG_HIGH("%s: E",__func__); int32_t rc = NO_ERROR; // 'values' should be in "idx1,idx2,idx3,..." format uint8_t hdrFrameCount = gCamCapability[mCameraId]->hdr_bracketing_setting.num_frames; CDBG_HIGH("%s : HDR values %d, %d frame count: %d", __func__, (int8_t) gCamCapability[mCameraId]->hdr_bracketing_setting.exp_val.values[0], (int8_t) gCamCapability[mCameraId]->hdr_bracketing_setting.exp_val.values[1], hdrFrameCount); // Enable AE Bracketing for HDR cam_exp_bracketing_t aeBracket; memset(&aeBracket, 0, sizeof(cam_exp_bracketing_t)); aeBracket.mode = gCamCapability[mCameraId]->hdr_bracketing_setting.exp_val.mode; String8 tmp; for ( unsigned int i = 0; i < hdrFrameCount ; i++ ) { tmp.appendFormat("%d", (int8_t) gCamCapability[mCameraId]->hdr_bracketing_setting.exp_val.values[i]); tmp.append(","); } if (mParameters.isHDR1xFrameEnabled() && mParameters.isHDR1xExtraBufferNeeded()) { tmp.appendFormat("%d", 0); tmp.append(","); } if( !tmp.isEmpty() && ( MAX_EXP_BRACKETING_LENGTH > tmp.length() ) ) { //Trim last comma memset(aeBracket.values, '\0', MAX_EXP_BRACKETING_LENGTH); memcpy(aeBracket.values, tmp.string(), tmp.length() - 1); } CDBG_HIGH("%s : HDR config values %s", __func__, aeBracket.values); rc = mParameters.setHDRAEBracket(aeBracket); if ( NO_ERROR != rc ) { ALOGE("%s: cannot configure HDR bracketing", __func__); return rc; } CDBG_HIGH("%s: X",__func__); return rc; } /*=========================================================================== * FUNCTION : configureAEBracketing * * DESCRIPTION: configure AE Bracketing. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureAEBracketing() { CDBG_HIGH("%s: E",__func__); int32_t rc = NO_ERROR; rc = mParameters.setAEBracketing(); if ( NO_ERROR != rc ) { ALOGE("%s: cannot configure AE bracketing", __func__); return rc; } CDBG_HIGH("%s: X",__func__); return rc; } /*=========================================================================== * FUNCTION : configureOptiZoom * * DESCRIPTION: configure Opti Zoom. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::configureOptiZoom() { int32_t rc = NO_ERROR; //store current zoom level. mZoomLevel = (uint8_t) mParameters.getInt(CameraParameters::KEY_ZOOM); //set zoom level to 1x; mParameters.setAndCommitZoom(0); mParameters.set3ALock(QCameraParameters::VALUE_TRUE); mIs3ALocked = true; return rc; } /*=========================================================================== * FUNCTION : startAdvancedCapture * * DESCRIPTION: starts advanced capture based on capture type * * PARAMETERS : * @pChannel : channel. * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::startAdvancedCapture( QCameraPicChannel *pChannel) { CDBG_HIGH("%s: Start bracketig",__func__); int32_t rc = NO_ERROR; if(mParameters.isUbiFocusEnabled()) { rc = pChannel->startAdvancedCapture(MM_CAMERA_AF_BRACKETING); } else if (mParameters.isChromaFlashEnabled()) { rc = pChannel->startAdvancedCapture(MM_CAMERA_FLASH_BRACKETING); } else if (mParameters.isHDREnabled() || mParameters.isAEBracketEnabled()) { rc = pChannel->startAdvancedCapture(MM_CAMERA_AE_BRACKETING); } else if (mParameters.isOptiZoomEnabled()) { rc = pChannel->startAdvancedCapture(MM_CAMERA_ZOOM_1X); } else { ALOGE("%s: No Advanced Capture feature enabled!",__func__); rc = BAD_VALUE; } return rc; } /*=========================================================================== * FUNCTION : takePicture * * DESCRIPTION: take picture impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::takePicture() { int rc = NO_ERROR; uint8_t numSnapshots = mParameters.getNumOfSnapshots(); #ifdef ARCSOFT_FB_SUPPORT if(mArcsoftEnabled)flawlessface.Init(); #endif if (mParameters.isUbiFocusEnabled() || mParameters.isOptiZoomEnabled() || mParameters.isHDREnabled() || mParameters.isChromaFlashEnabled() || mParameters.isAEBracketEnabled()) { rc = configureAdvancedCapture(); if (rc == NO_ERROR) { numSnapshots = mParameters.getBurstCountForAdvancedCapture(); } } CDBG_HIGH("%s: numSnapshot = %d",__func__, numSnapshots); getOrientation(); CDBG_HIGH("%s: E", __func__); if (mParameters.isZSLMode()) { QCameraPicChannel *pZSLChannel = (QCameraPicChannel *)m_channels[QCAMERA_CH_TYPE_ZSL]; if (NULL != pZSLChannel) { // start postprocessor rc = m_postprocessor.start(pZSLChannel); if (rc != NO_ERROR) { ALOGE("%s: cannot start postprocessor", __func__); return rc; } if (mParameters.isUbiFocusEnabled() || mParameters.isOptiZoomEnabled() || mParameters.isHDREnabled() || mParameters.isChromaFlashEnabled() || mParameters.isAEBracketEnabled()) { rc = startAdvancedCapture(pZSLChannel); if (rc != NO_ERROR) { ALOGE("%s: cannot start zsl advanced capture", __func__); return rc; } } if (mLongshotEnabled && mPrepSnapRun) { mCameraHandle->ops->start_zsl_snapshot( mCameraHandle->camera_handle, pZSLChannel->getMyHandle()); } rc = pZSLChannel->takePicture(numSnapshots); if (rc != NO_ERROR) { ALOGE("%s: cannot take ZSL picture", __func__); m_postprocessor.stop(); return rc; } } else { ALOGE("%s: ZSL channel is NULL", __func__); return UNKNOWN_ERROR; } } else { // start snapshot if (mParameters.isJpegPictureFormat() || mParameters.isNV16PictureFormat() || mParameters.isNV21PictureFormat()) { if (!isLongshotEnabled()) { rc = addCaptureChannel(); // normal capture case // need to stop preview channel stopChannel(QCAMERA_CH_TYPE_PREVIEW); delChannel(QCAMERA_CH_TYPE_PREVIEW); waitDefferedWork(mSnapshotJob); waitDefferedWork(mMetadataJob); waitDefferedWork(mRawdataJob); { DefferWorkArgs args; DefferAllocBuffArgs allocArgs; memset(&args, 0, sizeof(DefferWorkArgs)); memset(&allocArgs, 0, sizeof(DefferAllocBuffArgs)); allocArgs.ch = m_channels[QCAMERA_CH_TYPE_CAPTURE]; allocArgs.type = CAM_STREAM_TYPE_POSTVIEW; args.allocArgs = allocArgs; mPostviewJob = queueDefferedWork(CMD_DEFF_ALLOCATE_BUFF, args); if ( mPostviewJob == -1) rc = UNKNOWN_ERROR; } waitDefferedWork(mPostviewJob); } else { // normal capture case // need to stop preview channel stopChannel(QCAMERA_CH_TYPE_PREVIEW); delChannel(QCAMERA_CH_TYPE_PREVIEW); rc = addCaptureChannel(); } if ((rc == NO_ERROR) && (NULL != m_channels[QCAMERA_CH_TYPE_CAPTURE])) { // configure capture channel rc = m_channels[QCAMERA_CH_TYPE_CAPTURE]->config(); if (rc != NO_ERROR) { ALOGE("%s: cannot configure capture channel", __func__); delChannel(QCAMERA_CH_TYPE_CAPTURE); return rc; } DefferWorkArgs args; memset(&args, 0, sizeof(DefferWorkArgs)); args.pprocArgs = m_channels[QCAMERA_CH_TYPE_CAPTURE]; mReprocJob = queueDefferedWork(CMD_DEFF_PPROC_START, args); // start catpure channel rc = m_channels[QCAMERA_CH_TYPE_CAPTURE]->start(); if (rc != NO_ERROR) { ALOGE("%s: cannot start capture channel", __func__); delChannel(QCAMERA_CH_TYPE_CAPTURE); return rc; } QCameraPicChannel *pCapChannel = (QCameraPicChannel *)m_channels[QCAMERA_CH_TYPE_CAPTURE]; if (NULL != pCapChannel) { if (mParameters.isUbiFocusEnabled()| mParameters.isChromaFlashEnabled()) { rc = startAdvancedCapture(pCapChannel); if (rc != NO_ERROR) { ALOGE("%s: cannot start advanced capture", __func__); return rc; } } } if ( mLongshotEnabled ) { rc = longShot(); if (NO_ERROR != rc) { delChannel(QCAMERA_CH_TYPE_CAPTURE); return rc; } } } else { ALOGE("%s: cannot add capture channel", __func__); return rc; } } else { stopChannel(QCAMERA_CH_TYPE_PREVIEW); delChannel(QCAMERA_CH_TYPE_PREVIEW); rc = addRawChannel(); if (rc == NO_ERROR) { // start postprocessor rc = m_postprocessor.start(m_channels[QCAMERA_CH_TYPE_RAW]); if (rc != NO_ERROR) { ALOGE("%s: cannot start postprocessor", __func__); delChannel(QCAMERA_CH_TYPE_RAW); return rc; } rc = startChannel(QCAMERA_CH_TYPE_RAW); if (rc != NO_ERROR) { ALOGE("%s: cannot start raw channel", __func__); m_postprocessor.stop(); delChannel(QCAMERA_CH_TYPE_RAW); return rc; } } else { ALOGE("%s: cannot add raw channel", __func__); return rc; } } } CDBG_HIGH("%s: X", __func__); return rc; } /*=========================================================================== * FUNCTION : longShot * * DESCRIPTION: Queue one more ZSL frame * in the longshot pipe. * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::longShot() { int32_t rc = NO_ERROR; uint8_t numSnapshots = mParameters.getNumOfSnapshots(); QCameraPicChannel *pChannel = NULL; if (mParameters.isZSLMode()) { pChannel = (QCameraPicChannel *)m_channels[QCAMERA_CH_TYPE_ZSL]; } else { pChannel = (QCameraPicChannel *)m_channels[QCAMERA_CH_TYPE_CAPTURE]; } if (NULL != pChannel) { rc = pChannel->takePicture(numSnapshots); } else { ALOGE(" %s : Capture channel not initialized!", __func__); rc = NO_INIT; goto end; } end: return rc; } /*=========================================================================== * FUNCTION : stopCaptureChannel * * DESCRIPTION: Stops capture channel * * PARAMETERS : * @destroy : Set to true to stop and delete camera channel. * Set to false to only stop capture channel. * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::stopCaptureChannel(bool destroy) { if (mParameters.isJpegPictureFormat() || mParameters.isNV16PictureFormat() || mParameters.isNV21PictureFormat()) { stopChannel(QCAMERA_CH_TYPE_CAPTURE); if (destroy) { // Destroy camera channel but dont release context delChannel(QCAMERA_CH_TYPE_CAPTURE, false); } } #ifdef ARCSOFT_FB_SUPPORT if(mArcsoftEnabled)flawlessface.Uninit(); #endif return NO_ERROR; } /*=========================================================================== * FUNCTION : cancelPicture * * DESCRIPTION: cancel picture impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::cancelPicture() { CDBG_HIGH("%s:%d] ",__func__, __LINE__); waitDefferedWork(mReprocJob); //stop post processor m_postprocessor.stop(); mParameters.setDisplayFrame(TRUE); if ( mParameters.isHDREnabled() || mParameters.isAEBracketEnabled()) { mParameters.stopAEBracket(); } if (mParameters.isZSLMode()) { QCameraPicChannel *pZSLChannel = (QCameraPicChannel *)m_channels[QCAMERA_CH_TYPE_ZSL]; if (NULL != pZSLChannel) { pZSLChannel->cancelPicture(); } } else { // normal capture case if (mParameters.isJpegPictureFormat() || mParameters.isNV16PictureFormat() || mParameters.isNV21PictureFormat()) { stopChannel(QCAMERA_CH_TYPE_CAPTURE); delChannel(QCAMERA_CH_TYPE_CAPTURE); } else { stopChannel(QCAMERA_CH_TYPE_RAW); delChannel(QCAMERA_CH_TYPE_RAW); } } if(mIs3ALocked) { mParameters.set3ALock(QCameraParameters::VALUE_FALSE); mIs3ALocked = false; } if (mParameters.isUbiFocusEnabled()) { configureAFBracketing(false); } return NO_ERROR; } /*=========================================================================== * FUNCTION : captureDone * * DESCRIPTION: Function called when the capture is completed before encoding * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::captureDone() { if (mParameters.isOptiZoomEnabled() && ++mOutputCount >= mParameters.getBurstCountForAdvancedCapture()) { ALOGE("%s: Restoring previous zoom value!!",__func__); mParameters.setAndCommitZoom(mZoomLevel); mOutputCount = 0; } #ifdef ARCSOFT_FB_SUPPORT if(mArcsoftEnabled)flawlessface.Uninit(); #endif } /*=========================================================================== * FUNCTION : Live_Snapshot_thread * * DESCRIPTION: Seperate thread for taking live snapshot during recording * * PARAMETERS : @data - pointer to QCamera2HardwareInterface class object * * RETURN : none *==========================================================================*/ void* Live_Snapshot_thread (void* data) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(data); if (!hw) { ALOGE("take_picture_thread: NULL camera device"); return (void *)BAD_VALUE; } hw->takeLiveSnapshot_internal(); return (void* )NULL; } /*=========================================================================== * FUNCTION : Int_Pic_thread * * DESCRIPTION: Seperate thread for taking snapshot triggered by camera backend * * PARAMETERS : @data - pointer to QCamera2HardwareInterface class object * * RETURN : none *==========================================================================*/ void* Int_Pic_thread (void* data) { QCamera2HardwareInterface *hw = reinterpret_cast<QCamera2HardwareInterface *>(data); if (!hw) { ALOGE("take_picture_thread: NULL camera device"); return (void *)BAD_VALUE; } bool JpegMemOpt = false; hw->takeBackendPic_internal(&JpegMemOpt); hw->checkIntPicPending(JpegMemOpt); return (void* )NULL; } /*=========================================================================== * FUNCTION : takeLiveSnapshot * * DESCRIPTION: take live snapshot during recording * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::takeLiveSnapshot() { int rc = NO_ERROR; rc= pthread_create(&mLiveSnapshotThread, NULL, Live_Snapshot_thread, (void *) this); return rc; } /*=========================================================================== * FUNCTION : takePictureInternal * * DESCRIPTION: take snapshot triggered by backend * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::takePictureInternal() { int rc = NO_ERROR; rc= pthread_create(&mIntPicThread, NULL, Int_Pic_thread, (void *) this); return rc; } /*=========================================================================== * FUNCTION : checkIntPicPending * * DESCRIPTION: timed wait for jpeg completion event, and send * back completion event to backend * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::checkIntPicPending(bool JpegMemOpt) { cam_int_evt_params_t params; int rc = NO_ERROR; struct timespec ts; struct timeval tp; gettimeofday(&tp, NULL); ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000 + 1000 * 1000000; if (true == m_bIntEvtPending) { //wait on the eztune condition variable pthread_mutex_lock(&m_int_lock); rc = pthread_cond_timedwait(&m_int_cond, &m_int_lock, &ts); m_bIntEvtPending = false; pthread_mutex_unlock(&m_int_lock); if (ETIMEDOUT == rc) { return; } params.dim = m_postprocessor.m_dst_dim; //send event back to server with the file path memcpy(&params.path[0], &m_BackendFileName[0], 50); params.size = mBackendFileSize; pthread_mutex_lock(&m_parm_lock); rc = mParameters.setIntEvent(params); pthread_mutex_unlock(&m_parm_lock); lockAPI(); rc = processAPI(QCAMERA_SM_EVT_SNAPSHOT_DONE, NULL); unlockAPI(); if (false == mParameters.isZSLMode()) { lockAPI(); rc = processAPI(QCAMERA_SM_EVT_START_PREVIEW, NULL); unlockAPI(); } m_postprocessor.setJpegMemOpt(JpegMemOpt); } return; } /*=========================================================================== * FUNCTION : takeBackendPic_internal * * DESCRIPTION: take snapshot triggered by backend * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::takeBackendPic_internal(bool *JpegMemOpt) { int rc; *JpegMemOpt = m_postprocessor.getJpegMemOpt(); m_postprocessor.setJpegMemOpt(false); lockAPI(); rc = processAPI(QCAMERA_SM_EVT_TAKE_PICTURE, NULL); if (rc == NO_ERROR) { qcamera_api_result_t apiResult; waitAPIResult(QCAMERA_SM_EVT_TAKE_PICTURE, &apiResult); } unlockAPI(); return rc; } /*=========================================================================== * FUNCTION : takeLiveSnapshot_internal * * DESCRIPTION: take live snapshot during recording * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::takeLiveSnapshot_internal() { int rc = NO_ERROR; getOrientation(); QCameraChannel *pChannel = NULL; // start post processor rc = m_postprocessor.start(m_channels[QCAMERA_CH_TYPE_SNAPSHOT]); if (NO_ERROR != rc) { ALOGE("%s: Post-processor start failed %d", __func__, rc); goto end; } pChannel = m_channels[QCAMERA_CH_TYPE_SNAPSHOT]; if (NULL == pChannel) { ALOGE("%s: Snapshot channel not initialized", __func__); rc = NO_INIT; goto end; } // start snapshot channel if ((rc == NO_ERROR) && (NULL != pChannel)) { // Find and try to link a metadata stream from preview channel QCameraChannel *pMetaChannel = NULL; QCameraStream *pMetaStream = NULL; if (m_channels[QCAMERA_CH_TYPE_PREVIEW] != NULL) { pMetaChannel = m_channels[QCAMERA_CH_TYPE_PREVIEW]; uint32_t streamNum = pMetaChannel->getNumOfStreams(); QCameraStream *pStream = NULL; for (uint32_t i = 0 ; i < streamNum ; i++ ) { pStream = pMetaChannel->getStreamByIndex(i); if ((NULL != pStream) && (CAM_STREAM_TYPE_METADATA == pStream->getMyType())) { pMetaStream = pStream; break; } } } if ((NULL != pMetaChannel) && (NULL != pMetaStream)) { rc = pChannel->linkStream(pMetaChannel, pMetaStream); if (NO_ERROR != rc) { ALOGE("%s : Metadata stream link failed %d", __func__, rc); } } rc = pChannel->start(); } end: if (rc != NO_ERROR) { rc = processAPI(QCAMERA_SM_EVT_CANCEL_PICTURE, NULL); rc = sendEvtNotify(CAMERA_MSG_ERROR, UNKNOWN_ERROR, 0); } return rc; } /*=========================================================================== * FUNCTION : cancelLiveSnapshot * * DESCRIPTION: cancel current live snapshot request * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::cancelLiveSnapshot() { int rc = NO_ERROR; if (mLiveSnapshotThread != 0) { pthread_join(mLiveSnapshotThread,NULL); mLiveSnapshotThread = 0; } //stop post processor m_postprocessor.stop(); // stop snapshot channel rc = stopChannel(QCAMERA_CH_TYPE_SNAPSHOT); return rc; } /*=========================================================================== * FUNCTION : getParameters * * DESCRIPTION: get parameters impl * * PARAMETERS : none * * RETURN : a string containing parameter pairs *==========================================================================*/ char* QCamera2HardwareInterface::getParameters() { char* strParams = NULL; String8 str; int cur_width, cur_height; //Need take care Scale picture size if(mParameters.m_reprocScaleParam.isScaleEnabled() && mParameters.m_reprocScaleParam.isUnderScaling()){ int scale_width, scale_height; mParameters.m_reprocScaleParam.getPicSizeFromAPK(scale_width,scale_height); mParameters.getPictureSize(&cur_width, &cur_height); String8 pic_size; char buffer[32]; snprintf(buffer, sizeof(buffer), "%dx%d", scale_width, scale_height); pic_size.append(buffer); mParameters.set(CameraParameters::KEY_PICTURE_SIZE, pic_size); } str = mParameters.flatten( ); strParams = (char *)malloc(sizeof(char)*(str.length()+1)); if(strParams != NULL){ memset(strParams, 0, sizeof(char)*(str.length()+1)); strncpy(strParams, str.string(), str.length()); strParams[str.length()] = 0; } if(mParameters.m_reprocScaleParam.isScaleEnabled() && mParameters.m_reprocScaleParam.isUnderScaling()){ //need set back picture size String8 pic_size; char buffer[32]; snprintf(buffer, sizeof(buffer), "%dx%d", cur_width, cur_height); pic_size.append(buffer); mParameters.set(CameraParameters::KEY_PICTURE_SIZE, pic_size); } return strParams; } /*=========================================================================== * FUNCTION : putParameters * * DESCRIPTION: put parameters string impl * * PARAMETERS : * @parms : parameters string to be released * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::putParameters(char *parms) { free(parms); return NO_ERROR; } /*=========================================================================== * FUNCTION : sendCommand * * DESCRIPTION: send command impl * * PARAMETERS : * @command : command to be executed * @arg1 : optional argument 1 * @arg2 : optional argument 2 * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::sendCommand(int32_t command, int32_t &arg1, int32_t &/*arg2*/) { int rc = NO_ERROR; switch (command) { case CAMERA_CMD_LONGSHOT_ON: arg1 = 0; // Longshot can only be enabled when image capture // is not active. if ( !m_stateMachine.isCaptureRunning() ) { CDBG_HIGH("%s: Longshot Enabled", __func__); mLongshotEnabled = true; // Due to recent buffer count optimizations // ZSL might run with considerably less buffers // when not in longshot mode. Preview needs to // restart in this case. if (isZSLMode() && m_stateMachine.isPreviewRunning()) { QCameraChannel *pChannel = NULL; QCameraStream *pSnapStream = NULL; pChannel = m_channels[QCAMERA_CH_TYPE_ZSL]; if (NULL != pChannel) { QCameraStream *pStream = NULL; for(int i = 0; i < pChannel->getNumOfStreams(); i++) { pStream = pChannel->getStreamByIndex(i); if (pStream != NULL) { if (pStream->isTypeOf(CAM_STREAM_TYPE_SNAPSHOT)) { pSnapStream = pStream; break; } } } if (NULL != pSnapStream) { uint8_t required = 0; required = getBufNumRequired(CAM_STREAM_TYPE_SNAPSHOT); if (pSnapStream->getBufferCount() < required) { // We restart here, to reset the FPS and no // of buffers as per the requirement of longshot usecase. arg1 = QCAMERA_SM_EVT_RESTART_PERVIEW; } } } } rc = mParameters.setLongshotEnable(mLongshotEnabled); mPrepSnapRun = false; } else { rc = NO_INIT; } break; case CAMERA_CMD_LONGSHOT_OFF: if ( mLongshotEnabled && m_stateMachine.isCaptureRunning() ) { cancelPicture(); processEvt(QCAMERA_SM_EVT_SNAPSHOT_DONE, NULL); QCameraChannel *pZSLChannel = m_channels[QCAMERA_CH_TYPE_ZSL]; if (isZSLMode() && (NULL != pZSLChannel) && mPrepSnapRun) { mCameraHandle->ops->stop_zsl_snapshot( mCameraHandle->camera_handle, pZSLChannel->getMyHandle()); } } CDBG_HIGH("%s: Longshot Disabled", __func__); mPrepSnapRun = false; mLongshotEnabled = false; rc = mParameters.setLongshotEnable(mLongshotEnabled); break; case CAMERA_CMD_HISTOGRAM_ON: case CAMERA_CMD_HISTOGRAM_OFF: rc = setHistogram(command == CAMERA_CMD_HISTOGRAM_ON? true : false); CDBG_HIGH("%s: Histogram -> %s", __func__, mParameters.isHistogramEnabled() ? "Enabled" : "Disabled"); break; case CAMERA_CMD_START_FACE_DETECTION: case CAMERA_CMD_STOP_FACE_DETECTION: rc = setFaceDetection(command == CAMERA_CMD_START_FACE_DETECTION? true : false); CDBG_HIGH("%s: FaceDetection -> %s", __func__, mParameters.isFaceDetectionEnabled() ? "Enabled" : "Disabled"); break; case CAMERA_CMD_HISTOGRAM_SEND_DATA: default: rc = NO_ERROR; break; } return rc; } /*=========================================================================== * FUNCTION : registerFaceImage * * DESCRIPTION: register face image impl * * PARAMETERS : * @img_ptr : ptr to image buffer * @config : ptr to config struct about input image info * @faceID : [OUT] face ID to uniquely identifiy the registered face image * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::registerFaceImage(void *img_ptr, cam_pp_offline_src_config_t *config, int32_t &faceID) { int rc = NO_ERROR; faceID = -1; if (img_ptr == NULL || config == NULL) { ALOGE("%s: img_ptr or config is NULL", __func__); return BAD_VALUE; } // allocate ion memory for source image QCameraHeapMemory *imgBuf = new QCameraHeapMemory(QCAMERA_ION_USE_CACHE); if (imgBuf == NULL) { ALOGE("%s: Unable to new heap memory obj for image buf", __func__); return NO_MEMORY; } rc = imgBuf->allocate(1, config->input_buf_planes.plane_info.frame_len); if (rc < 0) { ALOGE("%s: Unable to allocate heap memory for image buf", __func__); delete imgBuf; return NO_MEMORY; } void *pBufPtr = imgBuf->getPtr(0); if (pBufPtr == NULL) { ALOGE("%s: image buf is NULL", __func__); imgBuf->deallocate(); delete imgBuf; return NO_MEMORY; } memcpy(pBufPtr, img_ptr, config->input_buf_planes.plane_info.frame_len); cam_pp_feature_config_t pp_feature; memset(&pp_feature, 0, sizeof(cam_pp_feature_config_t)); pp_feature.feature_mask = CAM_QCOM_FEATURE_REGISTER_FACE; QCameraReprocessChannel *pChannel = addOfflineReprocChannel(*config, pp_feature, NULL, NULL); if (pChannel == NULL) { ALOGE("%s: fail to add offline reprocess channel", __func__); imgBuf->deallocate(); delete imgBuf; return UNKNOWN_ERROR; } rc = pChannel->start(); if (rc != NO_ERROR) { ALOGE("%s: Cannot start reprocess channel", __func__); imgBuf->deallocate(); delete imgBuf; delete pChannel; return rc; } rc = pChannel->doReprocess(imgBuf->getFd(0), imgBuf->getSize(0), faceID); // done with register face image, free imgbuf and delete reprocess channel imgBuf->deallocate(); delete imgBuf; imgBuf = NULL; pChannel->stop(); delete pChannel; pChannel = NULL; return rc; } /*=========================================================================== * FUNCTION : release * * DESCRIPTION: release camera resource impl * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::release() { // stop and delete all channels for (int i = 0; i <QCAMERA_CH_TYPE_MAX ; i++) { if (m_channels[i] != NULL) { stopChannel((qcamera_ch_type_enum_t)i); delChannel((qcamera_ch_type_enum_t)i); } } return NO_ERROR; } /*=========================================================================== * FUNCTION : dump * * DESCRIPTION: camera status dump impl * * PARAMETERS : * @fd : fd for the buffer to be dumped with camera status * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::dump(int /*fd*/) { ALOGE("%s: not supported yet", __func__); return INVALID_OPERATION; } /*=========================================================================== * FUNCTION : processAPI * * DESCRIPTION: process API calls from upper layer * * PARAMETERS : * @api : API to be processed * @api_payload : ptr to API payload if any * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::processAPI(qcamera_sm_evt_enum_t api, void *api_payload) { return m_stateMachine.procAPI(api, api_payload); } /*=========================================================================== * FUNCTION : processEvt * * DESCRIPTION: process Evt from backend via mm-camera-interface * * PARAMETERS : * @evt : event type to be processed * @evt_payload : ptr to event payload if any * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::processEvt(qcamera_sm_evt_enum_t evt, void *evt_payload) { return m_stateMachine.procEvt(evt, evt_payload); } /*=========================================================================== * FUNCTION : processSyncEvt * * DESCRIPTION: process synchronous Evt from backend * * PARAMETERS : * @evt : event type to be processed * @evt_payload : ptr to event payload if any * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::processSyncEvt(qcamera_sm_evt_enum_t evt, void *evt_payload) { int rc = NO_ERROR; pthread_mutex_lock(&m_evtLock); rc = processEvt(evt, evt_payload); if (rc == NO_ERROR) { memset(&m_evtResult, 0, sizeof(qcamera_api_result_t)); while (m_evtResult.request_api != evt) { pthread_cond_wait(&m_evtCond, &m_evtLock); } rc = m_evtResult.status; } pthread_mutex_unlock(&m_evtLock); return rc; } /*=========================================================================== * FUNCTION : evtHandle * * DESCRIPTION: Function registerd to mm-camera-interface to handle backend events * * PARAMETERS : * @camera_handle : event type to be processed * @evt : ptr to event * @user_data : user data ptr * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::camEvtHandle(uint32_t /*camera_handle*/, mm_camera_event_t *evt, void *user_data) { QCamera2HardwareInterface *obj = (QCamera2HardwareInterface *)user_data; if (obj && evt) { mm_camera_event_t *payload = (mm_camera_event_t *)malloc(sizeof(mm_camera_event_t)); if (NULL != payload) { *payload = *evt; //peek into the event, if this is an eztune event from server, //then we don't need to post it to the SM Qs, we shud directly //spawn a thread and get the job done (jpeg or raw snapshot) if (CAM_EVENT_TYPE_INT_TAKE_PIC == payload->server_event_type) { pthread_mutex_lock(&obj->m_int_lock); obj->m_bIntEvtPending = true; pthread_mutex_unlock(&obj->m_int_lock); obj->takePictureInternal(); free(payload); } else { obj->processEvt(QCAMERA_SM_EVT_EVT_NOTIFY, payload); } } } else { ALOGE("%s: NULL user_data", __func__); } } /*=========================================================================== * FUNCTION : jpegEvtHandle * * DESCRIPTION: Function registerd to mm-jpeg-interface to handle jpeg events * * PARAMETERS : * @status : status of jpeg job * @client_hdl: jpeg client handle * @jobId : jpeg job Id * @p_ouput : ptr to jpeg output result struct * @userdata : user data ptr * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::jpegEvtHandle(jpeg_job_status_t status, uint32_t /*client_hdl*/, uint32_t jobId, mm_jpeg_output_t *p_output, void *userdata) { QCamera2HardwareInterface *obj = (QCamera2HardwareInterface *)userdata; if (obj) { qcamera_jpeg_evt_payload_t *payload = (qcamera_jpeg_evt_payload_t *)malloc(sizeof(qcamera_jpeg_evt_payload_t)); if (NULL != payload) { memset(payload, 0, sizeof(qcamera_jpeg_evt_payload_t)); payload->status = status; payload->jobId = jobId; if (p_output != NULL) { payload->out_data = *p_output; } obj->processUFDumps(payload); obj->processEvt(QCAMERA_SM_EVT_JPEG_EVT_NOTIFY, payload); } } else { ALOGE("%s: NULL user_data", __func__); } } /*=========================================================================== * FUNCTION : thermalEvtHandle * * DESCRIPTION: routine to handle thermal event notification * * PARAMETERS : * @level : thermal level * @userdata : userdata passed in during registration * @data : opaque data from thermal client * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::thermalEvtHandle( qcamera_thermal_level_enum_t level, void *userdata, void *data) { if (!mCameraOpened) { CDBG("%s: Camera is not opened, no need to handle thermal evt", __func__); return NO_ERROR; } // Make sure thermal events are logged CDBG("%s: level = %d, userdata = %p, data = %p", __func__, level, userdata, data); //We don't need to lockAPI, waitAPI here. QCAMERA_SM_EVT_THERMAL_NOTIFY // becomes an aync call. This also means we can only pass payload // by value, not by address. return processAPI(QCAMERA_SM_EVT_THERMAL_NOTIFY, (void *)level); } /*=========================================================================== * FUNCTION : sendEvtNotify * * DESCRIPTION: send event notify to notify thread * * PARAMETERS : * @msg_type: msg type to be sent * @ext1 : optional extension1 * @ext2 : optional extension2 * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::sendEvtNotify(int32_t msg_type, int32_t ext1, int32_t ext2) { qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_NOTIFY_CALLBACK; cbArg.msg_type = msg_type; cbArg.ext1 = ext1; cbArg.ext2 = ext2; return m_cbNotifier.notifyCallback(cbArg); } /*=========================================================================== * FUNCTION : processAutoFocusEvent * * DESCRIPTION: process auto focus event * * PARAMETERS : * @focus_data: struct containing auto focus result info * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processAutoFocusEvent(cam_auto_focus_data_t &focus_data) { int32_t ret = NO_ERROR; CDBG_HIGH("%s: E",__func__); m_currentFocusState = focus_data.focus_state; cam_focus_mode_type focusMode = mParameters.getFocusMode(); CDBG_HIGH("[AF_DBG] %s: focusMode=%d, m_currentFocusState=%d, m_bAFRunning=%d", __func__, focusMode, m_currentFocusState, isAFRunning()); switch (focusMode) { case CAM_FOCUS_MODE_AUTO: case CAM_FOCUS_MODE_MACRO: if (getCancelAutoFocus()) { // auto focus has canceled, just ignore it break; } if (focus_data.focus_state == CAM_AF_SCANNING || focus_data.focus_state == CAM_AF_INACTIVE) { // in the middle of focusing, just ignore it break; } // update focus distance mParameters.updateFocusDistances(&focus_data.focus_dist); ret = sendEvtNotify(CAMERA_MSG_FOCUS, (focus_data.focus_state == CAM_AF_FOCUSED)? true : false, 0); break; case CAM_FOCUS_MODE_CONTINOUS_VIDEO: case CAM_FOCUS_MODE_CONTINOUS_PICTURE: if (focus_data.focus_state == CAM_AF_FOCUSED || focus_data.focus_state == CAM_AF_NOT_FOCUSED) { // update focus distance mParameters.updateFocusDistances(&focus_data.focus_dist); ret = sendEvtNotify(CAMERA_MSG_FOCUS, (focus_data.focus_state == CAM_AF_FOCUSED)? true : false, 0); } ret = sendEvtNotify(CAMERA_MSG_FOCUS_MOVE, (focus_data.focus_state == CAM_AF_SCANNING)? true : false, 0); break; case CAM_FOCUS_MODE_INFINITY: case CAM_FOCUS_MODE_FIXED: case CAM_FOCUS_MODE_EDOF: default: CDBG_HIGH("%s: no ops for autofocus event in focusmode %d", __func__, focusMode); break; } // we save cam_auto_focus_data_t.focus_pos to parameters, // in any focus mode. CDBG_HIGH("%s, update focus position: %d", __func__, focus_data.focus_pos); mParameters.updateCurrentFocusPosition(focus_data.focus_pos); CDBG_HIGH("%s: X",__func__); return ret; } /*=========================================================================== * FUNCTION : processZoomEvent * * DESCRIPTION: process zoom event * * PARAMETERS : * @crop_info : crop info as a result of zoom operation * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processZoomEvent(cam_crop_data_t &crop_info) { int32_t ret = NO_ERROR; for (int i = 0; i < QCAMERA_CH_TYPE_MAX; i++) { if (m_channels[i] != NULL) { ret = m_channels[i]->processZoomDone(mPreviewWindow, crop_info); } } return ret; } /*=========================================================================== * FUNCTION : processHDRData * * DESCRIPTION: process HDR scene events * * PARAMETERS : * @hdr_scene : HDR scene event data * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processHDRData(cam_asd_hdr_scene_data_t hdr_scene) { int rc = NO_ERROR; if (hdr_scene.is_hdr_scene && (hdr_scene.hdr_confidence > HDR_CONFIDENCE_THRESHOLD) && mParameters.isAutoHDREnabled()) { m_HDRSceneEnabled = true; } else { m_HDRSceneEnabled = false; } pthread_mutex_lock(&m_parm_lock); mParameters.setHDRSceneEnable(m_HDRSceneEnabled); pthread_mutex_unlock(&m_parm_lock); if ( msgTypeEnabled(CAMERA_MSG_META_DATA) ) { size_t data_len = sizeof(int); size_t buffer_len = 1 *sizeof(int) //meta type + 1 *sizeof(int) //data len + 1 *sizeof(int); //data camera_memory_t *hdrBuffer = mGetMemory(-1, buffer_len, 1, mCallbackCookie); if ( NULL == hdrBuffer ) { ALOGE("%s: Not enough memory for auto HDR data", __func__); return NO_MEMORY; } int *pHDRData = (int *)hdrBuffer->data; if (pHDRData == NULL) { ALOGE("%s: memory data ptr is NULL", __func__); return UNKNOWN_ERROR; } pHDRData[0] = CAMERA_META_DATA_HDR; pHDRData[1] = data_len; pHDRData[2] = m_HDRSceneEnabled; qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_DATA_CALLBACK; cbArg.msg_type = CAMERA_MSG_META_DATA; cbArg.data = hdrBuffer; cbArg.user_data = hdrBuffer; cbArg.cookie = this; cbArg.release_cb = releaseCameraMemory; rc = m_cbNotifier.notifyCallback(cbArg); if (rc != NO_ERROR) { ALOGE("%s: fail sending auto HDR notification", __func__); hdrBuffer->release(hdrBuffer); } } CDBG("%s : hdr_scene_data: processHDRData: %d %f", __func__, hdr_scene.is_hdr_scene, hdr_scene.hdr_confidence); return rc; } /*=========================================================================== * FUNCTION : transAwbMetaToParams * * DESCRIPTION: translate awb params from metadata callback to QCameraParameters * * PARAMETERS : * @awb_params : awb params from metadata callback * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::transAwbMetaToParams(cam_awb_params_t &awb_params) { CDBG("%s, cct value: %d", __func__, awb_params.cct_value); return mParameters.updateCCTValue(awb_params.cct_value); } /*=========================================================================== * FUNCTION : processPrepSnapshotDone * * DESCRIPTION: process prep snapshot done event * * PARAMETERS : * @prep_snapshot_state : state of prepare snapshot done. In other words, * i.e. whether need future frames for capture. * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processPrepSnapshotDoneEvent( cam_prep_snapshot_state_t prep_snapshot_state) { int32_t ret = NO_ERROR; if (m_channels[QCAMERA_CH_TYPE_ZSL] && prep_snapshot_state == NEED_FUTURE_FRAME) { CDBG_HIGH("%s: already handled in mm-camera-intf, no ops here", __func__); } return ret; } /*=========================================================================== * FUNCTION : processASDUpdate * * DESCRIPTION: process ASD update event * * PARAMETERS : * @scene: selected scene mode * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processASDUpdate(cam_auto_scene_t scene) { //set ASD parameter mParameters.set(QCameraParameters::KEY_SELECTED_AUTO_SCENE, mParameters.getASDStateString(scene)); size_t data_len = sizeof(cam_auto_scene_t); size_t buffer_len = 1 *sizeof(int) //meta type + 1 *sizeof(int) //data len + data_len; //data camera_memory_t *asdBuffer = mGetMemory(-1, buffer_len, 1, mCallbackCookie); if ( NULL == asdBuffer ) { ALOGE("%s: Not enough memory for histogram data", __func__); return NO_MEMORY; } int *pASDData = (int *)asdBuffer->data; if (pASDData == NULL) { ALOGE("%s: memory data ptr is NULL", __func__); return UNKNOWN_ERROR; } pASDData[0] = CAMERA_META_DATA_ASD; pASDData[1] = data_len; pASDData[2] = scene; qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_DATA_CALLBACK; cbArg.msg_type = CAMERA_MSG_META_DATA; cbArg.data = asdBuffer; cbArg.user_data = asdBuffer; cbArg.cookie = this; cbArg.release_cb = releaseCameraMemory; int32_t rc = m_cbNotifier.notifyCallback(cbArg); if (rc != NO_ERROR) { ALOGE("%s: fail sending notification", __func__); asdBuffer->release(asdBuffer); } return NO_ERROR; } /*=========================================================================== * FUNCTION : processAWBUpdate * * DESCRIPTION: process AWB update event * * PARAMETERS : * @awb_params: current awb parameters from back-end. * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processAWBUpdate(cam_awb_params_t &awb_params) { return transAwbMetaToParams(awb_params); } /*=========================================================================== * FUNCTION : processJpegNotify * * DESCRIPTION: process jpeg event * * PARAMETERS : * @jpeg_evt: ptr to jpeg event payload * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processJpegNotify(qcamera_jpeg_evt_payload_t *jpeg_evt) { return m_postprocessor.processJpegEvt(jpeg_evt); } /*=========================================================================== * FUNCTION : lockAPI * * DESCRIPTION: lock to process API * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::lockAPI() { pthread_mutex_lock(&m_lock); } /*=========================================================================== * FUNCTION : waitAPIResult * * DESCRIPTION: wait for API result coming back. This is a blocking call, it will * return only cerntain API event type arrives * * PARAMETERS : * @api_evt : API event type * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::waitAPIResult(qcamera_sm_evt_enum_t api_evt, qcamera_api_result_t *apiResult) { CDBG("%s: wait for API result of evt (%d)", __func__, api_evt); int resultReceived = 0; while (!resultReceived) { pthread_cond_wait(&m_cond, &m_lock); if (m_apiResultList != NULL) { api_result_list *apiResultList = m_apiResultList; api_result_list *apiResultListPrevious = m_apiResultList; while (apiResultList != NULL) { if (apiResultList->result.request_api == api_evt) { resultReceived = 1; *apiResult = apiResultList->result; apiResultListPrevious->next = apiResultList->next; if (apiResultList == m_apiResultList) { m_apiResultList = apiResultList->next; } free(apiResultList); break; } else { apiResultListPrevious = apiResultList; apiResultList = apiResultList->next; } } } } CDBG("%s: return (%d) from API result wait for evt (%d)", __func__, apiResult->status, api_evt); } /*=========================================================================== * FUNCTION : unlockAPI * * DESCRIPTION: API processing is done, unlock * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::unlockAPI() { pthread_mutex_unlock(&m_lock); } /*=========================================================================== * FUNCTION : signalAPIResult * * DESCRIPTION: signal condition viarable that cerntain API event type arrives * * PARAMETERS : * @result : API result * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::signalAPIResult(qcamera_api_result_t *result) { pthread_mutex_lock(&m_lock); api_result_list *apiResult = (api_result_list *)malloc(sizeof(api_result_list)); if (apiResult == NULL) { ALOGE("%s: ERROR: malloc for api result failed", __func__); ALOGE("%s: ERROR: api thread will wait forever fot this lost result", __func__); goto malloc_failed; } apiResult->result = *result; apiResult->next = NULL; if (m_apiResultList == NULL) m_apiResultList = apiResult; else { api_result_list *apiResultList = m_apiResultList; while(apiResultList->next != NULL) apiResultList = apiResultList->next; apiResultList->next = apiResult; } malloc_failed: pthread_cond_broadcast(&m_cond); pthread_mutex_unlock(&m_lock); } /*=========================================================================== * FUNCTION : signalEvtResult * * DESCRIPTION: signal condition variable that certain event was processed * * PARAMETERS : * @result : Event result * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::signalEvtResult(qcamera_api_result_t *result) { pthread_mutex_lock(&m_evtLock); m_evtResult = *result; pthread_cond_signal(&m_evtCond); pthread_mutex_unlock(&m_evtLock); } int32_t QCamera2HardwareInterface::prepareRawStream(QCameraChannel *curChannel) { int32_t rc = NO_ERROR; cam_dimension_t str_dim,max_dim; QCameraChannel *pChannel; max_dim.width = 0; max_dim.height = 0; for (int j = 0; j < QCAMERA_CH_TYPE_MAX; j++) { if (m_channels[j] != NULL) { pChannel = m_channels[j]; for (int i = 0; i < pChannel->getNumOfStreams();i++) { QCameraStream *pStream = pChannel->getStreamByIndex(i); if (pStream != NULL) { if (pStream->isTypeOf(CAM_STREAM_TYPE_METADATA)) { continue; } pStream->getFrameDimension(str_dim); if (str_dim.width > max_dim.width) { max_dim.width = str_dim.width; } if (str_dim.height > max_dim.height) { max_dim.height = str_dim.height; } } } } } for (int i = 0; i < curChannel->getNumOfStreams();i++) { QCameraStream *pStream = curChannel->getStreamByIndex(i); if (pStream != NULL) { if (pStream->isTypeOf(CAM_STREAM_TYPE_METADATA)) { continue; } pStream->getFrameDimension(str_dim); if (str_dim.width > max_dim.width) { max_dim.width = str_dim.width; } if (str_dim.height > max_dim.height) { max_dim.height = str_dim.height; } } } rc = mParameters.updateRAW(max_dim); return rc; } /*=========================================================================== * FUNCTION : addStreamToChannel * * DESCRIPTION: add a stream into a channel * * PARAMETERS : * @pChannel : ptr to channel obj * @streamType : type of stream to be added * @streamCB : callback of stream * @userData : user data ptr to callback * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addStreamToChannel(QCameraChannel *pChannel, cam_stream_type_t streamType, stream_cb_routine streamCB, void *userData) { int32_t rc = NO_ERROR; if (streamType == CAM_STREAM_TYPE_RAW) { prepareRawStream(pChannel); } QCameraHeapMemory *pStreamInfo = allocateStreamInfoBuf(streamType); if (pStreamInfo == NULL) { ALOGE("%s: no mem for stream info buf", __func__); return NO_MEMORY; } uint8_t minStreamBufNum = getBufNumRequired(streamType); bool bDynAllocBuf = false; if (isZSLMode() && streamType == CAM_STREAM_TYPE_SNAPSHOT) { bDynAllocBuf = true; } if ( ( streamType == CAM_STREAM_TYPE_SNAPSHOT || streamType == CAM_STREAM_TYPE_POSTVIEW || streamType == CAM_STREAM_TYPE_METADATA || streamType == CAM_STREAM_TYPE_RAW) && !isZSLMode() && !isLongshotEnabled() && !mParameters.getRecordingHintValue()) { rc = pChannel->addStream(*this, pStreamInfo, minStreamBufNum, &gCamCapability[mCameraId]->padding_info, streamCB, userData, bDynAllocBuf, true); // Queue buffer allocation for Snapshot and Metadata streams if ( !rc ) { DefferWorkArgs args; DefferAllocBuffArgs allocArgs; memset(&args, 0, sizeof(DefferWorkArgs)); memset(&allocArgs, 0, sizeof(DefferAllocBuffArgs)); allocArgs.type = streamType; allocArgs.ch = pChannel; args.allocArgs = allocArgs; if (streamType == CAM_STREAM_TYPE_SNAPSHOT) { mSnapshotJob = queueDefferedWork(CMD_DEFF_ALLOCATE_BUFF, args); if ( mSnapshotJob == -1) { rc = UNKNOWN_ERROR; } } else if (streamType == CAM_STREAM_TYPE_METADATA) { mMetadataJob = queueDefferedWork(CMD_DEFF_ALLOCATE_BUFF, args); if ( mMetadataJob == -1) { rc = UNKNOWN_ERROR; } } else if (streamType == CAM_STREAM_TYPE_RAW) { mRawdataJob = queueDefferedWork(CMD_DEFF_ALLOCATE_BUFF, args); if ( mRawdataJob == -1) { rc = UNKNOWN_ERROR; } } } } else { rc = pChannel->addStream(*this, pStreamInfo, minStreamBufNum, &gCamCapability[mCameraId]->padding_info, streamCB, userData, bDynAllocBuf, false); } if (rc != NO_ERROR) { ALOGE("%s: add stream type (%d) failed, ret = %d", __func__, streamType, rc); pStreamInfo->deallocate(); delete pStreamInfo; return rc; } return rc; } /*=========================================================================== * FUNCTION : addPreviewChannel * * DESCRIPTION: add a preview channel that contains a preview stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addPreviewChannel() { int32_t rc = NO_ERROR; QCameraChannel *pChannel = NULL; if (m_channels[QCAMERA_CH_TYPE_PREVIEW] != NULL) { // Using the no preview torch WA it is possible // to already have a preview channel present before // start preview gets called. CDBG_HIGH(" %s : Preview Channel already added!", __func__); return NO_ERROR; } pChannel = new QCameraChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for preview channel", __func__); return NO_MEMORY; } // preview only channel, don't need bundle attr and cb rc = pChannel->init(NULL, NULL, NULL); if (rc != NO_ERROR) { ALOGE("%s: init preview channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } // meta data stream always coexists with preview if applicable rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_METADATA, metadata_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add metadata stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } if (isNoDisplayMode()) { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_PREVIEW, nodisplay_preview_stream_cb_routine, this); } else { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_PREVIEW, preview_stream_cb_routine, this); } if (rc != NO_ERROR) { ALOGE("%s: add preview stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } m_channels[QCAMERA_CH_TYPE_PREVIEW] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addVideoChannel * * DESCRIPTION: add a video channel that contains a video stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addVideoChannel() { int32_t rc = NO_ERROR; QCameraVideoChannel *pChannel = NULL; if (m_channels[QCAMERA_CH_TYPE_VIDEO] != NULL) { // if we had video channel before, delete it first delete m_channels[QCAMERA_CH_TYPE_VIDEO]; m_channels[QCAMERA_CH_TYPE_VIDEO] = NULL; } pChannel = new QCameraVideoChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for video channel", __func__); return NO_MEMORY; } // preview only channel, don't need bundle attr and cb rc = pChannel->init(NULL, NULL, NULL); if (rc != 0) { ALOGE("%s: init video channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_VIDEO, video_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add video stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } m_channels[QCAMERA_CH_TYPE_VIDEO] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addSnapshotChannel * * DESCRIPTION: add a snapshot channel that contains a snapshot stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code * NOTE : Add this channel for live snapshot usecase. Regular capture will * use addCaptureChannel. *==========================================================================*/ int32_t QCamera2HardwareInterface::addSnapshotChannel() { int32_t rc = NO_ERROR; QCameraChannel *pChannel = NULL; if (m_channels[QCAMERA_CH_TYPE_SNAPSHOT] != NULL) { // if we had ZSL channel before, delete it first delete m_channels[QCAMERA_CH_TYPE_SNAPSHOT]; m_channels[QCAMERA_CH_TYPE_SNAPSHOT] = NULL; } pChannel = new QCameraChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for snapshot channel", __func__); return NO_MEMORY; } mm_camera_channel_attr_t attr; memset(&attr, 0, sizeof(mm_camera_channel_attr_t)); attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_CONTINUOUS; attr.look_back = mParameters.getZSLBackLookCount(); attr.post_frame_skip = mParameters.getZSLBurstInterval(); attr.water_mark = mParameters.getZSLQueueDepth(); attr.max_unmatched_frames = mParameters.getMaxUnmatchedFramesInQueue(); rc = pChannel->init(&attr, snapshot_channel_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: init snapshot channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_SNAPSHOT, NULL, NULL); if (rc != NO_ERROR) { ALOGE("%s: add snapshot stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } m_channels[QCAMERA_CH_TYPE_SNAPSHOT] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addRawChannel * * DESCRIPTION: add a raw channel that contains a raw image stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addRawChannel() { int32_t rc = NO_ERROR; QCameraChannel *pChannel = NULL; if (m_channels[QCAMERA_CH_TYPE_RAW] != NULL) { // if we had raw channel before, delete it first delete m_channels[QCAMERA_CH_TYPE_RAW]; m_channels[QCAMERA_CH_TYPE_RAW] = NULL; } pChannel = new QCameraChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for raw channel", __func__); return NO_MEMORY; } rc = pChannel->init(NULL, NULL, NULL); if (rc != NO_ERROR) { ALOGE("%s: init raw channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } // meta data stream always coexists with snapshot in regular RAW capture case rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_METADATA, metadata_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add metadata stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } waitDefferedWork(mMetadataJob); rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_RAW, raw_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add snapshot stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } waitDefferedWork(mRawdataJob); m_channels[QCAMERA_CH_TYPE_RAW] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addZSLChannel * * DESCRIPTION: add a ZSL channel that contains a preview stream and * a snapshot stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addZSLChannel() { int32_t rc = NO_ERROR; QCameraPicChannel *pChannel = NULL; char value[PROPERTY_VALUE_MAX]; bool raw_yuv = false; if (m_channels[QCAMERA_CH_TYPE_ZSL] != NULL) { // if we had ZSL channel before, delete it first delete m_channels[QCAMERA_CH_TYPE_ZSL]; m_channels[QCAMERA_CH_TYPE_ZSL] = NULL; } if (m_channels[QCAMERA_CH_TYPE_PREVIEW] != NULL) { // if we had ZSL channel before, delete it first delete m_channels[QCAMERA_CH_TYPE_PREVIEW]; m_channels[QCAMERA_CH_TYPE_PREVIEW] = NULL; } pChannel = new QCameraPicChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for ZSL channel", __func__); return NO_MEMORY; } // ZSL channel, init with bundle attr and cb mm_camera_channel_attr_t attr; memset(&attr, 0, sizeof(mm_camera_channel_attr_t)); attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_BURST; attr.look_back = mParameters.getZSLBackLookCount(); attr.post_frame_skip = mParameters.getZSLBurstInterval(); attr.water_mark = mParameters.getZSLQueueDepth(); attr.max_unmatched_frames = mParameters.getMaxUnmatchedFramesInQueue(); rc = pChannel->init(&attr, zsl_channel_cb, this); if (rc != 0) { ALOGE("%s: init ZSL channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } // meta data stream always coexists with preview if applicable rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_METADATA, metadata_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add metadata stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } if (isNoDisplayMode()) { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_PREVIEW, nodisplay_preview_stream_cb_routine, this); } else { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_PREVIEW, preview_stream_cb_routine, this); } if (rc != NO_ERROR) { ALOGE("%s: add preview stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_SNAPSHOT, NULL, this); if (rc != NO_ERROR) { ALOGE("%s: add snapshot stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } property_get("persist.camera.raw_yuv", value, "0"); raw_yuv = atoi(value) > 0 ? true : false; if ( raw_yuv ) { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_RAW, NULL, this); if (rc != NO_ERROR) { ALOGE("%s: add raw stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } } m_channels[QCAMERA_CH_TYPE_ZSL] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addCaptureChannel * * DESCRIPTION: add a capture channel that contains a snapshot stream * and a postview stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code * NOTE : Add this channel for regular capture usecase. * For Live snapshot usecase, use addSnapshotChannel. *==========================================================================*/ int32_t QCamera2HardwareInterface::addCaptureChannel() { int32_t rc = NO_ERROR; QCameraPicChannel *pChannel = NULL; char value[PROPERTY_VALUE_MAX]; bool raw_yuv = false; if (m_channels[QCAMERA_CH_TYPE_CAPTURE] != NULL) { delete m_channels[QCAMERA_CH_TYPE_CAPTURE]; m_channels[QCAMERA_CH_TYPE_CAPTURE] = NULL; } pChannel = new QCameraPicChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for capture channel", __func__); return NO_MEMORY; } // Capture channel, only need snapshot and postview streams start together mm_camera_channel_attr_t attr; memset(&attr, 0, sizeof(mm_camera_channel_attr_t)); if ( mLongshotEnabled ) { attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_BURST; attr.look_back = mParameters.getZSLBackLookCount(); attr.water_mark = mParameters.getZSLQueueDepth(); } else { attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_CONTINUOUS; } attr.max_unmatched_frames = mParameters.getMaxUnmatchedFramesInQueue(); rc = pChannel->init(&attr, capture_channel_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: init capture channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } // meta data stream always coexists with snapshot in regular capture case rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_METADATA, metadata_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add metadata stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } if (!mLongshotEnabled) { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_POSTVIEW, NULL, this); if (rc != NO_ERROR) { ALOGE("%s: add postview stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } } else { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_PREVIEW, preview_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add preview stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } } rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_SNAPSHOT, NULL, this); if (rc != NO_ERROR) { ALOGE("%s: add snapshot stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } property_get("persist.camera.raw_yuv", value, "0"); raw_yuv = atoi(value) > 0 ? true : false; if ( raw_yuv ) { rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_RAW, snapshot_raw_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add raw stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } } m_channels[QCAMERA_CH_TYPE_CAPTURE] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addMetaDataChannel * * DESCRIPTION: add a meta data channel that contains a metadata stream * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addMetaDataChannel() { int32_t rc = NO_ERROR; QCameraChannel *pChannel = NULL; if (m_channels[QCAMERA_CH_TYPE_METADATA] != NULL) { delete m_channels[QCAMERA_CH_TYPE_METADATA]; m_channels[QCAMERA_CH_TYPE_METADATA] = NULL; } pChannel = new QCameraChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for metadata channel", __func__); return NO_MEMORY; } rc = pChannel->init(NULL, NULL, NULL); if (rc != NO_ERROR) { ALOGE("%s: init metadata channel failed, ret = %d", __func__, rc); delete pChannel; return rc; } rc = addStreamToChannel(pChannel, CAM_STREAM_TYPE_METADATA, metadata_stream_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: add metadata stream failed, ret = %d", __func__, rc); delete pChannel; return rc; } m_channels[QCAMERA_CH_TYPE_METADATA] = pChannel; return rc; } /*=========================================================================== * FUNCTION : addReprocChannel * * DESCRIPTION: add a reprocess channel that will do reprocess on frames * coming from input channel * * PARAMETERS : * @pInputChannel : ptr to input channel whose frames will be post-processed * * RETURN : Ptr to the newly created channel obj. NULL if failed. *==========================================================================*/ QCameraReprocessChannel *QCamera2HardwareInterface::addReprocChannel( QCameraChannel *pInputChannel) { int32_t rc = NO_ERROR; QCameraReprocessChannel *pChannel = NULL; const char *effect; if (pInputChannel == NULL) { ALOGE("%s: input channel obj is NULL", __func__); return NULL; } pChannel = new QCameraReprocessChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for reprocess channel", __func__); return NULL; } // Capture channel, only need snapshot and postview streams start together mm_camera_channel_attr_t attr; memset(&attr, 0, sizeof(mm_camera_channel_attr_t)); attr.notify_mode = MM_CAMERA_SUPER_BUF_NOTIFY_CONTINUOUS; attr.max_unmatched_frames = mParameters.getMaxUnmatchedFramesInQueue(); rc = pChannel->init(&attr, postproc_channel_cb_routine, this); if (rc != NO_ERROR) { ALOGE("%s: init reprocess channel failed, ret = %d", __func__, rc); delete pChannel; return NULL; } CDBG_HIGH("%s: Before pproc config check, ret = %x", __func__, gCamCapability[mCameraId]->min_required_pp_mask); // pp feature config cam_pp_feature_config_t pp_config; uint32_t required_mask = gCamCapability[mCameraId]->min_required_pp_mask; memset(&pp_config, 0, sizeof(cam_pp_feature_config_t)); if (mParameters.isZSLMode() || (required_mask & CAM_QCOM_FEATURE_CPP)) { if (gCamCapability[mCameraId]->min_required_pp_mask & CAM_QCOM_FEATURE_EFFECT) { pp_config.feature_mask |= CAM_QCOM_FEATURE_EFFECT; effect = mParameters.get(CameraParameters::KEY_EFFECT); if (effect != NULL) pp_config.effect = getEffectValue(effect); } if ((gCamCapability[mCameraId]->min_required_pp_mask & CAM_QCOM_FEATURE_SHARPNESS) && !mParameters.isOptiZoomEnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_SHARPNESS; pp_config.sharpness = mParameters.getInt(QCameraParameters::KEY_QC_SHARPNESS); } if (gCamCapability[mCameraId]->min_required_pp_mask & CAM_QCOM_FEATURE_CROP) { pp_config.feature_mask |= CAM_QCOM_FEATURE_CROP; } if (mParameters.isWNREnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_DENOISE2D; pp_config.denoise2d.denoise_enable = 1; pp_config.denoise2d.process_plates = mParameters.getWaveletDenoiseProcessPlate(); } if (required_mask & CAM_QCOM_FEATURE_CPP) { pp_config.feature_mask |= CAM_QCOM_FEATURE_CPP; } } if (isCACEnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_CAC; } if (needRotationReprocess()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_CPP; int rotation = getJpegRotation(); if (rotation == 0) { pp_config.rotation = ROTATE_0; } else if (rotation == 90) { pp_config.rotation = ROTATE_90; } else if (rotation == 180) { pp_config.rotation = ROTATE_180; } else if (rotation == 270) { pp_config.rotation = ROTATE_270; } } uint8_t minStreamBufNum = getBufNumRequired(CAM_STREAM_TYPE_OFFLINE_PROC); if (mParameters.isHDREnabled()){ pp_config.feature_mask |= CAM_QCOM_FEATURE_HDR; pp_config.hdr_param.hdr_enable = 1; pp_config.hdr_param.hdr_need_1x = mParameters.isHDR1xFrameEnabled(); pp_config.hdr_param.hdr_mode = CAM_HDR_MODE_MULTIFRAME; } else { pp_config.feature_mask &= ~CAM_QCOM_FEATURE_HDR; pp_config.hdr_param.hdr_enable = 0; } if(needScaleReprocess()){ pp_config.feature_mask |= CAM_QCOM_FEATURE_SCALE; mParameters.m_reprocScaleParam.getPicSizeFromAPK( pp_config.scale_param.output_width, pp_config.scale_param.output_height); } CDBG_HIGH("%s: After pproc config check, ret = %x", __func__, pp_config.feature_mask); if(mParameters.isUbiFocusEnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_UBIFOCUS; } else { pp_config.feature_mask &= ~CAM_QCOM_FEATURE_UBIFOCUS; } if(mParameters.isChromaFlashEnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_CHROMA_FLASH; //TODO: check flash value for captured image, then assign. pp_config.flash_value = CAM_FLASH_ON; } else { pp_config.feature_mask &= ~CAM_QCOM_FEATURE_CHROMA_FLASH; } if(mParameters.isOptiZoomEnabled()) { pp_config.feature_mask |= CAM_QCOM_FEATURE_OPTIZOOM; pp_config.zoom_level = (uint8_t) mParameters.getInt(CameraParameters::KEY_ZOOM); } else { pp_config.feature_mask &= ~CAM_QCOM_FEATURE_OPTIZOOM; } //WNR and HDR happen inline. No extra buffers needed. uint32_t temp_feature_mask = pp_config.feature_mask; temp_feature_mask &= ~CAM_QCOM_FEATURE_DENOISE2D; temp_feature_mask &= ~CAM_QCOM_FEATURE_HDR; if (temp_feature_mask && mParameters.isHDREnabled()) { minStreamBufNum = 1 + mParameters.getNumOfExtraHDRInBufsIfNeeded(); } // Add non inplace image lib buffers only when ppproc is present, // becuase pproc is non inplace and input buffers for img lib // are output for pproc and this number of extra buffers is required // If pproc is not there, input buffers for imglib are from snapshot stream uint8_t imglib_extra_bufs = mParameters.getNumOfExtraBuffersForImageProc(); if (temp_feature_mask && imglib_extra_bufs) { // 1 is added because getNumOfExtraBuffersForImageProc returns extra // buffers assuming number of capture is already added minStreamBufNum += imglib_extra_bufs + 1; } CDBG_HIGH("%s: Allocating %d reproc buffers",__func__,minStreamBufNum); bool offlineReproc = isRegularCapture(); rc = pChannel->addReprocStreamsFromSource(*this, pp_config, pInputChannel, minStreamBufNum, mParameters.getNumOfSnapshots(), &gCamCapability[mCameraId]->padding_info, mParameters, mLongshotEnabled, offlineReproc); if (rc != NO_ERROR) { delete pChannel; return NULL; } return pChannel; } /*=========================================================================== * FUNCTION : addOfflineReprocChannel * * DESCRIPTION: add a offline reprocess channel contains one reproc stream, * that will do reprocess on frames coming from external images * * PARAMETERS : * @img_config : offline reporcess image info * @pp_feature : pp feature config * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ QCameraReprocessChannel *QCamera2HardwareInterface::addOfflineReprocChannel( cam_pp_offline_src_config_t &img_config, cam_pp_feature_config_t &pp_feature, stream_cb_routine stream_cb, void *userdata) { int32_t rc = NO_ERROR; QCameraReprocessChannel *pChannel = NULL; pChannel = new QCameraReprocessChannel(mCameraHandle->camera_handle, mCameraHandle->ops); if (NULL == pChannel) { ALOGE("%s: no mem for reprocess channel", __func__); return NULL; } rc = pChannel->init(NULL, NULL, NULL); if (rc != NO_ERROR) { ALOGE("%s: init reprocess channel failed, ret = %d", __func__, rc); delete pChannel; return NULL; } QCameraHeapMemory *pStreamInfo = allocateStreamInfoBuf(CAM_STREAM_TYPE_OFFLINE_PROC); if (pStreamInfo == NULL) { ALOGE("%s: no mem for stream info buf", __func__); delete pChannel; return NULL; } cam_stream_info_t *streamInfoBuf = (cam_stream_info_t *)pStreamInfo->getPtr(0); memset(streamInfoBuf, 0, sizeof(cam_stream_info_t)); streamInfoBuf->stream_type = CAM_STREAM_TYPE_OFFLINE_PROC; streamInfoBuf->fmt = img_config.input_fmt; streamInfoBuf->dim = img_config.input_dim; streamInfoBuf->buf_planes = img_config.input_buf_planes; streamInfoBuf->streaming_mode = CAM_STREAMING_MODE_BURST; streamInfoBuf->num_of_burst = img_config.num_of_bufs; streamInfoBuf->reprocess_config.pp_type = CAM_OFFLINE_REPROCESS_TYPE; streamInfoBuf->reprocess_config.offline = img_config; streamInfoBuf->reprocess_config.pp_feature_config = pp_feature; rc = pChannel->addStream(*this, pStreamInfo, img_config.num_of_bufs, &gCamCapability[mCameraId]->padding_info, stream_cb, userdata, false); if (rc != NO_ERROR) { ALOGE("%s: add reprocess stream failed, ret = %d", __func__, rc); pStreamInfo->deallocate(); delete pStreamInfo; delete pChannel; return NULL; } return pChannel; } /*=========================================================================== * FUNCTION : addChannel * * DESCRIPTION: add a channel by its type * * PARAMETERS : * @ch_type : channel type * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::addChannel(qcamera_ch_type_enum_t ch_type) { int32_t rc = UNKNOWN_ERROR; switch (ch_type) { case QCAMERA_CH_TYPE_ZSL: rc = addZSLChannel(); break; case QCAMERA_CH_TYPE_CAPTURE: rc = addCaptureChannel(); break; case QCAMERA_CH_TYPE_PREVIEW: rc = addPreviewChannel(); break; case QCAMERA_CH_TYPE_VIDEO: rc = addVideoChannel(); break; case QCAMERA_CH_TYPE_SNAPSHOT: rc = addSnapshotChannel(); break; case QCAMERA_CH_TYPE_RAW: rc = addRawChannel(); break; case QCAMERA_CH_TYPE_METADATA: rc = addMetaDataChannel(); break; default: break; } return rc; } /*=========================================================================== * FUNCTION : delChannel * * DESCRIPTION: delete a channel by its type * * PARAMETERS : * @ch_type : channel type * @destroy : delete context as well * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::delChannel(qcamera_ch_type_enum_t ch_type, bool destroy) { if (m_channels[ch_type] != NULL) { if (destroy) { delete m_channels[ch_type]; m_channels[ch_type] = NULL; } else { m_channels[ch_type]->deleteChannel(); } } return NO_ERROR; } /*=========================================================================== * FUNCTION : startChannel * * DESCRIPTION: start a channel by its type * * PARAMETERS : * @ch_type : channel type * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::startChannel(qcamera_ch_type_enum_t ch_type) { int32_t rc = UNKNOWN_ERROR; if (m_channels[ch_type] != NULL) { rc = m_channels[ch_type]->config(); if (NO_ERROR == rc) { rc = m_channels[ch_type]->start(); } } return rc; } /*=========================================================================== * FUNCTION : stopChannel * * DESCRIPTION: stop a channel by its type * * PARAMETERS : * @ch_type : channel type * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::stopChannel(qcamera_ch_type_enum_t ch_type) { int32_t rc = UNKNOWN_ERROR; if (m_channels[ch_type] != NULL) { rc = m_channels[ch_type]->stop(); } return rc; } /*=========================================================================== * FUNCTION : preparePreview * * DESCRIPTION: add channels needed for preview * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::preparePreview() { int32_t rc = NO_ERROR; if (mParameters.isZSLMode() && mParameters.getRecordingHintValue() !=true) { rc = addChannel(QCAMERA_CH_TYPE_ZSL); if (rc != NO_ERROR) { return rc; } } else { bool recordingHint = mParameters.getRecordingHintValue(); if(recordingHint) { cam_dimension_t videoSize; mParameters.getVideoSize(&videoSize.width, &videoSize.height); if (!is4k2kResolution(&videoSize)) { rc = addChannel(QCAMERA_CH_TYPE_SNAPSHOT); if (rc != NO_ERROR) { return rc; } } rc = addChannel(QCAMERA_CH_TYPE_VIDEO); if (rc != NO_ERROR) { delChannel(QCAMERA_CH_TYPE_SNAPSHOT); return rc; } } rc = addChannel(QCAMERA_CH_TYPE_PREVIEW); if (rc != NO_ERROR) { if (recordingHint) { delChannel(QCAMERA_CH_TYPE_SNAPSHOT); delChannel(QCAMERA_CH_TYPE_VIDEO); } return rc; } if (!recordingHint) { waitDefferedWork(mMetadataJob); } } return rc; } /*=========================================================================== * FUNCTION : unpreparePreview * * DESCRIPTION: delete channels for preview * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::unpreparePreview() { delChannel(QCAMERA_CH_TYPE_ZSL); delChannel(QCAMERA_CH_TYPE_PREVIEW); delChannel(QCAMERA_CH_TYPE_VIDEO); delChannel(QCAMERA_CH_TYPE_SNAPSHOT); } /*=========================================================================== * FUNCTION : playShutter * * DESCRIPTION: send request to play shutter sound * * PARAMETERS : none * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::playShutter(){ if (mNotifyCb == NULL || msgTypeEnabledWithLock(CAMERA_MSG_SHUTTER) == 0){ CDBG("%s: shutter msg not enabled or NULL cb", __func__); return; } CDBG_HIGH("%s: CAMERA_MSG_SHUTTER ", __func__); qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_NOTIFY_CALLBACK; cbArg.msg_type = CAMERA_MSG_SHUTTER; cbArg.ext1 = 0; cbArg.ext2 = false; m_cbNotifier.notifyCallback(cbArg); } /*=========================================================================== * FUNCTION : getChannelByHandle * * DESCRIPTION: return a channel by its handle * * PARAMETERS : * @channelHandle : channel handle * * RETURN : a channel obj if found, NULL if not found *==========================================================================*/ QCameraChannel *QCamera2HardwareInterface::getChannelByHandle(uint32_t channelHandle) { for(int i = 0; i < QCAMERA_CH_TYPE_MAX; i++) { if (m_channels[i] != NULL && m_channels[i]->getMyHandle() == channelHandle) { return m_channels[i]; } } return NULL; } /*=========================================================================== * FUNCTION : processFaceDetectionReuslt * * DESCRIPTION: process face detection reuslt * * PARAMETERS : * @fd_data : ptr to face detection result struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processFaceDetectionResult(cam_face_detection_data_t *fd_data) { if (!mParameters.isFaceDetectionEnabled()) { CDBG_HIGH("%s: FaceDetection not enabled, no ops here", __func__); return NO_ERROR; } qcamera_face_detect_type_t fd_type = fd_data->fd_type; if ((NULL == mDataCb) || (fd_type == QCAMERA_FD_PREVIEW && !msgTypeEnabled(CAMERA_MSG_PREVIEW_METADATA)) || (fd_type == QCAMERA_FD_SNAPSHOT && !msgTypeEnabled(CAMERA_MSG_META_DATA)) ) { CDBG_HIGH("%s: metadata msgtype not enabled, no ops here", __func__); return NO_ERROR; } cam_dimension_t display_dim; mParameters.getStreamDimension(CAM_STREAM_TYPE_PREVIEW, display_dim); if (display_dim.width <= 0 || display_dim.height <= 0) { ALOGE("%s: Invalid preview width or height (%d x %d)", __func__, display_dim.width, display_dim.height); return UNKNOWN_ERROR; } // process face detection result // need separate face detection in preview or snapshot type size_t faceResultSize = 0; size_t data_len = 0; if(fd_type == QCAMERA_FD_PREVIEW){ //fd for preview frames faceResultSize = sizeof(camera_frame_metadata_t); faceResultSize += sizeof(camera_face_t) * MAX_ROI; }else if(fd_type == QCAMERA_FD_SNAPSHOT){ // fd for snapshot frames //check if face is detected in this frame if(fd_data->num_faces_detected > 0){ data_len = sizeof(camera_frame_metadata_t) + sizeof(camera_face_t) * fd_data->num_faces_detected; }else{ //no face data_len = 0; } faceResultSize = 1 *sizeof(int) //meta data type + 1 *sizeof(int) // meta data len + data_len; //data } camera_memory_t *faceResultBuffer = mGetMemory(-1, faceResultSize, 1, mCallbackCookie); if ( NULL == faceResultBuffer ) { ALOGE("%s: Not enough memory for face result data", __func__); return NO_MEMORY; } unsigned char *pFaceResult = ( unsigned char * ) faceResultBuffer->data; memset(pFaceResult, 0, faceResultSize); unsigned char *faceData = NULL; if(fd_type == QCAMERA_FD_PREVIEW){ faceData = pFaceResult; }else if(fd_type == QCAMERA_FD_SNAPSHOT){ //need fill meta type and meta data len first int *data_header = (int* )pFaceResult; data_header[0] = CAMERA_META_DATA_FD; data_header[1] = data_len; if(data_len <= 0){ //if face is not valid or do not have face, return qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_DATA_CALLBACK; cbArg.msg_type = CAMERA_MSG_META_DATA; cbArg.data = faceResultBuffer; cbArg.user_data = faceResultBuffer; cbArg.cookie = this; cbArg.release_cb = releaseCameraMemory; int32_t rc = m_cbNotifier.notifyCallback(cbArg); if (rc != NO_ERROR) { ALOGE("%s: fail sending notification", __func__); faceResultBuffer->release(faceResultBuffer); } return rc; } faceData = pFaceResult + 2 *sizeof(int); //skip two int length } camera_frame_metadata_t *roiData = (camera_frame_metadata_t * ) faceData; camera_face_t *faces = (camera_face_t *) ( faceData + sizeof(camera_frame_metadata_t) ); roiData->number_of_faces = fd_data->num_faces_detected; roiData->faces = faces; if (roiData->number_of_faces > 0) { for (int i = 0; i < roiData->number_of_faces; i++) { faces[i].id = fd_data->faces[i].face_id; faces[i].score = fd_data->faces[i].score; // left faces[i].rect[0] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].face_boundary.left, display_dim.width, 2000, -1000); // top faces[i].rect[1] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].face_boundary.top, display_dim.height, 2000, -1000); // right faces[i].rect[2] = faces[i].rect[0] + MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].face_boundary.width, display_dim.width, 2000, 0); // bottom faces[i].rect[3] = faces[i].rect[1] + MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].face_boundary.height, display_dim.height, 2000, 0); // Center of left eye faces[i].left_eye[0] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].left_eye_center.x, display_dim.width, 2000, -1000); faces[i].left_eye[1] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].left_eye_center.y, display_dim.height, 2000, -1000); // Center of right eye faces[i].right_eye[0] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].right_eye_center.x, display_dim.width, 2000, -1000); faces[i].right_eye[1] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].right_eye_center.y, display_dim.height, 2000, -1000); // Center of mouth faces[i].mouth[0] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].mouth_center.x, display_dim.width, 2000, -1000); faces[i].mouth[1] = MAP_TO_DRIVER_COORDINATE(fd_data->faces[i].mouth_center.y, display_dim.height, 2000, -1000); faces[i].smile_degree = fd_data->faces[i].smile_degree; faces[i].smile_score = fd_data->faces[i].smile_confidence; faces[i].blink_detected = fd_data->faces[i].blink_detected; faces[i].face_recognised = fd_data->faces[i].face_recognised; faces[i].gaze_angle = fd_data->faces[i].gaze_angle; // upscale by 2 to recover from demaen downscaling faces[i].updown_dir = fd_data->faces[i].updown_dir * 2; faces[i].leftright_dir = fd_data->faces[i].leftright_dir * 2; faces[i].roll_dir = fd_data->faces[i].roll_dir * 2; faces[i].leye_blink = fd_data->faces[i].left_blink; faces[i].reye_blink = fd_data->faces[i].right_blink; faces[i].left_right_gaze = fd_data->faces[i].left_right_gaze; faces[i].top_bottom_gaze = fd_data->faces[i].top_bottom_gaze; } } qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_DATA_CALLBACK; if(fd_type == QCAMERA_FD_PREVIEW){ cbArg.msg_type = CAMERA_MSG_PREVIEW_METADATA; }else if(fd_type == QCAMERA_FD_SNAPSHOT){ cbArg.msg_type = CAMERA_MSG_META_DATA; } cbArg.data = faceResultBuffer; cbArg.metadata = roiData; cbArg.user_data = faceResultBuffer; cbArg.cookie = this; cbArg.release_cb = releaseCameraMemory; int32_t rc = m_cbNotifier.notifyCallback(cbArg); if (rc != NO_ERROR) { ALOGE("%s: fail sending notification", __func__); faceResultBuffer->release(faceResultBuffer); } return rc; } /*=========================================================================== * FUNCTION : releaseCameraMemory * * DESCRIPTION: releases camera memory objects * * PARAMETERS : * @data : buffer to be released * @cookie : context data * @cbStatus: callback status * * RETURN : None *==========================================================================*/ void QCamera2HardwareInterface::releaseCameraMemory(void *data, void */*cookie*/, int32_t /*cbStatus*/) { camera_memory_t *mem = ( camera_memory_t * ) data; if ( NULL != mem ) { mem->release(mem); } } /*=========================================================================== * FUNCTION : returnStreamBuffer * * DESCRIPTION: returns back a stream buffer * * PARAMETERS : * @data : buffer to be released * @cookie : context data * @cbStatus: callback status * * RETURN : None *==========================================================================*/ void QCamera2HardwareInterface::returnStreamBuffer(void *data, void *cookie, int32_t /*cbStatus*/) { QCameraStream *stream = ( QCameraStream * ) cookie; int idx = ( int ) data; if ( ( NULL != stream )) { stream->bufDone(idx); } } /*=========================================================================== * FUNCTION : processHistogramStats * * DESCRIPTION: process histogram stats * * PARAMETERS : * @hist_data : ptr to histogram stats struct * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::processHistogramStats(cam_hist_stats_t &stats_data) { if (!mParameters.isHistogramEnabled()) { CDBG("%s: Histogram not enabled, no ops here", __func__); return NO_ERROR; } camera_memory_t *histBuffer = mGetMemory(-1, sizeof(cam_histogram_data_t), 1, mCallbackCookie); if ( NULL == histBuffer ) { ALOGE("%s: Not enough memory for histogram data", __func__); return NO_MEMORY; } cam_histogram_data_t *pHistData = (cam_histogram_data_t *)histBuffer->data; if (pHistData == NULL) { ALOGE("%s: memory data ptr is NULL", __func__); return UNKNOWN_ERROR; } switch (stats_data.type) { case CAM_HISTOGRAM_TYPE_BAYER: *pHistData = stats_data.bayer_stats.gb_stats; break; case CAM_HISTOGRAM_TYPE_YUV: *pHistData = stats_data.yuv_stats; break; } qcamera_callback_argm_t cbArg; memset(&cbArg, 0, sizeof(qcamera_callback_argm_t)); cbArg.cb_type = QCAMERA_DATA_CALLBACK; cbArg.msg_type = CAMERA_MSG_STATS_DATA; cbArg.data = histBuffer; cbArg.user_data = histBuffer; cbArg.cookie = this; cbArg.release_cb = releaseCameraMemory; int32_t rc = m_cbNotifier.notifyCallback(cbArg); if (rc != NO_ERROR) { ALOGE("%s: fail sending notification", __func__); histBuffer->release(histBuffer); } return NO_ERROR; } /*=========================================================================== * FUNCTION : calcThermalLevel * * DESCRIPTION: Calculates the target fps range depending on * the thermal level. * * PARAMETERS : * @level : received thermal level * @minFPS : minimum configured fps range * @maxFPS : maximum configured fps range * @adjustedRange : target fps range * @skipPattern : target skip pattern * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::calcThermalLevel( qcamera_thermal_level_enum_t level, const int minFPS, const int maxFPS, cam_fps_range_t &adjustedRange, enum msm_vfe_frame_skip_pattern &skipPattern) { // Initialize video fps to preview fps int minVideoFps = minFPS, maxVideoFps = maxFPS; cam_fps_range_t videoFps; // If HFR mode, update video fps accordingly if(isHFRMode()) { mParameters.getHfrFps(videoFps); minVideoFps = videoFps.video_min_fps; maxVideoFps = videoFps.video_max_fps; } CDBG_HIGH("%s: level: %d, preview minfps %d, preview maxfpS %d" "video minfps %d, video maxfpS %d", __func__, level, minFPS, maxFPS, minVideoFps, maxVideoFps); switch(level) { case QCAMERA_THERMAL_NO_ADJUSTMENT: { adjustedRange.min_fps = minFPS / 1000.0f; adjustedRange.max_fps = maxFPS / 1000.0f; adjustedRange.video_min_fps = minVideoFps / 1000.0f; adjustedRange.video_max_fps = maxVideoFps / 1000.0f; skipPattern = NO_SKIP; } break; case QCAMERA_THERMAL_SLIGHT_ADJUSTMENT: { adjustedRange.min_fps = (minFPS / 2) / 1000.0f; adjustedRange.max_fps = (maxFPS / 2) / 1000.0f; adjustedRange.video_min_fps = (minVideoFps / 2) / 1000.0f; adjustedRange.video_max_fps = (maxVideoFps / 2 ) / 1000.0f; if ( adjustedRange.min_fps < 1 ) { adjustedRange.min_fps = 1; } if ( adjustedRange.max_fps < 1 ) { adjustedRange.max_fps = 1; } if ( adjustedRange.video_min_fps < 1 ) { adjustedRange.video_min_fps = 1; } if ( adjustedRange.video_max_fps < 1 ) { adjustedRange.video_max_fps = 1; } skipPattern = EVERY_2FRAME; } break; case QCAMERA_THERMAL_BIG_ADJUSTMENT: { adjustedRange.min_fps = (minFPS / 4) / 1000.0f; adjustedRange.max_fps = (maxFPS / 4) / 1000.0f; adjustedRange.video_min_fps = (minVideoFps / 4) / 1000.0f; adjustedRange.video_max_fps = (maxVideoFps / 4 ) / 1000.0f; if ( adjustedRange.min_fps < 1 ) { adjustedRange.min_fps = 1; } if ( adjustedRange.max_fps < 1 ) { adjustedRange.max_fps = 1; } if ( adjustedRange.video_min_fps < 1 ) { adjustedRange.video_min_fps = 1; } if ( adjustedRange.video_max_fps < 1 ) { adjustedRange.video_max_fps = 1; } skipPattern = EVERY_4FRAME; } break; case QCAMERA_THERMAL_SHUTDOWN: { // Stop Preview? // Set lowest min FPS for now adjustedRange.min_fps = minFPS/1000.0f; adjustedRange.max_fps = minFPS/1000.0f; for ( int i = 0 ; i < gCamCapability[mCameraId]->fps_ranges_tbl_cnt ; i++ ) { if ( gCamCapability[mCameraId]->fps_ranges_tbl[i].min_fps < adjustedRange.min_fps ) { adjustedRange.min_fps = gCamCapability[mCameraId]->fps_ranges_tbl[i].min_fps; adjustedRange.max_fps = adjustedRange.min_fps; } } skipPattern = MAX_SKIP; adjustedRange.video_min_fps = adjustedRange.min_fps; adjustedRange.video_max_fps = adjustedRange.max_fps; } break; default: { CDBG("%s: Invalid thermal level %d", __func__, level); return BAD_VALUE; } break; } CDBG_HIGH("%s: Thermal level %d, FPS [%3.2f,%3.2f, %3.2f,%3.2f], frameskip %d", __func__, level, adjustedRange.min_fps, adjustedRange.max_fps, adjustedRange.video_min_fps, adjustedRange.video_max_fps,skipPattern); return NO_ERROR; } /*=========================================================================== * FUNCTION : recalcFPSRange * * DESCRIPTION: adjust the configured fps range regarding * the last thermal level. * * PARAMETERS : * @minFPS : minimum configured fps range * @maxFPS : maximum configured fps range * @adjustedRange : target fps range * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::recalcFPSRange(int &minFPS, int &maxFPS, cam_fps_range_t &adjustedRange) { enum msm_vfe_frame_skip_pattern skipPattern; calcThermalLevel(mThermalLevel, minFPS, maxFPS, adjustedRange, skipPattern); return NO_ERROR; } /*=========================================================================== * FUNCTION : updateThermalLevel * * DESCRIPTION: update thermal level depending on thermal events * * PARAMETERS : * @level : thermal level * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::updateThermalLevel( qcamera_thermal_level_enum_t level) { int ret = NO_ERROR; cam_fps_range_t adjustedRange; int minFPS, maxFPS; enum msm_vfe_frame_skip_pattern skipPattern; pthread_mutex_lock(&m_parm_lock); if (!mCameraOpened) { CDBG("%s: Camera is not opened, no need to update camera parameters", __func__); pthread_mutex_unlock(&m_parm_lock); return NO_ERROR; } mParameters.getPreviewFpsRange(&minFPS, &maxFPS); qcamera_thermal_mode thermalMode = mParameters.getThermalMode(); calcThermalLevel(level, minFPS, maxFPS, adjustedRange, skipPattern); mThermalLevel = level; if (thermalMode == QCAMERA_THERMAL_ADJUST_FPS) ret = mParameters.adjustPreviewFpsRange(&adjustedRange); else if (thermalMode == QCAMERA_THERMAL_ADJUST_FRAMESKIP) ret = mParameters.setFrameSkip(skipPattern); else ALOGE("%s: Incorrect thermal mode %d", __func__, thermalMode); pthread_mutex_unlock(&m_parm_lock); return ret; } /*=========================================================================== * FUNCTION : updateParameters * * DESCRIPTION: update parameters * * PARAMETERS : * @parms : input parameters string * @needRestart : output, flag to indicate if preview restart is needed * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int QCamera2HardwareInterface::updateParameters(const char *parms, bool &needRestart) { int rc = NO_ERROR; pthread_mutex_lock(&m_parm_lock); String8 str = String8(parms); QCameraParameters param(str); rc = mParameters.updateParameters(param, needRestart); // update stream based parameter settings for (int i = 0; i < QCAMERA_CH_TYPE_MAX; i++) { if (m_channels[i] != NULL) { m_channels[i]->UpdateStreamBasedParameters(mParameters); } } pthread_mutex_unlock(&m_parm_lock); return rc; } /*=========================================================================== * FUNCTION : commitParameterChanges * * DESCRIPTION: commit parameter changes to the backend to take effect * * PARAMETERS : none * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code * NOTE : This function must be called after updateParameters. * Otherwise, no change will be passed to backend to take effect. *==========================================================================*/ int QCamera2HardwareInterface::commitParameterChanges() { int rc = NO_ERROR; pthread_mutex_lock(&m_parm_lock); rc = mParameters.commitParameters(); if (rc == NO_ERROR) { // update number of snapshot based on committed parameters setting rc = mParameters.setNumOfSnapshot(); } pthread_mutex_unlock(&m_parm_lock); return rc; } /*=========================================================================== * FUNCTION : needDebugFps * * DESCRIPTION: if fps log info need to be printed out * * PARAMETERS : none * * RETURN : true: need print out fps log * false: no need to print out fps log *==========================================================================*/ bool QCamera2HardwareInterface::needDebugFps() { bool needFps = false; pthread_mutex_lock(&m_parm_lock); needFps = mParameters.isFpsDebugEnabled(); pthread_mutex_unlock(&m_parm_lock); return needFps; } /*=========================================================================== * FUNCTION : isCACEnabled * * DESCRIPTION: if CAC is enabled * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::isCACEnabled() { char prop[PROPERTY_VALUE_MAX]; memset(prop, 0, sizeof(prop)); property_get("persist.camera.feature.cac", prop, "0"); int enableCAC = atoi(prop); return enableCAC == 1; } /*=========================================================================== * FUNCTION : is4k2kResolution * * DESCRIPTION: if resolution is 4k x 2k or true 4k x 2k * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::is4k2kResolution(cam_dimension_t* resolution) { bool enabled = false; if ((resolution->width == 4096 && resolution->height == 2160) || (resolution->width == 3840 && resolution->height == 2160) ) { enabled = true; } return enabled; } /*=========================================================================== * * FUNCTION : isPreviewRestartEnabled * * DESCRIPTION: Check whether preview should be restarted automatically * during image capture. * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::isPreviewRestartEnabled() { char prop[PROPERTY_VALUE_MAX]; memset(prop, 0, sizeof(prop)); property_get("persist.camera.feature.restart", prop, "0"); int earlyRestart = atoi(prop); return earlyRestart == 1; } /*=========================================================================== ======= * FUNCTION : isAFRunning * * DESCRIPTION: if AF is in progress while in Auto/Macro focus modes * * PARAMETERS : none * * RETURN : true: AF in progress * false: AF not in progress *==========================================================================*/ bool QCamera2HardwareInterface::isAFRunning() { bool isAFInProgress = (m_currentFocusState == CAM_AF_SCANNING && (mParameters.getFocusMode() == CAM_FOCUS_MODE_AUTO || mParameters.getFocusMode() == CAM_FOCUS_MODE_MACRO)); return isAFInProgress; } /*=========================================================================== >>>>>>> c709c9a... Camera: Block CancelAF till HAL receives AF event. * FUNCTION : needReprocess * * DESCRIPTION: if reprocess is needed * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::needReprocess() { pthread_mutex_lock(&m_parm_lock); if (!mParameters.isJpegPictureFormat() && !mParameters.isNV21PictureFormat()) { // RAW image, no need to reprocess pthread_mutex_unlock(&m_parm_lock); return false; } if (mParameters.isHDREnabled()) { CDBG_HIGH("%s: need do reprocess for HDR", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } uint32_t feature_mask = 0; uint32_t required_mask = 0; feature_mask = gCamCapability[mCameraId]->qcom_supported_feature_mask; required_mask = gCamCapability[mCameraId]->min_required_pp_mask; if (((feature_mask & CAM_QCOM_FEATURE_CPP) > 0) && (getJpegRotation() > 0) && (mParameters.getRecordingHintValue() == false)) { // current rotation is not zero, and pp has the capability to process rotation CDBG_HIGH("%s: need to do reprocess for rotation=%d", __func__, getJpegRotation()); pthread_mutex_unlock(&m_parm_lock); return true; } if (isZSLMode()) { if (((gCamCapability[mCameraId]->min_required_pp_mask > 0) || mParameters.isWNREnabled() || isCACEnabled())) { // TODO: add for ZSL HDR later CDBG_HIGH("%s: need do reprocess for ZSL WNR or min PP reprocess", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } int snapshot_flipMode = mParameters.getFlipMode(CAM_STREAM_TYPE_SNAPSHOT); if (snapshot_flipMode > 0) { CDBG_HIGH("%s: Need do flip for snapshot in ZSL mode", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } } else { if (required_mask & CAM_QCOM_FEATURE_CPP) { ALOGD("%s: Need CPP in non-ZSL mode", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } } if ((gCamCapability[mCameraId]->qcom_supported_feature_mask & CAM_QCOM_FEATURE_SCALE) > 0 && mParameters.m_reprocScaleParam.isScaleEnabled() && mParameters.m_reprocScaleParam.isUnderScaling()) { // Reproc Scale is enaled and also need Scaling to current Snapshot CDBG_HIGH("%s: need do reprocess for scale", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } if (mParameters.isUbiFocusEnabled() | mParameters.isChromaFlashEnabled() | mParameters.isHDREnabled() | mParameters.isOptiZoomEnabled()) { CDBG_HIGH("%s: need reprocess for |UbiFocus=%d|ChramaFlash=%d|OptiZoom=%d|", __func__, mParameters.isUbiFocusEnabled(), mParameters.isChromaFlashEnabled(), mParameters.isOptiZoomEnabled()); pthread_mutex_unlock(&m_parm_lock); return true; } pthread_mutex_unlock(&m_parm_lock); return false; } /*=========================================================================== * FUNCTION : needRotationReprocess * * DESCRIPTION: if rotation needs to be done by reprocess in pp * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::needRotationReprocess() { pthread_mutex_lock(&m_parm_lock); if (!mParameters.isJpegPictureFormat() && !mParameters.isNV21PictureFormat()) { // RAW image, no need to reprocess pthread_mutex_unlock(&m_parm_lock); return false; } uint32_t feature_mask = 0; feature_mask = gCamCapability[mCameraId]->qcom_supported_feature_mask; if (((feature_mask & CAM_QCOM_FEATURE_CPP) > 0) && (getJpegRotation() > 0)) { // current rotation is not zero // and pp has the capability to process rotation CDBG_HIGH("%s: need to do reprocess for rotation=%d", __func__, getJpegRotation()); pthread_mutex_unlock(&m_parm_lock); return true; } pthread_mutex_unlock(&m_parm_lock); return false; } /*=========================================================================== * FUNCTION : needScaleReprocess * * DESCRIPTION: if scale needs to be done by reprocess in pp * * PARAMETERS : none * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::needScaleReprocess() { pthread_mutex_lock(&m_parm_lock); if (!mParameters.isJpegPictureFormat() && !mParameters.isNV21PictureFormat()) { // RAW image, no need to reprocess pthread_mutex_unlock(&m_parm_lock); return false; } if ((gCamCapability[mCameraId]->qcom_supported_feature_mask & CAM_QCOM_FEATURE_SCALE) > 0 && mParameters.m_reprocScaleParam.isScaleEnabled() && mParameters.m_reprocScaleParam.isUnderScaling()) { // Reproc Scale is enaled and also need Scaling to current Snapshot CDBG_HIGH("%s: need do reprocess for scale", __func__); pthread_mutex_unlock(&m_parm_lock); return true; } pthread_mutex_unlock(&m_parm_lock); return false; } /*=========================================================================== * FUNCTION : getThumbnailSize * * DESCRIPTION: get user set thumbnail size * * PARAMETERS : * @dim : output of thumbnail dimension * * RETURN : none *==========================================================================*/ void QCamera2HardwareInterface::getThumbnailSize(cam_dimension_t &dim) { pthread_mutex_lock(&m_parm_lock); mParameters.getThumbnailSize(&dim.width, &dim.height); pthread_mutex_unlock(&m_parm_lock); } /*=========================================================================== * FUNCTION : getJpegQuality * * DESCRIPTION: get user set jpeg quality * * PARAMETERS : none * * RETURN : jpeg quality setting *==========================================================================*/ int QCamera2HardwareInterface::getJpegQuality() { int quality = 0; pthread_mutex_lock(&m_parm_lock); quality = mParameters.getJpegQuality(); pthread_mutex_unlock(&m_parm_lock); return quality; } /*=========================================================================== * FUNCTION : getJpegRotation * * DESCRIPTION: get rotation information to be passed into jpeg encoding * * PARAMETERS : none * * RETURN : rotation information *==========================================================================*/ int QCamera2HardwareInterface::getJpegRotation() { return mCaptureRotation; } /*=========================================================================== * FUNCTION : getOrientation * * DESCRIPTION: get rotation information from camera parameters * * PARAMETERS : none * * RETURN : rotation information *==========================================================================*/ void QCamera2HardwareInterface::getOrientation() { pthread_mutex_lock(&m_parm_lock); mCaptureRotation = mParameters.getJpegRotation(); pthread_mutex_unlock(&m_parm_lock); } /*=========================================================================== * FUNCTION : getExifData * * DESCRIPTION: get exif data to be passed into jpeg encoding * * PARAMETERS : none * * RETURN : exif data from user setting and GPS *==========================================================================*/ QCameraExif *QCamera2HardwareInterface::getExifData() { QCameraExif *exif = new QCameraExif(); if (exif == NULL) { ALOGE("%s: No memory for QCameraExif", __func__); return NULL; } int32_t rc = NO_ERROR; uint32_t count = 0; pthread_mutex_lock(&m_parm_lock); //set flash value mFlash = mParameters.getFlashValue(); mRedEye = mParameters.getRedEyeValue(); mFlashPresence = mParameters.getSupportedFlashModes(); // add exif entries char dateTime[20]; memset(dateTime, 0, sizeof(dateTime)); count = 20; rc = mParameters.getExifDateTime(dateTime, count); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_EXIF_DATE_TIME_ORIGINAL, EXIF_ASCII, count, (void *)dateTime); } else { ALOGE("%s: getExifDateTime failed", __func__); } rat_t focalLength; rc = mParameters.getExifFocalLength(&focalLength); if (rc == NO_ERROR) { exif->addEntry(EXIFTAGID_FOCAL_LENGTH, EXIF_RATIONAL, 1, (void *)&(focalLength)); } else { ALOGE("%s: getExifFocalLength failed", __func__); } uint16_t isoSpeed = mParameters.getExifIsoSpeed(); exif->addEntry(EXIFTAGID_ISO_SPEED_RATING, EXIF_SHORT, 1, (void *)&(isoSpeed)); char gpsProcessingMethod[EXIF_ASCII_PREFIX_SIZE + GPS_PROCESSING_METHOD_SIZE]; count = 0; rc = mParameters.getExifGpsProcessingMethod(gpsProcessingMethod, count); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_GPS_PROCESSINGMETHOD, EXIF_ASCII, count, (void *)gpsProcessingMethod); } else { CDBG("%s: getExifGpsProcessingMethod failed", __func__); } rat_t latitude[3]; char latRef[2]; rc = mParameters.getExifLatitude(latitude, latRef); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_GPS_LATITUDE, EXIF_RATIONAL, 3, (void *)latitude); exif->addEntry(EXIFTAGID_GPS_LATITUDE_REF, EXIF_ASCII, 2, (void *)latRef); } else { CDBG("%s: getExifLatitude failed", __func__); } rat_t longitude[3]; char lonRef[2]; rc = mParameters.getExifLongitude(longitude, lonRef); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_GPS_LONGITUDE, EXIF_RATIONAL, 3, (void *)longitude); exif->addEntry(EXIFTAGID_GPS_LONGITUDE_REF, EXIF_ASCII, 2, (void *)lonRef); } else { CDBG("%s: getExifLongitude failed", __func__); } rat_t altitude; char altRef; rc = mParameters.getExifAltitude(&altitude, &altRef); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_GPS_ALTITUDE, EXIF_RATIONAL, 1, (void *)&(altitude)); exif->addEntry(EXIFTAGID_GPS_ALTITUDE_REF, EXIF_BYTE, 1, (void *)&altRef); } else { CDBG("%s: getExifAltitude failed", __func__); } char gpsDateStamp[20]; rat_t gpsTimeStamp[3]; rc = mParameters.getExifGpsDateTimeStamp(gpsDateStamp, 20, gpsTimeStamp); if(rc == NO_ERROR) { exif->addEntry(EXIFTAGID_GPS_DATESTAMP, EXIF_ASCII, strlen(gpsDateStamp) + 1, (void *)gpsDateStamp); exif->addEntry(EXIFTAGID_GPS_TIMESTAMP, EXIF_RATIONAL, 3, (void *)gpsTimeStamp); } else { ALOGE("%s: getExifGpsDataTimeStamp failed", __func__); } pthread_mutex_unlock(&m_parm_lock); return exif; } /*=========================================================================== * FUNCTION : setHistogram * * DESCRIPTION: set if histogram should be enabled * * PARAMETERS : * @histogram_en : bool flag if histogram should be enabled * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::setHistogram(bool histogram_en) { return mParameters.setHistogram(histogram_en); } /*=========================================================================== * FUNCTION : setFaceDetection * * DESCRIPTION: set if face detection should be enabled * * PARAMETERS : * @enabled : bool flag if face detection should be enabled * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::setFaceDetection(bool enabled) { return mParameters.setFaceDetection(enabled); } /*=========================================================================== * FUNCTION : needProcessPreviewFrame * * DESCRIPTION: returns whether preview frame need to be displayed * * PARAMETERS : * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ bool QCamera2HardwareInterface::needProcessPreviewFrame() { return m_stateMachine.isPreviewRunning() && mParameters.isDisplayFrameNeeded(); }; /*=========================================================================== * FUNCTION : prepareHardwareForSnapshot * * DESCRIPTION: prepare hardware for snapshot, such as LED * * PARAMETERS : * @afNeeded: flag indicating if Auto Focus needs to be done during preparation * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::prepareHardwareForSnapshot(int32_t afNeeded) { CDBG_HIGH("[KPI Perf] %s: Prepare hardware such as LED",__func__); return mCameraHandle->ops->prepare_snapshot(mCameraHandle->camera_handle, afNeeded); } /*=========================================================================== * FUNCTION : needFDMetadata * * DESCRIPTION: check whether we need process Face Detection metadata in this chanel * * PARAMETERS : * @channel_type: channel type * * RETURN : true: needed * false: no need *==========================================================================*/ bool QCamera2HardwareInterface::needFDMetadata(qcamera_ch_type_enum_t channel_type) { //Note: Currently we only process ZSL channel bool value = false; if(channel_type == QCAMERA_CH_TYPE_ZSL){ //check if FD requirement is enabled if(mParameters.isSnapshotFDNeeded() && mParameters.isFaceDetectionEnabled()){ value = true; CDBG_HIGH("%s: Face Detection metadata is required in ZSL mode.", __func__); } } return value; } bool QCamera2HardwareInterface::removeSizeFromList(cam_dimension_t* size_list, uint8_t length, cam_dimension_t size) { bool found = false; int index = 0; for (int i = 0; i < length; i++) { if ((size_list[i].width == size.width && size_list[i].height == size.height)) { found = true; index = i; break; } } if (found) { for (int i = index; i < length; i++) { size_list[i] = size_list[i+1]; } } return found; } void QCamera2HardwareInterface::copyList(cam_dimension_t* src_list, cam_dimension_t* dst_list, uint8_t len){ for (int i = 0; i < len; i++) { dst_list[i] = src_list[i]; } } /*=========================================================================== * FUNCTION : defferedWorkRoutine * * DESCRIPTION: data process routine that executes deffered tasks * * PARAMETERS : * @data : user data ptr (QCamera2HardwareInterface) * * RETURN : None *==========================================================================*/ void *QCamera2HardwareInterface::defferedWorkRoutine(void *obj) { int running = 1; int ret; uint8_t is_active = FALSE; QCamera2HardwareInterface *pme = (QCamera2HardwareInterface *)obj; QCameraCmdThread *cmdThread = &pme->mDefferedWorkThread; do { do { ret = cam_sem_wait(&cmdThread->cmd_sem); if (ret != 0 && errno != EINVAL) { ALOGE("%s: cam_sem_wait error (%s)", __func__, strerror(errno)); return NULL; } } while (ret != 0); // we got notified about new cmd avail in cmd queue camera_cmd_type_t cmd = cmdThread->getCmd(); switch (cmd) { case CAMERA_CMD_TYPE_START_DATA_PROC: CDBG_HIGH("%s: start data proc", __func__); is_active = TRUE; break; case CAMERA_CMD_TYPE_STOP_DATA_PROC: CDBG_HIGH("%s: stop data proc", __func__); is_active = FALSE; // signal cmd is completed cam_sem_post(&cmdThread->sync_sem); break; case CAMERA_CMD_TYPE_DO_NEXT_JOB: { DeffWork *dw = reinterpret_cast<DeffWork *>(pme->mCmdQueue.dequeue()); if ( NULL == dw ) { ALOGE("%s : Invalid deferred work", __func__); break; } switch( dw->cmd ) { case CMD_DEFF_ALLOCATE_BUFF: { QCameraChannel * pChannel = dw->args.allocArgs.ch; if ( NULL == pChannel ) { ALOGE("%s : Invalid deferred work channel", __func__); break; } cam_stream_type_t streamType = dw->args.allocArgs.type; uint32_t iNumOfStreams = pChannel->getNumOfStreams(); QCameraStream *pStream = NULL; for ( uint32_t i = 0; i < iNumOfStreams; ++i) { pStream = pChannel->getStreamByIndex(i); if ( NULL == pStream ) { break; } if ( pStream->isTypeOf(streamType)) { if ( pStream->allocateBuffers() ) { ALOGE("%s: Error allocating buffers !!!", __func__); } break; } } { Mutex::Autolock l(pme->mDeffLock); pme->mDeffOngoingJobs[dw->id] = false; delete dw; pme->mDeffCond.signal(); } } break; case CMD_DEFF_PPROC_START: { QCameraChannel * pChannel = dw->args.pprocArgs; assert(pChannel); if (pme->m_postprocessor.start(pChannel) != NO_ERROR) { ALOGE("%s: cannot start postprocessor", __func__); pme->delChannel(QCAMERA_CH_TYPE_CAPTURE); } { Mutex::Autolock l(pme->mDeffLock); pme->mDeffOngoingJobs[dw->id] = false; delete dw; pme->mDeffCond.signal(); } } break; default: ALOGE("%s[%d]: Incorrect command : %d", __func__, __LINE__, dw->cmd); } } break; case CAMERA_CMD_TYPE_EXIT: running = 0; break; default: break; } } while (running); return NULL; } /*=========================================================================== * FUNCTION : isCaptureShutterEnabled * * DESCRIPTION: Check whether shutter should be triggered immediately after * capture * * PARAMETERS : * * RETURN : true - regular capture * false - other type of capture *==========================================================================*/ bool QCamera2HardwareInterface::isCaptureShutterEnabled() { char prop[PROPERTY_VALUE_MAX]; memset(prop, 0, sizeof(prop)); property_get("persist.camera.feature.shutter", prop, "0"); int enableShutter = atoi(prop); return enableShutter == 1; } /*=========================================================================== * FUNCTION : queueDefferedWork * * DESCRIPTION: function which queues deferred tasks * * PARAMETERS : * @cmd : deferred task * @args : deffered task arguments * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::queueDefferedWork(DefferedWorkCmd cmd, DefferWorkArgs args) { Mutex::Autolock l(mDeffLock); for (int i = 0; i < MAX_ONGOING_JOBS; ++i) { if (!mDeffOngoingJobs[i]) { mCmdQueue.enqueue(new DeffWork(cmd, i, args)); mDeffOngoingJobs[i] = true; mDefferedWorkThread.sendCmd(CAMERA_CMD_TYPE_DO_NEXT_JOB, FALSE, FALSE); return i; } } return -1; } /*=========================================================================== * FUNCTION : waitDefferedWork * * DESCRIPTION: waits for a deffered task to finish * * PARAMETERS : * @job_id : deferred task id * * RETURN : int32_t type of status * NO_ERROR -- success * none-zero failure code *==========================================================================*/ int32_t QCamera2HardwareInterface::waitDefferedWork(int32_t &job_id) { Mutex::Autolock l(mDeffLock); if ((MAX_ONGOING_JOBS <= job_id) || (0 > job_id)) { return NO_ERROR; } while ( mDeffOngoingJobs[job_id] == true ) { mDeffCond.wait(mDeffLock); } job_id = MAX_ONGOING_JOBS; return NO_ERROR; } /*=========================================================================== * FUNCTION : isRegularCapture * * DESCRIPTION: Check configuration for regular catpure * * PARAMETERS : * * RETURN : true - regular capture * false - other type of capture *==========================================================================*/ bool QCamera2HardwareInterface::isRegularCapture() { bool ret = false; if (numOfSnapshotsExpected() == 1 && !isLongshotEnabled() && !mParameters.getRecordingHintValue() && !isZSLMode() && !mParameters.isHDREnabled()) { ret = true; } return ret; } /*=========================================================================== * FUNCTION : getLogLevel * * DESCRIPTION: Reads the log level property into a variable * * PARAMETERS : * None * * RETURN : * None *==========================================================================*/ void QCamera2HardwareInterface::getLogLevel() { char prop[PROPERTY_VALUE_MAX]; uint32_t temp; uint32_t log_level; uint32_t debug_mask; memset(prop, 0, sizeof(prop)); /* Higher 4 bits : Value of Debug log level (Default level is 1 to print all CDBG_HIGH) Lower 28 bits : Control mode for sub module logging(Only 3 sub modules in HAL) 0x1 for HAL 0x10 for mm-camera-interface 0x100 for mm-jpeg-interface */ property_get("persist.camera.hal.debug.mask", prop, "268435463"); // 0x10000007=268435463 temp = atoi(prop); log_level = ((temp >> 28) & 0xF); debug_mask = (temp & HAL_DEBUG_MASK_HAL); if (debug_mask > 0) gCamHalLogLevel = log_level; else gCamHalLogLevel = 0; // Debug logs are not required if debug_mask is zero ALOGI("%s gCamHalLogLevel=%d",__func__, gCamHalLogLevel); return; } }; // namespace qcamera
bastir85/android_device_wiko_l5510
camera/QCamera2/HAL/QCamera2HWI.cpp
C++
gpl-2.0
228,133
<?php /** * * @package Groups page * @version $Id: groups.php 06/11/2010 RMcGirr83 * @copyright (c) 2005 phpBB Group * @license http://opensource.org/licenses/gpl-license.php GNU Public License * */ /** * @ignore */ define('IN_PHPBB', true); $phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './'; // Remember and change this to refelct your site $phpEx = substr(strrchr(__FILE__, '.'), 1); include($phpbb_root_path . 'common.' . $phpEx); // Start session management $user->session_begin(); $auth->acl($user->data); $user->setup('mods/groups'); // what groups is the user a member of? // this allows hidden groups to display $sql = 'SELECT group_id FROM ' . USER_GROUP_TABLE . ' WHERE user_id = ' . (int) $user->data['user_id'] . ' AND user_pending = 0'; $result = $db->sql_query($sql); $in_group = $db->sql_fetchrowset($result); $db->sql_freeresult($result); // groups not displayed // you can add to the array if wanted // by adding the group name to ignore into the array // default group names are GUESTS REGISTERED REGISTERED_COPPA GLOBAL_MODERATORS ADMINISTRATORS BOTS $groups_not_display = array('GUESTS', 'BOTS', 'TESTING'); // don't want coppa group? if (!$config['coppa_enable']) { $no_coppa = array('REGISTERED_COPPA'); $groups_not_display = array_merge($groups_not_display, $no_coppa); //free up a bit 'o memory unset($no_coppa); } // get the groups $sql = 'SELECT * FROM ' . GROUPS_TABLE . ' WHERE ' . $db->sql_in_set('group_name', $groups_not_display, true) . ' ORDER BY group_name'; $result = $db->sql_query($sql); $group_rows = array(); while ($row = $db->sql_fetchrow($result) ) { $group_rows[] = $row; } $db->sql_freeresult($result); // Grab rank information for later $ranks = $cache->obtain_ranks(); if ($total_groups = count($group_rows)) { // Obtain list of users of each group $sql = 'SELECT u.user_id, u.username, u.username_clean, u.user_colour, ug.group_id, ug.group_leader FROM ' . USER_GROUP_TABLE . ' ug, ' . USERS_TABLE . ' u WHERE ug.user_id = u.user_id AND ug.user_pending = 0 AND u.user_id <> ' . ANONYMOUS . ' ORDER BY ug.group_leader DESC, u.username ASC'; $result = $db->sql_query($sql); $group_users = $group_leaders = array(); while ($row = $db->sql_fetchrow($result)) { if ($row['group_leader']) { $group_leaders[$row['group_id']][] = get_username_string('full', $row['user_id'], $row['username'], $row['user_colour']); } else { $group_users[$row['group_id']][] = get_username_string('full', $row['user_id'], $row['username'], $row['user_colour']); } } $db->sql_freeresult($result); for($i = 0; $i < $total_groups; $i++) { $group_id = (int) $group_rows[$i]['group_id']; if ($group_rows[$i]['group_type'] == GROUP_HIDDEN && !$auth->acl_gets('a_group', 'a_groupadd', 'a_groupdel') && !in_array($group_id, $in_group[0])) { continue; } // Do we have a Group Rank? if ($group_rows[$i]['group_rank']) { if (isset($ranks['special'][$group_rows[$i]['group_rank']])) { $rank_title = $ranks['special'][$group_rows[$i]['group_rank']]['rank_title']; } $rank_img = (!empty($ranks['special'][$group_rows[$i]['group_rank']]['rank_image'])) ? '<img src="' . $config['ranks_path'] . '/' . $ranks['special'][$group_rows[$i]['group_rank']]['rank_image'] . '" alt="' . $ranks['special'][$group_rows[$i]['group_rank']]['rank_title'] . '" title="' . $ranks['special'][$group_rows[$i]['group_rank']]['rank_title'] . '" /><br />' : ''; } else { $rank_title = ''; $rank_img = ''; } $template->assign_block_vars('groups', array( 'GROUP_ID' => $group_rows[$i]['group_id'], 'GROUP_NAME' => ($group_rows[$i]['group_type'] == GROUP_SPECIAL) ? $user->lang['G_' . $group_rows[$i]['group_name']] : $group_rows[$i]['group_name'], 'GROUP_DESC' => generate_text_for_display($group_rows[$i]['group_desc'], $group_rows[$i]['group_desc_uid'], $group_rows[$i]['group_desc_bitfield'], $group_rows[$i]['group_desc_options']), 'GROUP_COLOUR' => $group_rows[$i]['group_colour'], 'GROUP_RANK' => $rank_title, 'RANK_IMG' => $rank_img, 'U_VIEW_GROUP' => append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=group&amp;g=' . $group_id), 'S_SHOW_RANK' => true, )); if (!empty($group_leaders[$group_id])) { foreach($group_leaders[$group_id] as $group_leader) { $template->assign_block_vars('groups.leaders', array( 'U_VIEW_PROFILE' => $group_leader, )); } } if (!empty($group_users[$group_id])) { foreach($group_users[$group_id] as $group_user) { $template->assign_block_vars('groups.members', array( 'U_VIEW_PROFILE' => $group_user, )); } } } } $db->sql_freeresult($result); // Set up the Navlinks for the forums navbar $template->assign_block_vars('navlinks', array( 'FORUM_NAME' => $user->lang['GROUPS'], 'U_VIEW_FORUM' => append_sid("{$phpbb_root_path}groups.$phpEx")) ); // Assign specific vars $template->assign_vars(array( 'L_GROUPS_TEXT' => $user->lang['GROUPS_TEXT'], )); // Output page page_header($user->lang['GROUP_TITLE']); // Set the template for the page $template->set_filenames(array( 'body' => 'groups_body.html') ); page_footer(); ?>
phpbbmodders-30x-mods/groups_page
root/groups.php
PHP
gpl-2.0
5,213
package klaue.mcschematictool.blocktypes; /** * A farmland block with wetness * * @author klaue * */ public class Farmland extends Block { /** * initializes the farmland block * * @param wetness 0-8 */ public Farmland(byte wetness) { super((short) 60, wetness); this.type = Type.FARMLAND; if (wetness < 0 || wetness > 8) { throw new IllegalArgumentException("wetness " + wetness + "outside boundaries"); } } /** * Get the wetness value of the farmland. 0 is dry, 8 is the wettest. This is ingame set by the distance to the next * water block * * @return the wetness */ public byte getWetness() { return this.data; } /** * Get the wetness value of the farmland. 0 is dry, 8 is the wettest. This is ingame set by the distance to the next * water block, so it may not be a good idea to set this. * * @param wetness the wetness to set */ public void setWetness(byte wetness) { if (wetness < 0 || wetness > 8) { throw new IllegalArgumentException("wetness " + wetness + "outside boundaries"); } this.data = wetness; } @Override public String toString() { return super.toString() + ", wetness: " + this.data; } @Override public void setData(byte data) { setWetness(data); } }
Fernando-Marquardt/mcarchitect
MCArchitect/src/klaue/mcschematictool/blocktypes/Farmland.java
Java
gpl-2.0
1,419
/* * Copyright (c) 1998-2012 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Nam Nguyen */ package com.caucho.quercus.lib.curl; import java.io.IOException; import java.io.OutputStream; import com.caucho.quercus.env.Callable; import com.caucho.quercus.env.Callback; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.StringValue; import com.caucho.quercus.env.Value; public class UrlEncodedBody extends PostBody { private StringValue _body; private int _length; private String _contentType = "application/x-www-form-urlencoded"; public UrlEncodedBody (Env env, Value body) { _body = body.toStringValue(env); _length = _body.length(); } public String getContentType() { return _contentType; } public void setContentType(String type) { _contentType = type; } @Override public long getContentLength() { return (long) _length; } public void writeTo(Env env, OutputStream os) throws IOException { for (int i = 0; i < _length; i++) { os.write(_body.charAt(i)); } } }
mdaniel/svn-caucho-com-resin
modules/quercus/src/com/caucho/quercus/lib/curl/UrlEncodedBody.java
Java
gpl-2.0
2,002
<?php /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// /////// SISFOKOL_SMK_v4.0_(NyurungBAN) /////// /////// (Sistem Informasi Sekolah untuk SMK) /////// /////////////////////////////////////////////////////////////////////// /////// Dibuat oleh : /////// /////// Agus Muhajir, S.Kom /////// /////// URL : /////// /////// * http://sisfokol.wordpress.com/ /////// /////// * http://hajirodeon.wordpress.com/ /////// /////// * http://yahoogroup.com/groups/sisfokol/ /////// /////// * http://yahoogroup.com/groups/linuxbiasawae/ /////// /////// E-Mail : /////// /////// * hajirodeon@yahoo.com /////// /////// * hajirodeon@gmail.com /////// /////// HP/SMS : 081-829-88-54 /////// /////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// session_start(); //fungsi - fungsi require("../../../inc/config.php"); require("../../../inc/fungsi.php"); require("../../../inc/koneksi.php"); require("../../../inc/cek/janissari.php"); require("../../../inc/class/paging2.php"); require("../../../inc/class/pagingx.php"); require("../../../inc/class/thumbnail_images.php"); $tpl = LoadTpl("../../../template/janissari.html"); nocache; //nilai $filenya = "album_detail_view.php"; $s = nosql($_REQUEST['s']); $msgkd = nosql($_REQUEST['msgkd']); $alkd = nosql($_REQUEST['alkd']); $fkd = nosql($_REQUEST['fkd']); $page = nosql($_REQUEST['page']); if ((empty($page)) OR ($page == "0")) { $page = "1"; } //file-nya $qfle = mysql_query("SELECT * FROM user_blog_album_filebox ". "WHERE kd_album = '$alkd' ". "AND kd = '$fkd'"); $rfle = mysql_fetch_assoc($qfle); $fle_filex = $rfle['filex']; $fle_ket = balikin($rfle['ket']); //nek null if (empty($fle_ket)) { $fle_ket = "-"; } //judul $judul = "Foto : $fle_filex"; $judulku = "[$tipe_session : $no1_session.$nm1_session] ==> $judul"; $judulx = $judul; //focus $diload = "document.formx.bk_foto.focus();"; //isi *START ob_start(); //js require("../../../inc/js/jumpmenu.js"); require("../../../inc/js/swap.js"); require("../../../inc/menu/janissari.php"); //view ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// echo '<form name="formx" method="post" action="'.$filenya.'"> <table bgcolor="#FDF0DE" width="100%" border="0" cellspacing="3" cellpadding="0"> <tr valign="top"> <td width="80%"> <table bgcolor="'.$warnaover.'" width="100%" height="100%" border="0" cellspacing="3" cellpadding="0"> <tr align="center"> <td> <img src="'.$sumber.'/filebox/album/'.$alkd.'/'.$fle_filex.'" border="1"> </td> </tr> </table> <table bgcolor="'.$warna02.'" width="100%" height="100%" border="0" cellspacing="3" cellpadding="0"> <tr align="center"> <td valign="top"> <em>'.$fle_ket.'</em> </td> </tr> </table> <br> <br> <hr>'; //hapus komentar //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if ($s == "hapus") { //nilai $alkd = nosql($_REQUEST['alkd']); $fkd = nosql($_REQUEST['fkd']); $msgkd = nosql($_REQUEST['msgkd']); //hapus mysql_query("DELETE FROM user_blog_album_msg ". "WHERE kd = '$msgkd'"); //re-direct $ke = "$filenya?alkd=$alkd&fkd=$fkd"; xloc($ke); exit(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //daftar komentar /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// $qdko = mysql_query("SELECT * FROM user_blog_album_msg ". "WHERE kd_user_blog_album = '$fkd' ". "ORDER BY postdate ASC"); $rdko = mysql_fetch_assoc($qdko); $tdko = mysql_num_rows($qdko); if ($tdko != 0) { do { //nilai $dko_kd = nosql($rdko['kd']); $dko_msg = balikin($rdko['msg']); $dko_dari = nosql($rdko['dari']); $dko_postdate = $rdko['postdate']; //user-nya $qtuse = mysql_query("SELECT m_user.*, m_user.kd AS uskd, ". "user_blog.* ". "FROM m_user, user_blog ". "WHERE user_blog.kd_user = m_user.kd ". "AND m_user.kd = '$dko_dari'"); $rtuse = mysql_fetch_assoc($qtuse); $tuse_kd = nosql($rtuse['uskd']); $tuse_no = nosql($rtuse['nomor']); $tuse_nm = balikin($rtuse['nama']); $tuse_tipe = nosql($rtuse['tipe']); $tuse_foto_path = $rtuse['foto_path']; //nek null foto if (empty($tuse_foto_path)) { $nilz_foto = "$sumber/img/foto_blank.jpg"; } else { //gawe mini thumnail $nilz_foto = "$sumber/filebox/profil/$tuse_kd/thumb_$tuse_foto_path"; } echo '<table width="100%" border="0" cellspacing="3" cellpadding="0"> <tr valign="top"> <td width="50" valign="top"> <a href="'.$sumber.'/janissari/p/index.php?uskd='.$tuse_kd.'" title="('.$tuse_tipe.'). '.$tuse_no.'. '.$tuse_nm.'"> <img src="'.$nilz_foto.'" align="left" alt="'.$tuse_nm.'" width="50" height="75" border="1"> </a> </td> <td valign="top"> <em>'.$dko_msg.'. <br> [Oleh : <strong><a href="'.$sumber.'/janissari/p/index.php?uskd='.$tuse_kd.'" title="('.$tuse_tipe.'). '.$tuse_no.'. '.$tuse_nm.'">('.$tuse_tipe.'). '.$tuse_no.'. '.$tuse_nm.'</a></strong>]. ['.$dko_postdate.'].</em> [<a href="'.$filenya.'?alkd='.$alkd.'&fkd='.$fkd.'&msgkd='.$dko_kd.'&s=hapus" title="HAPUS"><img src="'.$sumber.'/img/delete.gif" width="16" height="16" border="0"></a>] <br><br> </td> </tr> </table> <br>'; } while ($rdko = mysql_fetch_assoc($qdko)); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //simpan komentar /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// if ($_POST['btnSMP']) { //nilai $uskd = nosql($_POST['uskd']); $fkd = nosql($_POST['fkd']); $bk_foto = cegah($_POST['bk_foto']); $page = nosql($_POST['page']); //insert mysql_query("INSERT INTO user_blog_album_msg(kd, kd_user_blog_album, dari, msg, postdate) VALUES ". "('$x', '$fkd', '$kd1_session', '$bk_foto', '$today')"); //re-direct $ke = "$filenya?alkd=$alkd&fkd=$fkd"; xloc($ke); exit(); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// echo '</p> <br> <br> <p> Beri Komentar : (<a href="album_detail.php?alkd='.$alkd.'" title="Lihat Foto Lainnya...">Lihat Foto Lainnya...</a>) <br> <textarea name="bk_foto" cols="50" rows="5" wrap="virtual"></textarea> <br> <input name="fkd" type="hidden" value="'.$fkd.'"> <input name="alkd" type="hidden" value="'.$alkd.'"> <input name="uskd" type="hidden" value="'.$uskd.'"> <input name="page" type="hidden" value="'.$page.'"> <input name="btnSMP" type="submit" value="SIMPAN"> <input name="btnBTL" type="reset" value="BATAL"> </p> <td width="1%"> </td> <td>'; //ambil sisi require("../../../inc/menu/k_sisi.php"); echo '<br> <br> <br> </td> </tr> </table>'; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //isi $isi = ob_get_contents(); ob_end_clean(); require("../../../inc/niltpl.php"); //diskonek xfree($qbw); xclose($koneksi); exit(); ?>
MuhammadArdhi/sisfokol
janissari/k/album/album_detail_view.php
PHP
gpl-2.0
7,774
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com // ****************************************************************** // ****************************************************************** // * // * This file is part of the Cxbx project. // * // * Cxbx and Cxbe are free software; you can redistribute them // * and/or modify them under the terms of the GNU General Public // * License as published by the Free Software Foundation; either // * version 2 of the license, or (at your option) any later version. // * // * This program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have recieved a copy of the GNU General Public License // * along with this program; see the file COPYING. // * If not, write to the Free Software Foundation, Inc., // * 59 Temple Place - Suite 330, Bostom, MA 02111-1307, USA. // * // * (c) 2018 Luke Usher <luke.usher@outlook.com> // * // * All rights reserved // * // ****************************************************************** #include "core\kernel\init\CxbxKrnl.h" #include "core\kernel\support\Emu.h" #include "core\hle\D3D8\Direct3D9/Direct3D9.h" #include "core\hle\DSOUND\DirectSound\DirectSound.hpp" #include "Patches.hpp" #include "Intercept.hpp" #include <map> #include <unordered_map> #include <subhook.h> typedef struct { const void* patchFunc; // Function pointer of the patch in Cxbx-R codebase const uint32_t flags; // Patch Flags } xbox_patch_t; const uint32_t PATCH_ALWAYS = 1 << 0; const uint32_t PATCH_HLE_D3D = 1 << 1; const uint32_t PATCH_HLE_DSOUND = 1 << 2; const uint32_t PATCH_HLE_OHCI = 1 << 3; const uint32_t PATCH_IS_FIBER = 1 << 4; #define PATCH_ENTRY(Name, Func, Flags) \ { Name, xbox_patch_t { (void *)&Func, Flags} } // Map of Xbox Patch names to Emulator Patches // A std::string is used as it's possible for a symbol to have multiple names // This allows for the eventual importing of Dxbx symbol files and even IDA signatures too! std::map<const std::string, const xbox_patch_t> g_PatchTable = { // Direct3D PATCH_ENTRY("CDevice_SetStateUP", xbox::EMUPATCH(CDevice_SetStateUP), PATCH_HLE_D3D), PATCH_ENTRY("CDevice_SetStateVB", xbox::EMUPATCH(CDevice_SetStateVB), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_Begin", xbox::EMUPATCH(D3DDevice_Begin), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_BeginPush", xbox::EMUPATCH(D3DDevice_BeginPush), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_BeginPush2", xbox::EMUPATCH(D3DDevice_BeginPush2), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_BeginVisibilityTest", xbox::EMUPATCH(D3DDevice_BeginVisibilityTest), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_BlockOnFence", xbox::EMUPATCH(D3DDevice_BlockOnFence), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_BlockUntilVerticalBlank", xbox::EMUPATCH(D3DDevice_BlockUntilVerticalBlank), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_Clear", xbox::EMUPATCH(D3DDevice_Clear), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_CopyRects", xbox::EMUPATCH(D3DDevice_CopyRects), PATCH_HLE_D3D), // PATCH_ENTRY("D3DDevice_CreateVertexShader", xbox::EMUPATCH(D3DDevice_CreateVertexShader), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_DeleteVertexShader", xbox::EMUPATCH(D3DDevice_DeleteVertexShader), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_DeleteVertexShader_0", xbox::EMUPATCH(D3DDevice_DeleteVertexShader_0), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_DrawIndexedVertices", xbox::EMUPATCH(D3DDevice_DrawIndexedVertices), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_DrawIndexedVerticesUP", xbox::EMUPATCH(D3DDevice_DrawIndexedVerticesUP), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_DrawRectPatch", xbox::EMUPATCH(D3DDevice_DrawRectPatch), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_DrawTriPatch", xbox::EMUPATCH(D3DDevice_DrawTriPatch), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_DrawVertices", xbox::EMUPATCH(D3DDevice_DrawVertices), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_DrawVertices_4", xbox::EMUPATCH(D3DDevice_DrawVertices_4), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_DrawVerticesUP", xbox::EMUPATCH(D3DDevice_DrawVerticesUP), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_DrawVerticesUP_12", xbox::EMUPATCH(D3DDevice_DrawVerticesUP_12), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_EnableOverlay", xbox::EMUPATCH(D3DDevice_EnableOverlay), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_End", xbox::EMUPATCH(D3DDevice_End), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_EndPush", xbox::EMUPATCH(D3DDevice_EndPush), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_EndVisibilityTest", xbox::EMUPATCH(D3DDevice_EndVisibilityTest), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_EndVisibilityTest_0", xbox::EMUPATCH(D3DDevice_EndVisibilityTest_0), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_FlushVertexCache", xbox::EMUPATCH(D3DDevice_FlushVertexCache), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetBackBuffer", xbox::EMUPATCH(D3DDevice_GetBackBuffer), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetBackBuffer2", xbox::EMUPATCH(D3DDevice_GetBackBuffer2), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetBackBuffer2_0__LTCG_eax1", xbox::EMUPATCH(D3DDevice_GetBackBuffer2_0__LTCG_eax1), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetDisplayFieldStatus", xbox::EMUPATCH(D3DDevice_GetDisplayFieldStatus), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetGammaRamp", xbox::EMUPATCH(D3DDevice_GetGammaRamp), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetMaterial", xbox::EMUPATCH(D3DDevice_GetMaterial), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetModelView", xbox::EMUPATCH(D3DDevice_GetModelView), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetOverlayUpdateStatus", xbox::EMUPATCH(D3DDevice_GetOverlayUpdateStatus), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetProjectionViewportMatrix", xbox::EMUPATCH(D3DDevice_GetProjectionViewportMatrix), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetShaderConstantMode", xbox::EMUPATCH(D3DDevice_GetShaderConstantMode), PATCH_HLE_D3D), //PATCH_ENTRY("D3DDevice_GetTransform", xbox::EMUPATCH(D3DDevice_GetTransform), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetVertexShader", xbox::EMUPATCH(D3DDevice_GetVertexShader), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetVertexShaderConstant", xbox::EMUPATCH(D3DDevice_GetVertexShaderConstant), PATCH_HLE_D3D), //PATCH_ENTRY("D3DDevice_GetVertexShaderDeclaration", xbox::EMUPATCH(D3DDevice_GetVertexShaderDeclaration), PATCH_HLE_D3D), //PATCH_ENTRY("D3DDevice_GetVertexShaderFunction", xbox::EMUPATCH(D3DDevice_GetVertexShaderFunction), PATCH_HLE_D3D), //PATCH_ENTRY("D3DDevice_GetVertexShaderInput", xbox::EMUPATCH(D3DDevice_GetVertexShaderInput), PATCH_HLE_D3D), //PATCH_ENTRY("D3DDevice_GetVertexShaderSize", xbox::EMUPATCH(D3DDevice_GetVertexShaderSize), PATCH_HLE_D3D), //PATCH_ENTRY("D3DDevice_GetVertexShaderType", xbox::EMUPATCH(D3DDevice_GetVertexShaderType), PATCH_HLE_D3D), //PATCH_ENTRY("D3DDevice_GetViewportOffsetAndScale", xbox::EMUPATCH(D3DDevice_GetViewportOffsetAndScale), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_GetVisibilityTestResult", xbox::EMUPATCH(D3DDevice_GetVisibilityTestResult), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_InsertCallback", xbox::EMUPATCH(D3DDevice_InsertCallback), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_InsertFence", xbox::EMUPATCH(D3DDevice_InsertFence), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_IsBusy", xbox::EMUPATCH(D3DDevice_IsBusy), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_IsFencePending", xbox::EMUPATCH(D3DDevice_IsFencePending), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_LightEnable", xbox::EMUPATCH(D3DDevice_LightEnable), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_LoadVertexShader", xbox::EMUPATCH(D3DDevice_LoadVertexShader), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_LoadVertexShaderProgram", xbox::EMUPATCH(D3DDevice_LoadVertexShaderProgram), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_LoadVertexShader_0__LTCG_eax_Address_ecx_Handle", xbox::EMUPATCH(D3DDevice_LoadVertexShader_0__LTCG_eax_Address_ecx_Handle), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_LoadVertexShader_0__LTCG_eax_Address_edx_Handle", xbox::EMUPATCH(D3DDevice_LoadVertexShader_0__LTCG_eax_Address_edx_Handle), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_LoadVertexShader_4", xbox::EMUPATCH(D3DDevice_LoadVertexShader_4), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_MultiplyTransform", xbox::EMUPATCH(D3DDevice_MultiplyTransform), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_PersistDisplay", xbox::EMUPATCH(D3DDevice_PersistDisplay), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_Present", xbox::EMUPATCH(D3DDevice_Present), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_PrimeVertexCache", xbox::EMUPATCH(D3DDevice_PrimeVertexCache), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_Reset", xbox::EMUPATCH(D3DDevice_Reset), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_RunPushBuffer", xbox::EMUPATCH(D3DDevice_RunPushBuffer), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_RunVertexStateShader", xbox::EMUPATCH(D3DDevice_RunVertexStateShader), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SelectVertexShader", xbox::EMUPATCH(D3DDevice_SelectVertexShader), PATCH_HLE_D3D), //PATCH_ENTRY("D3DDevice_SelectVertexShaderDirect", xbox::EMUPATCH(D3DDevice_SelectVertexShaderDirect), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SelectVertexShader_0", xbox::EMUPATCH(D3DDevice_SelectVertexShader_0), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SelectVertexShader_4", xbox::EMUPATCH(D3DDevice_SelectVertexShader_4), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetBackBufferScale", xbox::EMUPATCH(D3DDevice_SetBackBufferScale), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetDepthClipPlanes", xbox::EMUPATCH(D3DDevice_SetDepthClipPlanes), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetFlickerFilter", xbox::EMUPATCH(D3DDevice_SetFlickerFilter), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetFlickerFilter_0", xbox::EMUPATCH(D3DDevice_SetFlickerFilter_0), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetGammaRamp", xbox::EMUPATCH(D3DDevice_SetGammaRamp), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetIndices", xbox::EMUPATCH(D3DDevice_SetIndices), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetIndices_4", xbox::EMUPATCH(D3DDevice_SetIndices_4), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetLight", xbox::EMUPATCH(D3DDevice_SetLight), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetMaterial", xbox::EMUPATCH(D3DDevice_SetMaterial), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetModelView", xbox::EMUPATCH(D3DDevice_SetModelView), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetPalette", xbox::EMUPATCH(D3DDevice_SetPalette), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetPalette_4", xbox::EMUPATCH(D3DDevice_SetPalette_4), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetPixelShader", xbox::EMUPATCH(D3DDevice_SetPixelShader), PATCH_HLE_D3D), //PATCH_ENTRY("D3DDevice_SetPixelShaderConstant_4", xbox::EMUPATCH(D3DDevice_SetPixelShaderConstant_4), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetPixelShader_0", xbox::EMUPATCH(D3DDevice_SetPixelShader_0), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetRenderState_Simple", xbox::EMUPATCH(D3DDevice_SetRenderState_Simple), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetRenderTarget", xbox::EMUPATCH(D3DDevice_SetRenderTarget), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetRenderTargetFast", xbox::EMUPATCH(D3DDevice_SetRenderTargetFast), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetRenderTarget_0", xbox::EMUPATCH(D3DDevice_SetRenderTarget_0), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetScreenSpaceOffset", xbox::EMUPATCH(D3DDevice_SetScreenSpaceOffset), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetShaderConstantMode", xbox::EMUPATCH(D3DDevice_SetShaderConstantMode), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetShaderConstantMode_0__LTCG_eax1", xbox::EMUPATCH(D3DDevice_SetShaderConstantMode_0__LTCG_eax1), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetSoftDisplayFilter", xbox::EMUPATCH(D3DDevice_SetSoftDisplayFilter), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetStipple", xbox::EMUPATCH(D3DDevice_SetStipple), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetStreamSource", xbox::EMUPATCH(D3DDevice_SetStreamSource), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetStreamSource_0__LTCG_eax_StreamNumber_edi_pStreamData_ebx_Stride", xbox::EMUPATCH(D3DDevice_SetStreamSource_0__LTCG_eax_StreamNumber_edi_pStreamData_ebx_Stride), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetStreamSource_4", xbox::EMUPATCH(D3DDevice_SetStreamSource_4), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetStreamSource_8", xbox::EMUPATCH(D3DDevice_SetStreamSource_8), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetStreamSource_8__LTCG_edx_StreamNumber", xbox::EMUPATCH(D3DDevice_SetStreamSource_8__LTCG_edx_StreamNumber), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetSwapCallback", xbox::EMUPATCH(D3DDevice_SetSwapCallback), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetTexture", xbox::EMUPATCH(D3DDevice_SetTexture), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetTexture_4__LTCG_eax_pTexture", xbox::EMUPATCH(D3DDevice_SetTexture_4__LTCG_eax_pTexture), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetTexture_4", xbox::EMUPATCH(D3DDevice_SetTexture_4), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetTransform", xbox::EMUPATCH(D3DDevice_SetTransform), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetTransform_0__LTCG_eax1_edx2", xbox::EMUPATCH(D3DDevice_SetTransform_0__LTCG_eax1_edx2), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexData2f", xbox::EMUPATCH(D3DDevice_SetVertexData2f), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexData2s", xbox::EMUPATCH(D3DDevice_SetVertexData2s), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexData4f", xbox::EMUPATCH(D3DDevice_SetVertexData4f), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexData4f_16", xbox::EMUPATCH(D3DDevice_SetVertexData4f_16), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexData4s", xbox::EMUPATCH(D3DDevice_SetVertexData4s), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexData4ub", xbox::EMUPATCH(D3DDevice_SetVertexData4ub), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexDataColor", xbox::EMUPATCH(D3DDevice_SetVertexDataColor), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexShader", xbox::EMUPATCH(D3DDevice_SetVertexShader), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexShader_0", xbox::EMUPATCH(D3DDevice_SetVertexShader_0), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexShaderConstant", xbox::EMUPATCH(D3DDevice_SetVertexShaderConstant), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexShaderConstant1", xbox::EMUPATCH(D3DDevice_SetVertexShaderConstant1), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexShaderConstant1Fast", xbox::EMUPATCH(D3DDevice_SetVertexShaderConstant1Fast), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexShaderConstant4", xbox::EMUPATCH(D3DDevice_SetVertexShaderConstant4), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexShaderConstantNotInline", xbox::EMUPATCH(D3DDevice_SetVertexShaderConstantNotInline), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexShaderConstantNotInlineFast", xbox::EMUPATCH(D3DDevice_SetVertexShaderConstantNotInlineFast), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexShaderConstant_8", xbox::EMUPATCH(D3DDevice_SetVertexShaderConstant_8), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVertexShaderInput", xbox::EMUPATCH(D3DDevice_SetVertexShaderInput), PATCH_HLE_D3D), //PATCH_ENTRY("D3DDevice_SetVertexShaderInputDirect", xbox::EMUPATCH(D3DDevice_SetVertexShaderInputDirect), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetVerticalBlankCallback", xbox::EMUPATCH(D3DDevice_SetVerticalBlankCallback), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SetViewport", xbox::EMUPATCH(D3DDevice_SetViewport), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_Swap", xbox::EMUPATCH(D3DDevice_Swap), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_Swap_0", xbox::EMUPATCH(D3DDevice_Swap_0), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_SwitchTexture", xbox::EMUPATCH(D3DDevice_SwitchTexture), PATCH_HLE_D3D), PATCH_ENTRY("D3DDevice_UpdateOverlay", xbox::EMUPATCH(D3DDevice_UpdateOverlay), PATCH_HLE_D3D), PATCH_ENTRY("D3DResource_BlockUntilNotBusy", xbox::EMUPATCH(D3DResource_BlockUntilNotBusy), PATCH_HLE_D3D), PATCH_ENTRY("D3D_BlockOnTime", xbox::EMUPATCH(D3D_BlockOnTime), PATCH_HLE_D3D), PATCH_ENTRY("D3D_BlockOnTime_4", xbox::EMUPATCH(D3D_BlockOnTime_4), PATCH_HLE_D3D), PATCH_ENTRY("D3D_CommonSetRenderTarget", xbox::EMUPATCH(D3D_CommonSetRenderTarget), PATCH_HLE_D3D), PATCH_ENTRY("D3D_DestroyResource", xbox::EMUPATCH(D3D_DestroyResource), PATCH_HLE_D3D), PATCH_ENTRY("D3D_DestroyResource__LTCG", xbox::EMUPATCH(D3D_DestroyResource__LTCG), PATCH_HLE_D3D), PATCH_ENTRY("D3D_LazySetPointParams", xbox::EMUPATCH(D3D_LazySetPointParams), PATCH_HLE_D3D), PATCH_ENTRY("D3D_SetCommonDebugRegisters", xbox::EMUPATCH(D3D_SetCommonDebugRegisters), PATCH_HLE_D3D), PATCH_ENTRY("Direct3D_CreateDevice", xbox::EMUPATCH(Direct3D_CreateDevice), PATCH_HLE_D3D), PATCH_ENTRY("Direct3D_CreateDevice_16__LTCG_eax_BehaviorFlags_ebx_ppReturnedDeviceInterface", xbox::EMUPATCH(Direct3D_CreateDevice_16__LTCG_eax_BehaviorFlags_ebx_ppReturnedDeviceInterface), PATCH_HLE_D3D), PATCH_ENTRY("Direct3D_CreateDevice_16__LTCG_eax_BehaviorFlags_ecx_ppReturnedDeviceInterface", xbox::EMUPATCH(Direct3D_CreateDevice_16__LTCG_eax_BehaviorFlags_ecx_ppReturnedDeviceInterface), PATCH_HLE_D3D), PATCH_ENTRY("Direct3D_CreateDevice_4", xbox::EMUPATCH(Direct3D_CreateDevice_4), PATCH_HLE_D3D), PATCH_ENTRY("Lock2DSurface", xbox::EMUPATCH(Lock2DSurface), PATCH_HLE_D3D), PATCH_ENTRY("Lock3DSurface", xbox::EMUPATCH(Lock3DSurface), PATCH_HLE_D3D), // DSOUND PATCH_ENTRY("CDirectSound3DCalculator_Calculate3D", xbox::EMUPATCH(CDirectSound3DCalculator_Calculate3D), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSound3DCalculator_GetVoiceData", xbox::EMUPATCH(CDirectSound3DCalculator_GetVoiceData), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_AddRef", xbox::EMUPATCH(CDirectSoundStream_AddRef), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_Discontinuity", xbox::EMUPATCH(CDirectSoundStream_Discontinuity), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_Flush", xbox::EMUPATCH(CDirectSoundStream_Flush), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_FlushEx", xbox::EMUPATCH(CDirectSoundStream_FlushEx), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_GetInfo", xbox::EMUPATCH(CDirectSoundStream_GetInfo), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_GetStatus__r1", xbox::EMUPATCH(CDirectSoundStream_GetStatus__r1), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_GetStatus__r2", xbox::EMUPATCH(CDirectSoundStream_GetStatus__r2), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_GetVoiceProperties", xbox::EMUPATCH(CDirectSoundStream_GetVoiceProperties), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_Pause", xbox::EMUPATCH(CDirectSoundStream_Pause), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_PauseEx", xbox::EMUPATCH(CDirectSoundStream_PauseEx), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_Process", xbox::EMUPATCH(CDirectSoundStream_Process), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_Release", xbox::EMUPATCH(CDirectSoundStream_Release), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetAllParameters", xbox::EMUPATCH(CDirectSoundStream_SetAllParameters), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetConeAngles", xbox::EMUPATCH(CDirectSoundStream_SetConeAngles), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetConeOrientation", xbox::EMUPATCH(CDirectSoundStream_SetConeOrientation), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetConeOutsideVolume", xbox::EMUPATCH(CDirectSoundStream_SetConeOutsideVolume), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetDistanceFactor", xbox::EMUPATCH(CDirectSoundStream_SetDistanceFactor), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetDopplerFactor", xbox::EMUPATCH(CDirectSoundStream_SetDopplerFactor), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetEG", xbox::EMUPATCH(CDirectSoundStream_SetEG), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetFilter", xbox::EMUPATCH(CDirectSoundStream_SetFilter), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetFormat", xbox::EMUPATCH(CDirectSoundStream_SetFormat), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetFrequency", xbox::EMUPATCH(CDirectSoundStream_SetFrequency), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetHeadroom", xbox::EMUPATCH(CDirectSoundStream_SetHeadroom), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetI3DL2Source", xbox::EMUPATCH(CDirectSoundStream_SetI3DL2Source), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetLFO", xbox::EMUPATCH(CDirectSoundStream_SetLFO), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetMaxDistance", xbox::EMUPATCH(CDirectSoundStream_SetMaxDistance), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetMinDistance", xbox::EMUPATCH(CDirectSoundStream_SetMinDistance), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetMixBinVolumes_12", xbox::EMUPATCH(CDirectSoundStream_SetMixBinVolumes_12), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetMixBinVolumes_8", xbox::EMUPATCH(CDirectSoundStream_SetMixBinVolumes_8), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetMixBins", xbox::EMUPATCH(CDirectSoundStream_SetMixBins), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetMode", xbox::EMUPATCH(CDirectSoundStream_SetMode), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetOutputBuffer", xbox::EMUPATCH(CDirectSoundStream_SetOutputBuffer), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetPitch", xbox::EMUPATCH(CDirectSoundStream_SetPitch), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetPosition", xbox::EMUPATCH(CDirectSoundStream_SetPosition), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetRolloffCurve", xbox::EMUPATCH(CDirectSoundStream_SetRolloffCurve), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetRolloffFactor", xbox::EMUPATCH(CDirectSoundStream_SetRolloffFactor), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetVelocity", xbox::EMUPATCH(CDirectSoundStream_SetVelocity), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSoundStream_SetVolume", xbox::EMUPATCH(CDirectSoundStream_SetVolume), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSound_CommitDeferredSettings", xbox::EMUPATCH(CDirectSound_CommitDeferredSettings), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSound_GetSpeakerConfig", xbox::EMUPATCH(CDirectSound_GetSpeakerConfig), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSound_SynchPlayback", xbox::EMUPATCH(CDirectSound_SynchPlayback), PATCH_HLE_DSOUND), PATCH_ENTRY("CMcpxStream_Dummy_0x10", xbox::EMUPATCH(CMcpxStream_Dummy_0x10), PATCH_HLE_DSOUND), PATCH_ENTRY("DirectSoundCreate", xbox::EMUPATCH(DirectSoundCreate), PATCH_HLE_DSOUND), PATCH_ENTRY("DirectSoundCreateBuffer", xbox::EMUPATCH(DirectSoundCreateBuffer), PATCH_HLE_DSOUND), PATCH_ENTRY("DirectSoundCreateStream", xbox::EMUPATCH(DirectSoundCreateStream), PATCH_HLE_DSOUND), PATCH_ENTRY("DirectSoundDoWork", xbox::EMUPATCH(DirectSoundDoWork), PATCH_HLE_DSOUND), PATCH_ENTRY("DirectSoundGetSampleTime", xbox::EMUPATCH(DirectSoundGetSampleTime), PATCH_HLE_DSOUND), PATCH_ENTRY("DirectSoundUseFullHRTF", xbox::EMUPATCH(DirectSoundUseFullHRTF), PATCH_HLE_DSOUND), PATCH_ENTRY("DirectSoundUseFullHRTF4Channel", xbox::EMUPATCH(DirectSoundUseFullHRTF4Channel), PATCH_HLE_DSOUND), PATCH_ENTRY("DirectSoundUseLightHRTF", xbox::EMUPATCH(DirectSoundUseLightHRTF), PATCH_HLE_DSOUND), PATCH_ENTRY("DirectSoundUseLightHRTF4Channel", xbox::EMUPATCH(DirectSoundUseLightHRTF4Channel), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_AddRef", xbox::EMUPATCH(IDirectSoundBuffer_AddRef), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_GetCurrentPosition", xbox::EMUPATCH(IDirectSoundBuffer_GetCurrentPosition), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_GetStatus", xbox::EMUPATCH(IDirectSoundBuffer_GetStatus), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_GetVoiceProperties", xbox::EMUPATCH(IDirectSoundBuffer_GetVoiceProperties), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_Lock", xbox::EMUPATCH(IDirectSoundBuffer_Lock), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_Pause", xbox::EMUPATCH(IDirectSoundBuffer_Pause), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_PauseEx", xbox::EMUPATCH(IDirectSoundBuffer_PauseEx), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_Play", xbox::EMUPATCH(IDirectSoundBuffer_Play), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_PlayEx", xbox::EMUPATCH(IDirectSoundBuffer_PlayEx), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_Release", xbox::EMUPATCH(IDirectSoundBuffer_Release), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_Set3DVoiceData", xbox::EMUPATCH(IDirectSoundBuffer_Set3DVoiceData), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetAllParameters", xbox::EMUPATCH(IDirectSoundBuffer_SetAllParameters), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetBufferData", xbox::EMUPATCH(IDirectSoundBuffer_SetBufferData), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetConeAngles", xbox::EMUPATCH(IDirectSoundBuffer_SetConeAngles), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetConeOrientation", xbox::EMUPATCH(IDirectSoundBuffer_SetConeOrientation), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetConeOutsideVolume", xbox::EMUPATCH(IDirectSoundBuffer_SetConeOutsideVolume), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetCurrentPosition", xbox::EMUPATCH(IDirectSoundBuffer_SetCurrentPosition), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetDistanceFactor", xbox::EMUPATCH(IDirectSoundBuffer_SetDistanceFactor), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetDopplerFactor", xbox::EMUPATCH(IDirectSoundBuffer_SetDopplerFactor), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetEG", xbox::EMUPATCH(IDirectSoundBuffer_SetEG), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetFilter", xbox::EMUPATCH(IDirectSoundBuffer_SetFilter), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetFormat", xbox::EMUPATCH(IDirectSoundBuffer_SetFormat), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetFrequency", xbox::EMUPATCH(IDirectSoundBuffer_SetFrequency), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetHeadroom", xbox::EMUPATCH(IDirectSoundBuffer_SetHeadroom), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetI3DL2Source", xbox::EMUPATCH(IDirectSoundBuffer_SetI3DL2Source), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetLFO", xbox::EMUPATCH(IDirectSoundBuffer_SetLFO), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetLoopRegion", xbox::EMUPATCH(IDirectSoundBuffer_SetLoopRegion), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetMaxDistance", xbox::EMUPATCH(IDirectSoundBuffer_SetMaxDistance), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetMinDistance", xbox::EMUPATCH(IDirectSoundBuffer_SetMinDistance), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetMixBinVolumes_12", xbox::EMUPATCH(IDirectSoundBuffer_SetMixBinVolumes_12), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetMixBinVolumes_8", xbox::EMUPATCH(IDirectSoundBuffer_SetMixBinVolumes_8), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetMixBins", xbox::EMUPATCH(IDirectSoundBuffer_SetMixBins), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetMode", xbox::EMUPATCH(IDirectSoundBuffer_SetMode), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetNotificationPositions", xbox::EMUPATCH(IDirectSoundBuffer_SetNotificationPositions), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetOutputBuffer", xbox::EMUPATCH(IDirectSoundBuffer_SetOutputBuffer), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetPitch", xbox::EMUPATCH(IDirectSoundBuffer_SetPitch), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetPlayRegion", xbox::EMUPATCH(IDirectSoundBuffer_SetPlayRegion), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetPosition", xbox::EMUPATCH(IDirectSoundBuffer_SetPosition), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetRolloffCurve", xbox::EMUPATCH(IDirectSoundBuffer_SetRolloffCurve), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetRolloffFactor", xbox::EMUPATCH(IDirectSoundBuffer_SetRolloffFactor), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetVelocity", xbox::EMUPATCH(IDirectSoundBuffer_SetVelocity), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_SetVolume", xbox::EMUPATCH(IDirectSoundBuffer_SetVolume), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_Stop", xbox::EMUPATCH(IDirectSoundBuffer_Stop), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_StopEx", xbox::EMUPATCH(IDirectSoundBuffer_StopEx), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_Unlock", xbox::EMUPATCH(IDirectSoundBuffer_Unlock), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundBuffer_Use3DVoiceData", xbox::EMUPATCH(IDirectSoundBuffer_Use3DVoiceData), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundStream_Set3DVoiceData", xbox::EMUPATCH(IDirectSoundStream_Set3DVoiceData), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundStream_SetEG", xbox::EMUPATCH(IDirectSoundStream_SetEG), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundStream_SetFilter", xbox::EMUPATCH(IDirectSoundStream_SetFilter), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundStream_SetFrequency", xbox::EMUPATCH(IDirectSoundStream_SetFrequency), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundStream_SetHeadroom", xbox::EMUPATCH(IDirectSoundStream_SetHeadroom), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundStream_SetLFO", xbox::EMUPATCH(IDirectSoundStream_SetLFO), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundStream_SetMixBins", xbox::EMUPATCH(IDirectSoundStream_SetMixBins), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundStream_SetPitch", xbox::EMUPATCH(IDirectSoundStream_SetPitch), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundStream_SetVolume", xbox::EMUPATCH(IDirectSoundStream_SetVolume), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSoundStream_Use3DVoiceData", xbox::EMUPATCH(IDirectSoundStream_Use3DVoiceData), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_AddRef", xbox::EMUPATCH(IDirectSound_AddRef), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_CommitDeferredSettings", xbox::EMUPATCH(IDirectSound_CommitDeferredSettings), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_CommitEffectData", xbox::EMUPATCH(IDirectSound_CommitEffectData), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_CreateSoundBuffer", xbox::EMUPATCH(IDirectSound_CreateSoundBuffer), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_CreateSoundStream", xbox::EMUPATCH(IDirectSound_CreateSoundStream), PATCH_HLE_DSOUND), // PATCH_ENTRY("IDirectSound_DownloadEffectsImage", xbox::EMUPATCH(IDirectSound_DownloadEffectsImage), PATCH_HLE_DSOUND), PATCH_ENTRY("CDirectSound_DownloadEffectsImage", xbox::EMUPATCH(CDirectSound_DownloadEffectsImage), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_EnableHeadphones", xbox::EMUPATCH(IDirectSound_EnableHeadphones), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_GetCaps", xbox::EMUPATCH(IDirectSound_GetCaps), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_GetEffectData", xbox::EMUPATCH(IDirectSound_GetEffectData), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_GetOutputLevels", xbox::EMUPATCH(IDirectSound_GetOutputLevels), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_GetSpeakerConfig", xbox::EMUPATCH(IDirectSound_GetSpeakerConfig), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_Release", xbox::EMUPATCH(IDirectSound_Release), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_SetAllParameters", xbox::EMUPATCH(IDirectSound_SetAllParameters), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_SetDistanceFactor", xbox::EMUPATCH(IDirectSound_SetDistanceFactor), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_SetDopplerFactor", xbox::EMUPATCH(IDirectSound_SetDopplerFactor), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_SetEffectData", xbox::EMUPATCH(IDirectSound_SetEffectData), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_SetI3DL2Listener", xbox::EMUPATCH(IDirectSound_SetI3DL2Listener), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_SetMixBinHeadroom", xbox::EMUPATCH(IDirectSound_SetMixBinHeadroom), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_SetOrientation", xbox::EMUPATCH(IDirectSound_SetOrientation), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_SetPosition", xbox::EMUPATCH(IDirectSound_SetPosition), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_SetRolloffFactor", xbox::EMUPATCH(IDirectSound_SetRolloffFactor), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_SetVelocity", xbox::EMUPATCH(IDirectSound_SetVelocity), PATCH_HLE_DSOUND), PATCH_ENTRY("IDirectSound_SynchPlayback", xbox::EMUPATCH(IDirectSound_SynchPlayback), PATCH_HLE_DSOUND), //PATCH_ENTRY("XAudioCreateAdpcmFormat", xbox::EMUPATCH(XAudioCreateAdpcmFormat), PATCH_HLE_DSOUND), // NOTE: Not require to patch PATCH_ENTRY("XAudioDownloadEffectsImage", xbox::EMUPATCH(XAudioDownloadEffectsImage), PATCH_HLE_DSOUND), PATCH_ENTRY("XAudioSetEffectData", xbox::EMUPATCH(XAudioSetEffectData), PATCH_HLE_DSOUND), // OHCI PATCH_ENTRY("XGetDeviceChanges", xbox::EMUPATCH(XGetDeviceChanges), PATCH_HLE_OHCI), PATCH_ENTRY("XGetDeviceEnumerationStatus", xbox::EMUPATCH(XGetDeviceEnumerationStatus), PATCH_HLE_OHCI), PATCH_ENTRY("XGetDevices", xbox::EMUPATCH(XGetDevices), PATCH_HLE_OHCI), PATCH_ENTRY("XInitDevices", xbox::EMUPATCH(XInitDevices), PATCH_HLE_OHCI), PATCH_ENTRY("XInputClose", xbox::EMUPATCH(XInputClose), PATCH_HLE_OHCI), PATCH_ENTRY("XInputGetCapabilities", xbox::EMUPATCH(XInputGetCapabilities), PATCH_HLE_OHCI), PATCH_ENTRY("XInputGetDeviceDescription", xbox::EMUPATCH(XInputGetDeviceDescription), PATCH_HLE_OHCI), PATCH_ENTRY("XInputGetState", xbox::EMUPATCH(XInputGetState), PATCH_HLE_OHCI), PATCH_ENTRY("XInputOpen", xbox::EMUPATCH(XInputOpen), PATCH_HLE_OHCI), PATCH_ENTRY("XInputPoll", xbox::EMUPATCH(XInputPoll), PATCH_HLE_OHCI), PATCH_ENTRY("XInputSetLightgunCalibration", xbox::EMUPATCH(XInputSetLightgunCalibration), PATCH_HLE_OHCI), PATCH_ENTRY("XInputSetState", xbox::EMUPATCH(XInputSetState), PATCH_HLE_OHCI), // XAPI PATCH_ENTRY("ConvertThreadToFiber", xbox::EMUPATCH(ConvertThreadToFiber), PATCH_IS_FIBER), PATCH_ENTRY("CreateFiber", xbox::EMUPATCH(CreateFiber), PATCH_IS_FIBER), PATCH_ENTRY("DeleteFiber", xbox::EMUPATCH(DeleteFiber), PATCH_IS_FIBER), //PATCH_ENTRY("GetExitCodeThread", xbox::EMUPATCH(GetExitCodeThread), PATCH_ALWAYS), //PATCH_ENTRY("GetThreadPriority", xbox::EMUPATCH(GetThreadPriority), PATCH_ALWAYS), PATCH_ENTRY("OutputDebugStringA", xbox::EMUPATCH(OutputDebugStringA), PATCH_ALWAYS), //PATCH_ENTRY("RaiseException", xbox::EMUPATCH(RaiseException), PATCH_ALWAYS), //PATCH_ENTRY("SetThreadPriority", xbox::EMUPATCH(SetThreadPriority), PATCH_ALWAYS), //PATCH_ENTRY("SetThreadPriorityBoost", xbox::EMUPATCH(SetThreadPriorityBoost), PATCH_ALWAYS), PATCH_ENTRY("SignalObjectAndWait", xbox::EMUPATCH(SignalObjectAndWait), PATCH_ALWAYS), PATCH_ENTRY("SwitchToFiber", xbox::EMUPATCH(SwitchToFiber), PATCH_IS_FIBER), PATCH_ENTRY("XMountMUA", xbox::EMUPATCH(XMountMUA), PATCH_ALWAYS), PATCH_ENTRY("XMountMURootA", xbox::EMUPATCH(XMountMURootA), PATCH_ALWAYS), //PATCH_ENTRY("XSetProcessQuantumLength", xbox::EMUPATCH(XSetProcessQuantumLength), PATCH_ALWAYS), //PATCH_ENTRY("timeKillEvent", xbox::EMUPATCH(timeKillEvent), PATCH_ALWAYS), //PATCH_ENTRY("timeSetEvent", xbox::EMUPATCH(timeSetEvent), PATCH_ALWAYS), PATCH_ENTRY("XReadMUMetaData", xbox::EMUPATCH(XReadMUMetaData), PATCH_ALWAYS), PATCH_ENTRY("XUnmountMU", xbox::EMUPATCH(XUnmountMU), PATCH_ALWAYS), }; std::unordered_map<std::string, subhook::Hook> g_FunctionHooks; inline bool TitleRequiresUnpatchedFibers() { static bool detected = false; static bool result = false; // Prevent running the check every time this function is called if (detected) { return result; } // Array of known games that require the fiber unpatch hack DWORD titleIds[] = { 0x46490002, // Futurama PAL 0x56550008, // Futurama NTSC 0 }; DWORD* pTitleId = &titleIds[0]; while (*pTitleId != 0) { if (g_pCertificate->dwTitleId == *pTitleId) { result = true; break; } pTitleId++; } detected = true; return result; } // NOTE: EmuInstallPatch do not get to be in XbSymbolDatabase, do the patches in Cxbx project only. inline void EmuInstallPatch(const std::string FunctionName, const xbox::addr_xt FunctionAddr) { auto it = g_PatchTable.find(FunctionName); if (it == g_PatchTable.end()) { return; } auto patch = it->second; if ((patch.flags & PATCH_HLE_D3D) && bLLE_GPU) { printf("HLE: %s: Skipped (LLE GPU Enabled)\n", FunctionName.c_str()); return; } if ((patch.flags & PATCH_HLE_DSOUND) && bLLE_APU) { printf("HLE: %s: Skipped (LLE APU Enabled)\n", FunctionName.c_str()); return; } if ((patch.flags & PATCH_HLE_OHCI) && bLLE_USB) { printf("HLE: %s: Skipped (LLE OHCI Enabled)\n", FunctionName.c_str()); return; } // HACK: Some titles require unpatched Fibers, otherwise they enter an infinite loop // while others require patched Fibers, otherwise they outright crash // This is caused by limitations of Direct Code Execution and Cxbx-R's threading model if ((patch.flags & PATCH_IS_FIBER) && TitleRequiresUnpatchedFibers()) { printf("HLE: %s: Skipped (Game requires unpatched Fibers)\n", FunctionName.c_str()); return; } g_FunctionHooks[FunctionName].Install((void*)(FunctionAddr), (void*)patch.patchFunc); printf("HLE: %s Patched\n", FunctionName.c_str()); } void EmuInstallPatches() { for (const auto& it : g_SymbolAddresses) { EmuInstallPatch(it.first, it.second); } LookupTrampolinesD3D(); LookupTrampolinesXAPI(); } void* GetPatchedFunctionTrampoline(const std::string functionName) { auto it = g_FunctionHooks.find(functionName); if (it != g_FunctionHooks.end()) { auto trampoline = it->second.GetTrampoline(); if (trampoline == nullptr) { EmuLogEx(CXBXR_MODULE::HLE, LOG_LEVEL::WARNING, "Failed to get XB_Trampoline for %s", functionName.c_str()); } return trampoline; } return nullptr; }
LukeUsher/Cxbx-Reloaded
src/core/hle/Patches.cpp
C++
gpl-2.0
37,876
# This file is part of the Enkel web programming library. # # Copyright (C) 2007 Espen Angell Kristiansen (espen@wsgi.net) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. from unittest import TestCase from enkel.wansgli.testhelpers import unit_case_suite, run_suite class Test(TestCase): def suite(): return unit_case_suite(Test) if __name__ == '__main__': run_suite(suite())
espenak/enkel
testsuite/unittest_tpl.py
Python
gpl-2.0
1,046
<?php /** * @package WordPress * @subpackage Adventure_Journal */ $themeOpts = get_option('ctx-adventurejournal-options'); get_header(); ?> <div class="content" <?php ctx_aj_getlayout(); ?>> <div id="col-main" style="<?php echo ctx_aj_customwidth('content'); ?>"> <div id="main-content" <?php //ctx_aj_crinkled_paper(); ?>> <!-- BEGIN Main Content--> <?php //Start the Loop if (have_posts()) : while (have_posts()) : the_post(); ?> <div <?php post_class() ?> id="post-<?php the_ID(); ?>"> <?php echo sprintf('<h1 class="storytitle">%s</h1>',get_the_title());?> <?php if($themeOpts['featured-header']!='true') { the_post_thumbnail(); } ?> <div class="meta">Posted by <?php the_author_posts_link(); ?> on <?php the_date();?></div> <?php if(!function_exists('is_admin_bar_showing')){ edit_post_link(__('Edit Post', 'adventurejournal')); } else if ( !is_admin_bar_showing() ){ edit_post_link(__('Edit Post', 'adventurejournal')); } ?> <div class="storycontent"> <?php the_content(__('(more...)')); ?> <div class="clear"></div> </div> <div class="feedback"> <?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'adventurejournal' ), 'after' => '</div>' ) ); ?> <?php _e('Posted under ','adventurejournal'); ?> <?php the_category(',') ?> <?php the_tags(__('and tagged with '), ', ', ' '); ?><br /> <?php comments_popup_link(__('Comments (0)'), __('Comments (1)'), __('Comments (%)')); ?> </div> </div> <?php comments_template(); // Get wp-comments.php template ?> <?php endwhile; else: ?> <p><?php _e('Sorry, no posts matched your criteria.','adventurejournal'); ?></p> <?php endif; ?> <?php posts_nav_link(' &#8212; ', __('&laquo; Newer Posts'), __('Older Posts &raquo;')); ?> <!-- END Main Content--> </div> </div> <?php get_sidebar(); ?> <div class="clear"></div> </div> <?php get_footer(); ?>
Deepak23in/askForSolutionTest
wp-content/themes/adventure-journal/single.php
PHP
gpl-2.0
2,510
<?php /** * File containing the ezpRestRequest class * * @copyright Copyright (C) 1999-2011 eZ Systems AS. All rights reserved. * @license http://ez.no/software/proprietary_license_options/ez_proprietary_use_license_v1_0 eZ Proprietary Use License v1.0 * @package rest * */ /** * Class mimicking ezcMvcRequest with distinct containers for GET and POST variables. * * The current implementation is a tentative implementation, for long term * usage, we are likely to use dedicated structs such as for cookie. This in * addition or alternatively to a more selective parser, which could cherry pick * variables depending on request type, context and so forth. */ class ezpRestRequest extends ezcMvcRequest { /** * GET variables * * @var array */ public $get; /** * POST variables * * @var array */ public $post; /** * Original request method * * @var string */ public $originalProtocol; /** * PUT & POST variables * * @var array */ public $inputVariables; /** * Variables related to content, extracted from GET * * @var array */ public $contentVariables; /** * Signifies whether the request was made over an encrypted connection. * * @var bool */ public $isEncrypted; /** * Constructs a new ezpRestRequest. * * @param DateTime $date * @param string $protocol * @param string $host * @param string $uri * @param string $requestId * @param string $referrer * @param array $variables Containing request variables set by the router * @param array $get The GET variables which are available in the request * @param array $post The POST variables that are available in the request * @param array $contentVariables GET variables related to eZ Publish content * @param bool $isEncrypted Is the request made over an encrypted connection * @param string $body * @param array(ezcMvcRequestFile) $files * @param ezcMvcRequestAccept $accept * @param ezcMvcRequestUserAgent $agent * @param ezcMvcRequestAuthentication $authentication * @param ezcMvcRawRequest $raw * @param array(ezcMvcRequestCookie) $cookies * @param bool $isFatal * @param array $inputVariables The PUT & DELETE input variables that are available in the request */ public function __construct( $date = null, $protocol = '', $host = '', $uri = '', $requestId = '', $referrer = '', $variables = array(), $get = array(), $post = array(), $contentVariables = array(), $isEncrypted = false, $body = '', $files = null, $accept = null, $agent = null, $authentication = null, $raw = null, $cookies = array(), $isFatal = false, $originalProtocol = null, $inputVariables = array() ) { $this->date = $date; $this->protocol = $protocol; $this->host = $host; $this->uri = $uri; $this->requestId = $requestId; $this->referrer = $referrer; $this->variables = $variables; $this->get = $get; $this->post = $post; $this->contentVariables = $contentVariables; $this->isEncrypted = $isEncrypted; $this->body = $body; $this->files = $files; $this->accept = $accept; $this->agent = $agent; $this->authentication = $authentication; $this->raw = $raw; $this->cookies = $cookies; $this->originalProtocol = ( $originalProtocol === null ? $protocol : $originalProtocol ); $this->inputVariables = $inputVariables; } /** * Returns a new instance of this class with the data specified by $array. * * $array contains all the data members of this class in the form: * array('member_name'=>value). * * __set_state makes this class exportable with var_export. * var_export() generates code, that calls this method when it * is parsed with PHP. * * @param array(string=>mixed) $array * @return ezpRestRequest */ static public function __set_state( array $array ) { return new ezpRestRequest( $array['date'], $array['protocol'], $array['host'], $array['uri'], $array['requestId'], $array['referrer'], $array['variables'], $array['get'], $array['post'], $array['contentVariables'], $array['isEncrypted'], $array['body'], $array['files'], $array['accept'], $array['agent'], $array['authentication'], $array['raw'], $array['cookies'], $array['isFatal'], $array['originalProtocol'], $array['inputVariables'] ); } /** * Returns base URI with protocol and host (e.g. http://myhost.com/foo/bar) * @return string */ public function getBaseURI() { $hostUri = $this->getHostURI(); $apiName = ezpRestPrefixFilterInterface::getApiProviderName(); $apiPrefix = eZINI::instance( 'rest.ini' )->variable( 'System', 'ApiPrefix'); $uri = str_replace( $apiPrefix, $apiPrefix.'/'.$apiName, $this->uri ); $baseUri = $hostUri.$uri; return $baseUri; } /** * Returns the host with the protocol * @return string */ public function getHostURI() { $protIndex = strpos( $this->protocol, '-' ); $protocol = substr( $this->protocol, 0, $protIndex ); $hostUri = $protocol.'://'.$this->host; return $hostUri; } /** * Returns current content variables as a regular query string (e.g. "foo=bar&this=that") * @param bool $withQuestionMark If true, the question mark ("?") will be added * @return string */ public function getContentQueryString( $withQuestionMark = false ) { $queryString = ''; $aParams = array(); foreach( $this->contentVariables as $name => $value ) { if( $value !== null ) $aParams[] = $name.'='.$value; } if( !empty( $aParams ) ) { $queryString = $withQuestionMark ? '?' : ''; $queryString .= implode( '&', $aParams ); } return $queryString; } } ?>
gggeek/ezcontentstaging
patches/4.5/kernel/private/rest/classes/request/rest_request.php
PHP
gpl-2.0
6,241
/* * Copyright (c) 1998-2010 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package javax.el; /** * EL exceptions */ public class PropertyNotFoundException extends ELException { public PropertyNotFoundException() { } public PropertyNotFoundException(String message) { super(message); } public PropertyNotFoundException(String message, Throwable cause) { super(message, cause); } public PropertyNotFoundException(Throwable cause) { super(cause); } }
christianchristensen/resin
modules/servlet16/src/javax/el/PropertyNotFoundException.java
Java
gpl-2.0
1,449
<div class="row"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); /** * Get blog posts by blog layout. */ get_template_part('loop/content', 'team-full'); endwhile; else : /** * Display no posts message if none are found. */ get_template_part('loop/content','none'); endif; ?> </div>
seyekuyinu/highlifer
wp-content/themes/highlifer/loop/loop-team-full.php
PHP
gpl-2.0
355
/* * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.xml.internal.bind.v2.runtime; /** * Namespace URIs and local names sorted by their indices. * Number of Names used for EIIs and AIIs * * @author Kohsuke Kawaguchi */ public final class NameList { /** * Namespace URIs by their indices. No nulls in this array. * Read-only. */ public final String[] namespaceURIs; /** * For each entry in {@link #namespaceURIs}, whether the namespace URI * can be declared as the default. If namespace URI is used in attributes, * we always need a prefix, so we can't. * * True if this URI has to have a prefix. */ public final boolean[] nsUriCannotBeDefaulted; /** * Local names by their indices. No nulls in this array. * Read-only. */ public final String[] localNames; /** * Number of Names for elements */ public final int numberOfElementNames; /** * Number of Names for attributes */ public final int numberOfAttributeNames; public NameList(String[] namespaceURIs, boolean[] nsUriCannotBeDefaulted, String[] localNames, int numberElementNames, int numberAttributeNames) { this.namespaceURIs = namespaceURIs; this.nsUriCannotBeDefaulted = nsUriCannotBeDefaulted; this.localNames = localNames; this.numberOfElementNames = numberElementNames; this.numberOfAttributeNames = numberAttributeNames; } }
TheTypoMaster/Scaper
openjdk/jaxws/drop_included/jaxws_src/src/com/sun/xml/internal/bind/v2/runtime/NameList.java
Java
gpl-2.0
2,634
<?php /** * @file * Displays a single Drupal page. * * Available variables: * * General utility variables: * - $base_path: The base URL path of the Drupal installation. At the very * least, this will always default to /. * - $css: An array of CSS files for the current page. * - $directory: The directory the theme is located in, e.g. themes/garland or * themes/garland/minelli. * - $is_front: TRUE if the current page is the front page. * - $logged_in: TRUE if the user is registered and signed in. * - $is_admin: TRUE if the user has permission to access administration pages. * * Page metadata: * - $language: (object) The language the site is being displayed in. * $language->language contains its textual representation. * $language->dir contains the language direction. It will either be 'ltr' or * 'rtl'. * - $head_title: A modified version of the page title, for use in the TITLE * element. * - $head: Markup for the HEAD element (including meta tags, keyword tags, and * so on). * - $styles: Style tags necessary to import all CSS files for the page. * - $scripts: Script tags necessary to load the JavaScript files and settings * for the page. * - $body_classes: A set of CSS classes for the BODY tag. This contains flags * indicating the current layout (multiple columns, single column), the * current path, whether the user is logged in, and so on. * * Site identity: * - $front_page: The URL of the front page. Use this instead of $base_path, * when linking to the front page. This includes the language domain or * prefix. * - $logo: The path to the logo image, as defined in theme configuration. * - $site_name: The name of the site, empty when display has been disabled in * theme settings. * - $site_slogan: The slogan of the site, empty when display has been disabled * in theme settings. * - $mission: The text of the site mission, empty when display has been * disabled in theme settings. * * Navigation: * - $search_box: HTML to display the search box, empty if search has been * disabled. * - $primary_links (array): An array containing primary navigation links for * the site, if they have been configured. * - $secondary_links (array): An array containing secondary navigation links * for the site, if they have been configured. * * Page content (in order of occurrence in the default page.tpl.php): * - $left: The HTML for the left sidebar. * - $breadcrumb: The breadcrumb trail for the current page. * - $title: The page title, for use in the actual HTML content. * - $help: Dynamic help text, mostly for admin pages. * - $messages: HTML for status and error messages. Should be displayed * prominently. * - $tabs: Tabs linking to any sub-pages beneath the current page (e.g., the * view and edit tabs when displaying a node). * - $content: The main content of the current Drupal page. * - $right: The HTML for the right sidebar. * - $node: The node object, if there is an automatically-loaded node associated * with the page, and the node ID is the second argument in the page's path * (e.g. node/12345 and node/12345/revisions, but not comment/reply/12345). * * Footer/closing data: * - $feed_icons: A string of all feed icons for the current page. * - $footer_message: The footer message as defined in the admin settings. * - $footer : The footer region. * - $closure: Final closing markup from any modules that have altered the page. * This variable should always be output last, after all other dynamic * content. * * @see template_preprocess() * @see template_preprocess_page() */ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>"> <head> <?php print $head; ?> <title><?php print $head_title; ?></title> <?php print $styles; ?> <?php print $scripts; ?> <script type="text/javascript"><?php /* Needed to avoid Flash of Unstyled Content in IE */ ?> </script> </head> <body class="<?php print $body_classes; ?>"> <div id="page"> <div id="header"> <div id="logo-title"> <?php if (!empty($logo)): ?> <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" id="logo"> <img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" /> </a> <?php endif; ?> <div id="name-and-slogan"> <?php if (!empty($site_name)): ?> <h1 id="site-name"> <a href="<?php print $front_page ?>" title="<?php print t('Home'); ?>" rel="home"><span><?php print $site_name; ?></span></a> </h1> <?php endif; ?> <?php if (!empty($site_slogan)): ?> <div id="site-slogan"><?php print $site_slogan; ?></div> <?php endif; ?> </div> <!-- /name-and-slogan --> </div> <!-- /logo-title --> <?php if (!empty($search_box)): ?> <div id="search-box"><?php print $search_box; ?></div> <?php endif; ?> <?php if (!empty($header)): ?> <div id="header-region"> <?php print $header; ?> </div> <?php endif; ?> </div> <!-- /header --> <div id="container" class="clear-block"> <div id="navigation" class="menu <?php if (!empty($primary_links)) { print "withprimary"; } if (!empty($secondary_links)) { print " withsecondary"; } ?> "> <?php if (!empty($primary_links)): ?> <div id="primary" class="clear-block"> <?php print theme('links', $primary_links, array('class' => 'links primary-links')); ?> </div> <?php endif; ?> <?php if (!empty($secondary_links)): ?> <div id="secondary" class="clear-block"> <?php print theme('links', $secondary_links, array('class' => 'links secondary-links')); ?> </div> <?php endif; ?> </div> <!-- /navigation --> <?php if (!empty($left)): ?> <div id="sidebar-left" class="column sidebar"> <?php print $left; ?> </div> <!-- /sidebar-left --> <?php endif; ?> <div id="main" class="column"><div id="main-squeeze"> <?php if (!empty($breadcrumb)): ?><div id="breadcrumb"><?php print $breadcrumb; ?></div><?php endif; ?> <?php if (!empty($mission)): ?><div id="mission"><?php print $mission; ?></div><?php endif; ?> <div id="content"> <?php if (!empty($title)): ?><h1 class="title" id="page-title"><?php print $title; ?></h1><?php endif; ?> <?php if (!empty($tabs)): ?><div class="tabs"><?php print $tabs; ?></div><?php endif; ?> <?php if (!empty($messages)): print $messages; endif; ?> <?php if (!empty($help)): print $help; endif; ?> <div id="content-content" class="clear-block"> <?php print $content; ?> </div> <!-- /content-content --> <?php print $feed_icons; ?> </div> <!-- /content --> </div></div> <!-- /main-squeeze /main --> <?php if (!empty($right)): ?> <div id="sidebar-right" class="column sidebar"> <?php print $right; ?> </div> <!-- /sidebar-right --> <?php endif; ?> </div> <!-- /container --> <div id="footer-wrapper"> <div id="footer"> <?php print $footer_message; ?> <?php if (!empty($footer)): print $footer; endif; ?> </div> <!-- /footer --> </div> <!-- /footer-wrapper --> <?php print $closure; ?> </div> <!-- /page --> </body> </html>
ReubenScott/websites
sites/all/themes/custom/greyscale/page.tpl.php
PHP
gpl-2.0
7,699
<?php /** * Provide the output functions for the SelectUser class * @author Nick Korbel <lqqkout13@users.sourceforge.net> * @version 02-05-05 * @package Templates * * Copyright (C) 2003 - 2005 phpScheduleIt * License: GPL, see LICENSE */ $link = CmnFns::getNewLink(); // Get Link object /** * Prints out the user management table * @param Object $pager pager object * @param mixed $users array of user data * @param string $err last database error */ function print_user_list(&$pager, $users, $err, $javascript) { global $link; ?> <table width="100%" border="0" cellspacing="0" cellpadding="1" align="center"> <tr> <td class="tableBorder"> <table width="100%" border="0" cellspacing="1" cellpadding="0"> <tr> <td colspan="7" class="tableTitle">&#8250; <?=translate('All Users')?> </td> </tr> <tr class="rowHeaders"> <td width="40%"><?=translate('Name')?></td> <td width="60%"><?=translate('Email')?></td> </tr> <? if (!$users) echo '<tr class="cellColor0"><td colspan="2" style="text-align: center;">' . $err . '</td></tr>' . "\n"; for ($i = 0; is_array($users) && $i < count($users); $i++) { $cur = $users[$i]; $first_name = $cur['first_name']; $last_name = $cur['last_name']; $email = $cur['email']; $first_name_last_name = array($first_name, $last_name); echo "<tr class=\"cellColor" . ($i%2) . "\" align=\"center\" onmouseover=\"this.className='SelectUserRowOver';\" onmouseout=\"this.className='cellColor" . ($i%2) . "';\" onclick=\"" . sprintf("$javascript('%s','%s','%s','%s');", $cur['user_id'], $first_name, str_replace("'", "\'",$last_name), $email) . ";\">\n" . "<td style=\"text-align:left;\">$first_name $last_name</td>\n" . "<td style=\"text-align:left;\">$email</td>\n" . "</tr>\n"; } // Close users table ?> </table> </td> </tr> </table> <br /> <form name="name_search" action="<?=$_SERVER['PHP_SELF']?>" method="get"> <p align="center"> <? print_last_name_links(); ?> </p> <br /> <p align="center"> <?=translate('First Name')?> <input type="text" name="firstName" class="textbox" /> <?=translate('Last Name')?> <input type="text" name="lastName" class="textbox" /> <input type="hidden" name="searchUsers" value="true" /> <input type="hidden" name="<?=$pager->getLimitVar()?>" value="<?=$pager->getLimit()?>" /> <? if (isset($_GET['order'])) { ?> <input type="hidden" name="order" value="<?=$_GET['order']?>" /> <? } ?> <? if (isset($_GET['vert'])) { ?> <input type="hidden" name="vert" value="<?=$_GET['vert']?>" /> <? } ?> <input type="submit" name="searchUsersBtn" value="<?=translate('Search Users')?>" class="button" /> </p> </form> <? } /** * Prints out the links to select last names * @param none */ function print_last_name_links() { global $letters; echo '<a href="javascript: search_user_last_name(\'\');">' . translate('All Users') . '</a>'; foreach($letters as $letter) { echo '<a href="javascript: search_user_last_name(\''. $letter . '\');" style="padding-left: 10px; font-size: 12px;">' . $letter . '</a>'; } } ?>
ecleveland5/open-equipment-scheduler
templates/selectuser.template.php
PHP
gpl-2.0
3,158
package com.jon.exchangemarket.interceptor; import com.jfinal.aop.Interceptor; import com.jfinal.core.ActionInvocation; public class LoginInterceptor implements Interceptor{ @Override public void intercept(ActionInvocation ai) { System.out.println("Before action invoking"); ai.invoke(); ai.getViewPath(); System.out.println("After action invoking"); } }
johnzzc/JFExchangemarket
ExchangeMarket/src/com/jon/exchangemarket/interceptor/LoginInterceptor.java
Java
gpl-2.0
373
<?php namespace SBL; use OutputPage; use Title; /** * @license GNU GPL v2+ * @since 1.0 * * @author mwjames */ class PageDisplayOutputModifier { /** * @var boolean */ private $hideSubpageParentState; /** * @var array */ private $subpageByNamespace; /** * @since 1.0 * * @param boolean $hideSubpageParentState */ public function setHideSubpageParentState( $hideSubpageParentState ) { $this->hideSubpageParentState = $hideSubpageParentState; } /** * @since 1.0 * * @param array $subpageByNamespace */ public function setSubpageByNamespace( array $subpageByNamespace ) { $this->subpageByNamespace = $subpageByNamespace; } /** * @since 1.0 * * @param OutputPage $output */ public function modifyOutput( OutputPage $output ) { $output->addModules( 'ext.semanticbreadcrumblinks' ); if ( !$this->hideSubpageParentState || !$this->hasSubpageEnabledNamespace( $output->getTitle()->getNamespace() ) ) { return; } if ( $output->getTitle()->isSubpage() ) { $output->setPageTitle( $output->getTitle()->getSubpageText() ); } } private function hasSubpageEnabledNamespace( $namespace ) { return isset( $this->subpageByNamespace[ $namespace ] ) && $this->subpageByNamespace[ $namespace ]; } }
brandonphuong/mediawiki
extensions/SemanticBreadcrumbLinks/src/PageDisplayOutputModifier.php
PHP
gpl-2.0
1,267
<?php /** * moduleFunctions.php * Copyright 2013-2016 by Juan Antonio Martinez ( juansgaviota at gmail dot com ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ require_once(__DIR__."/../server/logging.php"); require_once(__DIR__."/../server/tools.php"); require_once(__DIR__."/Federations.php"); try { $result=null; $federation=http_request("Federation","i",-1); // -1 defaults to all federations $operation=http_request("Operation","s",null); // retrieve requested operation $recorrido=http_request("Recorrido","i",0); // 0:separate 1:mixed 2:common if ($operation===null) throw new Exception("Call to moduleFunctions without 'Operation' requested"); switch ($operation) { case "list": $result= Federations::getFederationList(); break; case "info": $result= Federations::getFederation($federation); break; case "enumerate": $result= Federations::enumerate(); break; case "infomanga": $result= Federations::infomanga($federation,$recorrido); break; default: throw new Exception("moduleFunctions:: invalid operation: '$operation' provided"); } if ($result===null) throw new Exception($jueces->errormsg); if ($result==="") echo json_encode(array('success'=>true)); else echo json_encode($result); } catch (Exception $e) { do_log($e->getMessage()); echo json_encode(array('errorMsg'=>$e->getMessage())); } ?>
nedy13/AgilityContest
agility/modules/moduleFunctions.php
PHP
gpl-2.0
2,052
<?php header('Content-type: text/html; charset=iso-8859-1'); ?><html> <head> <title>Administration Help</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body style="font-family: Verdana; font-size: 10px" link="#000000" vlink="#000000" alink="#000000" bgcolor="#FFFFFF"> <center><big><b>Calendar Administration</b></big></center><br> <li><b>Index</b> : Events list<br> <br> <li><b>Add event </b> : To add an event<br> <br> <li><b>Edit event</b> : To edit an event<br> <br> <li><b>Preferences</b> : Calendar's preferences<br> <br> </body></html>
donaldinou/nuked-gamer
help/english/Calendar.php
PHP
gpl-2.0
586
module Admin class PhotosController < AdminController def initialize(photo_repository = Photo, storage = Spank::IOC.resolve(:blob_storage)) @photo_repository = photo_repository @storage = storage super() end def index @photos = paginate(@photo_repository.order(id: :desc)) end def show @photo = @photo_repository.find(params[:id]) end def update ReProcessPhotoJob.perform_later(@photo_repository.find(params[:id])) redirect_to admin_photos_path end end end
cakeside/cakeside
app/controllers/admin/photos_controller.rb
Ruby
gpl-2.0
538
#!/usr/bin/env python # # Copyright (C) 2004 Mark H. Lyon <mark@marklyon.org> # # This file is the Mbox & Maildir to Gmail Loader (GML). # # Mbox & Maildir to Gmail Loader (GML) is free software; you can redistribute # it and/or modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # GML is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License # for more details. # # You should have received a copy of the GNU General Public License # along with GML; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # Origional development thread at Ars Technica: # http://episteme.arstechnica.com/eve/ubb.x?a=tpc&s=50009562&f=6330927813&m=108000474631 # # Version 0.1 - 15 Jun 04 16:28 Supports Mbox # Version 0.2 - 15 Jun 04 18:48 Implementing Magus` suggestion for Maildir # Version 0.3 - 16 Jun 04 16:17 Implement Rold Gold suggestion for counters # Version 0.4 - 17 Jun 04 13:15 Add support for changing SMTP server at command line # Version 0.5 - 05 Oct 09 redo exception handling to see what Google's # complaints are on failure, update to use TLS import mailbox, smtplib, sys, time, string def main (): print "\nMbox & Maildir to Gmail Loader (GML) by Mark Lyon <mark@marklyon.org>\n" if len(sys.argv) in (5, 6) : boxtype_in = sys.argv[1] mailboxname_in = sys.argv[2] emailname_in = sys.argv[3] password_in = sys.argv[4] else: usage() try: smtpserver_in = sys.argv[5] except: smtpserver_in = 'smtp.gmail.com' print "Using smtpserver %s\n" % smtpserver_in count = [0,0,0] try: if boxtype_in == "maildir": mb = mailbox.Maildir(mailboxname_in) else: mb = mailbox.UnixMailbox (file(mailboxname_in,'r')) msg = mb.next() except: print "*** Can't open file or directory. Is the path correct? ***\n" usage() while msg is not None: try: document = msg.fp.read() except: count[2] = count[2] + 1 print "*** %d MESSAGE READ FAILED, SKIPPED" % (count[2]) msg = mb.next() if document is not None: fullmsg = msg.__str__( ) + '\x0a' + document server = smtplib.SMTP(smtpserver_in) #server.set_debuglevel(1) server.ehlo() server.starttls() # smtplib won't send auth info without this second ehlo after # starttls -- thanks to # http://bytes.com/topic/python/answers/475531-smtplib-authentication-required-error # for the tip server.ehlo() server.login(emailname_in, password_in) server.sendmail(msg.getaddr('From')[1], emailname_in, fullmsg) server.quit() count[0] = count[0] + 1 print " %d Forwarded a message from: %s" % (count[0], msg.getaddr('From')[1]) msg = mb.next() print "\nDone. Stats: %d success %d error %d skipped." % (count[0], count[1], count[2]) def usage(): print 'Usage: gml.py [mbox or maildir] [mbox file or maildir path] [gmail address] [gmail password] [Optional SMTP Server]' print 'Exmpl: gml.py mbox "c:\mail\Inbox" marklyon@gmail.com password' print 'Exmpl: gml.py maildir "c:\mail\Inbox\" marklyon@gmail.com password gsmtp171.google.com\n' sys.exit() if __name__ == '__main__': main ()
jslag/gml
gml.py
Python
gpl-2.0
3,630
package pl.azurro.kafka.groupmonitor; import static java.util.Collections.singletonList; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import kafka.cluster.Broker; import kafka.javaapi.OffsetRequest; import kafka.javaapi.OffsetResponse; import kafka.javaapi.PartitionMetadata; import kafka.javaapi.TopicMetadata; import kafka.javaapi.TopicMetadataRequest; import kafka.javaapi.TopicMetadataResponse; import kafka.javaapi.consumer.SimpleConsumer; import org.I0Itec.zkclient.ZkClient; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import pl.azurro.kafka.groupmonitor.model.GroupInfo; import pl.azurro.kafka.zookeeper.ZookeeperUtils; @RunWith(MockitoJUnitRunner.class) public class GroupMonitorTest { private static final String TOPIC_NAME = "topicName"; private static final String GROUP_ID = "testGroup"; private static final String zkServers = "host1:2181,host2:2181,host3:2181/mychroot"; @Mock private SimpleConsumer consumer; @Mock private ZookeeperUtils zookeeperUtils; @Mock private ZkClient zkClient; @Mock private Broker broker; private GroupMonitor monitor = new GroupMonitor(zkServers) { @Override SimpleConsumer createSimpleConsumerFor(Broker broker) { return consumer; } @Override ZookeeperUtils createZookeeperUtils() { return zookeeperUtils; } }; @Before public void setUp() { when(zookeeperUtils.getZkClient(zkServers)).thenReturn(zkClient); when(zookeeperUtils.getBrokers(zkClient)).thenReturn(singletonList(broker)); when(broker.getConnectionString()).thenReturn("host1:9092"); } @Test public void shouldReturnGroupInfo() throws Exception { OffsetResponse offsetResponse = mock(OffsetResponse.class); TopicMetadataResponse response = mock(TopicMetadataResponse.class); TopicMetadata topicMetadata = mock(TopicMetadata.class); PartitionMetadata partitionMetadata = mock(PartitionMetadata.class); when(topicMetadata.partitionsMetadata()).thenReturn(singletonList(partitionMetadata)); when(response.topicsMetadata()).thenReturn(singletonList(topicMetadata)); when(consumer.send(any(TopicMetadataRequest.class))).thenReturn(response); when(topicMetadata.topic()).thenReturn(TOPIC_NAME); when(partitionMetadata.leader()).thenReturn(broker); when(partitionMetadata.partitionId()).thenReturn(0); when(zookeeperUtils.getLastConsumedOffset(zkClient, GROUP_ID, TOPIC_NAME, 0)).thenReturn(90L); when(consumer.getOffsetsBefore(any(OffsetRequest.class))).thenReturn(offsetResponse); when(offsetResponse.hasError()).thenReturn(false); when(offsetResponse.offsets(TOPIC_NAME, 0)).thenReturn(new long[] { 1112 }); GroupInfo info = monitor.getGroupInfo(GROUP_ID); GroupInfo expectedInfo = new GroupInfo(GROUP_ID); expectedInfo.addInfoFor(TOPIC_NAME, 0, 1112, 90); assertThat(info).isEqualTo(expectedInfo); } }
azurro/kafka-group-monitor
src/test/java/pl/azurro/kafka/groupmonitor/GroupMonitorTest.java
Java
gpl-2.0
3,275
<?php /** * Core file * * @author Vince Wooll <sales@jomres.net> * @version Jomres 7 * @package Jomres * @copyright 2005-2013 Vince Wooll * Jomres (tm) PHP, CSS & Javascript files are released under both MIT and GPL2 licenses. This means that you can choose the license that best suits your project, and use it accordingly. **/ // ################################################################ defined( '_JOMRES_INITCHECK' ) or die( '' ); // ################################################################ class j06000module_popup { function j06000module_popup() { $MiniComponents = jomres_singleton_abstract::getInstance( 'mcHandler' ); if ( $MiniComponents->template_touch ) { $this->template_touchable = false; return; } //add_gmaps_source(); $property_uid = (int) jomresGetParam( $_REQUEST, "id", 0 ); $result = ''; if ( $property_uid > 0 ) { $current_property_details = jomres_singleton_abstract::getInstance( 'basic_property_details' ); $current_property_details->gather_data($property_uid); $inline_calendar = $MiniComponents->specificEvent( '06000', 'ui_availability_calendar', array ( 'property_uid' => $property_uid, 'return_calendar' => "1", 'noshowlegend' => "1" ) ); $mrConfig = getPropertySpecificSettings( $property_uid ); set_showtime( 'property_uid', $property_uid ); $customTextObj = jomres_singleton_abstract::getInstance( 'custom_text' ); //$property_image = get_showtime( 'live_site' ) . "/jomres/images/jrhouse.png"; //if ( file_exists( JOMRESCONFIG_ABSOLUTE_PATH . JRDS . "jomres" . JRDS . "uploadedimages" . JRDS . $property_uid . "_property_" . $property_uid . ".jpg" ) ) //$property_image = get_showtime( 'live_site' ) . "/jomres/uploadedimages/" . $property_uid . "_property_" . $property_uid . ".jpg"; $output = array (); $price_output = get_property_price_for_display_in_lists( $property_uid ); $output[ 'PRICE_PRE_TEXT' ] = $price_output[ 'PRE_TEXT' ]; $output[ 'PRICE_PRICE' ] = $price_output[ 'PRICE' ]; $output[ 'PRICE_POST_TEXT' ] = $price_output[ 'POST_TEXT' ]; $output[ 'PROPERTY_UID' ] = $property_uid; $output[ 'RANDOM_IDENTIFIER' ] = generateJomresRandomString( 10 ); $output[ 'JOMRES_SITEPAGE_URL_AJAX' ] = JOMRES_SITEPAGE_URL_AJAX; $output[ 'LIVE_SITE' ] = get_showtime( 'live_site' ); $output[ 'MOREINFORMATION' ] = jr_gettext( '_JOMRES_COM_A_CLICKFORMOREINFORMATION', _JOMRES_COM_A_CLICKFORMOREINFORMATION, $editable = false, true ); $output[ 'MOREINFORMATIONLINK' ] = jomresURL( JOMRES_SITEPAGE_URL . "&task=viewproperty&property_uid=" . $property_uid ); $output[ 'STARSIMAGES' ] = ''; for ( $i = 1; $i <= $current_property_details->stars; $i++ ) { $output[ 'STARSIMAGES' ] .= "<img src=\"" . get_showtime( 'live_site' ) . "/jomres/images/star.png\" alt=\"star\" border=\"0\" />"; } $output[ 'SUPERIOR' ] = ''; if ( $current_property_details->superior == 1 ) $output[ 'SUPERIOR' ] = "<img src=\"" . get_showtime( 'live_site' ) . "/jomres/images/superior.png\" alt=\"superior\" border=\"0\" />"; $output[ 'PROPERTY_NAME' ] = $current_property_details->property_name; $output[ 'PROPERTY_STREET' ] = $current_property_details->property_street; $output[ 'PROPERTY_TOWN' ] = $current_property_details->property_town; $output[ 'PROPERTY_POSTCODE' ] = $current_property_details->property_postcode; $output[ 'PROPERTY_REGION' ] = $current_property_details->property_region; $output[ 'PROPERTY_COUNTRY' ] = $current_property_details->property_country; $output[ 'PROPERTY_COUNTRY_CODE' ] = $current_property_details->property_country_code; $output[ 'PROPERTY_TEL' ] = $current_property_details->property_tel; $output[ 'PROPERTY_EMAIL' ] = $current_property_details->property_email; $output[ 'STARS' ] = $current_property_details->stars; $output[ 'LAT' ] = $current_property_details->lat; $output[ 'LONG' ] = $current_property_details->long; $output[ 'PROPERTY_DESCRIPTION' ] = $current_property_details->property_description; $output[ 'PROPERTY_CHECKIN_TIMES' ] = $current_property_details->property_checkin_times; $output[ 'PROPERTY_AREA_ACTIVITIES' ] = $current_property_details->property_area_activities; $output[ 'PROPERTY_DRIVING_DIRECTIONS' ] = $current_property_details->property_driving_directions; $output[ 'PROPERTY_AIRPORTS' ] = $current_property_details->property_airports; $output[ 'PROPERTY_OTHERTRANSPORT' ] = $current_property_details->property_othertransport; $output[ 'PROPERTY_POLICIES_DISCLAIMERS' ] = $current_property_details->property_policies_disclaimers; $output[ '_JOMRES_COM_MR_PROPERTIESLISTING_THISPROPERTYADDRESS' ] = jr_gettext( _JOMRES_COM_MR_PROPERTIESLISTING_THISPROPERTYADDRESS, _JOMRES_COM_MR_PROPERTIESLISTING_THISPROPERTYADDRESS, false, false ); $output[ '_JOMRES_COM_MR_VRCT_PROPERTY_HEADER_TELEPHONE' ] = jr_gettext( _JOMRES_COM_MR_VRCT_PROPERTY_HEADER_TELEPHONE, _JOMRES_COM_MR_VRCT_PROPERTY_HEADER_TELEPHONE, false, false ); $jomres_media_centre_images = jomres_singleton_abstract::getInstance( 'jomres_media_centre_images' ); $jomres_media_centre_images->get_images($property_uid, array('property')); $output[ 'IMAGELARGE' ] = $jomres_media_centre_images->images ['property'][0][0]['large']; $output[ 'IMAGEMEDIUM' ] = $jomres_media_centre_images->images ['property'][0][0]['medium']; $output[ 'IMAGETHUMB' ] = $jomres_media_centre_images->images ['property'][0][0]['small']; $siteConfig = jomres_singleton_abstract::getInstance( 'jomres_config_site_singleton' ); $jrConfig = $siteConfig->get(); if ( $jrConfig[ 'make_gifs_from_slideshows' ] == "1" && $images ['gif'] [ 'small' ] != '' ) { $output[ 'IMAGETHUMB' ] = $images ['gif'] [ 'small' ]; $output[ 'IMAGEMEDIUM' ] = $images ['gif'] [ 'medium' ]; } $query = "SELECT room_classes_uid FROM #__jomres_rooms WHERE propertys_uid = '" . (int) $property_uid . "' "; $rt = doSelectSql( $query ); if ( count( $rt ) > 0 ) { $roomTypeArray = array (); foreach ( $rt as $roomtype ) { $roomTypeArray[ ] = $roomtype->room_classes_uid; } if ( count( $roomTypeArray ) > 1 ) $roomTypeArray = array_unique( $roomTypeArray ); if ( count( $roomTypeArray ) > 0 ) { $output[ 'HRTYPES' ] = jr_gettext( '_JOMRES_FRONT_ROOMTYPES', _JOMRES_FRONT_ROOMTYPES ); foreach ( $roomTypeArray as $type ) { $roomtype_abbv = $current_property_details->all_room_types[ $type ][ 'room_class_abbv' ]; $roomtype_desc = $current_property_details->all_room_types[ $type ][ 'room_class_full_desc' ]; $rtRows[ 'ROOM_TYPE' ] = jomres_makeTooltip( $roomtype_abbv, $roomtype_abbv, $roomtype_desc, $current_property_details->all_room_types[ $type ][ 'image' ], "", "room_type", array () ); $roomtypes[ ] = $rtRows; } } } $features = $current_property_details->features; $featureList = array (); if ( count( $features ) > 0 ) { foreach ( $features as $f ) { $propertyFeatureDescriptionsArray[ 'FEATURE' ] = jomres_makeTooltip( $f[ 'abbv' ], $f[ 'abbv' ], $f[ 'desc' ], $f[ 'image' ], "", "property_feature", array () ); $featureList[ ] = $propertyFeatureDescriptionsArray; } $output[ 'HFEATURES' ] = jr_gettext( '_JOMRES_COM_MR_VRCT_PROPERTY_HEADER_FEATURES', _JOMRES_COM_MR_VRCT_PROPERTY_HEADER_FEATURES ); } else $output[ 'HFEATURES' ] = ""; $componentArgs = array ( 'property_uid' => $property_uid, "width" => '200', "height" => '214' ); $MiniComponents->specificEvent( '01050', 'x_geocoder', $componentArgs ); $output[ 'MAP' ] = $MiniComponents->miniComponentData[ '01050' ][ 'x_geocoder' ]; $pageoutput = array ( $output ); $tmpl = new patTemplate(); $tmpl->setRoot( JOMRES_TEMPLATEPATH_FRONTEND ); $tmpl->addRows( 'pageoutput', $pageoutput ); if ( count( $roomtypes ) > 0 ) $tmpl->addRows( 'room_types', $roomtypes ); if ( count( $featureList ) > 0 ) $tmpl->addRows( 'property_features', $featureList ); $tmpl->readTemplatesFromInput( 'module_popup_contents.html' ); $result = $tmpl->getParsedTemplate(); } echo $result; } // This must be included in every Event/Mini-component function getRetVals() { return null; } } ?>
parksandwildlife/parkstay
jomres/core-minicomponents/j06000module_popup.class.php
PHP
gpl-2.0
8,699
# -*- coding: utf-8 -*- ## Comments and reviews for records. ## This file is part of Invenio. ## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """HTML Templates for commenting features """ __revision__ = "$Id$" import cgi # Invenio imports from invenio.urlutils import create_html_link from invenio.webuser import get_user_info, collect_user_info, isGuestUser, get_email from invenio.dateutils import convert_datetext_to_dategui from invenio.webmessage_mailutils import email_quoted_txt2html from invenio.webcomment_config import \ CFG_WEBCOMMENT_MAX_ATTACHED_FILES, \ CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE from invenio.config import CFG_SITE_URL, \ CFG_SITE_SECURE_URL, \ CFG_SITE_LANG, \ CFG_SITE_NAME, \ CFG_SITE_NAME_INTL,\ CFG_SITE_SUPPORT_EMAIL,\ CFG_WEBCOMMENT_ALLOW_REVIEWS, \ CFG_WEBCOMMENT_ALLOW_COMMENTS, \ CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR, \ CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN, \ CFG_WEBCOMMENT_AUTHOR_DELETE_COMMENT_OPTION, \ CFG_CERN_SITE from invenio.htmlutils import get_html_text_editor from invenio.messages import gettext_set_language from invenio.bibformat import format_record from invenio.access_control_engine import acc_authorize_action from invenio.websearch_templates import get_fieldvalues class Template: """templating class, refer to webcomment.py for examples of call""" def tmpl_get_first_comments_without_ranking(self, recID, ln, comments, nb_comments_total, warnings): """ @param recID: record id @param ln: language @param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks @param nb_comments_total: total number of comments for this record @param warnings: list of warning tuples (warning_msg, arg1, arg2, ...) @return: html of comments """ # load the right message language _ = gettext_set_language(ln) # naming data fields of comments c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_id = 4 warnings = self.tmpl_warnings(warnings, ln) # comments comment_rows = '' max_comment_round_name = comments[-1][0] for comment_round_name, comments_list in comments: comment_rows += '<div id="cmtRound%i" class="cmtRound">' % (comment_round_name) comment_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "<br/>" for comment in comments_list: if comment[c_nickname]: nickname = comment[c_nickname] display = nickname else: (uid, nickname, display) = get_user_info(comment[c_user_id]) messaging_link = self.create_messaging_link(nickname, display, ln) comment_rows += """ <tr> <td>""" report_link = '%s/record/%s/comments/report?ln=%s&amp;comid=%s' % (CFG_SITE_URL, recID, ln, comment[c_id]) reply_link = '%s/record/%s/comments/add?ln=%s&amp;comid=%s&amp;action=REPLY' % (CFG_SITE_URL, recID, ln, comment[c_id]) comment_rows += self.tmpl_get_comment_without_ranking(req=None, ln=ln, nickname=messaging_link, comment_uid=comment[c_user_id], date_creation=comment[c_date_creation], body=comment[c_body], status='', nb_reports=0, report_link=report_link, reply_link=reply_link, recID=recID) comment_rows += """ <br /> <br /> </td> </tr>""" # Close comment round comment_rows += '</div>' # write button write_button_label = _("Write a comment") write_button_link = '%s/record/%s/comments/add' % (CFG_SITE_URL, recID) write_button_form = '<input type="hidden" name="ln" value="%s"/>' % ln write_button_form = self.createhiddenform(action=write_button_link, method="get", text=write_button_form, button=write_button_label) # output if nb_comments_total > 0: out = warnings comments_label = len(comments) > 1 and _("Showing the latest %i comments:") % len(comments) \ or "" out += """ <table> <tr> <td class="blocknote">%(comment_title)s</td> </tr> </table> %(comments_label)s<br /> <table border="0" cellspacing="5" cellpadding="5" width="100%%"> %(comment_rows)s </table> %(view_all_comments_link)s <br /> <br /> %(write_button_form)s<br />""" % \ {'comment_title': _("Discuss this document"), 'comments_label': comments_label, 'nb_comments_total' : nb_comments_total, 'recID': recID, 'comment_rows': comment_rows, 'tab': '&nbsp;'*4, 'siteurl': CFG_SITE_URL, 's': nb_comments_total>1 and 's' or "", 'view_all_comments_link': nb_comments_total>0 and '''<a href="%s/record/%s/comments/display">View all %s comments</a>''' \ % (CFG_SITE_URL, recID, nb_comments_total) or "", 'write_button_form': write_button_form, 'nb_comments': len(comments) } else: out = """ <!-- comments title table --> <table> <tr> <td class="blocknote">%(discuss_label)s:</td> </tr> </table> %(detailed_info)s <br /> %(form)s <br />""" % {'form': write_button_form, 'discuss_label': _("Discuss this document"), 'detailed_info': _("Start a discussion about any aspect of this document.") } return out def tmpl_record_not_found(self, status='missing', recID="", ln=CFG_SITE_LANG): """ Displays a page when bad or missing record ID was given. @param status: 'missing' : no recID was given 'inexistant': recID doesn't have an entry in the database 'nan' : recID is not a number 'invalid' : recID is an error code, i.e. in the interval [-99,-1] @param return: body of the page """ _ = gettext_set_language(ln) if status == 'inexistant': body = _("Sorry, the record %s does not seem to exist.") % (recID,) elif status in ('nan', 'invalid'): body = _("Sorry, %s is not a valid ID value.") % (recID,) else: body = _("Sorry, no record ID was provided.") body += "<br /><br />" link = "<a href=\"%s?ln=%s\">%s</a>." % (CFG_SITE_URL, ln, CFG_SITE_NAME_INTL.get(ln, CFG_SITE_NAME)) body += _("You may want to start browsing from %s") % link return body def tmpl_get_first_comments_with_ranking(self, recID, ln, comments=None, nb_comments_total=None, avg_score=None, warnings=[]): """ @param recID: record id @param ln: language @param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks @param nb_comments_total: total number of comments for this record @param avg_score: average score of all reviews @param warnings: list of warning tuples (warning_msg, arg1, arg2, ...) @return: html of comments """ # load the right message language _ = gettext_set_language(ln) # naming data fields of comments c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_nb_votes_yes = 4 c_nb_votes_total = 5 c_star_score = 6 c_title = 7 c_id = 8 warnings = self.tmpl_warnings(warnings, ln) #stars if avg_score > 0: avg_score_img = 'stars-' + str(avg_score).split('.')[0] + '-' + str(avg_score).split('.')[1] + '.png' else: avg_score_img = "stars-0-0.png" # voting links useful_dict = { 'siteurl' : CFG_SITE_URL, 'recID' : recID, 'ln' : ln, 'yes_img' : 'smchk_gr.gif', #'yes.gif', 'no_img' : 'iconcross.gif' #'no.gif' } link = '<a href="%(siteurl)s/record/%(recID)s/reviews/vote?ln=%(ln)s&amp;comid=%%(comid)s' % useful_dict useful_yes = link + '&amp;com_value=1">' + _("Yes") + '</a>' useful_no = link + '&amp;com_value=-1">' + _("No") + '</a>' #comment row comment_rows = ' ' max_comment_round_name = comments[-1][0] for comment_round_name, comments_list in comments: comment_rows += '<div id="cmtRound%i" class="cmtRound">' % (comment_round_name) comment_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "<br/>" for comment in comments_list: if comment[c_nickname]: nickname = comment[c_nickname] display = nickname else: (uid, nickname, display) = get_user_info(comment[c_user_id]) messaging_link = self.create_messaging_link(nickname, display, ln) comment_rows += ''' <tr> <td>''' report_link = '%s/record/%s/reviews/report?ln=%s&amp;comid=%s' % (CFG_SITE_URL, recID, ln, comment[c_id]) comment_rows += self.tmpl_get_comment_with_ranking(None, ln=ln, nickname=messaging_link, comment_uid=comment[c_user_id], date_creation=comment[c_date_creation], body=comment[c_body], status='', nb_reports=0, nb_votes_total=comment[c_nb_votes_total], nb_votes_yes=comment[c_nb_votes_yes], star_score=comment[c_star_score], title=comment[c_title], report_link=report_link, recID=recID) comment_rows += ''' %s %s / %s<br />''' % (_("Was this review helpful?"), useful_yes % {'comid':comment[c_id]}, useful_no % {'comid':comment[c_id]}) comment_rows += ''' <br /> </td> </tr>''' # Close comment round comment_rows += '</div>' # write button write_button_link = '''%s/record/%s/reviews/add''' % (CFG_SITE_URL, recID) write_button_form = ' <input type="hidden" name="ln" value="%s"/>' % ln write_button_form = self.createhiddenform(action=write_button_link, method="get", text=write_button_form, button=_("Write a review")) if nb_comments_total > 0: avg_score_img = str(avg_score_img) avg_score = str(avg_score) nb_comments_total = str(nb_comments_total) score = '<b>' score += _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \ {'x_nb_score': '</b><img src="' + CFG_SITE_URL + '/img/' + avg_score_img + '" alt="' + avg_score + '" />', 'x_nb_reviews': nb_comments_total} useful_label = _("Readers found the following %s reviews to be most helpful.") useful_label %= len(comments) > 1 and len(comments) or "" view_all_comments_link ='<a href="%s/record/%s/reviews/display?ln=%s&amp;do=hh">' % (CFG_SITE_URL, recID, ln) view_all_comments_link += _("View all %s reviews") % nb_comments_total view_all_comments_link += '</a><br />' out = warnings + """ <!-- review title table --> <table> <tr> <td class="blocknote">%(comment_title)s:</td> </tr> </table> %(score_label)s<br /> %(useful_label)s <!-- review table --> <table style="border: 0px; border-collapse: separate; border-spacing: 5px; padding: 5px; width: 100%%"> %(comment_rows)s </table> %(view_all_comments_link)s %(write_button_form)s<br /> """ % \ { 'comment_title' : _("Rate this document"), 'score_label' : score, 'useful_label' : useful_label, 'recID' : recID, 'view_all_comments' : _("View all %s reviews") % (nb_comments_total,), 'write_comment' : _("Write a review"), 'comment_rows' : comment_rows, 'tab' : '&nbsp;'*4, 'siteurl' : CFG_SITE_URL, 'view_all_comments_link': nb_comments_total>0 and view_all_comments_link or "", 'write_button_form' : write_button_form } else: out = ''' <!-- review title table --> <table> <tr> <td class="blocknote">%s:</td> </tr> </table> %s<br /> %s <br />''' % (_("Rate this document"), _("Be the first to review this document."), write_button_form) return out def tmpl_get_comment_without_ranking(self, req, ln, nickname, comment_uid, date_creation, body, status, nb_reports, reply_link=None, report_link=None, undelete_link=None, delete_links=None, unreport_link=None, recID=-1, com_id='', attached_files=None): """ private function @param req: request object to fetch user info @param ln: language @param nickname: nickname @param date_creation: date comment was written @param body: comment body @param status: status of the comment: da: deleted by author dm: deleted by moderator ok: active @param nb_reports: number of reports the comment has @param reply_link: if want reply and report, give the http links @param report_link: if want reply and report, give the http links @param undelete_link: http link to delete the message @param delete_links: http links to delete the message @param unreport_link: http link to unreport the comment @param recID: recID where the comment is posted @param com_id: ID of the comment displayed @param attached_files: list of attached files @return: html table of comment """ from invenio.search_engine import guess_primary_collection_of_a_record # load the right message language _ = gettext_set_language(ln) date_creation = convert_datetext_to_dategui(date_creation, ln=ln) if attached_files is None: attached_files = [] out = '' final_body = email_quoted_txt2html(body) title = _('%(x_name)s wrote on %(x_date)s:') % {'x_name': nickname, 'x_date': '<i>' + date_creation + '</i>'} title += '<a name=%s></a>' % com_id links = '' moderator_links = '' if reply_link: links += '<a href="' + reply_link +'">' + _("Reply") +'</a>' if report_link and status != 'ap': links += ' | ' if report_link and status != 'ap': links += '<a href="' + report_link +'">' + _("Report abuse") + '</a>' # Check if user is a comment moderator record_primary_collection = guess_primary_collection_of_a_record(recID) user_info = collect_user_info(req) (auth_code, auth_msg) = acc_authorize_action(user_info, 'moderatecomments', collection=record_primary_collection) if status in ['dm', 'da'] and req: if not auth_code: if status == 'dm': final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment deleted by the moderator) - not visible for users<br /><br />' +\ final_body + '</div>' else: final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment deleted by the author) - not visible for users<br /><br />' +\ final_body + '</div>' links = '' moderator_links += '<a style="color:#8B0000;" href="' + undelete_link + '">' + _("Undelete comment") + '</a>' else: if status == 'dm': final_body = '<div style="color:#a3a3a3;font-style:italic;">Comment deleted by the moderator</div>' else: final_body = '<div style="color:#a3a3a3;font-style:italic;">Comment deleted by the author</div>' links = '' else: if not auth_code: moderator_links += '<a style="color:#8B0000;" href="' + delete_links['mod'] +'">' + _("Delete comment") + '</a>' elif (user_info['uid'] == comment_uid) and CFG_WEBCOMMENT_AUTHOR_DELETE_COMMENT_OPTION: moderator_links += '<a style="color:#8B0000;" href="' + delete_links['auth'] +'">' + _("Delete comment") + '</a>' if nb_reports >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN: if not auth_code: final_body = '<div style="color:#a3a3a3;font-style:italic;">(Comment reported. Pending approval) - not visible for users<br /><br />' + final_body + '</div>' links = '' moderator_links += ' | ' moderator_links += '<a style="color:#8B0000;" href="' + unreport_link +'">' + _("Unreport comment") + '</a>' else: final_body = '<div style="color:#a3a3a3;font-style:italic;">This comment is pending approval due to user reports</div>' links = '' if links and moderator_links: links = links + ' || ' + moderator_links elif not links: links = moderator_links attached_files_html = '' if attached_files: attached_files_html = '<div class="cmtfilesblock"><b>%s:</b><br/>' % (len(attached_files) == 1 and _("Attached file") or _("Attached files")) for (filename, filepath, fileurl) in attached_files: attached_files_html += create_html_link(urlbase=fileurl, urlargd={}, link_label=cgi.escape(filename)) + '<br />' attached_files_html += '</div>' out += """ <div style="margin-bottom:20px;background:#F9F9F9;border:1px solid #DDD">%(title)s<br /> <blockquote> %(body)s </blockquote> <br /> %(attached_files_html)s <div style="float:right">%(links)s</div> </div>""" % \ {'title' : '<div style="background-color:#EEE;padding:2px;"><img src="%s/img/user-icon-1-24x24.gif" alt="" />&nbsp;%s</div>' % (CFG_SITE_URL, title), 'body' : final_body, 'links' : links, 'attached_files_html': attached_files_html} return out def tmpl_get_comment_with_ranking(self, req, ln, nickname, comment_uid, date_creation, body, status, nb_reports, nb_votes_total, nb_votes_yes, star_score, title, report_link=None, delete_links=None, undelete_link=None, unreport_link=None, recID=-1): """ private function @param req: request object to fetch user info @param ln: language @param nickname: nickname @param date_creation: date comment was written @param body: comment body @param status: status of the comment @param nb_reports: number of reports the comment has @param nb_votes_total: total number of votes for this review @param nb_votes_yes: number of positive votes for this record @param star_score: star score for this record @param title: title of review @param report_link: if want reply and report, give the http links @param undelete_link: http link to delete the message @param delete_link: http link to delete the message @param unreport_link: http link to unreport the comment @param recID: recID where the comment is posted @return: html table of review """ from invenio.search_engine import guess_primary_collection_of_a_record # load the right message language _ = gettext_set_language(ln) if star_score > 0: star_score_img = 'stars-' + str(star_score) + '-0.png' else: star_score_img = 'stars-0-0.png' out = "" date_creation = convert_datetext_to_dategui(date_creation, ln=ln) reviewed_label = _("Reviewed by %(x_nickname)s on %(x_date)s") % {'x_nickname': nickname, 'x_date':date_creation} useful_label = _("%(x_nb_people)i out of %(x_nb_total)i people found this review useful") % {'x_nb_people': nb_votes_yes, 'x_nb_total': nb_votes_total} links = '' _body = '' if body != '': _body = ''' <blockquote> %s </blockquote>''' % email_quoted_txt2html(body, linebreak_html='') # Check if user is a comment moderator record_primary_collection = guess_primary_collection_of_a_record(recID) user_info = collect_user_info(req) (auth_code, auth_msg) = acc_authorize_action(user_info, 'moderatecomments', collection=record_primary_collection) if status in ['dm', 'da'] and req: if not auth_code: if status == 'dm': _body = '<div style="color:#a3a3a3;font-style:italic;">(Review deleted by moderator) - not visible for users<br /><br />' +\ _body + '</div>' else: _body = '<div style="color:#a3a3a3;font-style:italic;">(Review deleted by author) - not visible for users<br /><br />' +\ _body + '</div>' links = '<a style="color:#8B0000;" href="' + undelete_link + '">' + _("Undelete review") + '</a>' else: if status == 'dm': _body = '<div style="color:#a3a3a3;font-style:italic;">Review deleted by moderator</div>' else: _body = '<div style="color:#a3a3a3;font-style:italic;">Review deleted by author</div>' links = '' else: if not auth_code: links += '<a style="color:#8B0000;" href="' + delete_links['mod'] +'">' + _("Delete review") + '</a>' if nb_reports >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN: if not auth_code: _body = '<div style="color:#a3a3a3;font-style:italic;">(Review reported. Pending approval) - not visible for users<br /><br />' + _body + '</div>' links += ' | ' links += '<a style="color:#8B0000;" href="' + unreport_link +'">' + _("Unreport review") + '</a>' else: _body = '<div style="color:#a3a3a3;font-style:italic;">This review is pending approval due to user reports.</div>' links = '' out += ''' <div style="background:#F9F9F9;border:1px solid #DDD"> <div style="background-color:#EEE;padding:2px;"> <img src="%(siteurl)s/img/%(star_score_img)s" alt="%(star_score)s" style="margin-right:10px;"/><b>%(title)s</b><br /> %(reviewed_label)s<br /> %(useful_label)s </div> %(body)s </div> %(abuse)s''' % {'siteurl' : CFG_SITE_URL, 'star_score_img': star_score_img, 'star_score' : star_score, 'title' : title, 'reviewed_label': reviewed_label, 'useful_label' : useful_label, 'body' : _body, 'abuse' : links } return out def tmpl_get_comments(self, req, recID, ln, nb_per_page, page, nb_pages, display_order, display_since, CFG_WEBCOMMENT_ALLOW_REVIEWS, comments, total_nb_comments, avg_score, warnings, border=0, reviews=0, total_nb_reviews=0, nickname='', uid=-1, note='',score=5, can_send_comments=False, can_attach_files=False, user_is_subscribed_to_discussion=False, user_can_unsubscribe_from_discussion=False, display_comment_rounds=None): """ Get table of all comments @param recID: record id @param ln: language @param nb_per_page: number of results per page @param page: page number @param display_order: hh = highest helpful score, review only lh = lowest helpful score, review only hs = highest star score, review only ls = lowest star score, review only od = oldest date nd = newest date @param display_since: all= no filtering by date nd = n days ago nw = n weeks ago nm = n months ago ny = n years ago where n is a single digit integer between 0 and 9 @param CFG_WEBCOMMENT_ALLOW_REVIEWS: is ranking enable, get from config.py/CFG_WEBCOMMENT_ALLOW_REVIEWS @param comments: tuple as returned from webcomment.py/query_retrieve_comments_or_remarks @param total_nb_comments: total number of comments for this record @param avg_score: average score of reviews for this record @param warnings: list of warning tuples (warning_msg, color) @param border: boolean, active if want to show border around each comment/review @param reviews: boolean, enabled for reviews, disabled for comments @param can_send_comments: boolean, if user can send comments or not @param can_attach_files: boolean, if user can attach file to comment or not @param user_is_subscribed_to_discussion: True if user already receives new comments by email @param user_can_unsubscribe_from_discussion: True is user is allowed to unsubscribe from discussion """ # load the right message language _ = gettext_set_language(ln) # CERN hack begins: display full ATLAS user name. Check further below too. current_user_fullname = "" override_nickname_p = False if CFG_CERN_SITE: from invenio.search_engine import get_all_collections_of_a_record user_info = collect_user_info(uid) if 'atlas-readaccess-active-members [CERN]' in user_info['group']: # An ATLAS member is never anonymous to its colleagues # when commenting inside ATLAS collections recid_collections = get_all_collections_of_a_record(recID) if 'ATLAS' in str(recid_collections): override_nickname_p = True current_user_fullname = user_info.get('external_fullname', '') # CERN hack ends # naming data fields of comments if reviews: c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_status = 4 c_nb_reports = 5 c_nb_votes_yes = 6 c_nb_votes_total = 7 c_star_score = 8 c_title = 9 c_id = 10 c_round_name = 11 c_restriction = 12 reply_to = 13 discussion = 'reviews' comments_link = '<a href="%s/record/%s/comments/">%s</a> (%i)' % (CFG_SITE_URL, recID, _('Comments'), total_nb_comments) reviews_link = '<b>%s (%i)</b>' % (_('Reviews'), total_nb_reviews) add_comment_or_review = self.tmpl_add_comment_form_with_ranking(recID, uid, current_user_fullname or nickname, ln, '', score, note, warnings, show_title_p=True, can_attach_files=can_attach_files) else: c_nickname = 0 c_user_id = 1 c_date_creation = 2 c_body = 3 c_status = 4 c_nb_reports = 5 c_id = 6 c_round_name = 7 c_restriction = 8 reply_to = 9 discussion = 'comments' comments_link = '<b>%s (%i)</b>' % (_('Comments'), total_nb_comments) reviews_link = '<a href="%s/record/%s/reviews/">%s</a> (%i)' % (CFG_SITE_URL, recID, _('Reviews'), total_nb_reviews) add_comment_or_review = self.tmpl_add_comment_form(recID, uid, nickname, ln, note, warnings, can_attach_files=can_attach_files, user_is_subscribed_to_discussion=user_is_subscribed_to_discussion) # voting links useful_dict = { 'siteurl' : CFG_SITE_URL, 'recID' : recID, 'ln' : ln, 'do' : display_order, 'ds' : display_since, 'nb' : nb_per_page, 'p' : page, 'reviews' : reviews, 'discussion' : discussion } useful_yes = '<a href="%(siteurl)s/record/%(recID)s/%(discussion)s/vote?ln=%(ln)s&amp;comid=%%(comid)s&amp;com_value=1&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/%(discussion)s/display">' + _("Yes") + '</a>' useful_yes %= useful_dict useful_no = '<a href="%(siteurl)s/record/%(recID)s/%(discussion)s/vote?ln=%(ln)s&amp;comid=%%(comid)s&amp;com_value=-1&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/%(discussion)s/display">' + _("No") + '</a>' useful_no %= useful_dict warnings = self.tmpl_warnings(warnings, ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'index', 'discussion': discussion, 'arguments' : 'do=%s&amp;ds=%s&amp;nb=%s' % (display_order, display_since, nb_per_page), 'arg_page' : '&amp;p=%s' % page, 'page' : page, 'rec_id' : recID} if not req: req = None ## comments table comments_rows = '' last_comment_round_name = None comment_round_names = [comment[0] for comment in comments] if comment_round_names: last_comment_round_name = comment_round_names[-1] for comment_round_name, comments_list in comments: comment_round_style = "display:none;" comment_round_is_open = False if comment_round_name in display_comment_rounds: comment_round_is_open = True comment_round_style = "" comments_rows += '<div id="cmtRound%s" class="cmtround">' % (comment_round_name) if not comment_round_is_open and \ (comment_round_name or len(comment_round_names) > 1): new_cmtgrp = list(display_comment_rounds) new_cmtgrp.append(comment_round_name) comments_rows += '''<img src="/img/right-trans.gif" id="cmtarrowiconright%(grp_id)s" alt="Open group" /><img src="/img/down-trans.gif" id="cmtarrowicondown%(grp_id)s" alt="Close group" style="display:none" /> <a class="cmtgrpswitch" name="cmtgrpLink%(grp_id)s" onclick="var cmtarrowicondown=document.getElementById('cmtarrowicondown%(grp_id)s');var cmtarrowiconright=document.getElementById('cmtarrowiconright%(grp_id)s');var subgrp=document.getElementById('cmtSubRound%(grp_id)s');if (subgrp.style.display==''){subgrp.style.display='none';cmtarrowiconright.style.display='';cmtarrowicondown.style.display='none';}else{subgrp.style.display='';cmtarrowiconright.style.display='none';cmtarrowicondown.style.display='';};return false;"''' % {'grp_id': comment_round_name} comments_rows += 'href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s' % link_dic comments_rows += '&amp;' + '&amp;'.join(["cmtgrp=" + grp for grp in new_cmtgrp if grp != 'none']) + \ '#cmtgrpLink%s' % (comment_round_name) + '\">' comments_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name} + "</a><br/>" elif comment_round_name or len(comment_round_names) > 1: new_cmtgrp = list(display_comment_rounds) new_cmtgrp.remove(comment_round_name) comments_rows += '''<img src="/img/right-trans.gif" id="cmtarrowiconright%(grp_id)s" alt="Open group" style="display:none" /><img src="/img/down-trans.gif" id="cmtarrowicondown%(grp_id)s" alt="Close group" /> <a class="cmtgrpswitch" name="cmtgrpLink%(grp_id)s" onclick="var cmtarrowicondown=document.getElementById('cmtarrowicondown%(grp_id)s');var cmtarrowiconright=document.getElementById('cmtarrowiconright%(grp_id)s');var subgrp=document.getElementById('cmtSubRound%(grp_id)s');if (subgrp.style.display==''){subgrp.style.display='none';cmtarrowiconright.style.display='';cmtarrowicondown.style.display='none';}else{subgrp.style.display='';cmtarrowiconright.style.display='none';cmtarrowicondown.style.display='';};return false;"''' % {'grp_id': comment_round_name} comments_rows += 'href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s' % link_dic comments_rows += '&amp;' + ('&amp;'.join(["cmtgrp=" + grp for grp in new_cmtgrp if grp != 'none']) or 'cmtgrp=none' ) + \ '#cmtgrpLink%s' % (comment_round_name) + '\">' comments_rows += _('%(x_nb)i comments for round "%(x_name)s"') % {'x_nb': len(comments_list), 'x_name': comment_round_name}+ "</a><br/>" comments_rows += '<div id="cmtSubRound%s" class="cmtsubround" style="%s">' % (comment_round_name, comment_round_style) thread_history = [0] for comment in comments_list: if comment[reply_to] not in thread_history: # Going one level down in the thread thread_history.append(comment[reply_to]) depth = thread_history.index(comment[reply_to]) else: depth = thread_history.index(comment[reply_to]) thread_history = thread_history[:depth + 1] # CERN hack begins: display full ATLAS user name. comment_user_fullname = "" if CFG_CERN_SITE and override_nickname_p: comment_user_fullname = get_email(comment[c_user_id]) # CERN hack ends if comment[c_nickname]: _nickname = comment[c_nickname] display = _nickname else: (uid, _nickname, display) = get_user_info(comment[c_user_id]) messaging_link = self.create_messaging_link(_nickname, comment_user_fullname or display, ln) from invenio.webcomment import get_attached_files # FIXME files = get_attached_files(recID, comment[c_id]) # do NOT delete the HTML comment below. It is used for parsing... (I plead unguilty!) comments_rows += """ <!-- start comment row --> <div style="margin-left:%spx">""" % (depth*20) delete_links = {} if not reviews: report_link = '%(siteurl)s/record/%(recID)s/comments/report?ln=%(ln)s&amp;comid=%%(comid)s&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/comments/display' % useful_dict % {'comid':comment[c_id]} reply_link = '%(siteurl)s/record/%(recID)s/comments/add?ln=%(ln)s&amp;action=REPLY&amp;comid=%%(comid)s' % useful_dict % {'comid':comment[c_id]} delete_links['mod'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_mod?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) delete_links['auth'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_auth?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) undelete_link = "%s/admin/webcomment/webcommentadmin.py/undel_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) unreport_link = "%s/admin/webcomment/webcommentadmin.py/unreport_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) comments_rows += self.tmpl_get_comment_without_ranking(req, ln, messaging_link, comment[c_user_id], comment[c_date_creation], comment[c_body], comment[c_status], comment[c_nb_reports], reply_link, report_link, undelete_link, delete_links, unreport_link, recID, comment[c_id], files) else: report_link = '%(siteurl)s/record/%(recID)s/reviews/report?ln=%(ln)s&amp;comid=%%(comid)s&amp;do=%(do)s&amp;ds=%(ds)s&amp;nb=%(nb)s&amp;p=%(p)s&amp;referer=%(siteurl)s/record/%(recID)s/reviews/display' % useful_dict % {'comid': comment[c_id]} delete_links['mod'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_mod?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) delete_links['auth'] = "%s/admin/webcomment/webcommentadmin.py/del_single_com_auth?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) undelete_link = "%s/admin/webcomment/webcommentadmin.py/undel_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) unreport_link = "%s/admin/webcomment/webcommentadmin.py/unreport_com?ln=%s&amp;id=%s" % (CFG_SITE_URL, ln, comment[c_id]) comments_rows += self.tmpl_get_comment_with_ranking(req, ln, messaging_link, comment[c_user_id], comment[c_date_creation], comment[c_body], comment[c_status], comment[c_nb_reports], comment[c_nb_votes_total], comment[c_nb_votes_yes], comment[c_star_score], comment[c_title], report_link, delete_links, undelete_link, unreport_link, recID) helpful_label = _("Was this review helpful?") report_abuse_label = "(" + _("Report abuse") + ")" yes_no_separator = '<td> / </td>' if comment[c_nb_reports] >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN or comment[c_status] in ['dm', 'da']: report_abuse_label = "" helpful_label = "" useful_yes = "" useful_no = "" yes_no_separator = "" comments_rows += """ <table> <tr> <td>%(helpful_label)s %(tab)s</td> <td> %(yes)s </td> %(yes_no_separator)s <td> %(no)s </td> <td class="reportabuse">%(tab)s%(tab)s<a href="%(report)s">%(report_abuse_label)s</a></td> </tr> </table>""" \ % {'helpful_label': helpful_label, 'yes' : useful_yes % {'comid':comment[c_id]}, 'yes_no_separator': yes_no_separator, 'no' : useful_no % {'comid':comment[c_id]}, 'report' : report_link % {'comid':comment[c_id]}, 'report_abuse_label': comment[c_nb_reports] >= CFG_WEBCOMMENT_NB_REPORTS_BEFORE_SEND_EMAIL_TO_ADMIN and '' or report_abuse_label, 'tab' : '&nbsp;'*2} # do NOT remove HTML comment below. It is used for parsing... comments_rows += """ </div> <!-- end comment row -->""" comments_rows += '</div></div>' ## page links page_links = '' # Previous if page != 1: link_dic['arg_page'] = 'p=%s' % (page - 1) page_links += '<a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s\">&lt;&lt;</a> ' % link_dic else: page_links += ' %s ' % ('&nbsp;'*(len(_('Previous'))+7)) # Page Numbers for i in range(1, nb_pages+1): link_dic['arg_page'] = 'p=%s' % i link_dic['page'] = '%s' % i if i != page: page_links += ''' <a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s\">%(page)s</a> ''' % link_dic else: page_links += ''' <b>%s</b> ''' % i # Next if page != nb_pages: link_dic['arg_page'] = 'p=%s' % (page + 1) page_links += ''' <a href=\"%(siteurl)s/record/%(rec_id)s/%(discussion)s/%(function)s?%(arguments)s&amp;%(arg_page)s\">&gt;&gt;</a> ''' % link_dic else: page_links += '%s' % ('&nbsp;'*(len(_('Next'))+7)) ## stuff for ranking if enabled if reviews: if avg_score > 0: avg_score_img = 'stars-' + str(avg_score).split('.')[0] + '-' + str(avg_score).split('.')[1] + '.png' else: avg_score_img = "stars-0-0.png" ranking_average = '<br /><b>' ranking_average += _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \ {'x_nb_score': '</b><img src="' + CFG_SITE_URL + '/img/' + avg_score_img + '" alt="' + str(avg_score) + '" />', 'x_nb_reviews': str(total_nb_reviews)} ranking_average += '<br />' else: ranking_average = "" write_button_link = '''%s/record/%s/%s/add''' % (CFG_SITE_URL, recID, discussion) write_button_form = '<input type="hidden" name="ln" value="%s"/>' write_button_form = self.createhiddenform(action=write_button_link, method="get", text=write_button_form, button = reviews and _('Write a review') or _('Write a comment')) if reviews: total_label = _("There is a total of %s reviews") else: total_label = _("There is a total of %s comments") total_label %= total_nb_comments review_or_comment_first = '' if reviews == 0 and total_nb_comments == 0 and can_send_comments: review_or_comment_first = _("Start a discussion about any aspect of this document.") + '<br />' elif reviews == 1 and total_nb_reviews == 0 and can_send_comments: review_or_comment_first = _("Be the first to review this document.") + '<br />' # do NOT remove the HTML comments below. Used for parsing body = ''' %(comments_and_review_tabs)s <!-- start comments table --> <div style="border: %(border)spx solid black; width: 95%%; margin:10px;font-size:small"> %(comments_rows)s </div> <!-- end comments table --> %(review_or_comment_first)s <br />''' % \ { 'record_label': _("Record"), 'back_label': _("Back to search results"), 'total_label': total_label, 'write_button_form' : write_button_form, 'write_button_form_again' : total_nb_comments>3 and write_button_form or "", 'comments_rows' : comments_rows, 'total_nb_comments' : total_nb_comments, 'comments_or_reviews' : reviews and _('review') or _('comment'), 'comments_or_reviews_title' : reviews and _('Review') or _('Comment'), 'siteurl' : CFG_SITE_URL, 'module' : "comments", 'recid' : recID, 'ln' : ln, 'border' : border, 'ranking_avg' : ranking_average, 'comments_and_review_tabs' : CFG_WEBCOMMENT_ALLOW_REVIEWS and \ CFG_WEBCOMMENT_ALLOW_COMMENTS and \ '%s | %s <br />' % \ (comments_link, reviews_link) or '', 'review_or_comment_first' : review_or_comment_first } # form is not currently used. reserved for an eventual purpose #form = """ # Display <select name="nb" size="1"> per page # <option value="all">All</option> # <option value="10">10</option> # <option value="25">20</option> # <option value="50">50</option> # <option value="100" selected="selected">100</option> # </select> # comments per page that are <select name="ds" size="1"> # <option value="all" selected="selected">Any age</option> # <option value="1d">1 day old</option> # <option value="3d">3 days old</option> # <option value="1w">1 week old</option> # <option value="2w">2 weeks old</option> # <option value="1m">1 month old</option> # <option value="3m">3 months old</option> # <option value="6m">6 months old</option> # <option value="1y">1 year old</option> # </select> # and sorted by <select name="do" size="1"> # <option value="od" selected="selected">Oldest first</option> # <option value="nd">Newest first</option> # %s # </select> # """ % \ # (reviews==1 and ''' # <option value=\"hh\">most helpful</option> # <option value=\"lh\">least helpful</option> # <option value=\"hs\">highest star ranking</option> # <option value=\"ls\">lowest star ranking</option> # </select>''' or ''' # </select>''') # #form_link = "%(siteurl)s/%(module)s/%(function)s" % link_dic #form = self.createhiddenform(action=form_link, method="get", text=form, button='Go', recid=recID, p=1) pages = """ <div> %(v_label)s %(comments_or_reviews)s %(results_nb_lower)s-%(results_nb_higher)s <br /> %(page_links)s </div> """ % \ {'v_label': _("Viewing"), 'page_links': _("Page:") + page_links , 'comments_or_reviews': reviews and _('review') or _('comment'), 'results_nb_lower': len(comments)>0 and ((page-1) * nb_per_page)+1 or 0, 'results_nb_higher': page == nb_pages and (((page-1) * nb_per_page) + len(comments)) or (page * nb_per_page)} if nb_pages > 1: #body = warnings + body + form + pages body = warnings + body + pages else: body = warnings + body if reviews == 0: if not user_is_subscribed_to_discussion: body += '<small>' body += '<div class="comment-subscribe">' + '<img src="%s/img/mail-icon-12x8.gif" border="0" alt="" />' % CFG_SITE_URL + \ '&nbsp;' + '<b>' + create_html_link(urlbase=CFG_SITE_URL + '/record/' + \ str(recID) + '/comments/subscribe', urlargd={}, link_label=_('Subscribe')) + \ '</b>' + ' to this discussion. You will then receive all new comments by email.' + '</div>' body += '</small><br />' elif user_can_unsubscribe_from_discussion: body += '<small>' body += '<div class="comment-subscribe">' + '<img src="%s/img/mail-icon-12x8.gif" border="0" alt="" />' % CFG_SITE_URL + \ '&nbsp;' + '<b>' + create_html_link(urlbase=CFG_SITE_URL + '/record/' + \ str(recID) + '/comments/unsubscribe', urlargd={}, link_label=_('Unsubscribe')) + \ '</b>' + ' from this discussion. You will no longer receive emails about new comments.' + '</div>' body += '</small><br />' if can_send_comments: body += add_comment_or_review else: body += '<br/><em>' + _("You are not authorized to comment or review.") + '</em>' return '<div style="margin-left:10px;margin-right:10px;">' + body + '</div>' def create_messaging_link(self, to, display_name, ln=CFG_SITE_LANG): """prints a link to the messaging system""" link = "%s/yourmessages/write?msg_to=%s&amp;ln=%s" % (CFG_SITE_URL, to, ln) if to: return '<a href="%s" class="maillink">%s</a>' % (link, display_name) else: return display_name def createhiddenform(self, action="", method="get", text="", button="confirm", cnfrm='', **hidden): """ create select with hidden values and submit button @param action: name of the action to perform on submit @param method: 'get' or 'post' @param text: additional text, can also be used to add non hidden input @param button: value/caption on the submit button @param cnfrm: if given, must check checkbox to confirm @param **hidden: dictionary with name=value pairs for hidden input @return: html form """ output = """ <form action="%s" method="%s">""" % (action, method.lower().strip() in ['get', 'post'] and method or 'get') output += """ <table style="width:90%"> <tr> <td style="vertical-align: top"> """ output += text + '\n' if cnfrm: output += """ <input type="checkbox" name="confirm" value="1" />""" for key in hidden.keys(): if type(hidden[key]) is list: for value in hidden[key]: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, value) else: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, hidden[key]) output += """ </td> </tr> <tr> <td>""" output += """ <input class="adminbutton" type="submit" value="%s" />""" % (button, ) output += """ </td> </tr> </table> </form>""" return output def create_write_comment_hiddenform(self, action="", method="get", text="", button="confirm", cnfrm='', enctype='', **hidden): """ create select with hidden values and submit button @param action: name of the action to perform on submit @param method: 'get' or 'post' @param text: additional text, can also be used to add non hidden input @param button: value/caption on the submit button @param cnfrm: if given, must check checkbox to confirm @param **hidden: dictionary with name=value pairs for hidden input @return: html form """ enctype_attr = '' if enctype: enctype_attr = 'enctype=' + enctype output = """ <form action="%s" method="%s" %s>""" % (action, method.lower().strip() in ['get', 'post'] and method or 'get', enctype_attr) if cnfrm: output += """ <input type="checkbox" name="confirm" value="1" />""" for key in hidden.keys(): if type(hidden[key]) is list: for value in hidden[key]: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, value) else: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, hidden[key]) output += text + '\n' output += """ </form>""" return output def tmpl_warnings(self, warnings, ln=CFG_SITE_LANG): """ Prepare the warnings list @param warnings: list of warning tuples (warning_msg, arg1, arg2, etc) @return: html string of warnings """ red_text_warnings = ['WRN_WEBCOMMENT_FEEDBACK_NOT_RECORDED', 'WRN_WEBCOMMENT_ALREADY_VOTED'] green_text_warnings = ['WRN_WEBCOMMENT_FEEDBACK_RECORDED', 'WRN_WEBCOMMENT_SUBSCRIBED', 'WRN_WEBCOMMENT_UNSUBSCRIBED'] from invenio.errorlib import get_msgs_for_code_list span_class = 'important' out = "" if type(warnings) is not list: warnings = [warnings] if len(warnings) > 0: warnings_parsed = get_msgs_for_code_list(warnings, 'warning', ln) for (warning_code, warning_text) in warnings_parsed: if not warning_code.startswith('WRN'): #display only warnings that begin with WRN to user continue if warning_code in red_text_warnings: span_class = 'important' elif warning_code in green_text_warnings: span_class = 'exampleleader' else: span_class = 'important' out += ''' <span class="%(span_class)s">%(warning)s</span><br />''' % \ { 'span_class' : span_class, 'warning' : warning_text } return out else: return "" def tmpl_add_comment_form(self, recID, uid, nickname, ln, msg, warnings, textual_msg=None, can_attach_files=False, user_is_subscribed_to_discussion=False, reply_to=None): """ Add form for comments @param recID: record id @param uid: user id @param ln: language @param msg: comment body contents for when refreshing due to warning, or when replying to a comment @param textual_msg: same as 'msg', but contains the textual version in case user cannot display FCKeditor @param warnings: list of warning tuples (warning_msg, color) @param can_attach_files: if user can upload attach file to record or not @param user_is_subscribed_to_discussion: True if user already receives new comments by email @param reply_to: the ID of the comment we are replying to. None if not replying @return html add comment form """ _ = gettext_set_language(ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'add', 'arguments' : 'ln=%s&amp;action=%s' % (ln, 'SUBMIT'), 'recID' : recID} if textual_msg is None: textual_msg = msg # FIXME a cleaner handling of nicknames is needed. if not nickname: (uid, nickname, display) = get_user_info(uid) if nickname: note = _("Note: Your nickname, %s, will be displayed as author of this comment.") % ('<i>' + nickname + '</i>') else: (uid, nickname, display) = get_user_info(uid) link = '<a href="%s/youraccount/edit">' % CFG_SITE_SECURE_URL note = _("Note: you have not %(x_url_open)sdefined your nickname%(x_url_close)s. %(x_nickname)s will be displayed as the author of this comment.") % \ {'x_url_open': link, 'x_url_close': '</a>', 'x_nickname': ' <br /><i>' + display + '</i>'} if not CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR: note += '<br />' + '&nbsp;'*10 + cgi.escape('You can use some HTML tags: <a href>, <strong>, <blockquote>, <br />, <p>, <em>, <ul>, <li>, <b>, <i>') #from invenio.search_engine import print_record #record_details = print_record(recID=recID, format='hb', ln=ln) warnings = self.tmpl_warnings(warnings, ln) # Prepare file upload settings. We must enable file upload in # the fckeditor + a simple file upload interface (independant from editor) file_upload_url = None simple_attach_file_interface = '' if isGuestUser(uid): simple_attach_file_interface = "<small><em>%s</em></small><br/>" % _("Once logged in, authorized users can also attach files.") if can_attach_files: # Note that files can be uploaded only when user is logged in #file_upload_url = '%s/record/%i/comments/attachments/put' % \ # (CFG_SITE_URL, recID) simple_attach_file_interface = ''' <div id="uploadcommentattachmentsinterface"> <small>%(attach_msg)s: <em>(%(nb_files_limit_msg)s. %(file_size_limit_msg)s)</em></small><br /> <input class="multi max-%(CFG_WEBCOMMENT_MAX_ATTACHED_FILES)s" type="file" name="commentattachment[]"/><br /> <noscript> <input type="file" name="commentattachment[]" /><br /> </noscript> </div> ''' % \ {'CFG_WEBCOMMENT_MAX_ATTACHED_FILES': CFG_WEBCOMMENT_MAX_ATTACHED_FILES, 'attach_msg': CFG_WEBCOMMENT_MAX_ATTACHED_FILES == 1 and _("Optionally, attach a file to this comment") or \ _("Optionally, attach files to this comment"), 'nb_files_limit_msg': _("Max one file") and CFG_WEBCOMMENT_MAX_ATTACHED_FILES == 1 or \ _("Max %i files") % CFG_WEBCOMMENT_MAX_ATTACHED_FILES, 'file_size_limit_msg': CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE > 0 and _("Max %(x_nb_bytes)s per file") % {'x_nb_bytes': (CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE < 1024*1024 and (str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/1024) + 'KB') or (str(CFG_WEBCOMMENT_MAX_ATTACHMENT_SIZE/(1024*1024)) + 'MB'))} or ''} editor = get_html_text_editor(name='msg', content=msg, textual_content=textual_msg, width='100%', height='400px', enabled=CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR, file_upload_url=file_upload_url, toolbar_set = "WebComment") subscribe_to_discussion = '' if not user_is_subscribed_to_discussion: # Offer to subscribe to discussion subscribe_to_discussion = '<small><input type="checkbox" name="subscribe" id="subscribe"/><label for="subscribe">%s</label></small>' % _("Send me an email when a new comment is posted") form = """<div id="comment-write"><h2>%(add_comment)s</h2> %(editor)s <br /> %(simple_attach_file_interface)s <span class="reportabuse">%(note)s</span> <div class="submit-area"> %(subscribe_to_discussion)s<br /> <input class="adminbutton" type="submit" value="Add comment" /> %(reply_to)s </div> """ % {'note': note, 'record_label': _("Article") + ":", 'comment_label': _("Comment") + ":", 'add_comment': _('Add comment'), 'editor': editor, 'subscribe_to_discussion': subscribe_to_discussion, 'reply_to': reply_to and '<input type="hidden" name="comid" value="%s"/>' % reply_to or '', 'simple_attach_file_interface': simple_attach_file_interface} form_link = "%(siteurl)s/record/%(recID)s/comments/%(function)s?%(arguments)s" % link_dic form = self.create_write_comment_hiddenform(action=form_link, method="post", text=form, button='Add comment', enctype='multipart/form-data') form += '</div>' return warnings + form def tmpl_add_comment_form_with_ranking(self, recID, uid, nickname, ln, msg, score, note, warnings, textual_msg=None, show_title_p=False, can_attach_files=False): """ Add form for reviews @param recID: record id @param uid: user id @param ln: language @param msg: comment body contents for when refreshing due to warning @param textual_msg: the textual version of 'msg' when user cannot display FCKeditor @param score: review score @param note: review title @param warnings: list of warning tuples (warning_msg, color) @param show_title_p: if True, prefix the form with "Add Review" as title @param can_attach_files: if user can upload attach file to record or not @return: html add review form """ _ = gettext_set_language(ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'add', 'arguments' : 'ln=%s&amp;action=%s' % (ln, 'SUBMIT'), 'recID' : recID} warnings = self.tmpl_warnings(warnings, ln) if textual_msg is None: textual_msg = msg #from search_engine import print_record #record_details = print_record(recID=recID, format='hb', ln=ln) if nickname: note_label = _("Note: Your nickname, %s, will be displayed as the author of this review.") note_label %= ('<i>' + nickname + '</i>') else: (uid, nickname, display) = get_user_info(uid) link = '<a href="%s/youraccount/edit">' % CFG_SITE_SECURE_URL note_label = _("Note: you have not %(x_url_open)sdefined your nickname%(x_url_close)s. %(x_nickname)s will be displayed as the author of this comment.") % \ {'x_url_open': link, 'x_url_close': '</a>', 'x_nickname': ' <br /><i>' + display + '</i>'} selected0 = '' selected1 = '' selected2 = '' selected3 = '' selected4 = '' selected5 = '' if score == 0: selected0 = ' selected="selected"' elif score == 1: selected1 = ' selected="selected"' elif score == 2: selected2 = ' selected="selected"' elif score == 3: selected3 = ' selected="selected"' elif score == 4: selected4 = ' selected="selected"' elif score == 5: selected5 = ' selected="selected"' ## file_upload_url = None ## if can_attach_files: ## file_upload_url = '%s/record/%i/comments/attachments/put' % \ ## (CFG_SITE_URL, recID) editor = get_html_text_editor(name='msg', content=msg, textual_content=msg, width='90%', height='400px', enabled=CFG_WEBCOMMENT_USE_RICH_TEXT_EDITOR, # file_upload_url=file_upload_url, toolbar_set = "WebComment") form = """%(add_review)s <table style="width: 100%%"> <tr> <td style="padding-bottom: 10px;">%(rate_label)s: <select name=\"score\" size=\"1\"> <option value=\"0\"%(selected0)s>-%(select_label)s-</option> <option value=\"5\"%(selected5)s>***** (best)</option> <option value=\"4\"%(selected4)s>****</option> <option value=\"3\"%(selected3)s>***</option> <option value=\"2\"%(selected2)s>**</option> <option value=\"1\"%(selected1)s>* (worst)</option> </select> </td> </tr> <tr> <td>%(title_label)s:</td> </tr> <tr> <td style="padding-bottom: 10px;"> <input type="text" name="note" maxlength="250" style="width:90%%" value="%(note)s" /> </td> </tr> <tr> <td>%(write_label)s:</td> </tr> <tr> <td> %(editor)s </td> </tr> <tr> <td class="reportabuse">%(note_label)s</td></tr> </table> """ % {'article_label': _('Article'), 'rate_label': _("Rate this article"), 'select_label': _("Select a score"), 'title_label': _("Give a title to your review"), 'write_label': _("Write your review"), 'note_label': note_label, 'note' : note!='' and note or "", 'msg' : msg!='' and msg or "", #'record' : record_details 'add_review': show_title_p and ('<h2>'+_('Add review')+'</h2>') or '', 'selected0': selected0, 'selected1': selected1, 'selected2': selected2, 'selected3': selected3, 'selected4': selected4, 'selected5': selected5, 'editor': editor, } form_link = "%(siteurl)s/record/%(recID)s/reviews/%(function)s?%(arguments)s" % link_dic form = self.createhiddenform(action=form_link, method="post", text=form, button=_('Add Review')) return warnings + form def tmpl_add_comment_successful(self, recID, ln, reviews, warnings, success): """ @param recID: record id @param ln: language @return: html page of successfully added comment/review """ _ = gettext_set_language(ln) link_dic = { 'siteurl' : CFG_SITE_URL, 'module' : 'comments', 'function' : 'display', 'arguments' : 'ln=%s&amp;do=od' % ln, 'recID' : recID, 'discussion': reviews == 1 and 'reviews' or 'comments'} link = "%(siteurl)s/record/%(recID)s/%(discussion)s/%(function)s?%(arguments)s" % link_dic if warnings: out = self.tmpl_warnings(warnings, ln) + '<br /><br />' else: if reviews: out = _("Your review was successfully added.") + '<br /><br />' else: out = _("Your comment was successfully added.") + '<br /><br />' link += "#%s" % success out += '<a href="%s">' % link out += _('Back to record') + '</a>' return out def tmpl_create_multiple_actions_form(self, form_name="", form_action="", method="get", action_display={}, action_field_name="", button_label="", button_name="", content="", **hidden): """ Creates an HTML form with a multiple choice of actions and a button to select it. @param form_action: link to the receiver of the formular @param form_name: name of the HTML formular @param method: either 'GET' or 'POST' @param action_display: dictionary of actions. action is HTML name (name of action) display is the string provided in the popup @param action_field_name: html name of action field @param button_label: what's written on the button @param button_name: html name of the button @param content: what's inside te formular @param **hidden: dictionary of name/value pairs of hidden fields. """ output = """ <form action="%s" method="%s">""" % (form_action, method) output += """ <table> <tr> <td style="vertical-align: top" colspan="2"> """ output += content + '\n' for key in hidden.keys(): if type(hidden[key]) is list: for value in hidden[key]: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, value) else: output += """ <input type="hidden" name="%s" value="%s" />""" % (key, hidden[key]) output += """ </td> </tr> <tr> <td style="text-align:right;">""" if type(action_display) is dict and len(action_display.keys()): output += """ <select name="%s">""" % action_field_name for (key, value) in action_display.items(): output += """ <option value="%s">%s</option>""" % (key, value) output += """ </select>""" output += """ </td> <td style="text-align:left;"> <input class="adminbutton" type="submit" value="%s" name="%s"/>""" % (button_label, button_name) output += """ </td> </tr> </table> </form>""" return output def tmpl_admin_index(self, ln): """ Index page """ # load the right message language _ = gettext_set_language(ln) out = '<ol>' if CFG_WEBCOMMENT_ALLOW_COMMENTS or CFG_WEBCOMMENT_ALLOW_REVIEWS: if CFG_WEBCOMMENT_ALLOW_COMMENTS: out += '<h3>Comments status</h3>' out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/hot?ln=%(ln)s&amp;comments=1">%(hot_cmt_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'hot_cmt_label': _("View most commented records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/latest?ln=%(ln)s&amp;comments=1">%(latest_cmt_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'latest_cmt_label': _("View latest commented records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/comments?ln=%(ln)s&amp;reviews=0">%(reported_cmt_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'reported_cmt_label': _("View all comments reported as abuse")} if CFG_WEBCOMMENT_ALLOW_REVIEWS: out += '<h3>Reviews status</h3>' out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/hot?ln=%(ln)s&amp;comments=0">%(hot_rev_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'hot_rev_label': _("View most reviewed records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/latest?ln=%(ln)s&amp;comments=0">%(latest_rev_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'latest_rev_label': _("View latest reviewed records")} out += '<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/comments?ln=%(ln)s&amp;reviews=1">%(reported_rev_label)s</a></li>' % \ {'siteurl': CFG_SITE_URL, 'ln': ln, 'reported_rev_label': _("View all reviews reported as abuse")} #<li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/delete?ln=%(ln)s&amp;comid=-1">%(delete_label)s</a></li> out +=""" <h3>General</h3> <li><a href="%(siteurl)s/admin/webcomment/webcommentadmin.py/users?ln=%(ln)s">%(view_users)s</a></li> <li><a href="%(siteurl)s/help/admin/webcomment-admin-guide">%(guide)s</a></li> """ % {'siteurl' : CFG_SITE_URL, #'delete_label': _("Delete/Undelete comment(s) or suppress abuse report(s)"), 'view_users': _("View all users who have been reported"), 'ln' : ln, 'guide' : _("Guide")} else: out += _("Comments and reviews are disabled") + '<br />' out += '</ol>' from invenio.bibrankadminlib import addadminbox return addadminbox('<b>%s</b>'% _("Menu"), [out]) def tmpl_admin_delete_form(self, ln, warnings): """ Display admin interface to fetch list of records to delete @param warnings: list of warning_tuples where warning_tuple is (warning_message, text_color) see tmpl_warnings, color is optional """ # load the right message language _ = gettext_set_language(ln) warnings = self.tmpl_warnings(warnings, ln) out = ''' <br /> %s<br /> <br />'''% _("Please enter the ID of the comment/review so that you can view it before deciding whether to delete it or not") form = ''' <table> <tr> <td>%s</td> <td><input type=text name="comid" size="10" maxlength="10" value="" /></td> </tr> <tr> <td><br /></td> <tr> </table> <br /> %s <br/> <br /> <table> <tr> <td>%s</td> <td><input type=text name="recid" size="10" maxlength="10" value="" /></td> </tr> <tr> <td><br /></td> <tr> </table> <br /> ''' % (_("Comment ID:"), _("Or enter a record ID to list all the associated comments/reviews:"), _("Record ID:")) form_link = "%s/admin/webcomment/webcommentadmin.py/delete?ln=%s" % (CFG_SITE_URL, ln) form = self.createhiddenform(action=form_link, method="get", text=form, button=_('View Comment')) return warnings + out + form def tmpl_admin_users(self, ln, users_data): """ @param users_data: tuple of ct, i.e. (ct, ct, ...) where ct is a tuple (total_number_reported, total_comments_reported, total_reviews_reported, total_nb_votes_yes_of_reported, total_nb_votes_total_of_reported, user_id, user_email, user_nickname) sorted by order of ct having highest total_number_reported """ _ = gettext_set_language(ln) u_reports = 0 u_comment_reports = 1 u_reviews_reports = 2 u_nb_votes_yes = 3 u_nb_votes_total = 4 u_uid = 5 u_email = 6 u_nickname = 7 if not users_data: return self.tmpl_warnings([(_("There have been no reports so far."), 'green')]) user_rows = "" for utuple in users_data: com_label = _("View all %s reported comments") % utuple[u_comment_reports] com_link = '''<a href="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&amp;uid=%s&amp;reviews=0">%s</a><br />''' % \ (CFG_SITE_URL, ln, utuple[u_uid], com_label) rev_label = _("View all %s reported reviews") % utuple[u_reviews_reports] rev_link = '''<a href="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&amp;uid=%s&amp;reviews=1">%s</a>''' % \ (CFG_SITE_URL, ln, utuple[u_uid], rev_label) if not utuple[u_nickname]: user_info = get_user_info(utuple[u_uid]) nickname = user_info[2] else: nickname = utuple[u_nickname] if CFG_WEBCOMMENT_ALLOW_REVIEWS: review_row = """ <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td>""" review_row %= (utuple[u_nb_votes_yes], utuple[u_nb_votes_total] - utuple[u_nb_votes_yes], utuple[u_nb_votes_total]) else: review_row = '' user_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(nickname)s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(email)s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(uid)s</td>%(review_row)s <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray; font-weight: bold;">%(reports)s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%(com_link)s%(rev_link)s</td> </tr>""" % { 'nickname' : nickname, 'email' : utuple[u_email], 'uid' : utuple[u_uid], 'reports' : utuple[u_reports], 'review_row': review_row, 'siteurl' : CFG_SITE_URL, 'ln' : ln, 'com_link' : CFG_WEBCOMMENT_ALLOW_COMMENTS and com_link or "", 'rev_link' : CFG_WEBCOMMENT_ALLOW_REVIEWS and rev_link or "" } out = "<br />" out += _("Here is a list, sorted by total number of reports, of all users who have had a comment reported at least once.") out += """ <br /> <br /> <table class="admin_wvar" style="width: 100%%;"> <thead> <tr class="adminheaderleft"> <th>""" out += _("Nickname") + '</th>\n' out += '<th>' + _("Email") + '</th>\n' out += '<th>' + _("User ID") + '</th>\n' if CFG_WEBCOMMENT_ALLOW_REVIEWS > 0: out += '<th>' + _("Number positive votes") + '</th>\n' out += '<th>' + _("Number negative votes") + '</th>\n' out += '<th>' + _("Total number votes") + '</th>\n' out += '<th>' + _("Total number of reports") + '</th>\n' out += '<th>' + _("View all user's reported comments/reviews") + '</th>\n' out += """ </tr> </thead> <tbody>%s </tbody> </table> """ % user_rows return out def tmpl_admin_select_comment_checkbox(self, cmt_id): """ outputs a checkbox named "comidXX" where XX is cmt_id """ return '<input type="checkbox" name="comid%i" />' % int(cmt_id) def tmpl_admin_user_info(self, ln, nickname, uid, email): """ prepares informations about a user""" _ = gettext_set_language(ln) out = """ %(nickname_label)s: %(messaging)s<br /> %(uid_label)s: %(uid)i<br /> %(email_label)s: <a href="mailto:%(email)s">%(email)s</a>""" out %= {'nickname_label': _("Nickname"), 'messaging': self.create_messaging_link(uid, nickname, ln), 'uid_label': _("User ID"), 'uid': int(uid), 'email_label': _("Email"), 'email': email} return out def tmpl_admin_review_info(self, ln, reviews, nb_reports, cmt_id, rec_id, status): """ outputs information about a review """ _ = gettext_set_language(ln) if reviews: reported_label = _("This review has been reported %i times") else: reported_label = _("This comment has been reported %i times") reported_label %= int(nb_reports) out = """ %(reported_label)s<br /> <a href="%(siteurl)s/record/%(rec_id)i?ln=%(ln)s">%(rec_id_label)s</a><br /> %(cmt_id_label)s""" out %= {'reported_label': reported_label, 'rec_id_label': _("Record") + ' #' + str(rec_id), 'siteurl': CFG_SITE_URL, 'rec_id': int(rec_id), 'cmt_id_label': _("Comment") + ' #' + str(cmt_id), 'ln': ln} if status in ['dm', 'da']: out += '<br /><div style="color:red;">Marked as deleted</div>' return out def tmpl_admin_latest(self, ln, comment_data, comments, error, user_collections, collection): """ @param comment_data: same type of tuple as that which is return by webcommentadminlib.py/query_get_latest i.e. tuple (nickname, uid, date_creation, body, id) if latest comments or tuple (nickname, uid, date_creation, body, star_score, id) if latest reviews """ _ = gettext_set_language(ln) out = """ <script type='text/javascript'> function collectionChange() { document.collection_form.submit(); } </script> """ out += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/latest?ln=%s&comments=%s">' % (CFG_SITE_URL, ln, comments) out += '<input type="hidden" name="ln" value=%s>' % ln out += '<input type="hidden" name="comments" value=%s>' % comments out += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">' for collection_name in user_collections: if collection_name == collection: out += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} else: out += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} out += '</select></div></form><br />' if error == 1: out += "<i>User is not authorized to view such collection.</i><br />" return out elif error == 2: out += "<i>There are no %s for this collection.</i><br />" % (comments and 'comments' or 'reviews') return out out += """ <ol> """ for (cmt_tuple, meta_data) in comment_data: bibrec_id = meta_data[3] content = format_record(bibrec_id, "hs") if not comments: out += """ <li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> reviewed by %(user)s</a> (%(stars)s) \"%(body)s\" on <i> %(date)s </i></li> </span> <br/> """ % {'content': content, 'comment_url': CFG_SITE_URL + '/record/' + str(bibrec_id) + '/reviews', 'user':cmt_tuple[0] , 'stars': '*' * int(cmt_tuple[4]) , 'body': cmt_tuple[3][:20] + '...', 'date': cmt_tuple[2]} else: out += """ <li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> commented by %(user)s</a>, \"%(body)s\" on <i> %(date)s </i></li> </span> <br/> """ % {'content': content, 'comment_url': CFG_SITE_URL + '/record/' + str(bibrec_id) + '/comments', 'user':cmt_tuple[0] , 'body': cmt_tuple[3][:20] + '...', 'date': cmt_tuple[2]} out += """</ol>""" return out def tmpl_admin_hot(self, ln, comment_data, comments, error, user_collections, collection): """ @param comment_data: same type of tuple as that which is return by webcommentadminlib.py/query_get_hot i.e. tuple (id_bibrec, date_last_comment, users, count) """ _ = gettext_set_language(ln) out = """ <script type='text/javascript'> function collectionChange() { document.collection_form.submit(); } </script> """ out += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/hot?ln=%s&comments=%s">' % (CFG_SITE_URL, ln, comments) out += '<input type="hidden" name="ln" value=%s>' % ln out += '<input type="hidden" name="comments" value=%s>' % comments out += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">' for collection_name in user_collections: if collection_name == collection: out += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} else: out += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} out += '</select></div></form><br />' if error == 1: out += "<i>User is not authorized to view such collection.</i><br />" return out elif error == 2: out += "<i>There are no %s for this collection.</i><br />" % (comments and 'comments' or 'reviews') return out for cmt_tuple in comment_data: bibrec_id = cmt_tuple[0] content = format_record(bibrec_id, "hs") last_comment_date = cmt_tuple[1] total_users = cmt_tuple[2] total_comments = cmt_tuple[3] if comments: comment_url = CFG_SITE_URL + '/record/' + str(bibrec_id) + '/comments' str_comment = int(total_comments) > 1 and 'comments' or 'comment' else: comment_url = CFG_SITE_URL + '/record/' + str(bibrec_id) + '/reviews' str_comment = int(total_comments) > 1 and 'reviews' or 'review' out += """ <li> %(content)s <br/> <span class="moreinfo"> <a class="moreinfo" href=%(comment_url)s> %(total_comments)s %(str_comment)s</a> (%(total_users)s %(user)s), latest on <i> %(last_comment_date)s </i></li> </span> <br/> """ % {'content': content, 'comment_url': comment_url , 'total_comments': total_comments, 'str_comment': str_comment, 'total_users': total_users, 'user': int(total_users) > 1 and 'users' or 'user', 'last_comment_date': last_comment_date} out += """</ol>""" return out def tmpl_admin_comments(self, ln, uid, comID, recID, comment_data, reviews, error, user_collections, collection): """ @param comment_data: same type of tuple as that which is returned by webcomment.py/query_retrieve_comments_or_remarks i.e. tuple of comment where comment is tuple (nickname, date_creation, body, id) if ranking disabled or tuple (nickname, date_creation, body, nb_votes_yes, nb_votes_total, star_score, title, id) """ _ = gettext_set_language(ln) coll_form = """ <script type='text/javascript'> function collectionChange() { document.collection_form.submit(); } </script> """ coll_form += '<form method="get" name="collection_form" action="%s/admin/webcomment/webcommentadmin.py/comments?ln=%s&reviews=%s">' % (CFG_SITE_URL, ln, reviews) coll_form += '<input type="hidden" name="ln" value=%s>' % ln coll_form += '<input type="hidden" name="reviews" value=%s>' % reviews coll_form += '<div> Filter by collection: <select name="collection" onchange="javascript:collectionChange();">' for collection_name in user_collections: if collection_name == collection: coll_form += '<option "SELECTED" value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} else: coll_form += '<option value="%(collection_name)s">%(collection_name)s</option>' % {'collection_name': cgi.escape(collection_name)} coll_form += '</select></div></form><br />' if error == 1: coll_form += "<i>User is not authorized to view such collection.</i><br />" return coll_form elif error == 2: coll_form += "<i>There are no %s for this collection.</i><br />" % (reviews and 'reviews' or 'comments') return coll_form comments = [] comments_info = [] checkboxes = [] users = [] for (cmt_tuple, meta_data) in comment_data: if reviews: comments.append(self.tmpl_get_comment_with_ranking(None,#request object ln, cmt_tuple[0],#nickname cmt_tuple[1],#userid cmt_tuple[2],#date_creation cmt_tuple[3],#body cmt_tuple[9],#status 0, cmt_tuple[5],#nb_votes_total cmt_tuple[4],#nb_votes_yes cmt_tuple[6],#star_score cmt_tuple[7]))#title else: comments.append(self.tmpl_get_comment_without_ranking(None,#request object ln, cmt_tuple[0],#nickname cmt_tuple[1],#userid cmt_tuple[2],#date_creation cmt_tuple[3],#body cmt_tuple[5],#status 0, None, #reply_link None, #report_link None, #undelete_link None)) #delete_links users.append(self.tmpl_admin_user_info(ln, meta_data[0], #nickname meta_data[1], #uid meta_data[2]))#email if reviews: status = cmt_tuple[9] else: status = cmt_tuple[5] comments_info.append(self.tmpl_admin_review_info(ln, reviews, meta_data[5], # nb abuse reports meta_data[3], # cmt_id meta_data[4], # rec_id status)) # status checkboxes.append(self.tmpl_admin_select_comment_checkbox(meta_data[3])) form_link = "%s/admin/webcomment/webcommentadmin.py/del_com?ln=%s" % (CFG_SITE_URL, ln) out = """ <table class="admin_wvar" style="width:100%%;"> <thead> <tr class="adminheaderleft"> <th>%(review_label)s</th> <th>%(written_by_label)s</th> <th>%(review_info_label)s</th> <th>%(select_label)s</th> </tr> </thead> <tbody>""" % {'review_label': reviews and _("Review") or _("Comment"), 'written_by_label': _("Written by"), 'review_info_label': _("General informations"), 'select_label': _("Select")} for i in range (0, len(comments)): out += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintd" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (comments[i], users[i], comments_info[i], checkboxes[i]) out += """ </tbody> </table>""" if reviews: action_display = { 'delete': _('Delete selected reviews'), 'unreport': _('Suppress selected abuse report'), 'undelete': _('Undelete selected reviews') } else: action_display = { 'undelete': _('Undelete selected comments'), 'delete': _('Delete selected comments'), 'unreport': _('Suppress selected abuse report') } form = self.tmpl_create_multiple_actions_form(form_name="admin_comment", form_action=form_link, method="post", action_display=action_display, action_field_name='action', button_label=_("OK"), button_name="okbutton", content=out) if uid > 0: header = '<br />' if reviews: header += _("Here are the reported reviews of user %s") % uid else: header += _("Here are the reported comments of user %s") % uid header += '<br /><br />' if comID > 0 and recID <= 0 and uid <= 0: if reviews: header = '<br />' +_("Here is review %s")% comID + '<br /><br />' else: header = '<br />' +_("Here is comment %s")% comID + '<br /><br />' if uid > 0 and comID > 0 and recID <= 0: if reviews: header = '<br />' + _("Here is review %(x_cmtID)s written by user %(x_user)s") % {'x_cmtID': comID, 'x_user': uid} else: header = '<br />' + _("Here is comment %(x_cmtID)s written by user %(x_user)s") % {'x_cmtID': comID, 'x_user': uid} header += '<br/ ><br />' if comID <= 0 and recID <= 0 and uid <= 0: header = '<br />' if reviews: header += _("Here are all reported reviews sorted by the most reported") else: header += _("Here are all reported comments sorted by the most reported") header += "<br /><br />" elif recID > 0: header = '<br />' if reviews: header += _("Here are all reviews for record %i, sorted by the most reported" % recID) header += '<br /><a href="%s/admin/webcomment/webcommentadmin.py/delete?comid=&recid=%s&amp;reviews=0">%s</a>' % (CFG_SITE_URL, recID, _("Show comments")) else: header += _("Here are all comments for record %i, sorted by the most reported" % recID) header += '<br /><a href="%s/admin/webcomment/webcommentadmin.py/delete?comid=&recid=%s&amp;reviews=1">%s</a>' % (CFG_SITE_URL, recID, _("Show reviews")) header += "<br /><br />" return coll_form + header + form def tmpl_admin_del_com(self, del_res, ln=CFG_SITE_LANG): """ @param del_res: list of the following tuple (comment_id, was_successfully_deleted), was_successfully_deleted is boolean (0=false, >0=true """ _ = gettext_set_language(ln) table_rows = '' for deltuple in del_res: table_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>") out = """ <table class="admin_wvar"> <tr class="adminheaderleft"> <td style="padding-right:10px;">%s</td> <td>%s</td> </tr>%s <table>""" % (_("comment ID"), _("successfully deleted"), table_rows) return out def tmpl_admin_undel_com(self, del_res, ln=CFG_SITE_LANG): """ @param del_res: list of the following tuple (comment_id, was_successfully_undeleted), was_successfully_undeleted is boolean (0=false, >0=true """ _ = gettext_set_language(ln) table_rows = '' for deltuple in del_res: table_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>") out = """ <table class="admin_wvar"> <tr class="adminheaderleft"> <td style="padding-right:10px;">%s</td> <td>%s</td> </tr>%s <table>""" % (_("comment ID"), _("successfully undeleted"), table_rows) return out def tmpl_admin_suppress_abuse_report(self, del_res, ln=CFG_SITE_LANG): """ @param del_res: list of the following tuple (comment_id, was_successfully_deleted), was_successfully_deleted is boolean (0=false, >0=true """ _ = gettext_set_language(ln) table_rows = '' for deltuple in del_res: table_rows += """ <tr> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> <td class="admintdleft" style="padding: 5px; border-bottom: 1px solid lightgray;">%s</td> </tr>""" % (deltuple[0], deltuple[1]>0 and _("Yes") or "<span class=\"important\">" +_("No") + "</span>") out = """ <table class="admin_wvar"> <tr class="adminheaderleft"> <td style ="padding-right: 10px;">%s</td> <td>%s</td> </tr>%s <table>""" % (_("comment ID"), _("successfully suppressed abuse report"), table_rows) return out def tmpl_mini_review(self, recID, ln=CFG_SITE_LANG, action='SUBMIT', avg_score=0, nb_comments_total=0): """Display the mini version of reviews (only the grading part)""" _ = gettext_set_language(ln) url = '%s/record/%s/reviews/add?ln=%s&amp;action=%s' % (CFG_SITE_URL, recID, ln, action) if avg_score > 0: score = _("Average review score: %(x_nb_score)s based on %(x_nb_reviews)s reviews") % \ {'x_nb_score': '<b>%.1f</b>' % avg_score, 'x_nb_reviews': nb_comments_total} else: score = '(' +_("Not yet reviewed") + ')' if avg_score == 5: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', 'full' elif avg_score >= 4.5: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', 'half' elif avg_score >= 4: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'full', '' elif avg_score >= 3.5: s1, s2, s3, s4, s5 = 'full', 'full', 'full', 'half', '' elif avg_score >= 3: s1, s2, s3, s4, s5 = 'full', 'full', 'full', '', '' elif avg_score >= 2.5: s1, s2, s3, s4, s5 = 'full', 'full', 'half', '', '' elif avg_score >= 2: s1, s2, s3, s4, s5 = 'full', 'full', '', '', '' elif avg_score >= 1.5: s1, s2, s3, s4, s5 = 'full', 'half', '', '', '' elif avg_score == 1: s1, s2, s3, s4, s5 = 'full', '', '', '', '' else: s1, s2, s3, s4, s5 = '', '', '', '', '' out = ''' <small class="detailedRecordActions">%(rate)s:</small><br /><br /> <div style="margin:auto;width:160px;"> <span style="display:none;">Rate this document:</span> <div class="star %(s1)s" ><a href="%(url)s&amp;score=1">1</a> <div class="star %(s2)s" ><a href="%(url)s&amp;score=2">2</a> <div class="star %(s3)s" ><a href="%(url)s&amp;score=3">3</a> <div class="star %(s4)s" ><a href="%(url)s&amp;score=4">4</a> <div class="star %(s5)s" ><a href="%(url)s&amp;score=5">5</a></div></div></div></div></div> <div style="clear:both">&nbsp;</div> </div> <small>%(score)s</small> ''' % {'url': url, 'score': score, 'rate': _("Rate this document"), 's1': s1, 's2': s2, 's3': s3, 's4': s4, 's5': s5 } return out def tmpl_email_new_comment_header(self, recID, title, reviews, comID, report_numbers, can_unsubscribe=True, ln=CFG_SITE_LANG, uid=-1): """ Prints the email header used to notify subscribers that a new comment/review was added. @param recid: the ID of the commented/reviewed record @param title: the title of the commented/reviewed record @param reviews: True if it is a review, else if a comment @param comID: the comment ID @param report_numbers: the report number(s) of the record @param can_unsubscribe: True if user can unsubscribe from alert @param ln: language """ # load the right message language _ = gettext_set_language(ln) user_info = collect_user_info(uid) out = _("Hello:") + '\n\n' + \ (reviews and _("The following review was sent to %(CFG_SITE_NAME)s by %(user_nickname)s:") or \ _("The following comment was sent to %(CFG_SITE_NAME)s by %(user_nickname)s:")) % \ {'CFG_SITE_NAME': CFG_SITE_NAME, 'user_nickname': user_info['nickname']} out += '\n(<%s>)' % (CFG_SITE_URL + '/record/' + str(recID)) out += '\n\n\n' return out def tmpl_email_new_comment_footer(self, recID, title, reviews, comID, report_numbers, can_unsubscribe=True, ln=CFG_SITE_LANG): """ Prints the email footer used to notify subscribers that a new comment/review was added. @param recid: the ID of the commented/reviewed record @param title: the title of the commented/reviewed record @param reviews: True if it is a review, else if a comment @param comID: the comment ID @param report_numbers: the report number(s) of the record @param can_unsubscribe: True if user can unsubscribe from alert @param ln: language """ # load the right message language _ = gettext_set_language(ln) out = '\n\n-- \n' out += _("This is an automatic message, please don't reply to it.") out += '\n' out += _("To post another comment, go to <%(x_url)s> instead.") % \ {'x_url': CFG_SITE_URL + '/record/' + str(recID) + \ (reviews and '/reviews' or '/comments') + '/add'} out += '\n' if not reviews: out += _("To specifically reply to this comment, go to <%(x_url)s>") % \ {'x_url': CFG_SITE_URL + '/record/' + str(recID) + \ '/comments/add?action=REPLY&comid=' + str(comID)} out += '\n' if can_unsubscribe: out += _("To unsubscribe from this discussion, go to <%(x_url)s>") % \ {'x_url': CFG_SITE_URL + '/record/' + str(recID) + \ '/comments/unsubscribe'} out += '\n' out += _("For any question, please use <%(CFG_SITE_SUPPORT_EMAIL)s>") % \ {'CFG_SITE_SUPPORT_EMAIL': CFG_SITE_SUPPORT_EMAIL} return out def tmpl_email_new_comment_admin(self, recID): """ Prints the record information used in the email to notify the system administrator that a new comment has been posted. @param recID: the ID of the commented/reviewed record """ out = "" title = get_fieldvalues(recID, "245__a") authors = ', '.join(get_fieldvalues(recID, "100__a") + get_fieldvalues(recID, "700__a")) #res_author = "" #res_rep_num = "" #for author in authors: # res_author = res_author + ' ' + author dates = get_fieldvalues(recID, "260__c") report_nums = get_fieldvalues(recID, "037__a") report_nums += get_fieldvalues(recID, "088__a") report_nums = ', '.join(report_nums) #for rep_num in report_nums: # res_rep_num = res_rep_num + ', ' + rep_num out += " Title = %s \n" % (title and title[0] or "No Title") out += " Authors = %s \n" % authors if dates: out += " Date = %s \n" % dates[0] out += " Report number = %s" % report_nums return out
kaplun/Invenio-OpenAIRE
modules/webcomment/lib/webcomment_templates.py
Python
gpl-2.0
109,494
#!/usr/bin/python import os, subprocess amsDecode = "/usr/local/bin/amsDecode" path = "/usr/local/bin" specDataFile = "specData.csv" f = open("processFile.log", "w") if os.path.exists(specDataFile): os.remove(specDataFile) for fileName in os.listdir('.'): if fileName.endswith('.bin'): #print 'file :' + fileName cmnd = [amsDecode, fileName, "-t -95", "-b", "68", "468" ] subprocess.call(cmnd,stdout=f) f.close
jennyb/amsDecode
processBinFiles.py
Python
gpl-2.0
451
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.model; import static org.opennms.core.utils.InetAddressUtils.toInteger; import java.io.Serializable; import java.math.BigInteger; import java.net.InetAddress; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.opennms.core.xml.bind.InetAddressXmlAdapter; @SuppressWarnings("serial") @XmlRootElement(name = "monitored-service") public class OnmsMonitoredServiceDetail implements Serializable, Comparable<OnmsMonitoredServiceDetail> { private String m_statusCode; private String m_status; private String m_nodeLabel; private String m_serviceName; private InetAddress m_ipAddress; private boolean m_isMonitored; private boolean m_isDown; public OnmsMonitoredServiceDetail() { } public OnmsMonitoredServiceDetail(OnmsMonitoredService service) { m_nodeLabel = service.getIpInterface().getNode().getLabel(); m_ipAddress = service.getIpAddress(); m_serviceName = service.getServiceName(); m_isMonitored = service.getStatus().equals("A"); m_isDown = service.isDown(); m_statusCode = service.getStatus(); m_status = service.getStatusLong(); } @XmlElement(name="status") public String getStatus() { return m_status; } public void setStatus(String status) { this.m_status = status; } @XmlAttribute(name="statusCode") public String getStatusCode() { return m_statusCode; } public void setStatusCode(String statusCode) { this.m_statusCode = statusCode; } @XmlElement(name="node") public String getNodeLabel() { return m_nodeLabel; } public void setNodeLabel(String nodeLabel) { this.m_nodeLabel = nodeLabel; } @XmlElement(name="serviceName") public String getServiceName() { return m_serviceName; } public void setServiceName(String serviceName) { this.m_serviceName = serviceName; } @XmlElement(name="ipAddress") @XmlJavaTypeAdapter(InetAddressXmlAdapter.class) public InetAddress getIpAddress() { return m_ipAddress; } public void setIpAddress(InetAddress ipAddress) { this.m_ipAddress = ipAddress; } @XmlAttribute(name="isMonitored") public boolean isMonitored() { return m_isMonitored; } @XmlAttribute(name="isDown") public boolean isDown() { return m_isDown; } @Override public int compareTo(OnmsMonitoredServiceDetail o) { int diff; diff = getNodeLabel().compareToIgnoreCase(o.getNodeLabel()); if (diff != 0) { return diff; } BigInteger a = toInteger(getIpAddress()); BigInteger b = toInteger(o.getIpAddress()); diff = a.compareTo(b); if (diff != 0) { return diff; } return getServiceName().compareToIgnoreCase(o.getServiceName()); } }
qoswork/opennmszh
opennms-model/src/main/java/org/opennms/netmgt/model/OnmsMonitoredServiceDetail.java
Java
gpl-2.0
4,276
/* * Copyright (C) 2014 Stanislav Nepochatov * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package org.ribbon.commands; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.ribbon.controller.Router; import javax.persistence.*; import org.ribbon.jpa.JPAManager; import org.ribbon.jpa.enteties.*; /** * LOGOUT command (for exit from the system). * @author Stanislav Nepochatov */ public class ComLogout implements Command{ @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { EntityManager em = JPAManager.getEntityManager(); TypedQuery<User> qr = em.createNamedQuery("User.findByLogin", User.class); qr.setParameter("login", request.getSession().getAttribute("username")); User findedUser = qr.getSingleResult(); EntityTransaction tr = em.getTransaction(); tr.begin(); if (findedUser != null) { findedUser.setIsActive(false); request.getSession().removeAttribute("username"); } tr.commit(); em.close(); return Router.DEFAULT_PAGE; } @Override public Boolean isAuthRequired() { return true; } }
spoilt-exile/RibbonSystem
src/java/org/ribbon/commands/ComLogout.java
Java
gpl-2.0
2,021
#!/usr/bin/env python # -*- coding: utf-8 -*- # # vertexdomain.py # # Copyright 2016 notna <notna@apparat.org> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # #
not-na/peng3d
docs/pyglet/graphics/vertexdomain.py
Python
gpl-2.0
851
angular.module('SpamExpertsApp') .run(['$rootScope', '$state', 'uiService', 'AuthService', 'API_EVENTS', function ($rootScope, $state, uiService, AuthService, API_EVENTS) { $rootScope.$on('$stateChangeStart', function (event, next) { if (next.name !== 'login') { $rootScope.username = AuthService.getUsername(); $rootScope.role = AuthService.getRole(); if (!AuthService.isAuthenticated()) { event.preventDefault(); $state.go('login'); } else if ('data' in next && 'authorizedRoles' in next.data) { var authorizedRoles = next.data.authorizedRoles; if (!AuthService.isAuthorized(authorizedRoles)) { event.preventDefault(); $state.go($state.current, {}, {reload: true}); $rootScope.$broadcast(API_EVENTS.notAuthorized); } } } else { if (AuthService.isAuthenticated()) { event.preventDefault(); $state.go('main.dash'); } } }); $rootScope.$on('$logout', function () { uiService.confirm({ title: 'Confirm logout', template: 'Are you sure you want to log out?' }, function() { AuthService.logout(); $state.go('login'); }); }); $rootScope.$on(API_EVENTS.notAuthorized, function() { uiService.alert({ title: 'Unauthorized!', template: 'You are not allowed to access this resource.' }); }); $rootScope.$on(API_EVENTS.userNotAllowed, function() { uiService.alert({ title: 'Error logging in!', template: 'Sorry, admin users are not able to use this app yet. Please log in as a domain or email user.' }); }); $rootScope.$on(API_EVENTS.notAuthenticated, function() { AuthService.logout(); AuthService.clearPassword(); $state.go('login'); uiService.alert({ title: 'Authentication expired', template: 'Sorry, you have to login again.' }); }); } ]);
SpamExperts/mobile-app
src/js/auth/init.js
JavaScript
gpl-2.0
2,639
<?php namespace Gossamer\Pesedget\Entities; /** * OneToManyJoinInterface - used for mapping between 2 tables on a 1 to many join * * usage: * key: namespaced path to object * * values: * 1st: table column name * 2nd: passed param from request object (easier readability if they match names) * * * example of when: * IncidentTypes table and Sections * an incident type can be associated to multiple sections - this takes 3 tables * Sections * IncidentTypes * IncidentTypesSections - mapping table used by this interface * * id IncidentTypes_id Sections_id * * getIdentityColumn would return IncidentTypes_id * - this would be $this->getTablename() . '_id'; * * the rest of the method is looping through an array of Sections_id values * passed in and inserting it into the Sections_id column of the * IncidentTypesSections table */ interface OneToManyJoinInterface { // private $manyJoinRelationships = array( // 'components\incidents\entities\IncidentTypeSection' => array('Sections_id' => 'Sections_id') // ); public function getManyJoinRelationships(); public function getIdentityColumn(); }
dmeikle/pesedget
src/Gossamer/Pesedget/Entities/OneToManyJoinInterface.php
PHP
gpl-2.0
1,173
#!/usr/bin/python3 from distutils.core import setup setup(name='PySh', version='0.0.1', py_modules=['pysh'], description="A tiny interface to intuitively access shell commands.", author="Bede Kelly", author_email="bedekelly97@gmail.com", url="https://github.com/bedekelly/pysh", provides=['pysh'])
bedekelly/pysh
setup.py
Python
gpl-2.0
340
module.exports = function (grunt) { "use strict"; grunt.initConfig({ dirs: { css: 'app/css', js: 'app/js', sass: 'app/sass', }, compass: { dist: { options: { config: 'config.rb', } } }, concat: { options: { seperator: ';', }, dist: { src: ['<%= dirs.js %>/modules/*.js', '<%= dirs.js %>/src/*.js'], dest: '<%= dirs.js %>/app.js' } }, uglify: { options: { // mangle: false, debug: true, }, target: { files: { '<%= dirs.js %>/app.min.js': ['<%= dirs.js %>/app.js'] } } }, watch: { css: { files: [ '<%= dirs.sass %>/*.scss', '<%= dirs.sass %>/modules/*.scss', '<%= dirs.sass %>/partials/*.scss' ], tasks: ['css'], options: { spawn: false, } }, js: { files: [ '<%= dirs.js %>/modules/*.js', '<%= dirs.js %>/src/*.js' ], tasks: ['js'], options: { spawn: false, } } } }); grunt.loadNpmTasks('grunt-contrib-compass'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['css', 'js']); grunt.registerTask('css', ['compass']); grunt.registerTask('js', ['concat', 'uglify']); };
SeerUK/WoWPR
Gruntfile.js
JavaScript
gpl-2.0
1,487
package java.lang; import org.checkerframework.dataflow.qual.Pure; import org.checkerframework.dataflow.qual.SideEffectFree; import org.checkerframework.checker.nullness.qual.EnsuresNonNullIf; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.PolyNull; public final class Class<T extends @Nullable Object> extends Object implements java.io.Serializable, java.lang.reflect.GenericDeclaration, java.lang.reflect.Type, java.lang.reflect.AnnotatedElement { private static final long serialVersionUID = 0; protected Class() {} @SideEffectFree public String toString() { throw new RuntimeException("skeleton method"); } public static Class<?> forName(String a1) throws ClassNotFoundException { throw new RuntimeException("skeleton method"); } public static Class<?> forName(String a1, boolean a2, @Nullable ClassLoader a3) throws ClassNotFoundException { throw new RuntimeException("skeleton method"); } public @NonNull T newInstance() throws InstantiationException, IllegalAccessException { throw new RuntimeException("skeleton method"); } @Pure public boolean isAnnotation() { throw new RuntimeException("skeleton method"); } @Pure public native boolean isInstance(@Nullable Object a1); @Pure public boolean isSynthetic() { throw new RuntimeException("skeleton method"); } public String getName() { throw new RuntimeException("skeleton method"); } public @Nullable ClassLoader getClassLoader() { throw new RuntimeException("skeleton method"); } public java.lang.reflect.TypeVariable<Class<T>>[] getTypeParameters() { throw new RuntimeException("skeleton method"); } public java.lang.reflect. @Nullable Type getGenericSuperclass() { throw new RuntimeException("skeleton method"); } @Pure public @Nullable Package getPackage() { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Type[] getGenericInterfaces() { throw new RuntimeException("skeleton method"); } public java.lang.reflect. @Nullable Method getEnclosingMethod() { throw new RuntimeException("skeleton method"); } public java.lang.reflect. @Nullable Constructor<?> getEnclosingConstructor() { throw new RuntimeException("skeleton method"); } public @Nullable Class<?> getEnclosingClass() { throw new RuntimeException("skeleton method"); } public String getSimpleName() { throw new RuntimeException("skeleton method"); } @Pure public native @Nullable Class<? super T> getSuperclass(); @Pure public native Class<?>[] getInterfaces(); public @Nullable String getCanonicalName() { throw new RuntimeException("skeleton method"); } @Pure public boolean isAnonymousClass() { throw new RuntimeException("skeleton method"); } @Pure public boolean isLocalClass() { throw new RuntimeException("skeleton method"); } @Pure public boolean isMemberClass() { throw new RuntimeException("skeleton method"); } public Class<?>[] getClasses() { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Field[] getFields() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Method[] getMethods() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Constructor<?>[] getConstructors() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Field getField(String a1) throws NoSuchFieldException, SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Method getMethod(String a1, Class<?> @Nullable ... a2) throws NoSuchMethodException, SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Constructor<T> getConstructor(Class<?>... a1) throws NoSuchMethodException, SecurityException { throw new RuntimeException("skeleton method"); } public Class<?>[] getDeclaredClasses() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Field[] getDeclaredFields() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Method[] getDeclaredMethods() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Constructor<?>[] getDeclaredConstructors() throws SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Field getDeclaredField(String a1) throws NoSuchFieldException, SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Method getDeclaredMethod(String a1, Class<?>... a2) throws NoSuchMethodException, SecurityException { throw new RuntimeException("skeleton method"); } public java.lang.reflect.Constructor<T> getDeclaredConstructor(Class<?>... a1) throws NoSuchMethodException, SecurityException { throw new RuntimeException("skeleton method"); } public java.io. @Nullable InputStream getResourceAsStream(String a1) { throw new RuntimeException("skeleton method"); } public java.net. @Nullable URL getResource(String a1) { throw new RuntimeException("skeleton method"); } public java.security.ProtectionDomain getProtectionDomain() { throw new RuntimeException("skeleton method"); } public boolean desiredAssertionStatus() { throw new RuntimeException("skeleton method"); } @Pure public boolean isEnum() { throw new RuntimeException("skeleton method"); } public T @Nullable [] getEnumConstants() { throw new RuntimeException("skeleton method"); } java.util.Map<String, T> enumConstantDirectory() { throw new RuntimeException("skeleton method"); } public @PolyNull T cast(@PolyNull Object a1) { throw new RuntimeException("skeleton method"); } public <U> Class<? extends U> asSubclass(Class<U> a1) { throw new RuntimeException("skeleton method"); } public <A extends java.lang.annotation.Annotation> @Nullable A getAnnotation(Class<A> a1) { throw new RuntimeException("skeleton method"); } @Pure public boolean isAnnotationPresent(Class<? extends java.lang.annotation.Annotation> a1) { throw new RuntimeException("skeleton method"); } public java.lang.annotation.Annotation[] getAnnotations() { throw new RuntimeException("skeleton method"); } public java.lang.annotation.Annotation[] getDeclaredAnnotations() { throw new RuntimeException("skeleton method"); } @Pure public native @Nullable Class<?> getComponentType(); public native Object @Nullable [] getSigners(); public native @Nullable Class<?> getDeclaringClass(); @Pure public native boolean isPrimitive(); @EnsuresNonNullIf(expression="getComponentType()", result=true) @Pure public native boolean isArray(); @Pure public native boolean isAssignableFrom(Class<? extends @Nullable Object> cls); @Pure public native boolean isInterface(); @Pure public native int getModifiers(); @Pure public boolean isTypeAnnotationPresent(Class<? extends java.lang.annotation.Annotation> annotationClass) { throw new RuntimeException("skeleton method"); } public <T extends java.lang.annotation.Annotation> T getTypeAnnotation(Class<T> annotationClass) { throw new RuntimeException("skeleton method"); } public java.lang.annotation.Annotation[] getTypeAnnotations() { throw new RuntimeException("skeleton method"); } public java.lang.annotation.Annotation[] getDeclaredTypeAnnotations() { throw new RuntimeException("skeleton method"); } }
biddyweb/checker-framework
checker/jdk/nullness/src/java/lang/Class.java
Java
gpl-2.0
7,450
<?php /** * Fired during plugin activation * * @link http://wp-rewords.com * @since 1.0.0 * * @package Wp_Rewords * @subpackage Wp_Rewords/includes */ /** * Fired during plugin activation. * * This class defines all code necessary to run during the plugin's activation. * * @since 1.0.0 * @package Wp_Rewords * @subpackage Wp_Rewords/includes * @author Yuval Oren <yuval@pinewise.com> */ class Wp_Rewords_Activator { /** * Short Description. (use period) * * Long Description. * * @since 1.0.0 */ public static function activate() { $wp_rewords_options = array( "campaigns" => array() // "campaigns" => array(array('4'=>array("name" => "Mailing list", "page_tile" => "10 things you wanted", "url" => "http://wprewords.com/?utm=123123))) ); if (!get_option("wp_rewords_options")) { update_option("wp_rewords_options", $wp_rewords_options); } } }
wp-plugins/wp-rewords
includes/class-wp-rewords-activator.php
PHP
gpl-2.0
966
// Copyright 2008 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include "Core/HW/EXI/EXI_DeviceMemoryCard.h" #include <array> #include <cstring> #include <memory> #include <string> #include "Common/ChunkFile.h" #include "Common/CommonPaths.h" #include "Common/CommonTypes.h" #include "Common/FileUtil.h" #include "Common/IniFile.h" #include "Common/Logging/Log.h" #include "Common/NandPaths.h" #include "Common/StringUtil.h" #include "Core/ConfigManager.h" #include "Core/CoreTiming.h" #include "Core/HW/EXI/EXI.h" #include "Core/HW/EXI/EXI_Channel.h" #include "Core/HW/EXI/EXI_Device.h" #include "Core/HW/GCMemcard/GCMemcard.h" #include "Core/HW/GCMemcard/GCMemcardDirectory.h" #include "Core/HW/GCMemcard/GCMemcardRaw.h" #include "Core/HW/Memmap.h" #include "Core/HW/Sram.h" #include "Core/HW/SystemTimers.h" #include "Core/Movie.h" #include "DiscIO/Enums.h" #include "DiscIO/NANDContentLoader.h" namespace ExpansionInterface { #define MC_STATUS_BUSY 0x80 #define MC_STATUS_UNLOCKED 0x40 #define MC_STATUS_SLEEP 0x20 #define MC_STATUS_ERASEERROR 0x10 #define MC_STATUS_PROGRAMEERROR 0x08 #define MC_STATUS_READY 0x01 #define SIZE_TO_Mb (1024 * 8 * 16) static const u32 MC_TRANSFER_RATE_READ = 512 * 1024; static const u32 MC_TRANSFER_RATE_WRITE = (u32)(96.125f * 1024.0f); static std::array<CoreTiming::EventType*, 2> s_et_cmd_done; static std::array<CoreTiming::EventType*, 2> s_et_transfer_complete; // Takes care of the nasty recovery of the 'this' pointer from card_index, // stored in the userdata parameter of the CoreTiming event. void CEXIMemoryCard::EventCompleteFindInstance(u64 userdata, std::function<void(CEXIMemoryCard*)> callback) { int card_index = (int)userdata; CEXIMemoryCard* pThis = (CEXIMemoryCard*)ExpansionInterface::FindDevice(EXIDEVICE_MEMORYCARD, card_index); if (pThis == nullptr) { pThis = (CEXIMemoryCard*)ExpansionInterface::FindDevice(EXIDEVICE_MEMORYCARDFOLDER, card_index); } if (pThis) { callback(pThis); } } void CEXIMemoryCard::CmdDoneCallback(u64 userdata, s64 cyclesLate) { EventCompleteFindInstance(userdata, [](CEXIMemoryCard* instance) { instance->CmdDone(); }); } void CEXIMemoryCard::TransferCompleteCallback(u64 userdata, s64 cyclesLate) { EventCompleteFindInstance(userdata, [](CEXIMemoryCard* instance) { instance->TransferComplete(); }); } void CEXIMemoryCard::Init() { static constexpr char DONE_PREFIX[] = "memcardDone"; static constexpr char TRANSFER_COMPLETE_PREFIX[] = "memcardTransferComplete"; static_assert(s_et_cmd_done.size() == s_et_transfer_complete.size(), "Event array size differs"); for (unsigned int i = 0; i < s_et_cmd_done.size(); ++i) { std::string name = DONE_PREFIX; name += static_cast<char>('A' + i); s_et_cmd_done[i] = CoreTiming::RegisterEvent(name, CmdDoneCallback); name = TRANSFER_COMPLETE_PREFIX; name += static_cast<char>('A' + i); s_et_transfer_complete[i] = CoreTiming::RegisterEvent(name, TransferCompleteCallback); } } void CEXIMemoryCard::Shutdown() { s_et_cmd_done.fill(nullptr); s_et_transfer_complete.fill(nullptr); } CEXIMemoryCard::CEXIMemoryCard(const int index, bool gciFolder) : card_index(index) { _assert_msg_(EXPANSIONINTERFACE, static_cast<std::size_t>(index) < s_et_cmd_done.size(), "Trying to create invalid memory card index %d.", index); // NOTE: When loading a save state, DMA completion callbacks (s_et_transfer_complete) and such // may have been restored, we need to anticipate those arriving. interruptSwitch = 0; m_bInterruptSet = 0; command = 0; status = MC_STATUS_BUSY | MC_STATUS_UNLOCKED | MC_STATUS_READY; m_uPosition = 0; memset(programming_buffer, 0, sizeof(programming_buffer)); // Nintendo Memory Card EXI IDs // 0x00000004 Memory Card 59 4Mbit // 0x00000008 Memory Card 123 8Mb // 0x00000010 Memory Card 251 16Mb // 0x00000020 Memory Card 507 32Mb // 0x00000040 Memory Card 1019 64Mb // 0x00000080 Memory Card 2043 128Mb // 0x00000510 16Mb "bigben" card // card_id = 0xc243; card_id = 0xc221; // It's a Nintendo brand memcard // The following games have issues with memory cards bigger than 16Mb // Darkened Skye GDQE6S GDQP6S // WTA Tour Tennis GWTEA4 GWTJA4 GWTPA4 // Disney Sports : Skate Boarding GDXEA4 GDXPA4 GDXJA4 // Disney Sports : Soccer GDKEA4 // Wallace and Gromit in Pet Zoo GWLE6L GWLX6L // Use a 16Mb (251 block) memory card for these games bool useMC251; IniFile gameIni = SConfig::GetInstance().LoadGameIni(); gameIni.GetOrCreateSection("Core")->Get("MemoryCard251", &useMC251, false); u16 sizeMb = useMC251 ? MemCard251Mb : MemCard2043Mb; if (gciFolder) { SetupGciFolder(sizeMb); } else { SetupRawMemcard(sizeMb); } memory_card_size = memorycard->GetCardId() * SIZE_TO_Mb; u8 header[20] = { 0 }; memorycard->Read(0, static_cast<s32>(ArraySize(header)), header); SetCardFlashID(header, card_index); } void CEXIMemoryCard::SetupGciFolder(u16 sizeMb) { DiscIO::Region region = SConfig::GetInstance().m_region; const std::string& game_id = SConfig::GetInstance().GetGameID(); u32 CurrentGameId = 0; if (game_id.length() >= 4 && game_id != "00000000" && game_id != TITLEID_SYSMENU_STRING) CurrentGameId = BE32((u8*)game_id.c_str()); const bool shift_jis = region == DiscIO::Region::NTSC_J; std::string strDirectoryName = File::GetUserPath(D_GCUSER_IDX); if (Movie::IsPlayingInput() && Movie::IsConfigSaved() && Movie::IsUsingMemcard(card_index) && Movie::IsStartingFromClearSave()) strDirectoryName += "Movie" DIR_SEP; strDirectoryName = strDirectoryName + SConfig::GetDirectoryForRegion(region) + DIR_SEP + StringFromFormat("Card %c", 'A' + card_index); if (!File::Exists(strDirectoryName)) // first use of memcard folder, migrate automatically { MigrateFromMemcardFile(strDirectoryName + DIR_SEP, card_index); } else if (!File::IsDirectory(strDirectoryName)) { if (File::Rename(strDirectoryName, strDirectoryName + ".original")) { PanicAlertT("%s was not a directory, moved to *.original", strDirectoryName.c_str()); MigrateFromMemcardFile(strDirectoryName + DIR_SEP, card_index); } else // we tried but the user wants to crash { // TODO more user friendly abort PanicAlertT("%s is not a directory, failed to move to *.original.\n Verify your " "write permissions or move the file outside of Dolphin", strDirectoryName.c_str()); exit(0); } } memorycard = std::make_unique<GCMemcardDirectory>(strDirectoryName + DIR_SEP, card_index, sizeMb, shift_jis, region, CurrentGameId); } void CEXIMemoryCard::SetupRawMemcard(u16 sizeMb) { std::string filename = (card_index == 0) ? SConfig::GetInstance().m_strMemoryCardA : SConfig::GetInstance().m_strMemoryCardB; if (Movie::IsPlayingInput() && Movie::IsConfigSaved() && Movie::IsUsingMemcard(card_index) && Movie::IsStartingFromClearSave()) filename = File::GetUserPath(D_GCUSER_IDX) + StringFromFormat("Movie%s.raw", (card_index == 0) ? "A" : "B"); if (sizeMb == MemCard251Mb) { filename.insert(filename.find_last_of("."), ".251"); } memorycard = std::make_unique<MemoryCard>(filename, card_index, sizeMb); } CEXIMemoryCard::~CEXIMemoryCard() { CoreTiming::RemoveEvent(s_et_cmd_done[card_index]); CoreTiming::RemoveEvent(s_et_transfer_complete[card_index]); } bool CEXIMemoryCard::UseDelayedTransferCompletion() const { return true; } bool CEXIMemoryCard::IsPresent() const { return true; } void CEXIMemoryCard::CmdDone() { status |= MC_STATUS_READY; status &= ~MC_STATUS_BUSY; m_bInterruptSet = 1; ExpansionInterface::UpdateInterrupts(); } void CEXIMemoryCard::TransferComplete() { // Transfer complete, send interrupt ExpansionInterface::GetChannel(card_index)->SendTransferComplete(); } void CEXIMemoryCard::CmdDoneLater(u64 cycles) { CoreTiming::RemoveEvent(s_et_cmd_done[card_index]); CoreTiming::ScheduleEvent((int)cycles, s_et_cmd_done[card_index], (u64)card_index); } void CEXIMemoryCard::SetCS(int cs) { if (cs) // not-selected to selected { m_uPosition = 0; } else { switch (command) { case cmdSectorErase: if (m_uPosition > 2) { memorycard->ClearBlock(address & (memory_card_size - 1)); status |= MC_STATUS_BUSY; status &= ~MC_STATUS_READY; //??? CmdDoneLater(5000); } break; case cmdChipErase: if (m_uPosition > 2) { // TODO: Investigate on HW, I (LPFaint99) believe that this only // erases the system area (Blocks 0-4) memorycard->ClearAll(); status &= ~MC_STATUS_BUSY; } break; case cmdPageProgram: if (m_uPosition >= 5) { int count = m_uPosition - 5; int i = 0; status &= ~0x80; while (count--) { memorycard->Write(address, 1, &(programming_buffer[i++])); i &= 127; address = (address & ~0x1FF) | ((address + 1) & 0x1FF); } CmdDoneLater(5000); } break; } } } bool CEXIMemoryCard::IsInterruptSet() { if (interruptSwitch) return m_bInterruptSet; return false; } void CEXIMemoryCard::TransferByte(u8& byte) { DEBUG_LOG(EXPANSIONINTERFACE, "EXI MEMCARD: > %02x", byte); if (m_uPosition == 0) { command = byte; // first byte is command byte = 0xFF; // would be tristate, but we don't care. switch (command) // This seems silly, do we really need it? { case cmdNintendoID: case cmdReadArray: case cmdArrayToBuffer: case cmdSetInterrupt: case cmdWriteBuffer: case cmdReadStatus: case cmdReadID: case cmdReadErrorBuffer: case cmdWakeUp: case cmdSleep: case cmdClearStatus: case cmdSectorErase: case cmdPageProgram: case cmdExtraByteProgram: case cmdChipErase: DEBUG_LOG(EXPANSIONINTERFACE, "EXI MEMCARD: command %02x at position 0. seems normal.", command); break; default: WARN_LOG(EXPANSIONINTERFACE, "EXI MEMCARD: command %02x at position 0", command); break; } if (command == cmdClearStatus) { status &= ~MC_STATUS_PROGRAMEERROR; status &= ~MC_STATUS_ERASEERROR; status |= MC_STATUS_READY; m_bInterruptSet = 0; byte = 0xFF; m_uPosition = 0; } } else { switch (command) { case cmdNintendoID: // // Nintendo card: // 00 | 80 00 00 00 10 00 00 00 // "bigben" card: // 00 | ff 00 00 05 10 00 00 00 00 00 00 00 00 00 00 // we do it the Nintendo way. if (m_uPosition == 1) byte = 0x80; // dummy cycle else byte = (u8)(memorycard->GetCardId() >> (24 - (((m_uPosition - 2) & 3) * 8))); break; case cmdReadArray: switch (m_uPosition) { case 1: // AD1 address = byte << 17; byte = 0xFF; break; case 2: // AD2 address |= byte << 9; break; case 3: // AD3 address |= (byte & 3) << 7; break; case 4: // BA address |= (byte & 0x7F); break; } if (m_uPosition > 1) // not specified for 1..8, anyway { memorycard->Read(address & (memory_card_size - 1), 1, &byte); // after 9 bytes, we start incrementing the address, // but only the sector offset - the pointer wraps around if (m_uPosition >= 9) address = (address & ~0x1FF) | ((address + 1) & 0x1FF); } break; case cmdReadStatus: // (unspecified for byte 1) byte = status; break; case cmdReadID: if (m_uPosition == 1) // (unspecified) byte = (u8)(card_id >> 8); else byte = (u8)((m_uPosition & 1) ? (card_id) : (card_id >> 8)); break; case cmdSectorErase: switch (m_uPosition) { case 1: // AD1 address = byte << 17; break; case 2: // AD2 address |= byte << 9; break; } byte = 0xFF; break; case cmdSetInterrupt: if (m_uPosition == 1) { interruptSwitch = byte; } byte = 0xFF; break; case cmdChipErase: byte = 0xFF; break; case cmdPageProgram: switch (m_uPosition) { case 1: // AD1 address = byte << 17; break; case 2: // AD2 address |= byte << 9; break; case 3: // AD3 address |= (byte & 3) << 7; break; case 4: // BA address |= (byte & 0x7F); break; } if (m_uPosition >= 5) programming_buffer[((m_uPosition - 5) & 0x7F)] = byte; // wrap around after 128 bytes byte = 0xFF; break; default: WARN_LOG(EXPANSIONINTERFACE, "EXI MEMCARD: unknown command byte %02x", byte); byte = 0xFF; } } m_uPosition++; DEBUG_LOG(EXPANSIONINTERFACE, "EXI MEMCARD: < %02x", byte); } void CEXIMemoryCard::DoState(PointerWrap& p) { // for movie sync, we need to save/load memory card contents (and other data) in savestates. // otherwise, we'll assume the user wants to keep their memcards and saves separate, // unless we're loading (in which case we let the savestate contents decide, in order to stay // aligned with them). bool storeContents = (Movie::IsMovieActive()); p.Do(storeContents); if (storeContents) { p.Do(interruptSwitch); p.Do(m_bInterruptSet); p.Do(command); p.Do(status); p.Do(m_uPosition); p.Do(programming_buffer); p.Do(address); memorycard->DoState(p); p.Do(card_index); } } IEXIDevice* CEXIMemoryCard::FindDevice(TEXIDevices device_type, int customIndex) { if (device_type != m_device_type) return nullptr; if (customIndex != card_index) return nullptr; return this; } // DMA reads are preceded by all of the necessary setup via IMMRead // read all at once instead of single byte at a time as done by IEXIDevice::DMARead void CEXIMemoryCard::DMARead(u32 _uAddr, u32 _uSize) { memorycard->Read(address, _uSize, Memory::GetPointer(_uAddr)); if ((address + _uSize) % BLOCK_SIZE == 0) { INFO_LOG(EXPANSIONINTERFACE, "reading from block: %x", address / BLOCK_SIZE); } // Schedule transfer complete later based on read speed CoreTiming::ScheduleEvent(_uSize * (SystemTimers::GetTicksPerSecond() / MC_TRANSFER_RATE_READ), s_et_transfer_complete[card_index], (u64)card_index); } // DMA write are preceded by all of the necessary setup via IMMWrite // write all at once instead of single byte at a time as done by IEXIDevice::DMAWrite void CEXIMemoryCard::DMAWrite(u32 _uAddr, u32 _uSize) { memorycard->Write(address, _uSize, Memory::GetPointer(_uAddr)); if (((address + _uSize) % BLOCK_SIZE) == 0) { INFO_LOG(EXPANSIONINTERFACE, "writing to block: %x", address / BLOCK_SIZE); } // Schedule transfer complete later based on write speed CoreTiming::ScheduleEvent(_uSize * (SystemTimers::GetTicksPerSecond() / MC_TRANSFER_RATE_WRITE), s_et_transfer_complete[card_index], (u64)card_index); } } // namespace ExpansionInterface
ntapiam/Ishiiruka
Source/Core/Core/HW/EXI/EXI_DeviceMemoryCard.cpp
C++
gpl-2.0
14,510
/** This package is part of the application VIF. Copyright (C) 2012-2014, Benno Luthiger This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.hip.vif.web.exc; import org.hip.kernel.exc.ExceptionHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Handler for VIF exceptions. * * @author lbenno */ public enum VIFExceptionHandler implements ExceptionHandler { INSTANCE; private static final Logger LOG = LoggerFactory .getLogger(VIFExceptionHandler.class); @Override public Throwable convert(final Throwable inThrowable) { return postProcess(inThrowable, new VIFWebException()); } @Override public Throwable convert(final Throwable inThrowable, final String inMessage) { return postProcess(inThrowable, new VIFWebException(inMessage)); } @Override public void handle(final Object inCatchingObject, final Throwable inThrowable) { printStackTrace(inCatchingObject, inThrowable); } @Override public void handle(final Object inCatchingObject, final Throwable inThrowable, final boolean inPrintStackTrace) { if (inPrintStackTrace) { printStackTrace(inCatchingObject, inThrowable); } } private void printStackTrace(final Object inCatchingObject, final Throwable inThrowable) { LOG.error("VIF application: Error catched in {}.", inCatchingObject .getClass().getName(), inThrowable); } private void printStackTrace(final Throwable inThrowable) { LOG.error("VIF application: Error handled:", inThrowable); } @Override public void handle(final Throwable inThrowable) { printStackTrace(inThrowable); } @Override public void handle(final Throwable inThrowable, final boolean inPrintStackTrace) { if (inPrintStackTrace) { printStackTrace(inThrowable); } } @Override public void rethrow(final Throwable inThrowable) throws Throwable { LOG.error("VIF application: Error rethrow:", inThrowable); throw inThrowable; } /** @param inThrowableToBeConverted java.lang.Throwable * @param inException org.hip.kernel.exc.VException * @return java.lang.Throwable */ private Throwable postProcess(final Throwable inThrowableToBeConverted, final VIFWebException inException) { LOG.error("Root cause:", inThrowableToBeConverted); inException.setRootCause(inThrowableToBeConverted); inException.fillInStackTrace(); return inException; } }
aktion-hip/vif
org.hip.vif.web/src/org/hip/vif/web/exc/VIFExceptionHandler.java
Java
gpl-2.0
3,265
/* *** MolShake Module - Core *** src/modules/molshake/core.cpp Copyright T. Youngs 2012-2018 This file is part of Dissolve. Dissolve is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Dissolve is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Dissolve. If not, see <http://www.gnu.org/licenses/>. */ #include "modules/molshake/molshake.h" // Static Members List<Module> MolShakeModule::instances_; /* * Constructor / Destructor */ // Constructor MolShakeModule::MolShakeModule() : Module() { // Add to instances list and set unique name for this instance uniqueName_.sprintf("%s%02i", type(), instances_.nItems()); instances_.own(this); // Set up variables / control parameters setUpKeywords(); // Set representative colour colour_[0] = 200; colour_[1] = 0; colour_[2] = 0; } // Destructor MolShakeModule::~MolShakeModule() { } /* * Instances */ // Create instance of this module List<Module>& MolShakeModule::instances() { return instances_; } // Create instance of this module Module* MolShakeModule::createInstance() { return new MolShakeModule; }
trisyoungs/duq
src/modules/molshake/core.cpp
C++
gpl-2.0
1,520
<?php #----------------------------------------------------------------- # grid related values #----------------------------------------------------------------- global $gridvalues; $gridvalues = array('220' => 'one_fourth', '300' => 'one_third', '460' => 'one_half', '620' => 'two_thirds', '700' => 'three_fourths', '940' => 'full-width', '960' => 'full-width'); #----------------------------------------------------------------- # dynamic grid builder #----------------------------------------------------------------- if( !function_exists( 'build_grid_opener' ) ) { function build_grid_opener($gridsize, $last, $boxtitle='lnotitle', $overflow=false, $entrycontent=false, $singlebox, $sidebar=false) { global $gridvalues; $activate_desktop = (isset($singlebox['activate_desktop']) && $singlebox['activate_desktop'] == 'on') ? ' lambda-hide-desktop ' : ''; $activate_landscape = (isset($singlebox['activate_landscape']) && $singlebox['activate_landscape'] == 'on') ? ' lambda-hide-tablet ' : ''; $activate_mobile = (isset($singlebox['activate_mobile']) && $singlebox['activate_mobile'] == 'on') ? ' lambda-hide-mobile ' : ''; $removebottom = ($sidebar) ? ' remove-bottom ' : ''; if($overflow) $overflow = 'style="overflow:hidden;"'; $entrycontent = ($entrycontent) ? ' entry-content' : ''; $last = ($last == "960") ? ' last' : ''; $gridopener = '<div class="'.$gridvalues[$gridsize].$last.$entrycontent.$activate_desktop.$activate_landscape.$activate_mobile.$removebottom.' clearfix" '.$overflow.'>'; if($boxtitle) { $gridopener .= '<div class="title-wrap clearfix"><h3 class="home-title"><span>'.lambda_translate_meta($boxtitle).'</span></h3></div>'; } echo $gridopener; } } #----------------------------------------------------------------- # dynamic article builder #----------------------------------------------------------------- if( !function_exists( 'build_article_opener' ) ) { function build_article_opener($gridsize, $last, $boxtitle='lnotitle', $overflow=false, $entrycontent=false) { global $gridvalues; $activate_desktop = (isset($singlebox['activate_desktop']) && $singlebox['activate_desktop'] == 'on') ? ' lambda-hide-desktop ' : ''; $activate_landscape = (isset($singlebox['activate_landscape']) && $singlebox['activate_landscape'] == 'on') ? ' lambda-hide-tablet ' : ''; $activate_mobile = (isset($singlebox['activate_mobile']) && $singlebox['activate_mobile'] == 'on') ? ' lambda-hide-mobile ' : ''; if($overflow) $overflow = 'style="overflow:hidden;'; $entrycontent = ($entrycontent) ? ' entry-content' : ''; $last = ($last == "960") ? ' last' : ''; $gridopener = '<section class="'.$gridvalues[$gridsize].$last.$entrycontent.$activate_desktop.$activate_landscape.$activate_mobile.' service clearfix" '.$overflow.'>'; if($boxtitle) { $gridopener .= '<div class="title-wrap clearfix"><h3 class="home-title"><span>'.lambda_translate_meta($boxtitle).'</span></h3></div>'; } echo $gridopener; } } #----------------------------------------------------------------- # simple text box with shortcodes #----------------------------------------------------------------- if( !function_exists( 'render_simple_textbox' ) ) { function render_simple_textbox($content) { $final_simple_textbox = do_shortcode(apply_filters( 'the_content' , $content) ); echo $final_simple_textbox; } } #----------------------------------------------------------------- # simple quote box #----------------------------------------------------------------- if( !function_exists( 'render_simple_quote' ) ) { function render_simple_quote($quote, $quote_cite) { $final_simple_quote = '<div class="quote"><div class="quote-border">'; $final_simple_quote.= '<h2 class="quote-title">'.do_shortcode(lambda_translate_meta($quote)).'</h2>'; $final_simple_quote.= '<cite>&#8722;'.do_shortcode($quote_cite).'</cite>'; echo $final_simple_quote.'</div></div>'; } } #----------------------------------------------------------------- # revolution slider #----------------------------------------------------------------- if( !function_exists( 'render_rev_slider' ) ) { function render_rev_slider($sliderid) { $revslider = '<div class="lambda-pc">'.do_shortcode('[rev_slider '.$sliderid.']').'</div>'; echo $revslider; } } #----------------------------------------------------------------- # Call to Action #----------------------------------------------------------------- if( !function_exists( 'render_cta_box' ) ) { function render_cta_box($cta_headline = '', $cta_content = '', $cta_link = '', $cta_button_text = '') { echo do_shortcode('[cta headline="'.lambda_translate_meta($cta_headline).'" buttonlink="'.$cta_link.'" buttontext="'.$cta_button_text.'"] '.lambda_translate_meta($cta_content).' [/cta]'); } } #----------------------------------------------------------------- # standard slider #----------------------------------------------------------------- if( !function_exists( 'render_standard_slider' ) ) { function render_standard_slider($sliderid) { $standardslider = '<div class="lambda-pc">'.do_shortcode('[lambdaslider id="'.$sliderid.'"]').'</div>'; echo $standardslider; } } #----------------------------------------------------------------- # soundcloud #----------------------------------------------------------------- if( !function_exists( 'render_soundcloud' ) ) { function render_soundcloud($soundcloud) { $soundcloud = '<div class="post_player">'.do_shortcode('[soundcloud url='.$soundcloud['soundcloud_url'].'/]').'</div>'; echo $soundcloud; } } #----------------------------------------------------------------- # horizontal row #----------------------------------------------------------------- if( !function_exists( 'render_row' ) ) { function render_row($hrdata) { $row = '<hr style="margin-top:0px !important;" />'; echo $row; } } #----------------------------------------------------------------- # pricing table #----------------------------------------------------------------- if( !function_exists( 'render_pricing_table' ) ) { function render_pricing_table($tableid) { $table = do_shortcode('[lambdatable id="'.$tableid.'"]'); echo $table; } } #----------------------------------------------------------------- # Portfolio #----------------------------------------------------------------- if( !function_exists( 'lambda_portfolio_columns' ) ) { function lambda_portfolio_columns($portfolio, $count, $pagebuilder = false, $containerID = 'none', $lastborder=false) { global $theme_options, $lambda_meta_data; //class change for home and pagebuilder $portfoliowidth = ($pagebuilder) ? 'fullwidth' : 'sixteen columns alpha omega'; $removebottom = ($pagebuilder) ? 'remove-bottom' : ''; $container = ($containerID != 'none') ? 'id="'.$containerID.'"' : ''; if((isset($portfolio['activate_portfolio']) && $portfolio['activate_portfolio'] == 'on') || $pagebuilder = true) { ?> <script type="text/javascript"> (function($){ $(document).ready(function(){ $(".portfolio-excerpt-<?php echo $count; ?> > li > .thumb").stop().hover(function(){ $(this).find('.hover-overlay').fadeIn(550); }, function () { $(this).find('.hover-overlay').stop().fadeOut(50); }); }); })(jQuery); </script> <section class="list_portfolio clearfix<?php echo ($count == 1) ? ' padding-top' : ''; echo ($lastborder) ? ' last-border' : ''; ?>"> <?php if(isset($portfolio['portfolio_headline']) && !empty($portfolio['portfolio_headline'])) :?> <div class="title-wrap clearfix"> <h3 class="home-title"><span><?php echo lambda_translate_meta($portfolio['portfolio_headline']); ?></span></h3> <?php if( isset($portfolio['portfolio_link']) && !empty($portfolio['portfolio_link'])) : ?> <span class="home-title-link"><a href="<?php echo $portfolio['portfolio_link'];?>"><?php echo $portfolio['portfolio_link_text']; ?></a></span> <?php endif; ?> </div> <?php endif; ?> <ul <?php echo $container; ?> class="clearfix portfolio-excerpt-<?php echo $count; ?> <?php echo $removebottom; ?>"> <?php #----------------------------------------------------------------- # custom project types for portfolio query #----------------------------------------------------------------- $project_types = ''; $preview = ''; $unkown = ''; if(isset($portfolio['project_type'])) { if(is_array($portfolio['project_type'])) { $project_types = "&project-type="; foreach($portfolio['project_type'] as $type) { $project_types .= $type.','; } $project_types = substr($project_types, 0, -1); } } $posts_per_page = (isset($portfolio['portfolio_count'])) ? $portfolio['portfolio_count'] : '12'; $portfoliogrid = ( isset($portfolio['portfolio_grid']) ) ? $portfolio['portfolio_grid'] : 'one_fourth'; $gridcount = array('full-width' => '1', 'one_third' => '3', 'portfolio-item four columns' => '4', 'portfolio-item fivep columns' => '3', 'portfolio-item eight columns' => '2', 'one_half' => '2', 'one_fourth' => '4', 'four columns' => '4'); $portfoliogrid = (!$pagebuilder && $gridcount[$portfoliogrid] == 4) ? 'four columns' : $portfoliogrid; $counter = 1; //start query query_posts('post_type='.UT_PORTFOLIO_SLUG.'&posts_per_page='.$posts_per_page.'&project_types='.$project_types); if (have_posts()) : while (have_posts()) : the_post(); $lambda_meta_data->the_meta(); #----------------------------------------------------------------- # get all project-types for this item #----------------------------------------------------------------- $projecttypeclean = NULL; $project_cats = wp_get_object_terms( get_the_ID(), 'project-type' ); if(is_array($project_cats)) { $i = '0'; foreach( $project_cats as $types ){ if($types->parent > 0) $projecttypeclean.= $types->name.', '; $i++; } } //cut last whitespace and comma $projecttypeclean = substr($projecttypeclean,0,-2); //fallback for selfhosted videos $unkown = $preview; //we need to keep the variable value $title= str_ireplace('"', '', trim(get_the_title())); $url = wp_get_attachment_url( get_post_thumbnail_id(get_the_ID())); $image = $url; ?> <li style="margin-left:0px !important;" class="<?php echo $portfoliogrid; ?> <?php echo ($counter % $gridcount[$portfoliogrid] == 0) ? 'last' : ''; ?> clearfix"> <div class="thumb <?php echo $removebottom; ?>"> <div class="overflow-hidden"> <?php the_post_thumbnail($gridcount[$portfoliogrid].'col-image', array('class' => 'hovereffect wp-post-image') ); ?> <a href="<?php echo get_permalink(); ?>"> <div class="hover-overlay"> <?php if(isset($portfolio['portfolio_item_title']) && $portfolio['portfolio_item_title'] != 'on') { ?> <h1 class="portfolio-title"><?php echo lambda_translate_meta($title); ?></h1> <?php } else { ?> <span class="circle-hover"><img src="<?php echo get_template_directory_uri(); ?>/images/circle-hover.png" alt="<?php _e('link icon', UT_THEME_INITIAL); ?>" /></span> <?php } ?> </div> </a> </div> <?php #----------------------------------------------------------------- # display title or not #----------------------------------------------------------------- if(isset($portfolio['portfolio_item_title']) && $portfolio['portfolio_item_title'] == 'on') { ?> <div class="portfolio-title-below-wrap"> <a href="<?php the_permalink(); ?>"> <h1 class="portfolio-title-below"> <?php echo lambda_translate_meta($title); ?> <span><?php echo lambda_translate_meta($projecttypeclean); ?></span> </h1> </a> </div> <?php } //endif ?> </div> </li> <?php $counter++; endwhile; endif; ?> <?php wp_reset_query(); ?> </ul> </section> <div class="clear"></div> <?php } // end portfolio } } #----------------------------------------------------------------- # Testimonial #----------------------------------------------------------------- if( !function_exists( 'render_testimonial' ) ) { function render_testimonial($metadata, $async = 2) { ?> <?php global $theme_path; if(isset($metadata['author_image'])) { $authorimage = aq_resize( $metadata['author_image'], 50, 50, true ); } ?> <?php if(empty($metadata['author_image'])) { $authorimage = $theme_path.'/images/default-avatar.jpg'; } ?> <article class="testimonial-entry <?php echo ($async % 2 == 0) ? 'dark' : 'white'; ?>"> <?php echo do_shortcode(lambda_translate_meta($metadata['author_comment'])); ?> </article> <figure class="testimonial-photo"> <img class="testimonial-img" src="<?php echo $authorimage; ?>"> </figure> <p class="testimonial-name"><?php echo (isset($metadata['author_name'])) ? $metadata['author_name'] : ''; ?><?php echo (isset($metadata['author_company'])) ? ', <span>'.$metadata['author_company'].'</span>' : '';?></p> <?php } } #----------------------------------------------------------------- # Service Boxes #----------------------------------------------------------------- if( !function_exists( 'render_service_box' ) ) { function render_service_box($metadata, $servicegrid='one_fourth', $last='', $home = false, $colnumber=1) { if($home) { $metadata['col_box_icon'] = isset($metadata['col_'.$colnumber.'_icon']) ? $metadata['col_'.$colnumber.'_icon'] : ''; $metadata['col_box_alt'] = isset($metadata['col_'.$colnumber.'_icon_alt']) ? $metadata['col_'.$colnumber.'_icon_alt'] : ''; $metadata['col_box_headline'] = isset($metadata['col_'.$colnumber.'_headline']) ? $metadata['col_'.$colnumber.'_headline'] : ''; $metadata['col_box_content'] = isset($metadata['col_'.$colnumber.'_content']) ? $metadata['col_'.$colnumber.'_content'] : ''; $metadata['col_box_buttontext'] = isset($metadata['col_'.$colnumber.'_buttontext']) ? $metadata['col_'.$colnumber.'_buttontext'] : ''; $metadata['col_box_link'] = isset($metadata['col_'.$colnumber.'_link']) ? $metadata['col_'.$colnumber.'_link'] : ''; $metadata['col_box_bgcolor'] = isset($metadata['col_'.$colnumber.'_bgcolor']) ? $metadata['col_'.$colnumber.'_bgcolor'] : '#222'; $metadata['col_box_textcolor'] = isset($metadata['col_'.$colnumber.'_textcolor']) ? $metadata['col_'.$colnumber.'_textcolor'] : '#FFF'; $metadata['col_box_texthovercolor'] = isset($metadata['col_'.$colnumber.'_texthovercolor']) ? $metadata['col_'.$colnumber.'_texthovercolor'] : '#FFF'; $metadata['col_box_hovercolor'] = isset($metadata['col_'.$colnumber.'_hovercolor']) ? $metadata['col_'.$colnumber.'_hovercolor'] : get_option_tree('color_scheme'); } ?> <?php if($home) { ?> <section class="<?php echo $servicegrid.$last; ?> service"> <?php } ?> <a style="color:<?php echo $metadata['col_box_textcolor']; ?>" data-textcolor="<?php echo $metadata['col_box_textcolor']; ?>" data-texthovercolor="<?php echo $metadata['col_box_texthovercolor']; ?>" href="<?php echo lambda_translate_meta($metadata['col_box_link']); ?>" target="_self"> <article class="service-box" style="background:<?php echo $metadata['col_box_bgcolor']; ?>;" data-bgcolor="<?php echo $metadata['col_box_bgcolor']; ?>" data-hovercolor="<?php echo $metadata['col_box_hovercolor']; ?>"> <h3 style="color:<?php echo $metadata['col_box_textcolor']; ?>"> <?php echo (isset($metadata['col_box_headline'])) ? lambda_translate_meta($metadata['col_box_headline']) : ''; ?> </h3> <?php if(isset($metadata['col_box_icon']) && !empty($metadata['col_box_icon'])) : $parsed_url = parse_url($metadata['col_box_icon']); $path = $parsed_url['path']; $filename = basename($path); ?> <figure class="service-box-icon"> <img src="<?php echo $metadata['col_box_icon']; ?>" alt="<?php echo (!empty($metadata['col_box_alt']) ) ? $metadata['col_box_alt'] : $filename; ?>" /> </figure> <?php endif; ?> <?php if(isset($metadata['col_box_content'])) : ?> <p><?php echo do_shortcode(lambda_translate_meta($metadata['col_box_content'])); ?></p> <?php endif; ?> </article> </a> <?php if($home) { ?> </section> <?php } ?> <?php } } #----------------------------------------------------------------- # Service Column #----------------------------------------------------------------- if( !function_exists( 'render_service_column' ) ) { function render_service_column($metadata, $servicegrid='one_fourth', $last='', $home = false, $colnumber=1) { if($home) { $metadata['col_icon'] = ( isset($metadata['cols_'.$colnumber.'_icon']) ) ? $metadata['cols_'.$colnumber.'_icon'] : ''; $metadata['col_alt'] = ( isset($metadata['cols_'.$colnumber.'_icon_alt']) ) ? $metadata['cols_'.$colnumber.'_icon_alt'] : ''; $metadata['col_headline'] = ( isset($metadata['cols_'.$colnumber.'_headline']) ) ? $metadata['cols_'.$colnumber.'_headline'] : ''; $metadata['col_content'] = ( isset($metadata['cols_'.$colnumber.'_content']) ) ? $metadata['cols_'.$colnumber.'_content'] : ''; $metadata['col_buttontext'] = ( isset($metadata['cols_'.$colnumber.'_buttontext']) ) ? $metadata['cols_'.$colnumber.'_buttontext'] : ''; $metadata['col_link'] = ( isset($metadata['cols_'.$colnumber.'_link']) ) ? $metadata['cols_'.$colnumber.'_link'] : ''; } ?> <?php if($home) { ?> <section class="<?php echo $servicegrid.$last; ?> service clearfix"> <?php } ?> <?php if(isset($metadata['col_icon']) && !empty($metadata['col_icon'])) : ?> <figure class="service-icon"> <img src="<?php echo $metadata['col_icon']; ?>" alt="<?php echo (isset($metadata['col_alt'])) ? $metadata['col_alt'] : ''; ?>" /> </figure> <?php endif; ?> <article class="service"> <h3> <?php echo (isset($metadata['col_headline'])) ? lambda_translate_meta($metadata['col_headline']) : ''; ?> </h3> <?php if(isset($metadata['col_content'])) : ?> <p><?php echo do_shortcode(lambda_translate_meta($metadata['col_content'])); ?></p> <?php endif; ?> <?php if(isset($metadata['col_buttontext']) && !empty($metadata['col_buttontext'])) { ?> <a href="<?php echo lambda_translate_meta($metadata['col_link']); ?>" class="excerpt" target="_self"><?php echo lambda_translate_meta($metadata['col_buttontext']); ?></a> <?php } ?> </article> <?php if($home) { ?> </section> <?php } ?> <?php } } #----------------------------------------------------------------- # Testimonial Carousel #----------------------------------------------------------------- if( !function_exists( 'render_testimonial_carousel' ) ) { function render_testimonial_carousel($metadata, $testimonials='', $ID=1, $type) { global $lambda_meta_data, $theme_path; if($type == 'page') { //get page meta data $pagemetadata = get_post_meta($metadata['testimonialcarousel'], $lambda_meta_data->get_the_id(), TRUE); $testimonials = $pagemetadata[UT_THEME_INITIAL.'testimonial_items']; } if(isset($metadata['testimonial_headline'])) : ?> <div class="title-wrap clearfix"> <h3 class="home-title"><span><?php echo lambda_translate_meta($metadata['testimonial_headline']); ?></span></h3> <?php if($type == 'home') { ?> <div class="carousel-navi clearfix"> <a class="tnext gon_<?php echo $ID; ?>" href="#">next</a> <a class="tprev pon_<?php echo $ID; ?>" href="#">prev</a> </div> <?php } ?> </div> <?php endif; ?> <?php if(isset($metadata['box_type'])) : ?> <div class="title-wrap clearfix"> <h3 class="home-title"><span><?php echo (isset($metadata['box_title']) && !empty($metadata['box_title'])) ? $metadata['box_title'] : ''; ?></span></h3> <div class="carousel-navi clearfix"> <a class="tnext gon_<?php echo $ID; ?>" href="#">next</a> <a class="tprev pon_<?php echo $ID; ?>" href="#">prev</a> </div> </div> <?php endif; ?> <?php if(is_array($testimonials)) { ?> <script type="text/javascript"> (function($){ $(document).ready(function(){ var testimonials = $(".single-testimonial_<?php echo $ID; ?>").find('ul').children().length; $(".single-testimonial_<?php echo $ID; ?>").jCarouselLite({ btnNext: ".gon_<?php echo $ID; ?>", btnPrev: ".pon_<?php echo $ID; ?>", <?php if( isset($metadata['testimonials_autoplay']) && $metadata['testimonials_autoplay'] == 'on') echo (isset($metadata['testimonial_time'])) ? 'auto:'.$metadata['testimonial_time'].',' : 'auto:1000,'; ?> visible: testimonials }); }); })(jQuery); </script> <?php } ?> <div class="single-testimonial_<?php echo $ID; ?>"> <ul class="clearfix"> <?php if(is_array($testimonials)) { $z = 1; foreach($testimonials as $testimonial) { ?> <li style="margin-bottom:0px !important; margin-left:0px !important; padding:0 1px;"> <?php if(isset($testimonial['author_image'])) { $authorimage = aq_resize( $testimonial['author_image'], 50, 50, true ); } ?> <?php if(empty($testimonial['author_image'])) { $authorimage = $theme_path.'/images/default-avatar.jpg'; } ?> <article class="testimonial-entry"> <?php echo do_shortcode(lambda_translate_meta($testimonial['author_comment'])); ?> </article> <figure class="testimonial-photo"> <img alt="<?php _e('customer photo', UT_THEME_INITIAL); ?>" class="testimonial-img" src="<?php echo $authorimage; ?>"> </figure> <p class="testimonial-name"><?php echo $testimonial['author_name']; ?><?php echo ($testimonial['author_company']) ? ', <span>'.$testimonial['author_company'].'</span>' : '';?></p> </li> <?php $z++; } } ?> </ul> </div> <?php } } #----------------------------------------------------------------- # Blog #----------------------------------------------------------------- if( !function_exists( 'render_lambda_blog' ) ) { function render_lambda_blog($metadata, $homeblog = false) { global $lambda_meta_data, $post, $theme_options; $numberpost = (isset($metadata['blog_length'])) ? $metadata['blog_length'] : 3; $blogcats = (isset($metadata['only_category']) && is_array($metadata['only_category'])) ? implode(",",$metadata['only_category']) : ''; $post_not_in = (isset($metadata['post_not_in']) && is_array($metadata['post_not_in'])) ? $metadata['post_not_in'] : ''; $z = 1; $args = array( 'posts_per_page' => $numberpost, 'post__not_in' => $post_not_in, 'cat' => $blogcats, 'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 ) ); query_posts( $args ); if (have_posts()) : while (have_posts()) : the_post(); $lambda_meta_data->the_meta(); global $more; $more = ($metadata['activate_blog_excerpt'] == 'on') ? 1 : 0; $bloggrid = ( isset($metadata['blog_grid']) ) ? $metadata['blog_grid'] : 'one_third'; $gridcount = array('full-width' => '1', 'one_third' => '3', 'one_half' => '2', 'one_fourth' => '4'); $removebottom = ($homeblog) ? 'remove-bottom' : ''; ?> <section class="post <?php echo $removebottom; ?> <?php echo $bloggrid; ?> <?php if($z%$gridcount[$bloggrid]==0) { echo 'last'; } ?>" id="post-<?php the_ID(); ?>"> <article class="entry-post clearfix"> <?php $pformat = get_post_format(); $postformat = (!empty( $pformat )) ? $pformat : 'standard'; ?> <?php $post_format = get_post_format(); $post_format = ( isset($postformat['portfolio_type']) && $postformat['portfolio_type'] == 'image_portfolio') ? 'gallery' : $post_format; if($metadata['activate_blog_images'] == 'on' || $postformat == 'link' || $postformat == 'quote') get_template_part( 'post-formats/' . $post_format ); ?> <?php if(has_post_thumbnail(get_the_ID()) && $metadata['activate_blog_images'] == 'on' && $post_format != 'video' && $post_format != 'gallery') : $imgID = get_post_thumbnail_id($post->ID); $url = wp_get_attachment_url( $imgID ); $alt = get_post_meta($imgID , '_wp_attachment_image_alt', true); echo '<div class="thumb"><div class="post-image"><div class="overflow-hidden imagepost">'; echo '<img class="wp-post-image" alt="'.trim( strip_tags($alt) ).'" src="'.$url.'" />'; echo '<a title="'.get_the_title().'" href="'.get_permalink().'"><div class="hover-overlay"><span class="circle-hover"><img src="'.get_template_directory_uri().'/images/circle-hover.png" alt="'.__('link icon', UT_THEME_INITIAL).'" /></span></div></a>'; echo '</div></div></div>'; endif; ?> <?php if($postformat != 'link') : ?> <header class="entry-header clearfix"> <?php if($postformat != 'quote') : ?> <h1 class="entry-title <?php echo $postformat; ?>-post-title"> <a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', UT_THEME_NAME ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a> </h1> <?php endif; ?> <div class="entry-meta clearfix"> <div class="post-ut"> <?php echo lambda_posted_on(); ?> </div> <!-- post date --> <div class="post-ut"> <span class="comments-link"><?php comments_popup_link( __( '0 Comments', UT_THEME_NAME ), __( '1 Comment', UT_THEME_NAME ), __( '% Comments', UT_THEME_NAME ) ); ?></span> </div><!-- post comments --> </div><!-- .entry-meta --> </header> <?php endif; ?> <div class="entry-summary"> <?php if($numberpost != 0 && $pformat != 'link') { if ($metadata['activate_blog_excerpt'] == 'on') : $excerptlength = (isset($metadata['blog_excerpt_length'])) ? $metadata['blog_excerpt_length'] : $theme_options['excerpt_blog_length']; echo excerpt_by_id($post->ID, $excerptlength, '', lambda_continue_reading_link(), $homeblog); else : the_content( __( 'Read more', UT_THEME_NAME ) ); endif; } ?> </div> </article> </section> <?php if(($z%$gridcount[$bloggrid]==0) && $bloggrid != 'full-width') { ?> <div class="clear"></div> <?php } ?> <?php $z++; endwhile; endif; ?> <?php if( !$homeblog ) : ?> <div id="nav-below" class="navigation clearfix"> <div class="nav-previous"><?php next_posts_link( __( '<span class="meta-nav">&#8656;</span> Older posts', UT_THEME_NAME ) ); ?></div> <div class="nav-next"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">&#8658;</span>', UT_THEME_NAME ) ); ?></div> </div><!-- #nav-below --> <?php endif; ?> <?php wp_reset_query(); ?> <?php } } #----------------------------------------------------------------- # google map #----------------------------------------------------------------- if( !function_exists( 'render_googlemap' ) ) { function render_googlemap($mapdata) { $map = do_shortcode('[googlemap address="'.$mapdata['map_address'].'" zoom="'.$mapdata['map_zoom'].'" height="'.$mapdata['map_height'].'"]'); echo $map; } } #----------------------------------------------------------------- # sidebar #----------------------------------------------------------------- if( !function_exists( 'render_simple_sidebar' ) ) { function render_simple_sidebar($content) { do_action('st_before_sidebar', 'widget-sidebar'); echo '<ul>'; dynamic_sidebar($content['sidebar']); echo '</ul>'; do_action('st_after_sidebar'); } } #----------------------------------------------------------------- # Client Box #----------------------------------------------------------------- if( !function_exists( 'render_clientbox' ) ) { function render_clientbox($clientdata) { global $lambda_meta_data, $theme_path; $pagemetadata = get_post_meta($clientdata['home_client_page'], $lambda_meta_data->get_the_id(), TRUE); $clients = $pagemetadata[UT_THEME_INITIAL.'client_images']; $grid = "one_fourth"; $columnset = 4; $z = 0; $loadmax = (isset($clientdata['client_load_last'])) ? $clientdata['client_load_last'] : $columnset; echo '<ul class="clientspc clearfix">'; if(is_array($clients)) { shuffle($clients); foreach($clients as $client) { if($z+1 <= $loadmax) { $itemposition = ''; //reset position //fallback $url = (isset($client['url'])) ? $client['url'] : '#'; $title = (isset($client['title'])) ? $client['title'] : ''; $src = (isset($client['imgurl'])) ? $client['imgurl'] : ''; $name = (isset($client['name'])) ? $client['name'] : ''; if($columnset == 4) { (($z%4)==3) ? $itemposition = ' last' : $itemposition = ''; } if($columnset == 5) { (($z%5)==4) ? $itemposition = ' last' : $itemposition = ''; } if($columnset == 6) { (($z%6)==5) ? $itemposition = ' last' : $itemposition = ''; } //Output client echo '<li class="overflow-hidden imagepost '.$grid.$itemposition.'"><div class="client-holder">'; echo '<a href="'.$url.'"> <span class="client-img"><img alt="'.$title.'" src="'.$src.'" /></span> <div class="hover-overlay"> <span class="client-title"><strong>'.$name.'</strong></span> </div> </a>'; echo '</div>'; echo '</li>'; } $z++; } } echo '</ul>'; } } ?>
NapsterAhmed/Vedo
wp-content/themes/nebraska/functions/pagecreator-functions.php
PHP
gpl-2.0
33,742
/* * Copyright (C) 2002-2010 The DOSBox Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* $Id: dos_files.cpp,v 1.113 2009-08-31 18:03:08 qbix79 Exp $ */ #include <string.h> #include <stdlib.h> #include <time.h> #include <ctype.h> #include "dosbox.h" #include "bios.h" #include "mem.h" #include "regs.h" #include "dos_inc.h" #include "drives.h" #include "cross.h" #define DOS_FILESTART 4 #define FCB_SUCCESS 0 #define FCB_READ_NODATA 1 #define FCB_READ_PARTIAL 3 #define FCB_ERR_NODATA 1 #define FCB_ERR_EOF 3 #define FCB_ERR_WRITE 1 DOS_File * Files[DOS_FILES]; DOS_Drive * Drives[DOS_DRIVES]; Bit8u DOS_GetDefaultDrive(void) { // return DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).GetDrive(); Bit8u d = DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).GetDrive(); if( d != dos.current_drive ) LOG(LOG_DOSMISC,LOG_ERROR)("SDA drive %d not the same as dos.current_drive %d",d,dos.current_drive); return dos.current_drive; } void DOS_SetDefaultDrive(Bit8u drive) { // if (drive<=DOS_DRIVES && ((drive<2) || Drives[drive])) DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).SetDrive(drive); if (drive<DOS_DRIVES && ((drive<2) || Drives[drive])) {dos.current_drive = drive; DOS_SDA(DOS_SDA_SEG,DOS_SDA_OFS).SetDrive(drive);} } bool DOS_MakeName(char const * const name,char * const fullname,Bit8u * drive) { if(!name || *name == 0 || *name == ' ') { /* Both \0 and space are seperators and * empty filenames report file not found */ DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } const char * name_int = name; char tempdir[DOS_PATHLENGTH]; char upname[DOS_PATHLENGTH]; Bitu r,w; *drive = DOS_GetDefaultDrive(); /* First get the drive */ if (name_int[1]==':') { *drive=(name_int[0] | 0x20)-'a'; name_int+=2; } if (*drive>=DOS_DRIVES || !Drives[*drive]) { DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } r=0;w=0; while (name_int[r]!=0 && (r<DOS_PATHLENGTH)) { Bit8u c=name_int[r++]; if ((c>='a') && (c<='z')) {upname[w++]=c-32;continue;} if ((c>='A') && (c<='Z')) {upname[w++]=c;continue;} if ((c>='0') && (c<='9')) {upname[w++]=c;continue;} switch (c) { case '/': upname[w++]='\\'; break; case ' ': /* should be seperator */ break; case '\\': case '$': case '#': case '@': case '(': case ')': case '!': case '%': case '{': case '}': case '`': case '~': case '_': case '-': case '.': case '*': case '?': case '&': case '\'': case '+': case '^': case 246: case 255: case 0xa0: case 0xe5: case 0xbd: upname[w++]=c; break; default: LOG(LOG_FILES,LOG_NORMAL)("Makename encountered an illegal char %c hex:%X in %s!",c,c,name); DOS_SetError(DOSERR_PATH_NOT_FOUND);return false; break; } } if (r>=DOS_PATHLENGTH) { DOS_SetError(DOSERR_PATH_NOT_FOUND);return false; } upname[w]=0; /* Now parse the new file name to make the final filename */ if (upname[0]!='\\') strcpy(fullname,Drives[*drive]->curdir); else fullname[0]=0; Bit32u lastdir=0;Bit32u t=0; while (fullname[t]!=0) { if ((fullname[t]=='\\') && (fullname[t+1]!=0)) lastdir=t; t++; }; r=0;w=0; tempdir[0]=0; bool stop=false; while (!stop) { if (upname[r]==0) stop=true; if ((upname[r]=='\\') || (upname[r]==0)){ tempdir[w]=0; if (tempdir[0]==0) { w=0;r++;continue;} if (strcmp(tempdir,".")==0) { tempdir[0]=0; w=0;r++; continue; } Bit32s iDown; bool dots = true; Bit32s templen=(Bit32s)strlen(tempdir); for(iDown=0;(iDown < templen) && dots;iDown++) if(tempdir[iDown] != '.') dots = false; // only dots? if (dots && (templen > 1)) { Bit32s cDots = templen - 1; for(iDown=(Bit32s)strlen(fullname)-1;iDown>=0;iDown--) { if(fullname[iDown]=='\\' || iDown==0) { lastdir = iDown; cDots--; if(cDots==0) break; } } fullname[lastdir]=0; t=0;lastdir=0; while (fullname[t]!=0) { if ((fullname[t]=='\\') && (fullname[t+1]!=0)) lastdir=t; t++; } tempdir[0]=0; w=0;r++; continue; } lastdir=(Bit32u)strlen(fullname); if (lastdir!=0) strcat(fullname,"\\"); char * ext=strchr(tempdir,'.'); if (ext) { if(strchr(ext+1,'.')) { //another dot in the extension =>file not found //Or path not found depending on wether //we are still in dir check stage or file stage if(stop) DOS_SetError(DOSERR_FILE_NOT_FOUND); else DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } ext[4] = 0; if((strlen(tempdir) - strlen(ext)) > 8) memmove(tempdir + 8, ext, 5); } else tempdir[8]=0; if (strlen(fullname)+strlen(tempdir)>=DOS_PATHLENGTH) { DOS_SetError(DOSERR_PATH_NOT_FOUND);return false; } strcat(fullname,tempdir); tempdir[0]=0; w=0;r++; continue; } tempdir[w++]=upname[r++]; } return true; } bool DOS_GetCurrentDir(Bit8u drive,char * const buffer) { if (drive==0) drive=DOS_GetDefaultDrive(); else drive--; if ((drive>=DOS_DRIVES) || (!Drives[drive])) { DOS_SetError(DOSERR_INVALID_DRIVE); return false; } strcpy(buffer,Drives[drive]->curdir); return true; } bool DOS_ChangeDir(char const * const dir) { Bit8u drive;char fulldir[DOS_PATHLENGTH]; if (!DOS_MakeName(dir,fulldir,&drive)) return false; if (Drives[drive]->TestDir(fulldir)) { strcpy(Drives[drive]->curdir,fulldir); return true; } else { DOS_SetError(DOSERR_PATH_NOT_FOUND); } return false; } bool DOS_MakeDir(char const * const dir) { Bit8u drive;char fulldir[DOS_PATHLENGTH]; size_t len = strlen(dir); if(!len || dir[len-1] == '\\') { DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } if (!DOS_MakeName(dir,fulldir,&drive)) return false; if(Drives[drive]->MakeDir(fulldir)) return true; /* Determine reason for failing */ if(Drives[drive]->TestDir(fulldir)) DOS_SetError(DOSERR_ACCESS_DENIED); else DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } bool DOS_RemoveDir(char const * const dir) { /* We need to do the test before the removal as can not rely on * the host to forbid removal of the current directory. * We never change directory. Everything happens in the drives. */ Bit8u drive;char fulldir[DOS_PATHLENGTH]; if (!DOS_MakeName(dir,fulldir,&drive)) return false; /* Check if exists */ if(!Drives[drive]->TestDir(fulldir)) { DOS_SetError(DOSERR_PATH_NOT_FOUND); return false; } /* See if it's current directory */ char currdir[DOS_PATHLENGTH]= { 0 }; DOS_GetCurrentDir(drive + 1 ,currdir); if(strcmp(currdir,fulldir) == 0) { DOS_SetError(DOSERR_REMOVE_CURRENT_DIRECTORY); return false; } if(Drives[drive]->RemoveDir(fulldir)) return true; /* Failed. We know it exists and it's not the current dir */ /* Assume non empty */ DOS_SetError(DOSERR_ACCESS_DENIED); return false; } bool DOS_Rename(char const * const oldname,char const * const newname) { Bit8u driveold;char fullold[DOS_PATHLENGTH]; Bit8u drivenew;char fullnew[DOS_PATHLENGTH]; if (!DOS_MakeName(oldname,fullold,&driveold)) return false; if (!DOS_MakeName(newname,fullnew,&drivenew)) return false; /* No tricks with devices */ if ( (DOS_FindDevice(oldname) != DOS_DEVICES) || (DOS_FindDevice(newname) != DOS_DEVICES) ) { DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } /* Must be on the same drive */ if(driveold != drivenew) { DOS_SetError(DOSERR_NOT_SAME_DEVICE); return false; } /*Test if target exists => no access */ Bit16u attr; if(Drives[drivenew]->GetFileAttr(fullnew,&attr)) { DOS_SetError(DOSERR_ACCESS_DENIED); return false; } /* Source must exist, check for path ? */ if (!Drives[driveold]->GetFileAttr( fullold, &attr ) ) { DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } if (Drives[drivenew]->Rename(fullold,fullnew)) return true; /* If it still fails. which error should we give ? PATH NOT FOUND or EACCESS */ LOG(LOG_FILES,LOG_NORMAL)("Rename fails for %s to %s, no proper errorcode returned.",oldname,newname); DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } bool DOS_FindFirst(char * search,Bit16u attr,bool fcb_findfirst) { DOS_DTA dta(dos.dta()); Bit8u drive;char fullsearch[DOS_PATHLENGTH]; char dir[DOS_PATHLENGTH];char pattern[DOS_PATHLENGTH]; size_t len = strlen(search); if(len && search[len - 1] == '\\' && !( (len > 2) && (search[len - 2] == ':') && (attr == DOS_ATTR_VOLUME) )) { //Dark Forces installer, but c:\ is allright for volume labels(exclusively set) DOS_SetError(DOSERR_NO_MORE_FILES); return false; } if (!DOS_MakeName(search,fullsearch,&drive)) return false; //Check for devices. FindDevice checks for leading subdir as well bool device = (DOS_FindDevice(search) != DOS_DEVICES); /* Split the search in dir and pattern */ char * find_last; find_last=strrchr(fullsearch,'\\'); if (!find_last) { /*No dir */ strcpy(pattern,fullsearch); dir[0]=0; } else { *find_last=0; strcpy(pattern,find_last+1); strcpy(dir,fullsearch); } dta.SetupSearch(drive,(Bit8u)attr,pattern); if(device) { find_last = strrchr(pattern,'.'); if(find_last) *find_last = 0; //TODO use current date and time dta.SetResult(pattern,0,0,0,DOS_ATTR_DEVICE); LOG(LOG_DOSMISC,LOG_WARN)("finding device %s",pattern); return true; } if (Drives[drive]->FindFirst(dir,dta,fcb_findfirst)) return true; return false; } bool DOS_FindNext(void) { DOS_DTA dta(dos.dta()); Bit8u i = dta.GetSearchDrive(); if(i >= DOS_DRIVES || !Drives[i]) { /* Corrupt search. */ LOG(LOG_FILES,LOG_ERROR)("Corrupt search!!!!"); DOS_SetError(DOSERR_NO_MORE_FILES); return false; } if (Drives[i]->FindNext(dta)) return true; return false; } bool DOS_ReadFile(Bit16u entry,Bit8u * data,Bit16u * amount) { Bit32u handle=RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; /* if ((Files[handle]->flags & 0x0f) == OPEN_WRITE)) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; } */ Bit16u toread=*amount; bool ret=Files[handle]->Read(data,&toread); *amount=toread; return ret; } bool DOS_WriteFile(Bit16u entry,Bit8u * data,Bit16u * amount) { Bit32u handle=RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; /* if ((Files[handle]->flags & 0x0f) == OPEN_READ)) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; } */ Bit16u towrite=*amount; bool ret=Files[handle]->Write(data,&towrite); *amount=towrite; return ret; } bool DOS_SeekFile(Bit16u entry,Bit32u * pos,Bit32u type) { Bit32u handle=RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; return Files[handle]->Seek(pos,type); } bool DOS_CloseFile(Bit16u entry) { Bit32u handle=RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle]) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (Files[handle]->IsOpen()) { Files[handle]->Close(); } DOS_PSP psp(dos.psp()); psp.SetFileHandle(entry,0xff); if (Files[handle]->RemoveRef()<=0) { delete Files[handle]; Files[handle]=0; } return true; } bool DOS_FlushFile(Bit16u entry) { Bit32u handle=RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; LOG(LOG_DOSMISC,LOG_NORMAL)("FFlush used."); return true; } static bool PathExists(char const * const name) { const char* leading = strrchr(name,'\\'); if(!leading) return true; char temp[CROSS_LEN]; strcpy(temp,name); char * lead = strrchr(temp,'\\'); if (lead == temp) return true; *lead = 0; Bit8u drive;char fulldir[DOS_PATHLENGTH]; if (!DOS_MakeName(temp,fulldir,&drive)) return false; if(!Drives[drive]->TestDir(fulldir)) return false; return true; } bool DOS_CreateFile(char const * name,Bit16u attributes,Bit16u * entry) { // Creation of a device is the same as opening it // Tc201 installer if (DOS_FindDevice(name) != DOS_DEVICES) return DOS_OpenFile(name, OPEN_READ, entry); LOG(LOG_FILES,LOG_NORMAL)("file create attributes %X file %s",attributes,name); char fullname[DOS_PATHLENGTH];Bit8u drive; DOS_PSP psp(dos.psp()); if (!DOS_MakeName(name,fullname,&drive)) return false; /* Check for a free file handle */ Bit8u handle=DOS_FILES;Bit8u i; for (i=0;i<DOS_FILES;i++) { if (!Files[i]) { handle=i; break; } } if (handle==DOS_FILES) { DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); return false; } /* We have a position in the main table now find one in the psp table */ *entry = psp.FindFreeFileEntry(); if (*entry==0xff) { DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); return false; } /* Don't allow directories to be created */ if (attributes&DOS_ATTR_DIRECTORY) { DOS_SetError(DOSERR_ACCESS_DENIED); return false; } bool foundit=Drives[drive]->FileCreate(&Files[handle],fullname,attributes); if (foundit) { Files[handle]->SetDrive(drive); Files[handle]->AddRef(); psp.SetFileHandle(*entry,handle); return true; } else { if(!PathExists(name)) DOS_SetError(DOSERR_PATH_NOT_FOUND); else DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } } bool DOS_OpenFile(char const * name,Bit8u flags,Bit16u * entry) { /* First check for devices */ if (flags>2) LOG(LOG_FILES,LOG_ERROR)("Special file open command %X file %s",flags,name); else LOG(LOG_FILES,LOG_NORMAL)("file open command %X file %s",flags,name); DOS_PSP psp(dos.psp()); Bit16u attr = 0; Bit8u devnum = DOS_FindDevice(name); bool device = (devnum != DOS_DEVICES); if(!device && DOS_GetFileAttr(name,&attr)) { //DON'T ALLOW directories to be openened.(skip test if file is device). if((attr & DOS_ATTR_DIRECTORY) || (attr & DOS_ATTR_VOLUME)){ DOS_SetError(DOSERR_ACCESS_DENIED); return false; } } char fullname[DOS_PATHLENGTH];Bit8u drive;Bit8u i; /* First check if the name is correct */ if (!DOS_MakeName(name,fullname,&drive)) return false; Bit8u handle=255; /* Check for a free file handle */ for (i=0;i<DOS_FILES;i++) { if (!Files[i]) { handle=i; break; } } if (handle==255) { DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); return false; } /* We have a position in the main table now find one in the psp table */ *entry = psp.FindFreeFileEntry(); if (*entry==0xff) { DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); return false; } bool exists=false; if (device) { Files[handle]=new DOS_Device(*Devices[devnum]); } else { exists=Drives[drive]->FileOpen(&Files[handle],fullname,flags); if (exists) Files[handle]->SetDrive(drive); } if (exists || device ) { Files[handle]->AddRef(); psp.SetFileHandle(*entry,handle); return true; } else { //Test if file exists, but opened in read-write mode (and writeprotected) if(((flags&3) != OPEN_READ) && Drives[drive]->FileExists(fullname)) DOS_SetError(DOSERR_ACCESS_DENIED); else { if(!PathExists(name)) DOS_SetError(DOSERR_PATH_NOT_FOUND); else DOS_SetError(DOSERR_FILE_NOT_FOUND); } return false; } } bool DOS_OpenFileExtended(char const * name, Bit16u flags, Bit16u createAttr, Bit16u action, Bit16u *entry, Bit16u* status) { // FIXME: Not yet supported : Bit 13 of flags (int 0x24 on critical error) Bit16u result = 0; if (action==0) { // always fail setting DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); return false; } else { if (((action & 0x0f)>2) || ((action & 0xf0)>0x10)) { // invalid action parameter DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); return false; } } if (DOS_OpenFile(name, (Bit8u)(flags&0xff), entry)) { // File already exists switch (action & 0x0f) { case 0x00: // failed DOS_SetError(DOSERR_FILE_ALREADY_EXISTS); return false; case 0x01: // file open (already done) result = 1; break; case 0x02: // replace DOS_CloseFile(*entry); if (!DOS_CreateFile(name, createAttr, entry)) return false; result = 3; break; default: DOS_SetError(DOSERR_FUNCTION_NUMBER_INVALID); E_Exit("DOS: OpenFileExtended: Unknown action."); break; } } else { // File doesn't exist if ((action & 0xf0)==0) { // uses error code from failed open return false; } // Create File if (!DOS_CreateFile(name, createAttr, entry)) { // uses error code from failed create return false; } result = 2; } // success *status = result; return true; } bool DOS_UnlinkFile(char const * const name) { char fullname[DOS_PATHLENGTH];Bit8u drive; if (!DOS_MakeName(name,fullname,&drive)) return false; if(Drives[drive]->FileUnlink(fullname)){ return true; } else { DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } } bool DOS_GetFileAttr(char const * const name,Bit16u * attr) { char fullname[DOS_PATHLENGTH];Bit8u drive; if (!DOS_MakeName(name,fullname,&drive)) return false; if (Drives[drive]->GetFileAttr(fullname,attr)) { return true; } else { DOS_SetError(DOSERR_FILE_NOT_FOUND); return false; } } bool DOS_SetFileAttr(char const * const name,Bit16u /*attr*/) // this function does not change the file attributs // it just does some tests if file is available // returns false when using on cdrom (stonekeep) { Bit16u attrTemp; char fullname[DOS_PATHLENGTH];Bit8u drive; if (!DOS_MakeName(name,fullname,&drive)) return false; if (strncmp(Drives[drive]->GetInfo(),"CDRom ",6)==0 || strncmp(Drives[drive]->GetInfo(),"isoDrive ",9)==0) { DOS_SetError(DOSERR_ACCESS_DENIED); return false; } return Drives[drive]->GetFileAttr(fullname,&attrTemp); } bool DOS_Canonicalize(char const * const name,char * const big) { //TODO Add Better support for devices and shit but will it be needed i doubt it :) Bit8u drive; char fullname[DOS_PATHLENGTH]; if (!DOS_MakeName(name,fullname,&drive)) return false; big[0]=drive+'A'; big[1]=':'; big[2]='\\'; strcpy(&big[3],fullname); return true; } bool DOS_GetFreeDiskSpace(Bit8u drive,Bit16u * bytes,Bit8u * sectors,Bit16u * clusters,Bit16u * free) { if (drive==0) drive=DOS_GetDefaultDrive(); else drive--; if ((drive>=DOS_DRIVES) || (!Drives[drive])) { DOS_SetError(DOSERR_INVALID_DRIVE); return false; } return Drives[drive]->AllocationInfo(bytes,sectors,clusters,free); } bool DOS_DuplicateEntry(Bit16u entry,Bit16u * newentry) { // Dont duplicate console handles /* if (entry<=STDPRN) { *newentry = entry; return true; }; */ Bit8u handle=RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; DOS_PSP psp(dos.psp()); *newentry = psp.FindFreeFileEntry(); if (*newentry==0xff) { DOS_SetError(DOSERR_TOO_MANY_OPEN_FILES); return false; } Files[handle]->AddRef(); psp.SetFileHandle(*newentry,handle); return true; } bool DOS_ForceDuplicateEntry(Bit16u entry,Bit16u newentry) { if(entry == newentry) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; } Bit8u orig = RealHandle(entry); if (orig >= DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[orig] || !Files[orig]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; Bit8u newone = RealHandle(newentry); if (newone < DOS_FILES && Files[newone]) { DOS_CloseFile(newentry); } DOS_PSP psp(dos.psp()); Files[orig]->AddRef(); psp.SetFileHandle(newentry,orig); return true; } bool DOS_CreateTempFile(char * const name,Bit16u * entry) { size_t namelen=strlen(name); char * tempname=name+namelen; if (namelen==0) { // temp file created in root directory tempname[0]='\\'; tempname++; } else { if ((name[namelen-1]!='\\') && (name[namelen-1]!='/')) { tempname[0]='\\'; tempname++; } } dos.errorcode=0; /* add random crap to the end of the name and try to open */ do { Bit32u i; for (i=0;i<8;i++) { tempname[i]=(rand()%26)+'A'; } tempname[8]=0; } while ((!DOS_CreateFile(name,0,entry)) && (dos.errorcode==DOSERR_FILE_ALREADY_EXISTS)); if (dos.errorcode) return false; return true; } #define FCB_SEP ":.;,=+" #define ILLEGAL ":.;,=+ \t/\"[]<>|" static bool isvalid(const char in){ const char ill[]=ILLEGAL; return (Bit8u(in)>0x1F) && (!strchr(ill,in)); } #define PARSE_SEP_STOP 0x01 #define PARSE_DFLT_DRIVE 0x02 #define PARSE_BLNK_FNAME 0x04 #define PARSE_BLNK_FEXT 0x08 #define PARSE_RET_NOWILD 0 #define PARSE_RET_WILD 1 #define PARSE_RET_BADDRIVE 0xff Bit8u FCB_Parsename(Bit16u seg,Bit16u offset,Bit8u parser ,char *string, Bit8u *change) { char * string_begin=string; Bit8u ret=0; if (!(parser & PARSE_DFLT_DRIVE)) { // default drive forced, this intentionally invalidates an extended FCB mem_writeb(PhysMake(seg,offset),0); } DOS_FCB fcb(seg,offset,false); // always a non-extended FCB bool hasdrive,hasname,hasext,finished; hasdrive=hasname=hasext=finished=false; Bitu index=0; Bit8u fill=' '; /* First get the old data from the fcb */ #ifdef _MSC_VER #pragma pack (1) #endif union { struct { char drive[2]; char name[9]; char ext[4]; } GCC_ATTRIBUTE (packed) part; char full[DOS_FCBNAME]; } fcb_name; #ifdef _MSC_VER #pragma pack() #endif /* Get the old information from the previous fcb */ fcb.GetName(fcb_name.full); fcb_name.part.drive[0]-='A'-1;fcb_name.part.drive[1]=0; fcb_name.part.name[8]=0;fcb_name.part.ext[3]=0; /* Strip of the leading sepetaror */ if((parser & PARSE_SEP_STOP) && *string) { //ignore leading seperator char sep[] = FCB_SEP;char a[2]; a[0]= *string;a[1]='\0'; if (strcspn(a,sep)==0) string++; } /* strip leading spaces */ while((*string==' ')||(*string=='\t')) string++; /* Check for a drive */ if (string[1]==':') { fcb_name.part.drive[0]=0; hasdrive=true; if (isalpha(string[0]) && Drives[toupper(string[0])-'A']) { fcb_name.part.drive[0]=(char)(toupper(string[0])-'A'+1); } else ret=0xff; string+=2; } /* Special checks for . and .. */ if (string[0]=='.') { string++; if (!string[0]) { hasname=true; ret=PARSE_RET_NOWILD; strcpy(fcb_name.part.name,". "); goto savefcb; } if (string[1]=='.' && !string[1]) { string++; hasname=true; ret=PARSE_RET_NOWILD; strcpy(fcb_name.part.name,".. "); goto savefcb; } goto checkext; } /* Copy the name */ hasname=true;finished=false;fill=' ';index=0; while (index<8) { if (!finished) { if (string[0]=='*') {fill='?';fcb_name.part.name[index]='?';if (!ret) ret=1;finished=true;} else if (string[0]=='?') {fcb_name.part.name[index]='?';if (!ret) ret=1;} else if (isvalid(string[0])) {fcb_name.part.name[index]=(char)(toupper(string[0]));} else { finished=true;continue; } string++; } else { fcb_name.part.name[index]=fill; } index++; } if (!(string[0]=='.')) goto savefcb; string++; checkext: /* Copy the extension */ hasext=true;finished=false;fill=' ';index=0; while (index<3) { if (!finished) { if (string[0]=='*') {fill='?';fcb_name.part.ext[index]='?';finished=true;} else if (string[0]=='?') {fcb_name.part.ext[index]='?';if (!ret) ret=1;} else if (isvalid(string[0])) {fcb_name.part.ext[index]=(char)(toupper(string[0]));} else { finished=true;continue; } string++; } else { fcb_name.part.ext[index]=fill; } index++; } savefcb: if (!hasdrive & !(parser & PARSE_DFLT_DRIVE)) fcb_name.part.drive[0] = 0; if (!hasname & !(parser & PARSE_BLNK_FNAME)) strcpy(fcb_name.part.name," "); if (!hasext & !(parser & PARSE_BLNK_FEXT)) strcpy(fcb_name.part.ext," "); fcb.SetName(fcb_name.part.drive[0],fcb_name.part.name,fcb_name.part.ext); *change=(Bit8u)(string-string_begin); return ret; } static void DTAExtendName(char * const name,char * const filename,char * const ext) { char * find=strchr(name,'.'); if (find) { strcpy(ext,find+1); *find=0; } else ext[0]=0; strcpy(filename,name); size_t i; for (i=strlen(name);i<8;i++) filename[i]=' '; filename[8]=0; for (i=strlen(ext);i<3;i++) ext[i]=' '; ext[3]=0; } static void SaveFindResult(DOS_FCB & find_fcb) { DOS_DTA find_dta(dos.tables.tempdta); char name[DOS_NAMELENGTH_ASCII];Bit32u size;Bit16u date;Bit16u time;Bit8u attr;Bit8u drive; char file_name[9];char ext[4]; find_dta.GetResult(name,size,date,time,attr); drive=find_fcb.GetDrive()+1; /* Create a correct file and extention */ DTAExtendName(name,file_name,ext); DOS_FCB fcb(RealSeg(dos.dta()),RealOff(dos.dta()));//TODO fcb.Create(find_fcb.Extended()); fcb.SetName(drive,file_name,ext); fcb.SetAttr(attr); /* Only adds attribute if fcb is extended */ fcb.SetSizeDateTime(size,date,time); } bool DOS_FCBCreate(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); char shortname[DOS_FCBNAME];Bit16u handle; fcb.GetName(shortname); if (!DOS_CreateFile(shortname,DOS_ATTR_ARCHIVE,&handle)) return false; fcb.FileOpen((Bit8u)handle); return true; } bool DOS_FCBOpen(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); char shortname[DOS_FCBNAME];Bit16u handle; fcb.GetName(shortname); /* First check if the name is correct */ Bit8u drive; char fullname[DOS_PATHLENGTH]; if (!DOS_MakeName(shortname,fullname,&drive)) return false; /* Check, if file is already opened */ for (Bit8u i=0;i<DOS_FILES;i++) { DOS_PSP psp(dos.psp()); if (Files[i] && Files[i]->IsOpen() && Files[i]->IsName(fullname)) { handle = psp.FindEntryByHandle(i); if (handle==0xFF) { // This shouldnt happen LOG(LOG_FILES,LOG_ERROR)("DOS: File %s is opened but has no psp entry.",shortname); return false; } fcb.FileOpen((Bit8u)handle); return true; } } if (!DOS_OpenFile(shortname,OPEN_READWRITE,&handle)) return false; fcb.FileOpen((Bit8u)handle); return true; } bool DOS_FCBClose(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); if(!fcb.Valid()) return false; Bit8u fhandle; fcb.FileClose(fhandle); DOS_CloseFile(fhandle); return true; } bool DOS_FCBFindFirst(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta); char name[DOS_FCBNAME];fcb.GetName(name); Bit8u attr = DOS_ATTR_ARCHIVE; fcb.GetAttr(attr); /* Gets search attributes if extended */ bool ret=DOS_FindFirst(name,attr,true); dos.dta(old_dta); if (ret) SaveFindResult(fcb); return ret; } bool DOS_FCBFindNext(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta); bool ret=DOS_FindNext(); dos.dta(old_dta); if (ret) SaveFindResult(fcb); return ret; } Bit8u DOS_FCBRead(Bit16u seg,Bit16u offset,Bit16u recno) { DOS_FCB fcb(seg,offset); Bit8u fhandle,cur_rec;Bit16u cur_block,rec_size; fcb.GetSeqData(fhandle,rec_size); fcb.GetRecord(cur_block,cur_rec); Bit32u pos=((cur_block*128)+cur_rec)*rec_size; if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET)) return FCB_READ_NODATA; Bit16u toread=rec_size; if (!DOS_ReadFile(fhandle,dos_copybuf,&toread)) return FCB_READ_NODATA; if (toread==0) return FCB_READ_NODATA; if (toread < rec_size) { //Zero pad copybuffer to rec_size Bitu i = toread; while(i < rec_size) dos_copybuf[i++] = 0; } MEM_BlockWrite(Real2Phys(dos.dta())+recno*rec_size,dos_copybuf,rec_size); if (++cur_rec>127) { cur_block++;cur_rec=0; } fcb.SetRecord(cur_block,cur_rec); if (toread==rec_size) return FCB_SUCCESS; if (toread==0) return FCB_READ_NODATA; return FCB_READ_PARTIAL; } Bit8u DOS_FCBWrite(Bit16u seg,Bit16u offset,Bit16u recno) { DOS_FCB fcb(seg,offset); Bit8u fhandle,cur_rec;Bit16u cur_block,rec_size; fcb.GetSeqData(fhandle,rec_size); fcb.GetRecord(cur_block,cur_rec); Bit32u pos=((cur_block*128)+cur_rec)*rec_size; if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET)) return FCB_ERR_WRITE; MEM_BlockRead(Real2Phys(dos.dta())+recno*rec_size,dos_copybuf,rec_size); Bit16u towrite=rec_size; if (!DOS_WriteFile(fhandle,dos_copybuf,&towrite)) return FCB_ERR_WRITE; Bit32u size;Bit16u date,time; fcb.GetSizeDateTime(size,date,time); if (pos+towrite>size) size=pos+towrite; //time doesn't keep track of endofday date = DOS_PackDate(dos.date.year,dos.date.month,dos.date.day); Bit32u ticks = mem_readd(BIOS_TIMER); Bit32u seconds = (ticks*10)/182; Bit16u hour = (Bit16u)(seconds/3600); Bit16u min = (Bit16u)((seconds % 3600)/60); Bit16u sec = (Bit16u)(seconds % 60); time = DOS_PackTime(hour,min,sec); Bit8u temp=RealHandle(fhandle); Files[temp]->time=time; Files[temp]->date=date; fcb.SetSizeDateTime(size,date,time); if (++cur_rec>127) { cur_block++;cur_rec=0; } fcb.SetRecord(cur_block,cur_rec); return FCB_SUCCESS; } Bit8u DOS_FCBIncreaseSize(Bit16u seg,Bit16u offset) { DOS_FCB fcb(seg,offset); Bit8u fhandle,cur_rec;Bit16u cur_block,rec_size; fcb.GetSeqData(fhandle,rec_size); fcb.GetRecord(cur_block,cur_rec); Bit32u pos=((cur_block*128)+cur_rec)*rec_size; if (!DOS_SeekFile(fhandle,&pos,DOS_SEEK_SET)) return FCB_ERR_WRITE; Bit16u towrite=0; if (!DOS_WriteFile(fhandle,dos_copybuf,&towrite)) return FCB_ERR_WRITE; Bit32u size;Bit16u date,time; fcb.GetSizeDateTime(size,date,time); if (pos+towrite>size) size=pos+towrite; //time doesn't keep track of endofday date = DOS_PackDate(dos.date.year,dos.date.month,dos.date.day); Bit32u ticks = mem_readd(BIOS_TIMER); Bit32u seconds = (ticks*10)/182; Bit16u hour = (Bit16u)(seconds/3600); Bit16u min = (Bit16u)((seconds % 3600)/60); Bit16u sec = (Bit16u)(seconds % 60); time = DOS_PackTime(hour,min,sec); Bit8u temp=RealHandle(fhandle); Files[temp]->time=time; Files[temp]->date=date; fcb.SetSizeDateTime(size,date,time); fcb.SetRecord(cur_block,cur_rec); return FCB_SUCCESS; } Bit8u DOS_FCBRandomRead(Bit16u seg,Bit16u offset,Bit16u numRec,bool restore) { /* if restore is true :random read else random blok read. * random read updates old block and old record to reflect the random data * before the read!!!!!!!!! and the random data is not updated! (user must do this) * Random block read updates these fields to reflect the state after the read! */ /* BUG: numRec should return the amount of records read! * Not implemented yet as I'm unsure how to count on error states (partial/failed) */ DOS_FCB fcb(seg,offset); Bit32u random; Bit16u old_block=0; Bit8u old_rec=0; Bit8u error=0; /* Set the correct record from the random data */ fcb.GetRandom(random); fcb.SetRecord((Bit16u)(random / 128),(Bit8u)(random & 127)); if (restore) fcb.GetRecord(old_block,old_rec);//store this for after the read. // Read records for (int i=0; i<numRec; i++) { error = DOS_FCBRead(seg,offset,(Bit16u)i); if (error!=0x00) break; } Bit16u new_block;Bit8u new_rec; fcb.GetRecord(new_block,new_rec); if (restore) fcb.SetRecord(old_block,old_rec); /* Update the random record pointer with new position only when restore is false*/ if(!restore) fcb.SetRandom(new_block*128+new_rec); return error; } Bit8u DOS_FCBRandomWrite(Bit16u seg,Bit16u offset,Bit16u numRec,bool restore) { /* see FCB_RandomRead */ DOS_FCB fcb(seg,offset); Bit32u random; Bit16u old_block=0; Bit8u old_rec=0; Bit8u error=0; /* Set the correct record from the random data */ fcb.GetRandom(random); fcb.SetRecord((Bit16u)(random / 128),(Bit8u)(random & 127)); if (restore) fcb.GetRecord(old_block,old_rec); if (numRec>0) { /* Write records */ for (int i=0; i<numRec; i++) { error = DOS_FCBWrite(seg,offset,(Bit16u)i);// dos_fcbwrite return 0 false when true... if (error!=0x00) break; } } else { DOS_FCBIncreaseSize(seg,offset); } Bit16u new_block;Bit8u new_rec; fcb.GetRecord(new_block,new_rec); if (restore) fcb.SetRecord(old_block,old_rec); /* Update the random record pointer with new position only when restore is false */ if(!restore) fcb.SetRandom(new_block*128+new_rec); return error; } bool DOS_FCBGetFileSize(Bit16u seg,Bit16u offset) { char shortname[DOS_PATHLENGTH];Bit16u entry;Bit8u handle;Bit16u rec_size; DOS_FCB fcb(seg,offset); fcb.GetName(shortname); if (!DOS_OpenFile(shortname,OPEN_READ,&entry)) return false; handle = RealHandle(entry); Bit32u size = 0; Files[handle]->Seek(&size,DOS_SEEK_END); DOS_CloseFile(entry);fcb.GetSeqData(handle,rec_size); Bit32u random=(size/rec_size); if (size % rec_size) random++; fcb.SetRandom(random); return true; } bool DOS_FCBDeleteFile(Bit16u seg,Bit16u offset){ /* FCB DELETE honours wildcards. it will return true if one or more * files get deleted. * To get this: the dta is set to temporary dta in which found files are * stored. This can not be the tempdta as that one is used by fcbfindfirst */ RealPt old_dta=dos.dta();dos.dta(dos.tables.tempdta_fcbdelete); DOS_FCB fcb(RealSeg(dos.dta()),RealOff(dos.dta())); bool nextfile = false; bool return_value = false; nextfile = DOS_FCBFindFirst(seg,offset); while(nextfile) { char shortname[DOS_FCBNAME] = { 0 }; fcb.GetName(shortname); bool res=DOS_UnlinkFile(shortname); if(!return_value && res) return_value = true; //at least one file deleted nextfile = DOS_FCBFindNext(seg,offset); } dos.dta(old_dta); /*Restore dta */ return return_value; } bool DOS_FCBRenameFile(Bit16u seg, Bit16u offset){ DOS_FCB fcbold(seg,offset); DOS_FCB fcbnew(seg,offset+16); char oldname[DOS_FCBNAME]; char newname[DOS_FCBNAME]; fcbold.GetName(oldname);fcbnew.GetName(newname); return DOS_Rename(oldname,newname); } void DOS_FCBSetRandomRecord(Bit16u seg, Bit16u offset) { DOS_FCB fcb(seg,offset); Bit16u block;Bit8u rec; fcb.GetRecord(block,rec); fcb.SetRandom(block*128+rec); } bool DOS_FileExists(char const * const name) { char fullname[DOS_PATHLENGTH];Bit8u drive; if (!DOS_MakeName(name,fullname,&drive)) return false; return Drives[drive]->FileExists(fullname); } bool DOS_GetAllocationInfo(Bit8u drive,Bit16u * _bytes_sector,Bit8u * _sectors_cluster,Bit16u * _total_clusters) { if (!drive) drive = DOS_GetDefaultDrive(); else drive--; if (drive >= DOS_DRIVES || !Drives[drive]) return false; Bit16u _free_clusters; Drives[drive]->AllocationInfo(_bytes_sector,_sectors_cluster,_total_clusters,&_free_clusters); SegSet16(ds,RealSeg(dos.tables.mediaid)); reg_bx=RealOff(dos.tables.mediaid+drive*2); return true; } bool DOS_SetDrive(Bit8u drive) { if (Drives[drive]) { DOS_SetDefaultDrive(drive); return true; } else { return false; } } bool DOS_GetFileDate(Bit16u entry, Bit16u* otime, Bit16u* odate) { Bit32u handle=RealHandle(entry); if (handle>=DOS_FILES) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle] || !Files[handle]->IsOpen()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; }; if (!Files[handle]->UpdateDateTimeFromHost()) { DOS_SetError(DOSERR_INVALID_HANDLE); return false; } *otime = Files[handle]->time; *odate = Files[handle]->date; return true; } void DOS_SetupFiles (void) { /* Setup the File Handles */ Bit32u i; for (i=0;i<DOS_FILES;i++) { Files[i]=0; } /* Setup the Virtual Disk System */ for (i=0;i<DOS_DRIVES;i++) { Drives[i]=0; } Drives[25]=new Virtual_Drive(); }
litchie/dospad
dosbox/src/dos/dos_files.cpp
C++
gpl-2.0
35,894