diff --git "a/codeparrot-valid_1033.txt" "b/codeparrot-valid_1033.txt" new file mode 100644--- /dev/null +++ "b/codeparrot-valid_1033.txt" @@ -0,0 +1,10000 @@ + +def register_Ns3EnumChecker_methods(root_module, cls): + ## enum.h (module 'core'): ns3::EnumChecker::EnumChecker(ns3::EnumChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::EnumChecker const &', 'arg0')]) + ## enum.h (module 'core'): ns3::EnumChecker::EnumChecker() [constructor] + cls.add_constructor([]) + ## enum.h (module 'core'): void ns3::EnumChecker::Add(int v, std::string name) [member function] + cls.add_method('Add', + 'void', + [param('int', 'v'), param('std::string', 'name')]) + ## enum.h (module 'core'): void ns3::EnumChecker::AddDefault(int v, std::string name) [member function] + cls.add_method('AddDefault', + 'void', + [param('int', 'v'), param('std::string', 'name')]) + ## enum.h (module 'core'): bool ns3::EnumChecker::Check(ns3::AttributeValue const & value) const [member function] + cls.add_method('Check', + 'bool', + [param('ns3::AttributeValue const &', 'value')], + is_const=True, is_virtual=True) + ## enum.h (module 'core'): bool ns3::EnumChecker::Copy(ns3::AttributeValue const & src, ns3::AttributeValue & dst) const [member function] + cls.add_method('Copy', + 'bool', + [param('ns3::AttributeValue const &', 'src'), param('ns3::AttributeValue &', 'dst')], + is_const=True, is_virtual=True) + ## enum.h (module 'core'): ns3::Ptr ns3::EnumChecker::Create() const [member function] + cls.add_method('Create', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## enum.h (module 'core'): std::string ns3::EnumChecker::GetUnderlyingTypeInformation() const [member function] + cls.add_method('GetUnderlyingTypeInformation', + 'std::string', + [], + is_const=True, is_virtual=True) + ## enum.h (module 'core'): std::string ns3::EnumChecker::GetValueTypeName() const [member function] + cls.add_method('GetValueTypeName', + 'std::string', + [], + is_const=True, is_virtual=True) + ## enum.h (module 'core'): bool ns3::EnumChecker::HasUnderlyingTypeInformation() const [member function] + cls.add_method('HasUnderlyingTypeInformation', + 'bool', + [], + is_const=True, is_virtual=True) + return + +def register_Ns3EnumValue_methods(root_module, cls): + ## enum.h (module 'core'): ns3::EnumValue::EnumValue(ns3::EnumValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::EnumValue const &', 'arg0')]) + ## enum.h (module 'core'): ns3::EnumValue::EnumValue() [constructor] + cls.add_constructor([]) + ## enum.h (module 'core'): ns3::EnumValue::EnumValue(int v) [constructor] + cls.add_constructor([param('int', 'v')]) + ## enum.h (module 'core'): ns3::Ptr ns3::EnumValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## enum.h (module 'core'): bool ns3::EnumValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## enum.h (module 'core'): int ns3::EnumValue::Get() const [member function] + cls.add_method('Get', + 'int', + [], + is_const=True) + ## enum.h (module 'core'): std::string ns3::EnumValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## enum.h (module 'core'): void ns3::EnumValue::Set(int v) [member function] + cls.add_method('Set', + 'void', + [param('int', 'v')]) + return + +def register_Ns3EventImpl_methods(root_module, cls): + ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl(ns3::EventImpl const & arg0) [copy constructor] + cls.add_constructor([param('ns3::EventImpl const &', 'arg0')]) + ## event-impl.h (module 'core'): ns3::EventImpl::EventImpl() [constructor] + cls.add_constructor([]) + ## event-impl.h (module 'core'): void ns3::EventImpl::Cancel() [member function] + cls.add_method('Cancel', + 'void', + []) + ## event-impl.h (module 'core'): void ns3::EventImpl::Invoke() [member function] + cls.add_method('Invoke', + 'void', + []) + ## event-impl.h (module 'core'): bool ns3::EventImpl::IsCancelled() [member function] + cls.add_method('IsCancelled', + 'bool', + []) + ## event-impl.h (module 'core'): void ns3::EventImpl::Notify() [member function] + cls.add_method('Notify', + 'void', + [], + is_pure_virtual=True, visibility='protected', is_virtual=True) + return + +def register_Ns3IntegerValue_methods(root_module, cls): + ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue() [constructor] + cls.add_constructor([]) + ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(ns3::IntegerValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::IntegerValue const &', 'arg0')]) + ## integer.h (module 'core'): ns3::IntegerValue::IntegerValue(int64_t const & value) [constructor] + cls.add_constructor([param('int64_t const &', 'value')]) + ## integer.h (module 'core'): ns3::Ptr ns3::IntegerValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## integer.h (module 'core'): bool ns3::IntegerValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## integer.h (module 'core'): int64_t ns3::IntegerValue::Get() const [member function] + cls.add_method('Get', + 'int64_t', + [], + is_const=True) + ## integer.h (module 'core'): std::string ns3::IntegerValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## integer.h (module 'core'): void ns3::IntegerValue::Set(int64_t const & value) [member function] + cls.add_method('Set', + 'void', + [param('int64_t const &', 'value')]) + return + +def register_Ns3Ipv4AddressChecker_methods(root_module, cls): + ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker() [constructor] + cls.add_constructor([]) + ## ipv4-address.h (module 'network'): ns3::Ipv4AddressChecker::Ipv4AddressChecker(ns3::Ipv4AddressChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv4AddressChecker const &', 'arg0')]) + return + +def register_Ns3Ipv4AddressValue_methods(root_module, cls): + ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue() [constructor] + cls.add_constructor([]) + ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4AddressValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv4AddressValue const &', 'arg0')]) + ## ipv4-address.h (module 'network'): ns3::Ipv4AddressValue::Ipv4AddressValue(ns3::Ipv4Address const & value) [constructor] + cls.add_constructor([param('ns3::Ipv4Address const &', 'value')]) + ## ipv4-address.h (module 'network'): ns3::Ptr ns3::Ipv4AddressValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## ipv4-address.h (module 'network'): bool ns3::Ipv4AddressValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## ipv4-address.h (module 'network'): ns3::Ipv4Address ns3::Ipv4AddressValue::Get() const [member function] + cls.add_method('Get', + 'ns3::Ipv4Address', + [], + is_const=True) + ## ipv4-address.h (module 'network'): std::string ns3::Ipv4AddressValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## ipv4-address.h (module 'network'): void ns3::Ipv4AddressValue::Set(ns3::Ipv4Address const & value) [member function] + cls.add_method('Set', + 'void', + [param('ns3::Ipv4Address const &', 'value')]) + return + +def register_Ns3Ipv4MaskChecker_methods(root_module, cls): + ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker() [constructor] + cls.add_constructor([]) + ## ipv4-address.h (module 'network'): ns3::Ipv4MaskChecker::Ipv4MaskChecker(ns3::Ipv4MaskChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv4MaskChecker const &', 'arg0')]) + return + +def register_Ns3Ipv4MaskValue_methods(root_module, cls): + ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue() [constructor] + cls.add_constructor([]) + ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4MaskValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv4MaskValue const &', 'arg0')]) + ## ipv4-address.h (module 'network'): ns3::Ipv4MaskValue::Ipv4MaskValue(ns3::Ipv4Mask const & value) [constructor] + cls.add_constructor([param('ns3::Ipv4Mask const &', 'value')]) + ## ipv4-address.h (module 'network'): ns3::Ptr ns3::Ipv4MaskValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## ipv4-address.h (module 'network'): bool ns3::Ipv4MaskValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## ipv4-address.h (module 'network'): ns3::Ipv4Mask ns3::Ipv4MaskValue::Get() const [member function] + cls.add_method('Get', + 'ns3::Ipv4Mask', + [], + is_const=True) + ## ipv4-address.h (module 'network'): std::string ns3::Ipv4MaskValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## ipv4-address.h (module 'network'): void ns3::Ipv4MaskValue::Set(ns3::Ipv4Mask const & value) [member function] + cls.add_method('Set', + 'void', + [param('ns3::Ipv4Mask const &', 'value')]) + return + +def register_Ns3Ipv6AddressChecker_methods(root_module, cls): + ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker() [constructor] + cls.add_constructor([]) + ## ipv6-address.h (module 'network'): ns3::Ipv6AddressChecker::Ipv6AddressChecker(ns3::Ipv6AddressChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv6AddressChecker const &', 'arg0')]) + return + +def register_Ns3Ipv6AddressValue_methods(root_module, cls): + ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue() [constructor] + cls.add_constructor([]) + ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6AddressValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv6AddressValue const &', 'arg0')]) + ## ipv6-address.h (module 'network'): ns3::Ipv6AddressValue::Ipv6AddressValue(ns3::Ipv6Address const & value) [constructor] + cls.add_constructor([param('ns3::Ipv6Address const &', 'value')]) + ## ipv6-address.h (module 'network'): ns3::Ptr ns3::Ipv6AddressValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6AddressValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## ipv6-address.h (module 'network'): ns3::Ipv6Address ns3::Ipv6AddressValue::Get() const [member function] + cls.add_method('Get', + 'ns3::Ipv6Address', + [], + is_const=True) + ## ipv6-address.h (module 'network'): std::string ns3::Ipv6AddressValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## ipv6-address.h (module 'network'): void ns3::Ipv6AddressValue::Set(ns3::Ipv6Address const & value) [member function] + cls.add_method('Set', + 'void', + [param('ns3::Ipv6Address const &', 'value')]) + return + +def register_Ns3Ipv6PrefixChecker_methods(root_module, cls): + ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker() [constructor] + cls.add_constructor([]) + ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixChecker::Ipv6PrefixChecker(ns3::Ipv6PrefixChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv6PrefixChecker const &', 'arg0')]) + return + +def register_Ns3Ipv6PrefixValue_methods(root_module, cls): + ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue() [constructor] + cls.add_constructor([]) + ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6PrefixValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Ipv6PrefixValue const &', 'arg0')]) + ## ipv6-address.h (module 'network'): ns3::Ipv6PrefixValue::Ipv6PrefixValue(ns3::Ipv6Prefix const & value) [constructor] + cls.add_constructor([param('ns3::Ipv6Prefix const &', 'value')]) + ## ipv6-address.h (module 'network'): ns3::Ptr ns3::Ipv6PrefixValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## ipv6-address.h (module 'network'): bool ns3::Ipv6PrefixValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## ipv6-address.h (module 'network'): ns3::Ipv6Prefix ns3::Ipv6PrefixValue::Get() const [member function] + cls.add_method('Get', + 'ns3::Ipv6Prefix', + [], + is_const=True) + ## ipv6-address.h (module 'network'): std::string ns3::Ipv6PrefixValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## ipv6-address.h (module 'network'): void ns3::Ipv6PrefixValue::Set(ns3::Ipv6Prefix const & value) [member function] + cls.add_method('Set', + 'void', + [param('ns3::Ipv6Prefix const &', 'value')]) + return + +def register_Ns3MobilityModel_methods(root_module, cls): + ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel(ns3::MobilityModel const & arg0) [copy constructor] + cls.add_constructor([param('ns3::MobilityModel const &', 'arg0')]) + ## mobility-model.h (module 'mobility'): ns3::MobilityModel::MobilityModel() [constructor] + cls.add_constructor([]) + ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetDistanceFrom(ns3::Ptr position) const [member function] + cls.add_method('GetDistanceFrom', + 'double', + [param('ns3::Ptr< ns3::MobilityModel const >', 'position')], + is_const=True) + ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetPosition() const [member function] + cls.add_method('GetPosition', + 'ns3::Vector', + [], + is_const=True) + ## mobility-model.h (module 'mobility'): double ns3::MobilityModel::GetRelativeSpeed(ns3::Ptr other) const [member function] + cls.add_method('GetRelativeSpeed', + 'double', + [param('ns3::Ptr< ns3::MobilityModel const >', 'other')], + is_const=True) + ## mobility-model.h (module 'mobility'): static ns3::TypeId ns3::MobilityModel::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::GetVelocity() const [member function] + cls.add_method('GetVelocity', + 'ns3::Vector', + [], + is_const=True) + ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::SetPosition(ns3::Vector const & position) [member function] + cls.add_method('SetPosition', + 'void', + [param('ns3::Vector const &', 'position')]) + ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::NotifyCourseChange() const [member function] + cls.add_method('NotifyCourseChange', + 'void', + [], + is_const=True, visibility='protected') + ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetPosition() const [member function] + cls.add_method('DoGetPosition', + 'ns3::Vector', + [], + is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) + ## mobility-model.h (module 'mobility'): ns3::Vector ns3::MobilityModel::DoGetVelocity() const [member function] + cls.add_method('DoGetVelocity', + 'ns3::Vector', + [], + is_pure_virtual=True, is_const=True, visibility='private', is_virtual=True) + ## mobility-model.h (module 'mobility'): void ns3::MobilityModel::DoSetPosition(ns3::Vector const & position) [member function] + cls.add_method('DoSetPosition', + 'void', + [param('ns3::Vector const &', 'position')], + is_pure_virtual=True, visibility='private', is_virtual=True) + return + +def register_Ns3NetDevice_methods(root_module, cls): + ## net-device.h (module 'network'): ns3::NetDevice::NetDevice() [constructor] + cls.add_constructor([]) + ## net-device.h (module 'network'): ns3::NetDevice::NetDevice(ns3::NetDevice const & arg0) [copy constructor] + cls.add_constructor([param('ns3::NetDevice const &', 'arg0')]) + ## net-device.h (module 'network'): void ns3::NetDevice::AddLinkChangeCallback(ns3::Callback callback) [member function] + cls.add_method('AddLinkChangeCallback', + 'void', + [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], + is_pure_virtual=True, is_virtual=True) + ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetAddress() const [member function] + cls.add_method('GetAddress', + 'ns3::Address', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetBroadcast() const [member function] + cls.add_method('GetBroadcast', + 'ns3::Address', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): ns3::Ptr ns3::NetDevice::GetChannel() const [member function] + cls.add_method('GetChannel', + 'ns3::Ptr< ns3::Channel >', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): uint32_t ns3::NetDevice::GetIfIndex() const [member function] + cls.add_method('GetIfIndex', + 'uint32_t', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): uint16_t ns3::NetDevice::GetMtu() const [member function] + cls.add_method('GetMtu', + 'uint16_t', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] + cls.add_method('GetMulticast', + 'ns3::Address', + [param('ns3::Ipv4Address', 'multicastGroup')], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): ns3::Address ns3::NetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] + cls.add_method('GetMulticast', + 'ns3::Address', + [param('ns3::Ipv6Address', 'addr')], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): ns3::Ptr ns3::NetDevice::GetNode() const [member function] + cls.add_method('GetNode', + 'ns3::Ptr< ns3::Node >', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): static ns3::TypeId ns3::NetDevice::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## net-device.h (module 'network'): bool ns3::NetDevice::IsBridge() const [member function] + cls.add_method('IsBridge', + 'bool', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): bool ns3::NetDevice::IsBroadcast() const [member function] + cls.add_method('IsBroadcast', + 'bool', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): bool ns3::NetDevice::IsLinkUp() const [member function] + cls.add_method('IsLinkUp', + 'bool', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): bool ns3::NetDevice::IsMulticast() const [member function] + cls.add_method('IsMulticast', + 'bool', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): bool ns3::NetDevice::IsPointToPoint() const [member function] + cls.add_method('IsPointToPoint', + 'bool', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): bool ns3::NetDevice::NeedsArp() const [member function] + cls.add_method('NeedsArp', + 'bool', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + ## net-device.h (module 'network'): bool ns3::NetDevice::Send(ns3::Ptr packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] + cls.add_method('Send', + 'bool', + [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], + is_pure_virtual=True, is_virtual=True) + ## net-device.h (module 'network'): bool ns3::NetDevice::SendFrom(ns3::Ptr packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] + cls.add_method('SendFrom', + 'bool', + [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], + is_pure_virtual=True, is_virtual=True) + ## net-device.h (module 'network'): void ns3::NetDevice::SetAddress(ns3::Address address) [member function] + cls.add_method('SetAddress', + 'void', + [param('ns3::Address', 'address')], + is_pure_virtual=True, is_virtual=True) + ## net-device.h (module 'network'): void ns3::NetDevice::SetIfIndex(uint32_t const index) [member function] + cls.add_method('SetIfIndex', + 'void', + [param('uint32_t const', 'index')], + is_pure_virtual=True, is_virtual=True) + ## net-device.h (module 'network'): bool ns3::NetDevice::SetMtu(uint16_t const mtu) [member function] + cls.add_method('SetMtu', + 'bool', + [param('uint16_t const', 'mtu')], + is_pure_virtual=True, is_virtual=True) + ## net-device.h (module 'network'): void ns3::NetDevice::SetNode(ns3::Ptr node) [member function] + cls.add_method('SetNode', + 'void', + [param('ns3::Ptr< ns3::Node >', 'node')], + is_pure_virtual=True, is_virtual=True) + ## net-device.h (module 'network'): void ns3::NetDevice::SetPromiscReceiveCallback(ns3::Callback,ns3::Ptr,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function] + cls.add_method('SetPromiscReceiveCallback', + 'void', + [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], + is_pure_virtual=True, is_virtual=True) + ## net-device.h (module 'network'): void ns3::NetDevice::SetReceiveCallback(ns3::Callback, ns3::Ptr, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] + cls.add_method('SetReceiveCallback', + 'void', + [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], + is_pure_virtual=True, is_virtual=True) + ## net-device.h (module 'network'): bool ns3::NetDevice::SupportsSendFrom() const [member function] + cls.add_method('SupportsSendFrom', + 'bool', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + return + +def register_Ns3NixVector_methods(root_module, cls): + cls.add_output_stream_operator() + ## nix-vector.h (module 'network'): ns3::NixVector::NixVector() [constructor] + cls.add_constructor([]) + ## nix-vector.h (module 'network'): ns3::NixVector::NixVector(ns3::NixVector const & o) [copy constructor] + cls.add_constructor([param('ns3::NixVector const &', 'o')]) + ## nix-vector.h (module 'network'): void ns3::NixVector::AddNeighborIndex(uint32_t newBits, uint32_t numberOfBits) [member function] + cls.add_method('AddNeighborIndex', + 'void', + [param('uint32_t', 'newBits'), param('uint32_t', 'numberOfBits')]) + ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::BitCount(uint32_t numberOfNeighbors) const [member function] + cls.add_method('BitCount', + 'uint32_t', + [param('uint32_t', 'numberOfNeighbors')], + is_const=True) + ## nix-vector.h (module 'network'): ns3::Ptr ns3::NixVector::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::NixVector >', + [], + is_const=True) + ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Deserialize(uint32_t const * buffer, uint32_t size) [member function] + cls.add_method('Deserialize', + 'uint32_t', + [param('uint32_t const *', 'buffer'), param('uint32_t', 'size')]) + ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::ExtractNeighborIndex(uint32_t numberOfBits) [member function] + cls.add_method('ExtractNeighborIndex', + 'uint32_t', + [param('uint32_t', 'numberOfBits')]) + ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetRemainingBits() [member function] + cls.add_method('GetRemainingBits', + 'uint32_t', + []) + ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_const=True) + ## nix-vector.h (module 'network'): uint32_t ns3::NixVector::Serialize(uint32_t * buffer, uint32_t maxSize) const [member function] + cls.add_method('Serialize', + 'uint32_t', + [param('uint32_t *', 'buffer'), param('uint32_t', 'maxSize')], + is_const=True) + return + +def register_Ns3Node_methods(root_module, cls): + ## node.h (module 'network'): ns3::Node::Node(ns3::Node const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Node const &', 'arg0')]) + ## node.h (module 'network'): ns3::Node::Node() [constructor] + cls.add_constructor([]) + ## node.h (module 'network'): ns3::Node::Node(uint32_t systemId) [constructor] + cls.add_constructor([param('uint32_t', 'systemId')]) + ## node.h (module 'network'): uint32_t ns3::Node::AddApplication(ns3::Ptr application) [member function] + cls.add_method('AddApplication', + 'uint32_t', + [param('ns3::Ptr< ns3::Application >', 'application')]) + ## node.h (module 'network'): uint32_t ns3::Node::AddDevice(ns3::Ptr device) [member function] + cls.add_method('AddDevice', + 'uint32_t', + [param('ns3::Ptr< ns3::NetDevice >', 'device')]) + ## node.h (module 'network'): static bool ns3::Node::ChecksumEnabled() [member function] + cls.add_method('ChecksumEnabled', + 'bool', + [], + is_static=True) + ## node.h (module 'network'): ns3::Ptr ns3::Node::GetApplication(uint32_t index) const [member function] + cls.add_method('GetApplication', + 'ns3::Ptr< ns3::Application >', + [param('uint32_t', 'index')], + is_const=True) + ## node.h (module 'network'): ns3::Ptr ns3::Node::GetDevice(uint32_t index) const [member function] + cls.add_method('GetDevice', + 'ns3::Ptr< ns3::NetDevice >', + [param('uint32_t', 'index')], + is_const=True) + ## node.h (module 'network'): uint32_t ns3::Node::GetId() const [member function] + cls.add_method('GetId', + 'uint32_t', + [], + is_const=True) + ## node.h (module 'network'): uint32_t ns3::Node::GetNApplications() const [member function] + cls.add_method('GetNApplications', + 'uint32_t', + [], + is_const=True) + ## node.h (module 'network'): uint32_t ns3::Node::GetNDevices() const [member function] + cls.add_method('GetNDevices', + 'uint32_t', + [], + is_const=True) + ## node.h (module 'network'): uint32_t ns3::Node::GetSystemId() const [member function] + cls.add_method('GetSystemId', + 'uint32_t', + [], + is_const=True) + ## node.h (module 'network'): static ns3::TypeId ns3::Node::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## node.h (module 'network'): void ns3::Node::RegisterDeviceAdditionListener(ns3::Callback,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] + cls.add_method('RegisterDeviceAdditionListener', + 'void', + [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) + ## node.h (module 'network'): void ns3::Node::RegisterProtocolHandler(ns3::Callback, ns3::Ptr, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler, uint16_t protocolType, ns3::Ptr device, bool promiscuous=false) [member function] + cls.add_method('RegisterProtocolHandler', + 'void', + [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler'), param('uint16_t', 'protocolType'), param('ns3::Ptr< ns3::NetDevice >', 'device'), param('bool', 'promiscuous', default_value='false')]) + ## node.h (module 'network'): void ns3::Node::UnregisterDeviceAdditionListener(ns3::Callback,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty,ns3::empty> listener) [member function] + cls.add_method('UnregisterDeviceAdditionListener', + 'void', + [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'listener')]) + ## node.h (module 'network'): void ns3::Node::UnregisterProtocolHandler(ns3::Callback, ns3::Ptr, unsigned short, ns3::Address const&, ns3::Address const&, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty> handler) [member function] + cls.add_method('UnregisterProtocolHandler', + 'void', + [param('ns3::Callback< void, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'handler')]) + ## node.h (module 'network'): void ns3::Node::DoDispose() [member function] + cls.add_method('DoDispose', + 'void', + [], + visibility='protected', is_virtual=True) + ## node.h (module 'network'): void ns3::Node::DoStart() [member function] + cls.add_method('DoStart', + 'void', + [], + visibility='protected', is_virtual=True) + return + +def register_Ns3ObjectFactoryChecker_methods(root_module, cls): + ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker() [constructor] + cls.add_constructor([]) + ## object-factory.h (module 'core'): ns3::ObjectFactoryChecker::ObjectFactoryChecker(ns3::ObjectFactoryChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::ObjectFactoryChecker const &', 'arg0')]) + return + +def register_Ns3ObjectFactoryValue_methods(root_module, cls): + ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue() [constructor] + cls.add_constructor([]) + ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactoryValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::ObjectFactoryValue const &', 'arg0')]) + ## object-factory.h (module 'core'): ns3::ObjectFactoryValue::ObjectFactoryValue(ns3::ObjectFactory const & value) [constructor] + cls.add_constructor([param('ns3::ObjectFactory const &', 'value')]) + ## object-factory.h (module 'core'): ns3::Ptr ns3::ObjectFactoryValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## object-factory.h (module 'core'): bool ns3::ObjectFactoryValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## object-factory.h (module 'core'): ns3::ObjectFactory ns3::ObjectFactoryValue::Get() const [member function] + cls.add_method('Get', + 'ns3::ObjectFactory', + [], + is_const=True) + ## object-factory.h (module 'core'): std::string ns3::ObjectFactoryValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## object-factory.h (module 'core'): void ns3::ObjectFactoryValue::Set(ns3::ObjectFactory const & value) [member function] + cls.add_method('Set', + 'void', + [param('ns3::ObjectFactory const &', 'value')]) + return + +def register_Ns3Packet_methods(root_module, cls): + cls.add_output_stream_operator() + ## packet.h (module 'network'): ns3::Packet::Packet() [constructor] + cls.add_constructor([]) + ## packet.h (module 'network'): ns3::Packet::Packet(ns3::Packet const & o) [copy constructor] + cls.add_constructor([param('ns3::Packet const &', 'o')]) + ## packet.h (module 'network'): ns3::Packet::Packet(uint32_t size) [constructor] + cls.add_constructor([param('uint32_t', 'size')]) + ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size, bool magic) [constructor] + cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size'), param('bool', 'magic')]) + ## packet.h (module 'network'): ns3::Packet::Packet(uint8_t const * buffer, uint32_t size) [constructor] + cls.add_constructor([param('uint8_t const *', 'buffer'), param('uint32_t', 'size')]) + ## packet.h (module 'network'): void ns3::Packet::AddAtEnd(ns3::Ptr packet) [member function] + cls.add_method('AddAtEnd', + 'void', + [param('ns3::Ptr< ns3::Packet const >', 'packet')]) + ## packet.h (module 'network'): void ns3::Packet::AddByteTag(ns3::Tag const & tag) const [member function] + cls.add_method('AddByteTag', + 'void', + [param('ns3::Tag const &', 'tag')], + is_const=True) + ## packet.h (module 'network'): void ns3::Packet::AddHeader(ns3::Header const & header) [member function] + cls.add_method('AddHeader', + 'void', + [param('ns3::Header const &', 'header')]) + ## packet.h (module 'network'): void ns3::Packet::AddPacketTag(ns3::Tag const & tag) const [member function] + cls.add_method('AddPacketTag', + 'void', + [param('ns3::Tag const &', 'tag')], + is_const=True) + ## packet.h (module 'network'): void ns3::Packet::AddPaddingAtEnd(uint32_t size) [member function] + cls.add_method('AddPaddingAtEnd', + 'void', + [param('uint32_t', 'size')]) + ## packet.h (module 'network'): void ns3::Packet::AddTrailer(ns3::Trailer const & trailer) [member function] + cls.add_method('AddTrailer', + 'void', + [param('ns3::Trailer const &', 'trailer')]) + ## packet.h (module 'network'): ns3::PacketMetadata::ItemIterator ns3::Packet::BeginItem() const [member function] + cls.add_method('BeginItem', + 'ns3::PacketMetadata::ItemIterator', + [], + is_const=True) + ## packet.h (module 'network'): ns3::Ptr ns3::Packet::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::Packet >', + [], + is_const=True) + ## packet.h (module 'network'): uint32_t ns3::Packet::CopyData(uint8_t * buffer, uint32_t size) const [member function] + cls.add_method('CopyData', + 'uint32_t', + [param('uint8_t *', 'buffer'), param('uint32_t', 'size')], + is_const=True) + ## packet.h (module 'network'): void ns3::Packet::CopyData(std::ostream * os, uint32_t size) const [member function] + cls.add_method('CopyData', + 'void', + [param('std::ostream *', 'os'), param('uint32_t', 'size')], + is_const=True) + ## packet.h (module 'network'): ns3::Ptr ns3::Packet::CreateFragment(uint32_t start, uint32_t length) const [member function] + cls.add_method('CreateFragment', + 'ns3::Ptr< ns3::Packet >', + [param('uint32_t', 'start'), param('uint32_t', 'length')], + is_const=True) + ## packet.h (module 'network'): static void ns3::Packet::EnableChecking() [member function] + cls.add_method('EnableChecking', + 'void', + [], + is_static=True) + ## packet.h (module 'network'): static void ns3::Packet::EnablePrinting() [member function] + cls.add_method('EnablePrinting', + 'void', + [], + is_static=True) + ## packet.h (module 'network'): bool ns3::Packet::FindFirstMatchingByteTag(ns3::Tag & tag) const [member function] + cls.add_method('FindFirstMatchingByteTag', + 'bool', + [param('ns3::Tag &', 'tag')], + is_const=True) + ## packet.h (module 'network'): ns3::ByteTagIterator ns3::Packet::GetByteTagIterator() const [member function] + cls.add_method('GetByteTagIterator', + 'ns3::ByteTagIterator', + [], + is_const=True) + ## packet.h (module 'network'): ns3::Ptr ns3::Packet::GetNixVector() const [member function] + cls.add_method('GetNixVector', + 'ns3::Ptr< ns3::NixVector >', + [], + is_const=True) + ## packet.h (module 'network'): ns3::PacketTagIterator ns3::Packet::GetPacketTagIterator() const [member function] + cls.add_method('GetPacketTagIterator', + 'ns3::PacketTagIterator', + [], + is_const=True) + ## packet.h (module 'network'): uint32_t ns3::Packet::GetSerializedSize() const [member function] + cls.add_method('GetSerializedSize', + 'uint32_t', + [], + is_const=True) + ## packet.h (module 'network'): uint32_t ns3::Packet::GetSize() const [member function] + cls.add_method('GetSize', + 'uint32_t', + [], + is_const=True) + ## packet.h (module 'network'): uint64_t ns3::Packet::GetUid() const [member function] + cls.add_method('GetUid', + 'uint64_t', + [], + is_const=True) + ## packet.h (module 'network'): uint8_t const * ns3::Packet::PeekData() const [member function] + cls.add_method('PeekData', + 'uint8_t const *', + [], + deprecated=True, is_const=True) + ## packet.h (module 'network'): uint32_t ns3::Packet::PeekHeader(ns3::Header & header) const [member function] + cls.add_method('PeekHeader', + 'uint32_t', + [param('ns3::Header &', 'header')], + is_const=True) + ## packet.h (module 'network'): bool ns3::Packet::PeekPacketTag(ns3::Tag & tag) const [member function] + cls.add_method('PeekPacketTag', + 'bool', + [param('ns3::Tag &', 'tag')], + is_const=True) + ## packet.h (module 'network'): uint32_t ns3::Packet::PeekTrailer(ns3::Trailer & trailer) [member function] + cls.add_method('PeekTrailer', + 'uint32_t', + [param('ns3::Trailer &', 'trailer')]) + ## packet.h (module 'network'): void ns3::Packet::Print(std::ostream & os) const [member function] + cls.add_method('Print', + 'void', + [param('std::ostream &', 'os')], + is_const=True) + ## packet.h (module 'network'): void ns3::Packet::PrintByteTags(std::ostream & os) const [member function] + cls.add_method('PrintByteTags', + 'void', + [param('std::ostream &', 'os')], + is_const=True) + ## packet.h (module 'network'): void ns3::Packet::PrintPacketTags(std::ostream & os) const [member function] + cls.add_method('PrintPacketTags', + 'void', + [param('std::ostream &', 'os')], + is_const=True) + ## packet.h (module 'network'): void ns3::Packet::RemoveAllByteTags() [member function] + cls.add_method('RemoveAllByteTags', + 'void', + []) + ## packet.h (module 'network'): void ns3::Packet::RemoveAllPacketTags() [member function] + cls.add_method('RemoveAllPacketTags', + 'void', + []) + ## packet.h (module 'network'): void ns3::Packet::RemoveAtEnd(uint32_t size) [member function] + cls.add_method('RemoveAtEnd', + 'void', + [param('uint32_t', 'size')]) + ## packet.h (module 'network'): void ns3::Packet::RemoveAtStart(uint32_t size) [member function] + cls.add_method('RemoveAtStart', + 'void', + [param('uint32_t', 'size')]) + ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveHeader(ns3::Header & header) [member function] + cls.add_method('RemoveHeader', + 'uint32_t', + [param('ns3::Header &', 'header')]) + ## packet.h (module 'network'): bool ns3::Packet::RemovePacketTag(ns3::Tag & tag) [member function] + cls.add_method('RemovePacketTag', + 'bool', + [param('ns3::Tag &', 'tag')]) + ## packet.h (module 'network'): uint32_t ns3::Packet::RemoveTrailer(ns3::Trailer & trailer) [member function] + cls.add_method('RemoveTrailer', + 'uint32_t', + [param('ns3::Trailer &', 'trailer')]) + ## packet.h (module 'network'): uint32_t ns3::Packet::Serialize(uint8_t * buffer, uint32_t maxSize) const [member function] + cls.add_method('Serialize', + 'uint32_t', + [param('uint8_t *', 'buffer'), param('uint32_t', 'maxSize')], + is_const=True) + ## packet.h (module 'network'): void ns3::Packet::SetNixVector(ns3::Ptr arg0) [member function] + cls.add_method('SetNixVector', + 'void', + [param('ns3::Ptr< ns3::NixVector >', 'arg0')]) + return + +def register_Ns3PointerChecker_methods(root_module, cls): + ## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker() [constructor] + cls.add_constructor([]) + ## pointer.h (module 'core'): ns3::PointerChecker::PointerChecker(ns3::PointerChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::PointerChecker const &', 'arg0')]) + ## pointer.h (module 'core'): ns3::TypeId ns3::PointerChecker::GetPointeeTypeId() const [member function] + cls.add_method('GetPointeeTypeId', + 'ns3::TypeId', + [], + is_pure_virtual=True, is_const=True, is_virtual=True) + return + +def register_Ns3PointerValue_methods(root_module, cls): + ## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::PointerValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::PointerValue const &', 'arg0')]) + ## pointer.h (module 'core'): ns3::PointerValue::PointerValue() [constructor] + cls.add_constructor([]) + ## pointer.h (module 'core'): ns3::PointerValue::PointerValue(ns3::Ptr object) [constructor] + cls.add_constructor([param('ns3::Ptr< ns3::Object >', 'object')]) + ## pointer.h (module 'core'): ns3::Ptr ns3::PointerValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## pointer.h (module 'core'): bool ns3::PointerValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## pointer.h (module 'core'): ns3::Ptr ns3::PointerValue::GetObject() const [member function] + cls.add_method('GetObject', + 'ns3::Ptr< ns3::Object >', + [], + is_const=True) + ## pointer.h (module 'core'): std::string ns3::PointerValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## pointer.h (module 'core'): void ns3::PointerValue::SetObject(ns3::Ptr object) [member function] + cls.add_method('SetObject', + 'void', + [param('ns3::Ptr< ns3::Object >', 'object')]) + return + +def register_Ns3TimeChecker_methods(root_module, cls): + ## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker() [constructor] + cls.add_constructor([]) + ## nstime.h (module 'core'): ns3::TimeChecker::TimeChecker(ns3::TimeChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::TimeChecker const &', 'arg0')]) + return + +def register_Ns3TimeValue_methods(root_module, cls): + ## nstime.h (module 'core'): ns3::TimeValue::TimeValue() [constructor] + cls.add_constructor([]) + ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::TimeValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::TimeValue const &', 'arg0')]) + ## nstime.h (module 'core'): ns3::TimeValue::TimeValue(ns3::Time const & value) [constructor] + cls.add_constructor([param('ns3::Time const &', 'value')]) + ## nstime.h (module 'core'): ns3::Ptr ns3::TimeValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## nstime.h (module 'core'): bool ns3::TimeValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## nstime.h (module 'core'): ns3::Time ns3::TimeValue::Get() const [member function] + cls.add_method('Get', + 'ns3::Time', + [], + is_const=True) + ## nstime.h (module 'core'): std::string ns3::TimeValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## nstime.h (module 'core'): void ns3::TimeValue::Set(ns3::Time const & value) [member function] + cls.add_method('Set', + 'void', + [param('ns3::Time const &', 'value')]) + return + +def register_Ns3TypeIdChecker_methods(root_module, cls): + ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker() [constructor] + cls.add_constructor([]) + ## type-id.h (module 'core'): ns3::TypeIdChecker::TypeIdChecker(ns3::TypeIdChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::TypeIdChecker const &', 'arg0')]) + return + +def register_Ns3TypeIdValue_methods(root_module, cls): + ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue() [constructor] + cls.add_constructor([]) + ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeIdValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::TypeIdValue const &', 'arg0')]) + ## type-id.h (module 'core'): ns3::TypeIdValue::TypeIdValue(ns3::TypeId const & value) [constructor] + cls.add_constructor([param('ns3::TypeId const &', 'value')]) + ## type-id.h (module 'core'): ns3::Ptr ns3::TypeIdValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## type-id.h (module 'core'): bool ns3::TypeIdValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## type-id.h (module 'core'): ns3::TypeId ns3::TypeIdValue::Get() const [member function] + cls.add_method('Get', + 'ns3::TypeId', + [], + is_const=True) + ## type-id.h (module 'core'): std::string ns3::TypeIdValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## type-id.h (module 'core'): void ns3::TypeIdValue::Set(ns3::TypeId const & value) [member function] + cls.add_method('Set', + 'void', + [param('ns3::TypeId const &', 'value')]) + return + +def register_Ns3UanChannel_methods(root_module, cls): + ## uan-channel.h (module 'uan'): ns3::UanChannel::UanChannel(ns3::UanChannel const & arg0) [copy constructor] + cls.add_constructor([param('ns3::UanChannel const &', 'arg0')]) + ## uan-channel.h (module 'uan'): ns3::UanChannel::UanChannel() [constructor] + cls.add_constructor([]) + ## uan-channel.h (module 'uan'): void ns3::UanChannel::AddDevice(ns3::Ptr dev, ns3::Ptr trans) [member function] + cls.add_method('AddDevice', + 'void', + [param('ns3::Ptr< ns3::UanNetDevice >', 'dev'), param('ns3::Ptr< ns3::UanTransducer >', 'trans')]) + ## uan-channel.h (module 'uan'): void ns3::UanChannel::Clear() [member function] + cls.add_method('Clear', + 'void', + []) + ## uan-channel.h (module 'uan'): ns3::Ptr ns3::UanChannel::GetDevice(uint32_t i) const [member function] + cls.add_method('GetDevice', + 'ns3::Ptr< ns3::NetDevice >', + [param('uint32_t', 'i')], + is_const=True, is_virtual=True) + ## uan-channel.h (module 'uan'): uint32_t ns3::UanChannel::GetNDevices() const [member function] + cls.add_method('GetNDevices', + 'uint32_t', + [], + is_const=True, is_virtual=True) + ## uan-channel.h (module 'uan'): double ns3::UanChannel::GetNoiseDbHz(double fKhz) [member function] + cls.add_method('GetNoiseDbHz', + 'double', + [param('double', 'fKhz')]) + ## uan-channel.h (module 'uan'): static ns3::TypeId ns3::UanChannel::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## uan-channel.h (module 'uan'): void ns3::UanChannel::SetNoiseModel(ns3::Ptr noise) [member function] + cls.add_method('SetNoiseModel', + 'void', + [param('ns3::Ptr< ns3::UanNoiseModel >', 'noise')]) + ## uan-channel.h (module 'uan'): void ns3::UanChannel::SetPropagationModel(ns3::Ptr prop) [member function] + cls.add_method('SetPropagationModel', + 'void', + [param('ns3::Ptr< ns3::UanPropModel >', 'prop')]) + ## uan-channel.h (module 'uan'): void ns3::UanChannel::TxPacket(ns3::Ptr src, ns3::Ptr packet, double txPowerDb, ns3::UanTxMode txmode) [member function] + cls.add_method('TxPacket', + 'void', + [param('ns3::Ptr< ns3::UanTransducer >', 'src'), param('ns3::Ptr< ns3::Packet >', 'packet'), param('double', 'txPowerDb'), param('ns3::UanTxMode', 'txmode')]) + ## uan-channel.h (module 'uan'): void ns3::UanChannel::DoDispose() [member function] + cls.add_method('DoDispose', + 'void', + [], + visibility='protected', is_virtual=True) + return + +def register_Ns3UanModesListChecker_methods(root_module, cls): + ## uan-tx-mode.h (module 'uan'): ns3::UanModesListChecker::UanModesListChecker() [constructor] + cls.add_constructor([]) + ## uan-tx-mode.h (module 'uan'): ns3::UanModesListChecker::UanModesListChecker(ns3::UanModesListChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::UanModesListChecker const &', 'arg0')]) + return + +def register_Ns3UanModesListValue_methods(root_module, cls): + ## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue() [constructor] + cls.add_constructor([]) + ## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue(ns3::UanModesListValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::UanModesListValue const &', 'arg0')]) + ## uan-tx-mode.h (module 'uan'): ns3::UanModesListValue::UanModesListValue(ns3::UanModesList const & value) [constructor] + cls.add_constructor([param('ns3::UanModesList const &', 'value')]) + ## uan-tx-mode.h (module 'uan'): ns3::Ptr ns3::UanModesListValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## uan-tx-mode.h (module 'uan'): bool ns3::UanModesListValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## uan-tx-mode.h (module 'uan'): ns3::UanModesList ns3::UanModesListValue::Get() const [member function] + cls.add_method('Get', + 'ns3::UanModesList', + [], + is_const=True) + ## uan-tx-mode.h (module 'uan'): std::string ns3::UanModesListValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## uan-tx-mode.h (module 'uan'): void ns3::UanModesListValue::Set(ns3::UanModesList const & value) [member function] + cls.add_method('Set', + 'void', + [param('ns3::UanModesList const &', 'value')]) + return + +def register_Ns3UanNetDevice_methods(root_module, cls): + ## uan-net-device.h (module 'uan'): ns3::UanNetDevice::UanNetDevice(ns3::UanNetDevice const & arg0) [copy constructor] + cls.add_constructor([param('ns3::UanNetDevice const &', 'arg0')]) + ## uan-net-device.h (module 'uan'): ns3::UanNetDevice::UanNetDevice() [constructor] + cls.add_constructor([]) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::AddLinkChangeCallback(ns3::Callback callback) [member function] + cls.add_method('AddLinkChangeCallback', + 'void', + [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')], + is_virtual=True) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::Clear() [member function] + cls.add_method('Clear', + 'void', + []) + ## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetAddress() const [member function] + cls.add_method('GetAddress', + 'ns3::Address', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetBroadcast() const [member function] + cls.add_method('GetBroadcast', + 'ns3::Address', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): ns3::Ptr ns3::UanNetDevice::GetChannel() const [member function] + cls.add_method('GetChannel', + 'ns3::Ptr< ns3::Channel >', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): uint32_t ns3::UanNetDevice::GetIfIndex() const [member function] + cls.add_method('GetIfIndex', + 'uint32_t', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): ns3::Ptr ns3::UanNetDevice::GetMac() const [member function] + cls.add_method('GetMac', + 'ns3::Ptr< ns3::UanMac >', + [], + is_const=True) + ## uan-net-device.h (module 'uan'): uint16_t ns3::UanNetDevice::GetMtu() const [member function] + cls.add_method('GetMtu', + 'uint16_t', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetMulticast(ns3::Ipv4Address multicastGroup) const [member function] + cls.add_method('GetMulticast', + 'ns3::Address', + [param('ns3::Ipv4Address', 'multicastGroup')], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): ns3::Address ns3::UanNetDevice::GetMulticast(ns3::Ipv6Address addr) const [member function] + cls.add_method('GetMulticast', + 'ns3::Address', + [param('ns3::Ipv6Address', 'addr')], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): ns3::Ptr ns3::UanNetDevice::GetNode() const [member function] + cls.add_method('GetNode', + 'ns3::Ptr< ns3::Node >', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): ns3::Ptr ns3::UanNetDevice::GetPhy() const [member function] + cls.add_method('GetPhy', + 'ns3::Ptr< ns3::UanPhy >', + [], + is_const=True) + ## uan-net-device.h (module 'uan'): ns3::Ptr ns3::UanNetDevice::GetTransducer() const [member function] + cls.add_method('GetTransducer', + 'ns3::Ptr< ns3::UanTransducer >', + [], + is_const=True) + ## uan-net-device.h (module 'uan'): static ns3::TypeId ns3::UanNetDevice::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsBridge() const [member function] + cls.add_method('IsBridge', + 'bool', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsBroadcast() const [member function] + cls.add_method('IsBroadcast', + 'bool', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsLinkUp() const [member function] + cls.add_method('IsLinkUp', + 'bool', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsMulticast() const [member function] + cls.add_method('IsMulticast', + 'bool', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::IsPointToPoint() const [member function] + cls.add_method('IsPointToPoint', + 'bool', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::NeedsArp() const [member function] + cls.add_method('NeedsArp', + 'bool', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::Send(ns3::Ptr packet, ns3::Address const & dest, uint16_t protocolNumber) [member function] + cls.add_method('Send', + 'bool', + [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], + is_virtual=True) + ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SendFrom(ns3::Ptr packet, ns3::Address const & source, ns3::Address const & dest, uint16_t protocolNumber) [member function] + cls.add_method('SendFrom', + 'bool', + [param('ns3::Ptr< ns3::Packet >', 'packet'), param('ns3::Address const &', 'source'), param('ns3::Address const &', 'dest'), param('uint16_t', 'protocolNumber')], + is_virtual=True) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetAddress(ns3::Address address) [member function] + cls.add_method('SetAddress', + 'void', + [param('ns3::Address', 'address')], + is_virtual=True) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetChannel(ns3::Ptr channel) [member function] + cls.add_method('SetChannel', + 'void', + [param('ns3::Ptr< ns3::UanChannel >', 'channel')]) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetIfIndex(uint32_t const index) [member function] + cls.add_method('SetIfIndex', + 'void', + [param('uint32_t const', 'index')], + is_virtual=True) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetMac(ns3::Ptr mac) [member function] + cls.add_method('SetMac', + 'void', + [param('ns3::Ptr< ns3::UanMac >', 'mac')]) + ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SetMtu(uint16_t const mtu) [member function] + cls.add_method('SetMtu', + 'bool', + [param('uint16_t const', 'mtu')], + is_virtual=True) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetNode(ns3::Ptr node) [member function] + cls.add_method('SetNode', + 'void', + [param('ns3::Ptr< ns3::Node >', 'node')], + is_virtual=True) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetPhy(ns3::Ptr phy) [member function] + cls.add_method('SetPhy', + 'void', + [param('ns3::Ptr< ns3::UanPhy >', 'phy')]) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetPromiscReceiveCallback(ns3::Callback,ns3::Ptr,short unsigned int,const ns3::Address&,const ns3::Address&,ns3::NetDevice::PacketType,ns3::empty,ns3::empty,ns3::empty> cb) [member function] + cls.add_method('SetPromiscReceiveCallback', + 'void', + [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, short unsigned int, ns3::Address const &, ns3::Address const &, ns3::NetDevice::PacketType, ns3::empty, ns3::empty, ns3::empty >', 'cb')], + is_virtual=True) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetReceiveCallback(ns3::Callback, ns3::Ptr, unsigned short, ns3::Address const&, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty> cb) [member function] + cls.add_method('SetReceiveCallback', + 'void', + [param('ns3::Callback< bool, ns3::Ptr< ns3::NetDevice >, ns3::Ptr< ns3::Packet const >, unsigned short, ns3::Address const &, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'cb')], + is_virtual=True) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetSleepMode(bool sleep) [member function] + cls.add_method('SetSleepMode', + 'void', + [param('bool', 'sleep')]) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::SetTransducer(ns3::Ptr trans) [member function] + cls.add_method('SetTransducer', + 'void', + [param('ns3::Ptr< ns3::UanTransducer >', 'trans')]) + ## uan-net-device.h (module 'uan'): bool ns3::UanNetDevice::SupportsSendFrom() const [member function] + cls.add_method('SupportsSendFrom', + 'bool', + [], + is_const=True, is_virtual=True) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::DoDispose() [member function] + cls.add_method('DoDispose', + 'void', + [], + visibility='protected', is_virtual=True) + ## uan-net-device.h (module 'uan'): void ns3::UanNetDevice::ForwardUp(ns3::Ptr pkt, ns3::UanAddress const & src) [member function] + cls.add_method('ForwardUp', + 'void', + [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('ns3::UanAddress const &', 'src')], + visibility='private', is_virtual=True) + return + +def register_Ns3UintegerValue_methods(root_module, cls): + ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue() [constructor] + cls.add_constructor([]) + ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(ns3::UintegerValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::UintegerValue const &', 'arg0')]) + ## uinteger.h (module 'core'): ns3::UintegerValue::UintegerValue(uint64_t const & value) [constructor] + cls.add_constructor([param('uint64_t const &', 'value')]) + ## uinteger.h (module 'core'): ns3::Ptr ns3::UintegerValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## uinteger.h (module 'core'): bool ns3::UintegerValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## uinteger.h (module 'core'): uint64_t ns3::UintegerValue::Get() const [member function] + cls.add_method('Get', + 'uint64_t', + [], + is_const=True) + ## uinteger.h (module 'core'): std::string ns3::UintegerValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## uinteger.h (module 'core'): void ns3::UintegerValue::Set(uint64_t const & value) [member function] + cls.add_method('Set', + 'void', + [param('uint64_t const &', 'value')]) + return + +def register_Ns3Vector2DChecker_methods(root_module, cls): + ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker() [constructor] + cls.add_constructor([]) + ## vector.h (module 'core'): ns3::Vector2DChecker::Vector2DChecker(ns3::Vector2DChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Vector2DChecker const &', 'arg0')]) + return + +def register_Ns3Vector2DValue_methods(root_module, cls): + ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue() [constructor] + cls.add_constructor([]) + ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2DValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Vector2DValue const &', 'arg0')]) + ## vector.h (module 'core'): ns3::Vector2DValue::Vector2DValue(ns3::Vector2D const & value) [constructor] + cls.add_constructor([param('ns3::Vector2D const &', 'value')]) + ## vector.h (module 'core'): ns3::Ptr ns3::Vector2DValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## vector.h (module 'core'): bool ns3::Vector2DValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## vector.h (module 'core'): ns3::Vector2D ns3::Vector2DValue::Get() const [member function] + cls.add_method('Get', + 'ns3::Vector2D', + [], + is_const=True) + ## vector.h (module 'core'): std::string ns3::Vector2DValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## vector.h (module 'core'): void ns3::Vector2DValue::Set(ns3::Vector2D const & value) [member function] + cls.add_method('Set', + 'void', + [param('ns3::Vector2D const &', 'value')]) + return + +def register_Ns3Vector3DChecker_methods(root_module, cls): + ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker() [constructor] + cls.add_constructor([]) + ## vector.h (module 'core'): ns3::Vector3DChecker::Vector3DChecker(ns3::Vector3DChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Vector3DChecker const &', 'arg0')]) + return + +def register_Ns3Vector3DValue_methods(root_module, cls): + ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue() [constructor] + cls.add_constructor([]) + ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3DValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::Vector3DValue const &', 'arg0')]) + ## vector.h (module 'core'): ns3::Vector3DValue::Vector3DValue(ns3::Vector3D const & value) [constructor] + cls.add_constructor([param('ns3::Vector3D const &', 'value')]) + ## vector.h (module 'core'): ns3::Ptr ns3::Vector3DValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## vector.h (module 'core'): bool ns3::Vector3DValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## vector.h (module 'core'): ns3::Vector3D ns3::Vector3DValue::Get() const [member function] + cls.add_method('Get', + 'ns3::Vector3D', + [], + is_const=True) + ## vector.h (module 'core'): std::string ns3::Vector3DValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## vector.h (module 'core'): void ns3::Vector3DValue::Set(ns3::Vector3D const & value) [member function] + cls.add_method('Set', + 'void', + [param('ns3::Vector3D const &', 'value')]) + return + +def register_Ns3AcousticModemEnergyModel_methods(root_module, cls): + ## acoustic-modem-energy-model.h (module 'uan'): ns3::AcousticModemEnergyModel::AcousticModemEnergyModel(ns3::AcousticModemEnergyModel const & arg0) [copy constructor] + cls.add_constructor([param('ns3::AcousticModemEnergyModel const &', 'arg0')]) + ## acoustic-modem-energy-model.h (module 'uan'): ns3::AcousticModemEnergyModel::AcousticModemEnergyModel() [constructor] + cls.add_constructor([]) + ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::ChangeState(int newState) [member function] + cls.add_method('ChangeState', + 'void', + [param('int', 'newState')], + is_virtual=True) + ## acoustic-modem-energy-model.h (module 'uan'): int ns3::AcousticModemEnergyModel::GetCurrentState() const [member function] + cls.add_method('GetCurrentState', + 'int', + [], + is_const=True) + ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetIdlePowerW() const [member function] + cls.add_method('GetIdlePowerW', + 'double', + [], + is_const=True) + ## acoustic-modem-energy-model.h (module 'uan'): ns3::Ptr ns3::AcousticModemEnergyModel::GetNode() const [member function] + cls.add_method('GetNode', + 'ns3::Ptr< ns3::Node >', + [], + is_const=True, is_virtual=True) + ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetRxPowerW() const [member function] + cls.add_method('GetRxPowerW', + 'double', + [], + is_const=True) + ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetSleepPowerW() const [member function] + cls.add_method('GetSleepPowerW', + 'double', + [], + is_const=True) + ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetTotalEnergyConsumption() const [member function] + cls.add_method('GetTotalEnergyConsumption', + 'double', + [], + is_const=True, is_virtual=True) + ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::GetTxPowerW() const [member function] + cls.add_method('GetTxPowerW', + 'double', + [], + is_const=True) + ## acoustic-modem-energy-model.h (module 'uan'): static ns3::TypeId ns3::AcousticModemEnergyModel::GetTypeId() [member function] + cls.add_method('GetTypeId', + 'ns3::TypeId', + [], + is_static=True) + ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::HandleEnergyDepletion() [member function] + cls.add_method('HandleEnergyDepletion', + 'void', + [], + is_virtual=True) + ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetEnergyDepletionCallback(ns3::Callback callback) [member function] + cls.add_method('SetEnergyDepletionCallback', + 'void', + [param('ns3::Callback< void, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty, ns3::empty >', 'callback')]) + ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetEnergySource(ns3::Ptr source) [member function] + cls.add_method('SetEnergySource', + 'void', + [param('ns3::Ptr< ns3::EnergySource >', 'source')], + is_virtual=True) + ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetIdlePowerW(double idlePowerW) [member function] + cls.add_method('SetIdlePowerW', + 'void', + [param('double', 'idlePowerW')]) + ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetNode(ns3::Ptr node) [member function] + cls.add_method('SetNode', + 'void', + [param('ns3::Ptr< ns3::Node >', 'node')], + is_virtual=True) + ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetRxPowerW(double rxPowerW) [member function] + cls.add_method('SetRxPowerW', + 'void', + [param('double', 'rxPowerW')]) + ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetSleepPowerW(double sleepPowerW) [member function] + cls.add_method('SetSleepPowerW', + 'void', + [param('double', 'sleepPowerW')]) + ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::SetTxPowerW(double txPowerW) [member function] + cls.add_method('SetTxPowerW', + 'void', + [param('double', 'txPowerW')]) + ## acoustic-modem-energy-model.h (module 'uan'): void ns3::AcousticModemEnergyModel::DoDispose() [member function] + cls.add_method('DoDispose', + 'void', + [], + visibility='private', is_virtual=True) + ## acoustic-modem-energy-model.h (module 'uan'): double ns3::AcousticModemEnergyModel::DoGetCurrentA() const [member function] + cls.add_method('DoGetCurrentA', + 'double', + [], + is_const=True, visibility='private', is_virtual=True) + return + +def register_Ns3AddressChecker_methods(root_module, cls): + ## address.h (module 'network'): ns3::AddressChecker::AddressChecker() [constructor] + cls.add_constructor([]) + ## address.h (module 'network'): ns3::AddressChecker::AddressChecker(ns3::AddressChecker const & arg0) [copy constructor] + cls.add_constructor([param('ns3::AddressChecker const &', 'arg0')]) + return + +def register_Ns3AddressValue_methods(root_module, cls): + ## address.h (module 'network'): ns3::AddressValue::AddressValue() [constructor] + cls.add_constructor([]) + ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::AddressValue const & arg0) [copy constructor] + cls.add_constructor([param('ns3::AddressValue const &', 'arg0')]) + ## address.h (module 'network'): ns3::AddressValue::AddressValue(ns3::Address const & value) [constructor] + cls.add_constructor([param('ns3::Address const &', 'value')]) + ## address.h (module 'network'): ns3::Ptr ns3::AddressValue::Copy() const [member function] + cls.add_method('Copy', + 'ns3::Ptr< ns3::AttributeValue >', + [], + is_const=True, is_virtual=True) + ## address.h (module 'network'): bool ns3::AddressValue::DeserializeFromString(std::string value, ns3::Ptr checker) [member function] + cls.add_method('DeserializeFromString', + 'bool', + [param('std::string', 'value'), param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_virtual=True) + ## address.h (module 'network'): ns3::Address ns3::AddressValue::Get() const [member function] + cls.add_method('Get', + 'ns3::Address', + [], + is_const=True) + ## address.h (module 'network'): std::string ns3::AddressValue::SerializeToString(ns3::Ptr checker) const [member function] + cls.add_method('SerializeToString', + 'std::string', + [param('ns3::Ptr< ns3::AttributeChecker const >', 'checker')], + is_const=True, is_virtual=True) + ## address.h (module 'network'): void ns3::AddressValue::Set(ns3::Address const & value) [member function] + cls.add_method('Set', + 'void', + [param('ns3::Address const &', 'value')]) + return + +def register_functions(root_module): + module = root_module + ## uan-tx-mode.h (module 'uan'): extern ns3::Ptr ns3::MakeUanModesListChecker() [free function] + module.add_function('MakeUanModesListChecker', + 'ns3::Ptr< ns3::AttributeChecker const >', + []) + register_functions_ns3_FatalImpl(module.get_submodule('FatalImpl'), root_module) + register_functions_ns3_internal(module.get_submodule('internal'), root_module) + return + +def register_functions_ns3_FatalImpl(module, root_module): + return + +def register_functions_ns3_internal(module, root_module): + return + +def main(): + out = FileCodeSink(sys.stdout) + root_module = module_init() + register_types(root_module) + register_methods(root_module) + register_functions(root_module) + root_module.generate(out) + +if __name__ == '__main__': + main() + + +# -*- test-case-name: twisted.news.test -*- +# Copyright (c) 2001-2010 Twisted Matrix Laboratories. +# See LICENSE for details. + +""" +News server backend implementations. +""" + +import getpass, pickle, time, socket +import os +import StringIO +from email.Message import Message +from email.Generator import Generator +from zope.interface import implements, Interface + +from twisted.news.nntp import NNTPError +from twisted.mail import smtp +from twisted.internet import defer +from twisted.enterprise import adbapi +from twisted.persisted import dirdbm +from twisted.python.hashlib import md5 + + + +ERR_NOGROUP, ERR_NOARTICLE = range(2, 4) # XXX - put NNTP values here (I guess?) + +OVERVIEW_FMT = [ + 'Subject', 'From', 'Date', 'Message-ID', 'References', + 'Bytes', 'Lines', 'Xref' +] + +def hexdigest(md5): #XXX: argh. 1.5.2 doesn't have this. + return ''.join(map(lambda x: hex(ord(x))[2:], md5.digest())) + +class Article: + def __init__(self, head, body): + self.body = body + self.headers = {} + header = None + for line in head.split('\r\n'): + if line[0] in ' \t': + i = list(self.headers[header]) + i[1] += '\r\n' + line + else: + i = line.split(': ', 1) + header = i[0].lower() + self.headers[header] = tuple(i) + + if not self.getHeader('Message-ID'): + s = str(time.time()) + self.body + id = hexdigest(md5(s)) + '@' + socket.gethostname() + self.putHeader('Message-ID', '<%s>' % id) + + if not self.getHeader('Bytes'): + self.putHeader('Bytes', str(len(self.body))) + + if not self.getHeader('Lines'): + self.putHeader('Lines', str(self.body.count('\n'))) + + if not self.getHeader('Date'): + self.putHeader('Date', time.ctime(time.time())) + + + def getHeader(self, header): + h = header.lower() + if self.headers.has_key(h): + return self.headers[h][1] + else: + return '' + + + def putHeader(self, header, value): + self.headers[header.lower()] = (header, value) + + + def textHeaders(self): + headers = [] + for i in self.headers.values(): + headers.append('%s: %s' % i) + return '\r\n'.join(headers) + '\r\n' + + def overview(self): + xover = [] + for i in OVERVIEW_FMT: + xover.append(self.getHeader(i)) + return xover + + +class NewsServerError(Exception): + pass + + +class INewsStorage(Interface): + """ + An interface for storing and requesting news articles + """ + + def listRequest(): + """ + Returns a deferred whose callback will be passed a list of 4-tuples + containing (name, max index, min index, flags) for each news group + """ + + + def subscriptionRequest(): + """ + Returns a deferred whose callback will be passed the list of + recommended subscription groups for new server users + """ + + + def postRequest(message): + """ + Returns a deferred whose callback will be invoked if 'message' + is successfully posted to one or more specified groups and + whose errback will be invoked otherwise. + """ + + + def overviewRequest(): + """ + Returns a deferred whose callback will be passed the a list of + headers describing this server's overview format. + """ + + + def xoverRequest(group, low, high): + """ + Returns a deferred whose callback will be passed a list of xover + headers for the given group over the given range. If low is None, + the range starts at the first article. If high is None, the range + ends at the last article. + """ + + + def xhdrRequest(group, low, high, header): + """ + Returns a deferred whose callback will be passed a list of XHDR data + for the given group over the given range. If low is None, + the range starts at the first article. If high is None, the range + ends at the last article. + """ + + + def listGroupRequest(group): + """ + Returns a deferred whose callback will be passed a two-tuple of + (group name, [article indices]) + """ + + + def groupRequest(group): + """ + Returns a deferred whose callback will be passed a five-tuple of + (group name, article count, highest index, lowest index, group flags) + """ + + + def articleExistsRequest(id): + """ + Returns a deferred whose callback will be passed with a true value + if a message with the specified Message-ID exists in the database + and with a false value otherwise. + """ + + + def articleRequest(group, index, id = None): + """ + Returns a deferred whose callback will be passed a file-like object + containing the full article text (headers and body) for the article + of the specified index in the specified group, and whose errback + will be invoked if the article or group does not exist. If id is + not None, index is ignored and the article with the given Message-ID + will be returned instead, along with its index in the specified + group. + """ + + + def headRequest(group, index): + """ + Returns a deferred whose callback will be passed the header for + the article of the specified index in the specified group, and + whose errback will be invoked if the article or group does not + exist. + """ + + + def bodyRequest(group, index): + """ + Returns a deferred whose callback will be passed the body for + the article of the specified index in the specified group, and + whose errback will be invoked if the article or group does not + exist. + """ + +class NewsStorage: + """ + Backwards compatibility class -- There is no reason to inherit from this, + just implement INewsStorage instead. + """ + def listRequest(self): + raise NotImplementedError() + def subscriptionRequest(self): + raise NotImplementedError() + def postRequest(self, message): + raise NotImplementedError() + def overviewRequest(self): + return defer.succeed(OVERVIEW_FMT) + def xoverRequest(self, group, low, high): + raise NotImplementedError() + def xhdrRequest(self, group, low, high, header): + raise NotImplementedError() + def listGroupRequest(self, group): + raise NotImplementedError() + def groupRequest(self, group): + raise NotImplementedError() + def articleExistsRequest(self, id): + raise NotImplementedError() + def articleRequest(self, group, index, id = None): + raise NotImplementedError() + def headRequest(self, group, index): + raise NotImplementedError() + def bodyRequest(self, group, index): + raise NotImplementedError() + + + +class _ModerationMixin: + """ + Storage implementations can inherit from this class to get the easy-to-use + C{notifyModerators} method which will take care of sending messages which + require moderation to a list of moderators. + """ + sendmail = staticmethod(smtp.sendmail) + + def notifyModerators(self, moderators, article): + """ + Send an article to a list of group moderators to be moderated. + + @param moderators: A C{list} of C{str} giving RFC 2821 addresses of + group moderators to notify. + + @param article: The article requiring moderation. + @type article: L{Article} + + @return: A L{Deferred} which fires with the result of sending the email. + """ + # Moderated postings go through as long as they have an Approved + # header, regardless of what the value is + group = article.getHeader('Newsgroups') + subject = article.getHeader('Subject') + + if self._sender is None: + # This case should really go away. This isn't a good default. + sender = 'twisted-news@' + socket.gethostname() + else: + sender = self._sender + + msg = Message() + msg['Message-ID'] = smtp.messageid() + msg['From'] = sender + msg['To'] = ', '.join(moderators) + msg['Subject'] = 'Moderate new %s message: %s' % (group, subject) + msg['Content-Type'] = 'message/rfc822' + + payload = Message() + for header, value in article.headers.values(): + payload.add_header(header, value) + payload.set_payload(article.body) + + msg.attach(payload) + + out = StringIO.StringIO() + gen = Generator(out, False) + gen.flatten(msg) + msg = out.getvalue() + + return self.sendmail(self._mailhost, sender, moderators, msg) + + + +class PickleStorage(_ModerationMixin): + """ + A trivial NewsStorage implementation using pickles + + Contains numerous flaws and is generally unsuitable for any + real applications. Consider yourself warned! + """ + + implements(INewsStorage) + + sharedDBs = {} + + def __init__(self, filename, groups=None, moderators=(), + mailhost=None, sender=None): + """ + @param mailhost: A C{str} giving the mail exchange host which will + accept moderation emails from this server. Must accept emails + destined for any address specified as a moderator. + + @param sender: A C{str} giving the address which will be used as the + sender of any moderation email generated by this server. + """ + self.datafile = filename + self.load(filename, groups, moderators) + self._mailhost = mailhost + self._sender = sender + + + def getModerators(self, groups): + # first see if any groups are moderated. if so, nothing gets posted, + # but the whole messages gets forwarded to the moderator address + moderators = [] + for group in groups: + moderators.extend(self.db['moderators'].get(group, None)) + return filter(None, moderators) + + + def listRequest(self): + "Returns a list of 4-tuples: (name, max index, min index, flags)" + l = self.db['groups'] + r = [] + for i in l: + if len(self.db[i].keys()): + low = min(self.db[i].keys()) + high = max(self.db[i].keys()) + 1 + else: + low = high = 0 + if self.db['moderators'].has_key(i): + flags = 'm' + else: + flags = 'y' + r.append((i, high, low, flags)) + return defer.succeed(r) + + def subscriptionRequest(self): + return defer.succeed(['alt.test']) + + def postRequest(self, message): + cleave = message.find('\r\n\r\n') + headers, article = message[:cleave], message[cleave + 4:] + + a = Article(headers, article) + groups = a.getHeader('Newsgroups').split() + xref = [] + + # Check moderated status + moderators = self.getModerators(groups) + if moderators and not a.getHeader('Approved'): + return self.notifyModerators(moderators, a) + + for group in groups: + if self.db.has_key(group): + if len(self.db[group].keys()): + index = max(self.db[group].keys()) + 1 + else: + index = 1 + xref.append((group, str(index))) + self.db[group][index] = a + + if len(xref) == 0: + return defer.fail(None) + + a.putHeader('Xref', '%s %s' % ( + socket.gethostname().split()[0], + ''.join(map(lambda x: ':'.join(x), xref)) + )) + + self.flush() + return defer.succeed(None) + + + def overviewRequest(self): + return defer.succeed(OVERVIEW_FMT) + + + def xoverRequest(self, group, low, high): + if not self.db.has_key(group): + return defer.succeed([]) + r = [] + for i in self.db[group].keys(): + if (low is None or i >= low) and (high is None or i <= high): + r.append([str(i)] + self.db[group][i].overview()) + return defer.succeed(r) + + + def xhdrRequest(self, group, low, high, header): + if not self.db.has_key(group): + return defer.succeed([]) + r = [] + for i in self.db[group].keys(): + if low is None or i >= low and high is None or i <= high: + r.append((i, self.db[group][i].getHeader(header))) + return defer.succeed(r) + + + def listGroupRequest(self, group): + if self.db.has_key(group): + return defer.succeed((group, self.db[group].keys())) + else: + return defer.fail(None) + + def groupRequest(self, group): + if self.db.has_key(group): + if len(self.db[group].keys()): + num = len(self.db[group].keys()) + low = min(self.db[group].keys()) + high = max(self.db[group].keys()) + else: + num = low = high = 0 + flags = 'y' + return defer.succeed((group, num, high, low, flags)) + else: + return defer.fail(ERR_NOGROUP) + + + def articleExistsRequest(self, id): + for group in self.db['groups']: + for a in self.db[group].values(): + if a.getHeader('Message-ID') == id: + return defer.succeed(1) + return defer.succeed(0) + + + def articleRequest(self, group, index, id = None): + if id is not None: + raise NotImplementedError + + if self.db.has_key(group): + if self.db[group].has_key(index): + a = self.db[group][index] + return defer.succeed(( + index, + a.getHeader('Message-ID'), + StringIO.StringIO(a.textHeaders() + '\r\n' + a.body) + )) + else: + return defer.fail(ERR_NOARTICLE) + else: + return defer.fail(ERR_NOGROUP) + + + def headRequest(self, group, index): + if self.db.has_key(group): + if self.db[group].has_key(index): + a = self.db[group][index] + return defer.succeed((index, a.getHeader('Message-ID'), a.textHeaders())) + else: + return defer.fail(ERR_NOARTICLE) + else: + return defer.fail(ERR_NOGROUP) + + + def bodyRequest(self, group, index): + if self.db.has_key(group): + if self.db[group].has_key(index): + a = self.db[group][index] + return defer.succeed((index, a.getHeader('Message-ID'), StringIO.StringIO(a.body))) + else: + return defer.fail(ERR_NOARTICLE) + else: + return defer.fail(ERR_NOGROUP) + + + def flush(self): + f = open(self.datafile, 'w') + pickle.dump(self.db, f) + f.close() + + + def load(self, filename, groups = None, moderators = ()): + if PickleStorage.sharedDBs.has_key(filename): + self.db = PickleStorage.sharedDBs[filename] + else: + try: + self.db = pickle.load(open(filename)) + PickleStorage.sharedDBs[filename] = self.db + except IOError: + self.db = PickleStorage.sharedDBs[filename] = {} + self.db['groups'] = groups + if groups is not None: + for i in groups: + self.db[i] = {} + self.db['moderators'] = dict(moderators) + self.flush() + + +class Group: + name = None + flags = '' + minArticle = 1 + maxArticle = 0 + articles = None + + def __init__(self, name, flags = 'y'): + self.name = name + self.flags = flags + self.articles = {} + + +class NewsShelf(_ModerationMixin): + """ + A NewStorage implementation using Twisted's dirdbm persistence module. + """ + + implements(INewsStorage) + + def __init__(self, mailhost, path, sender=None): + """ + @param mailhost: A C{str} giving the mail exchange host which will + accept moderation emails from this server. Must accept emails + destined for any address specified as a moderator. + + @param sender: A C{str} giving the address which will be used as the + sender of any moderation email generated by this server. + """ + self.path = path + self._mailhost = self.mailhost = mailhost + self._sender = sender + + if not os.path.exists(path): + os.mkdir(path) + + self.dbm = dirdbm.Shelf(os.path.join(path, "newsshelf")) + if not len(self.dbm.keys()): + self.initialize() + + + def initialize(self): + # A dictionary of group name/Group instance items + self.dbm['groups'] = dirdbm.Shelf(os.path.join(self.path, 'groups')) + + # A dictionary of group name/email address + self.dbm['moderators'] = dirdbm.Shelf(os.path.join(self.path, 'moderators')) + + # A list of group names + self.dbm['subscriptions'] = [] + + # A dictionary of MessageID strings/xref lists + self.dbm['Message-IDs'] = dirdbm.Shelf(os.path.join(self.path, 'Message-IDs')) + + + def addGroup(self, name, flags): + self.dbm['groups'][name] = Group(name, flags) + + + def addSubscription(self, name): + self.dbm['subscriptions'] = self.dbm['subscriptions'] + [name] + + + def addModerator(self, group, email): + self.dbm['moderators'][group] = email + + + def listRequest(self): + result = [] + for g in self.dbm['groups'].values(): + result.append((g.name, g.maxArticle, g.minArticle, g.flags)) + return defer.succeed(result) + + + def subscriptionRequest(self): + return defer.succeed(self.dbm['subscriptions']) + + + def getModerator(self, groups): + # first see if any groups are moderated. if so, nothing gets posted, + # but the whole messages gets forwarded to the moderator address + for group in groups: + try: + return self.dbm['moderators'][group] + except KeyError: + pass + return None + + + def notifyModerator(self, moderator, article): + """ + Notify a single moderator about an article requiring moderation. + + C{notifyModerators} should be preferred. + """ + return self.notifyModerators([moderator], article) + + + def postRequest(self, message): + cleave = message.find('\r\n\r\n') + headers, article = message[:cleave], message[cleave + 4:] + + article = Article(headers, article) + groups = article.getHeader('Newsgroups').split() + xref = [] + + # Check for moderated status + moderator = self.getModerator(groups) + if moderator and not article.getHeader('Approved'): + return self.notifyModerators([moderator], article) + + + for group in groups: + try: + g = self.dbm['groups'][group] + except KeyError: + pass + else: + index = g.maxArticle + 1 + g.maxArticle += 1 + g.articles[index] = article + xref.append((group, str(index))) + self.dbm['groups'][group] = g + + if not xref: + return defer.fail(NewsServerError("No groups carried: " + ' '.join(groups))) + + article.putHeader('Xref', '%s %s' % (socket.gethostname().split()[0], ' '.join(map(lambda x: ':'.join(x), xref)))) + self.dbm['Message-IDs'][article.getHeader('Message-ID')] = xref + return defer.succeed(None) + + + def overviewRequest(self): + return defer.succeed(OVERVIEW_FMT) + + + def xoverRequest(self, group, low, high): + if not self.dbm['groups'].has_key(group): + return defer.succeed([]) + + if low is None: + low = 0 + if high is None: + high = self.dbm['groups'][group].maxArticle + r = [] + for i in range(low, high + 1): + if self.dbm['groups'][group].articles.has_key(i): + r.append([str(i)] + self.dbm['groups'][group].articles[i].overview()) + return defer.succeed(r) + + + def xhdrRequest(self, group, low, high, header): + if group not in self.dbm['groups']: + return defer.succeed([]) + + if low is None: + low = 0 + if high is None: + high = self.dbm['groups'][group].maxArticle + r = [] + for i in range(low, high + 1): + if self.dbm['groups'][group].articles.has_key(i): + r.append((i, self.dbm['groups'][group].articles[i].getHeader(header))) + return defer.succeed(r) + + + def listGroupRequest(self, group): + if self.dbm['groups'].has_key(group): + return defer.succeed((group, self.dbm['groups'][group].articles.keys())) + return defer.fail(NewsServerError("No such group: " + group)) + + + def groupRequest(self, group): + try: + g = self.dbm['groups'][group] + except KeyError: + return defer.fail(NewsServerError("No such group: " + group)) + else: + flags = g.flags + low = g.minArticle + high = g.maxArticle + num = high - low + 1 + return defer.succeed((group, num, high, low, flags)) + + + def articleExistsRequest(self, id): + return defer.succeed(id in self.dbm['Message-IDs']) + + + def articleRequest(self, group, index, id = None): + if id is not None: + try: + xref = self.dbm['Message-IDs'][id] + except KeyError: + return defer.fail(NewsServerError("No such article: " + id)) + else: + group, index = xref[0] + index = int(index) + + try: + a = self.dbm['groups'][group].articles[index] + except KeyError: + return defer.fail(NewsServerError("No such group: " + group)) + else: + return defer.succeed(( + index, + a.getHeader('Message-ID'), + StringIO.StringIO(a.textHeaders() + '\r\n' + a.body) + )) + + + def headRequest(self, group, index, id = None): + if id is not None: + try: + xref = self.dbm['Message-IDs'][id] + except KeyError: + return defer.fail(NewsServerError("No such article: " + id)) + else: + group, index = xref[0] + index = int(index) + + try: + a = self.dbm['groups'][group].articles[index] + except KeyError: + return defer.fail(NewsServerError("No such group: " + group)) + else: + return defer.succeed((index, a.getHeader('Message-ID'), a.textHeaders())) + + + def bodyRequest(self, group, index, id = None): + if id is not None: + try: + xref = self.dbm['Message-IDs'][id] + except KeyError: + return defer.fail(NewsServerError("No such article: " + id)) + else: + group, index = xref[0] + index = int(index) + + try: + a = self.dbm['groups'][group].articles[index] + except KeyError: + return defer.fail(NewsServerError("No such group: " + group)) + else: + return defer.succeed((index, a.getHeader('Message-ID'), StringIO.StringIO(a.body))) + + +class NewsStorageAugmentation: + """ + A NewsStorage implementation using Twisted's asynchronous DB-API + """ + + implements(INewsStorage) + + schema = """ + + CREATE TABLE groups ( + group_id SERIAL, + name VARCHAR(80) NOT NULL, + + flags INTEGER DEFAULT 0 NOT NULL + ); + + CREATE UNIQUE INDEX group_id_index ON groups (group_id); + CREATE UNIQUE INDEX name_id_index ON groups (name); + + CREATE TABLE articles ( + article_id SERIAL, + message_id TEXT, + + header TEXT, + body TEXT + ); + + CREATE UNIQUE INDEX article_id_index ON articles (article_id); + CREATE UNIQUE INDEX article_message_index ON articles (message_id); + + CREATE TABLE postings ( + group_id INTEGER, + article_id INTEGER, + article_index INTEGER NOT NULL + ); + + CREATE UNIQUE INDEX posting_article_index ON postings (article_id); + + CREATE TABLE subscriptions ( + group_id INTEGER + ); + + CREATE TABLE overview ( + header TEXT + ); + """ + + def __init__(self, info): + self.info = info + self.dbpool = adbapi.ConnectionPool(**self.info) + + + def __setstate__(self, state): + self.__dict__ = state + self.info['password'] = getpass.getpass('Database password for %s: ' % (self.info['user'],)) + self.dbpool = adbapi.ConnectionPool(**self.info) + del self.info['password'] + + + def listRequest(self): + # COALESCE may not be totally portable + # it is shorthand for + # CASE WHEN (first parameter) IS NOT NULL then (first parameter) ELSE (second parameter) END + sql = """ + SELECT groups.name, + COALESCE(MAX(postings.article_index), 0), + COALESCE(MIN(postings.article_index), 0), + groups.flags + FROM groups LEFT OUTER JOIN postings + ON postings.group_id = groups.group_id + GROUP BY groups.name, groups.flags + ORDER BY groups.name + """ + return self.dbpool.runQuery(sql) + + + def subscriptionRequest(self): + sql = """ + SELECT groups.name FROM groups,subscriptions WHERE groups.group_id = subscriptions.group_id + """ + return self.dbpool.runQuery(sql) + + + def postRequest(self, message): + cleave = message.find('\r\n\r\n') + headers, article = message[:cleave], message[cleave + 4:] + article = Article(headers, article) + return self.dbpool.runInteraction(self._doPost, article) + + + def _doPost(self, transaction, article): + # Get the group ids + groups = article.getHeader('Newsgroups').split() + if not len(groups): + raise NNTPError('Missing Newsgroups header') + + sql = """ + SELECT name, group_id FROM groups + WHERE name IN (%s) + """ % (', '.join([("'%s'" % (adbapi.safe(group),)) for group in groups]),) + + transaction.execute(sql) + result = transaction.fetchall() + + # No relevant groups, bye bye! + if not len(result): + raise NNTPError('None of groups in Newsgroup header carried') + + # Got some groups, now find the indices this article will have in each + sql = """ + SELECT groups.group_id, COALESCE(MAX(postings.article_index), 0) + 1 + FROM groups LEFT OUTER JOIN postings + ON postings.group_id = groups.group_id + WHERE groups.group_id IN (%s) + GROUP BY groups.group_id + """ % (', '.join([("%d" % (id,)) for (group, id) in result]),) + + transaction.execute(sql) + indices = transaction.fetchall() + + if not len(indices): + raise NNTPError('Internal server error - no indices found') + + # Associate indices with group names + gidToName = dict([(b, a) for (a, b) in result]) + gidToIndex = dict(indices) + + nameIndex = [] + for i in gidToName: + nameIndex.append((gidToName[i], gidToIndex[i])) + + # Build xrefs + xrefs = socket.gethostname().split()[0] + xrefs = xrefs + ' ' + ' '.join([('%s:%d' % (group, id)) for (group, id) in nameIndex]) + article.putHeader('Xref', xrefs) + + # Hey! The article is ready to be posted! God damn f'in finally. + sql = """ + INSERT INTO articles (message_id, header, body) + VALUES ('%s', '%s', '%s') + """ % ( + adbapi.safe(article.getHeader('Message-ID')), + adbapi.safe(article.textHeaders()), + adbapi.safe(article.body) + ) + + transaction.execute(sql) + + # Now update the posting to reflect the groups to which this belongs + for gid in gidToName: + sql = """ + INSERT INTO postings (group_id, article_id, article_index) + VALUES (%d, (SELECT last_value FROM articles_article_id_seq), %d) + """ % (gid, gidToIndex[gid]) + transaction.execute(sql) + + return len(nameIndex) + + + def overviewRequest(self): + sql = """ + SELECT header FROM overview + """ + return self.dbpool.runQuery(sql).addCallback(lambda result: [header[0] for header in result]) + + + def xoverRequest(self, group, low, high): + sql = """ + SELECT postings.article_index, articles.header + FROM articles,postings,groups + WHERE postings.group_id = groups.group_id + AND groups.name = '%s' + AND postings.article_id = articles.article_id + %s + %s + """ % ( + adbapi.safe(group), + low is not None and "AND postings.article_index >= %d" % (low,) or "", + high is not None and "AND postings.article_index <= %d" % (high,) or "" + ) + + return self.dbpool.runQuery(sql).addCallback( + lambda results: [ + [id] + Article(header, None).overview() for (id, header) in results + ] + ) + + + def xhdrRequest(self, group, low, high, header): + sql = """ + SELECT articles.header + FROM groups,postings,articles + WHERE groups.name = '%s' AND postings.group_id = groups.group_id + AND postings.article_index >= %d + AND postings.article_index <= %d + """ % (adbapi.safe(group), low, high) + + return self.dbpool.runQuery(sql).addCallback( + lambda results: [ + (i, Article(h, None).getHeader(h)) for (i, h) in results + ] + ) + + + def listGroupRequest(self, group): + sql = """ + SELECT postings.article_index FROM postings,groups + WHERE postings.group_id = groups.group_id + AND groups.name = '%s' + """ % (adbapi.safe(group),) + + return self.dbpool.runQuery(sql).addCallback( + lambda results, group = group: (group, [res[0] for res in results]) + ) + + + def groupRequest(self, group): + sql = """ + SELECT groups.name, + COUNT(postings.article_index), + COALESCE(MAX(postings.article_index), 0), + COALESCE(MIN(postings.article_index), 0), + groups.flags + FROM groups LEFT OUTER JOIN postings + ON postings.group_id = groups.group_id + WHERE groups.name = '%s' + GROUP BY groups.name, groups.flags + """ % (adbapi.safe(group),) + + return self.dbpool.runQuery(sql).addCallback( + lambda results: tuple(results[0]) + ) + + + def articleExistsRequest(self, id): + sql = """ + SELECT COUNT(message_id) FROM articles + WHERE message_id = '%s' + """ % (adbapi.safe(id),) + + return self.dbpool.runQuery(sql).addCallback( + lambda result: bool(result[0][0]) + ) + + + def articleRequest(self, group, index, id = None): + if id is not None: + sql = """ + SELECT postings.article_index, articles.message_id, articles.header, articles.body + FROM groups,postings LEFT OUTER JOIN articles + ON articles.message_id = '%s' + WHERE groups.name = '%s' + AND groups.group_id = postings.group_id + """ % (adbapi.safe(id), adbapi.safe(group)) + else: + sql = """ + SELECT postings.article_index, articles.message_id, articles.header, articles.body + FROM groups,articles LEFT OUTER JOIN postings + ON postings.article_id = articles.article_id + WHERE postings.article_index = %d + AND postings.group_id = groups.group_id + AND groups.name = '%s' + """ % (index, adbapi.safe(group)) + + return self.dbpool.runQuery(sql).addCallback( + lambda result: ( + result[0][0], + result[0][1], + StringIO.StringIO(result[0][2] + '\r\n' + result[0][3]) + ) + ) + + + def headRequest(self, group, index): + sql = """ + SELECT postings.article_index, articles.message_id, articles.header + FROM groups,articles LEFT OUTER JOIN postings + ON postings.article_id = articles.article_id + WHERE postings.article_index = %d + AND postings.group_id = groups.group_id + AND groups.name = '%s' + """ % (index, adbapi.safe(group)) + + return self.dbpool.runQuery(sql).addCallback(lambda result: result[0]) + + + def bodyRequest(self, group, index): + sql = """ + SELECT postings.article_index, articles.message_id, articles.body + FROM groups,articles LEFT OUTER JOIN postings + ON postings.article_id = articles.article_id + WHERE postings.article_index = %d + AND postings.group_id = groups.group_id + AND groups.name = '%s' + """ % (index, adbapi.safe(group)) + + return self.dbpool.runQuery(sql).addCallback( + lambda result: result[0] + ).addCallback( + lambda (index, id, body): (index, id, StringIO.StringIO(body)) + ) + +#### +#### XXX - make these static methods some day +#### +def makeGroupSQL(groups): + res = '' + for g in groups: + res = res + """\n INSERT INTO groups (name) VALUES ('%s');\n""" % (adbapi.safe(g),) + return res + + +def makeOverviewSQL(): + res = '' + for o in OVERVIEW_FMT: + res = res + """\n INSERT INTO overview (header) VALUES ('%s');\n""" % (adbapi.safe(o),) + return res + +##################################################################################### +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# This source code is subject to terms and conditions of the Apache License, Version 2.0. A +# copy of the license can be found in the License.html file at the root of this distribution. If +# you cannot locate the Apache License, Version 2.0, please send an email to +# ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound +# by the terms of the Apache License, Version 2.0. +# +# You must not remove this notice, or any other, from this software. +# +# +##################################################################################### + +import sys +from iptest.assert_util import * +skiptest("silverlight") +skiptest("win32") +from iptest.process_util import * + +load_iron_python_test() +import IronPythonTest.LoadTest as lt +import clr + +def test_loadtest(): + AreEqual(lt.Name1.Value, lt.Values.GlobalName1) + AreEqual(lt.Name2.Value, lt.Values.GlobalName2) + AreEqual(lt.Nested.Name1.Value, lt.Values.NestedName1) + AreEqual(lt.Nested.Name2.Value, lt.Values.NestedName2) + +def test_negative_assembly_names(): + AssertError(IOError, clr.AddReferenceToFileAndPath, path_combine(testpath.public_testdir, 'this_file_does_not_exist.dll')) + AssertError(IOError, clr.AddReferenceToFileAndPath, path_combine(testpath.public_testdir, 'this_file_does_not_exist.dll')) + AssertError(IOError, clr.AddReferenceToFileAndPath, path_combine(testpath.public_testdir, 'this_file_does_not_exist.dll')) + AssertError(IOError, clr.AddReferenceByName, 'bad assembly name', 'WellFormed.But.Nonexistent, Version=9.9.9.9, Culture=neutral, PublicKeyToken=deadbeefdeadbeef, processorArchitecture=6502') + AssertError(IOError, clr.AddReference, 'this_assembly_does_not_exist_neither_by_file_name_nor_by_strong_name') + + AssertError(TypeError, clr.AddReference, 35) + + for method in [ + clr.AddReference, + clr.AddReferenceToFile, + clr.AddReferenceToFileAndPath, + clr.AddReferenceByName, + clr.AddReferenceByPartialName, + clr.LoadAssemblyFromFileWithPath, + clr.LoadAssemblyFromFile, + clr.LoadAssemblyByName, + clr.LoadAssemblyByPartialName, + ]: + AssertError(TypeError, method, None) + + for method in [ + clr.AddReference, + clr.AddReferenceToFile, + clr.AddReferenceToFileAndPath, + clr.AddReferenceByName, + clr.AddReferenceByPartialName, + ]: + AssertError(TypeError, method, None, None) + import System + AssertError(ValueError, clr.LoadAssemblyFromFile, System.IO.Path.DirectorySeparatorChar) + AssertError(ValueError, clr.LoadAssemblyFromFile, '') +def test_get_type(): + AreEqual(clr.GetClrType(None), None) + AssertError(TypeError, clr.GetPythonType, None) + +# load iron python test under an alias... +@skip("multiple_execute") +def test_ironpythontest_from_alias(): + IPTestAlias = load_iron_python_test(True) + AreEqual(dir(IPTestAlias).count('IronPythonTest'), 1) + +def test_references(): + refs = clr.References + atuple = refs + (clr.GetClrType(int).Assembly, ) # should be able to append to references_tuple + #AssertError(TypeError, refs.__add__, "I am not a tuple") + + s = str(refs) + temp = ',' + newline + AreEqual(s, '(' + temp.join(map((lambda x:'<'+x.ToString()+'>'), refs)) + ')' + newline) + +def test_gac(): + import System + def get_gac(): + process = System.Diagnostics.Process() + process.StartInfo.FileName = System.IO.Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), "gacutil.exe") + process.StartInfo.Arguments = "/nologo /l" + process.StartInfo.CreateNoWindow = True + process.StartInfo.UseShellExecute = False + process.StartInfo.RedirectStandardInput = True + process.StartInfo.RedirectStandardOutput = True + process.StartInfo.RedirectStandardError = True + try: + process.Start() + except WindowsError: + return [] + result = process.StandardOutput.ReadToEnd() + process.StandardError.ReadToEnd() + process.WaitForExit() + if process.ExitCode == 0: + try: + divByNewline = result.split(newline + ' ')[1:] + divByNewline[-1] = divByNewline[-1].split(newline + newline)[0] + return divByNewline + except Exception: + return [] + return [] + + gaclist = get_gac() + if (len(gaclist) > 0): + clr.AddReferenceByName(gaclist[-1]) + + +def test_nonamespaceloadtest(): + import NoNamespaceLoadTest + a = NoNamespaceLoadTest() + AreEqual(a.HelloWorld(), 'Hello World') + +@skip("multiple_execute") +def test_addreferencetofileandpath_conflict(): + """verify AddReferenceToFileAndPath picks up the path specified, not some arbitrary assembly somewhere in your path already""" + code1 = """ +using System; + +public class CollisionTest { + public static string Result(){ + return "Test1"; + } +} +""" + + code2 = """ +using System; + +public class CollisionTest { + public static string Result(){ + return "Test2"; + } +} +""" + + tmp = testpath.temporary_dir + + test1_cs, test1_dll = path_combine(tmp, 'test1.cs'), path_combine(tmp, 'CollisionTest.dll') + test2_cs, test2_dll = path_combine(tmp, 'test2.cs'), path_combine(sys.prefix, 'CollisionTest.dll') + + write_to_file(test1_cs, code1) + write_to_file(test2_cs, code2) + + AreEqual(run_csc("/nologo /target:library /out:" + test2_dll + ' ' + test2_cs), 0) + AreEqual(run_csc("/nologo /target:library /out:" + test1_dll + ' ' + test1_cs), 0) + + clr.AddReferenceToFileAndPath(test1_dll) + import CollisionTest + AreEqual(CollisionTest.Result(), "Test1") + +##################### +# VERIFY clr.AddReferenceToFile behavior... +@skip("multiple_execute") +def test_addreferencetofile_verification(): + tmp = testpath.temporary_dir + sys.path.append(tmp) + + code1 = """ +using System; + +public class test1{ + public static string Test1(){ + test2 t2 = new test2(); + return t2.DoSomething(); + } + + public static string Test2(){ + return "test1.test2"; + } +} +""" + + code2 = """ +using System; + +public class test2{ + public string DoSomething(){ + return "hello world"; + } +} +""" + + test1_dll_along_with_ipy = path_combine(sys.prefix, 'test1.dll') # this dll is need for peverify + + # delete the old test1.dll if exists + delete_files(test1_dll_along_with_ipy) + + test1_cs, test1_dll = path_combine(tmp, 'test1.cs'), path_combine(tmp, 'test1.dll') + test2_cs, test2_dll = path_combine(tmp, 'test2.cs'), path_combine(tmp, 'test2.dll') + + write_to_file(test1_cs, code1) + write_to_file(test2_cs, code2) + + AreEqual(run_csc("/nologo /target:library /out:"+ test2_dll + ' ' + test2_cs), 0) + AreEqual(run_csc("/nologo /target:library /r:" + test2_dll + " /out:" + test1_dll + ' ' + test1_cs), 0) + + clr.AddReferenceToFile('test1') + + AreEqual(len([x for x in clr.References if x.FullName.startswith("test1")]), 1) + + # test 2 shouldn't be loaded yet... + AreEqual(len([x for x in clr.References if x.FullName.startswith("test2")]), 0) + + import test1 + # should create test1 (even though we're a top-level namespace) + a = test1() + AreEqual(a.Test2(), 'test1.test2') + # should load test2 from path + AreEqual(a.Test1(), 'hello world') + AreEqual(len([x for x in clr.References if x.FullName.startswith("test2")]), 0) + + # this is to make peverify happy, apparently snippetx.dll referenced to test1 + filecopy(test1_dll, test1_dll_along_with_ipy) + +@skip("multiple_execute") +def test_assembly_resolve_isolation(): + # CodePlex issue 23506. This feature only works with .NET 4.0 + # builds of IronPython + if not is_dlr_in_ndp: + return + + import os + clr.AddReference("IronPython.dll") + clr.AddReference("Microsoft.Scripting.dll") + from IronPython.Hosting import Python + from Microsoft.Scripting import SourceCodeKind + tmp = testpath.temporary_dir + tmp1 = path_combine(tmp, 'resolve1') + tmp2 = path_combine(tmp, 'resolve2') + + if not os.path.exists(tmp1): + nt.mkdir(tmp1) + if not os.path.exists(tmp2): + nt.mkdir(tmp2) + + code1a = """ +using System; + +public class ResolveTestA { + public static string Test() { + ResolveTestB test = new ResolveTestB(); + return test.DoSomething(); + } +} +""" + + code1b = """ +using System; + +public class ResolveTestB { + public string DoSomething() { + return "resolve test 1"; + } +} +""" + + code2a = """ +using System; + +public class ResolveTestA { + public static string Test() { + ResolveTestB test = new ResolveTestB(); + return test.DoSomething(); + } +} +""" + + code2b = """ +using System; + +public class ResolveTestB { + public string DoSomething() { + return "resolve test 2"; + } +} +""" + + script_code = """import clr +clr.AddReferenceToFile("ResolveTestA") +from ResolveTestA import Test +result = Test() +""" + + test1a_cs, test1a_dll, test1b_cs, test1b_dll = map( + lambda x: path_combine(tmp1, x), + ['ResolveTestA.cs', 'ResolveTestA.dll', 'ResolveTestB.cs', 'ResolveTestB.dll'] + ) + + test2a_cs, test2a_dll, test2b_cs, test2b_dll = map( + lambda x: path_combine(tmp2, x), + ['ResolveTestA.cs', 'ResolveTestA.dll', 'ResolveTestB.cs', 'ResolveTestB.dll'] + ) + + write_to_file(test1a_cs, code1a) + write_to_file(test1b_cs, code1b) + write_to_file(test2a_cs, code2a) + write_to_file(test2b_cs, code2b) + + AreEqual(run_csc("/nologo /target:library /out:" + test1b_dll + ' ' + test1b_cs), 0) + AreEqual(run_csc("/nologo /target:library /r:" + test1b_dll + " /out:" + test1a_dll + ' ' + test1a_cs), 0) + AreEqual(run_csc("/nologo /target:library /out:" + test2b_dll + ' ' + test2b_cs), 0) + AreEqual(run_csc("/nologo /target:library /r:" + test2b_dll + " /out:" + test2a_dll + ' ' + test2a_cs), 0) + + engine1 = Python.CreateEngine() + paths1 = engine1.GetSearchPaths() + paths1.Add(tmp1) + engine1.SetSearchPaths(paths1) + scope1 = engine1.CreateScope() + script1 = engine1.CreateScriptSourceFromString(script_code, SourceCodeKind.Statements) + script1.Execute(scope1) + result1 = scope1.GetVariable("result") + AreEqual(result1, "resolve test 1") + + engine2 = Python.CreateEngine() + paths2 = engine2.GetSearchPaths() + paths2.Add(tmp2) + engine2.SetSearchPaths(paths2) + scope2 = engine2.CreateScope() + script2 = engine2.CreateScriptSourceFromString(script_code, SourceCodeKind.Statements) + script2.Execute(scope2) + result2 = scope2.GetVariable("result") + AreEqual(result2, "resolve test 2") + +##################### +def test_addreference_sanity(): + # add reference directly to assembly + clr.AddReference(''.GetType().Assembly) + # add reference via partial name + clr.AddReference('System.Xml') + + # add a reference via a fully qualified name + clr.AddReference(''.GetType().Assembly.FullName) + +def get_local_filename(base): + if __file__.count('\\'): + return __file__.rsplit("\\", 1)[0] + '\\'+ base + else: + return base + +def compileAndLoad(name, filename, *args): + import clr + sys.path.append(sys.exec_prefix) + AreEqual(run_csc("/nologo /t:library " + ' '.join(args) + " /out:\"" + sys.exec_prefix + "\"\\" + name +".dll \"" + filename + "\""), 0) + return clr.LoadAssemblyFromFile(name) + +@skip("multiple_execute") +def test_classname_same_as_ns(): + sys.path.append(sys.exec_prefix) + AreEqual(run_csc("/nologo /t:library /out:\"" + sys.exec_prefix + "\"\\c4.dll \"" + get_local_filename('c4.cs') + "\""), 0) + clr.AddReference("c4") + import c4 + Assert(not c4 is c4.c4) + Assert(c4!=c4.c4) + +@skip("multiple_execute") +def test_local_dll(): + x = compileAndLoad('c3', get_local_filename('c3.cs') ) + + AreEqual(repr(x), "") + AreEqual(repr(x.Foo), "") + AreEqual(repr(x.BarNamespace), "") + AreEqual(repr(x.BarNamespace.NestedNamespace), "") + AreEqual(repr(x.BarNamespace.Bar.NestedBar), "") + AreEqual(x.__dict__["BarNamespace"], x.BarNamespace) + AreEqual(x.BarNamespace.__dict__["Bar"], x.BarNamespace.Bar) + AreEqual(x.BarNamespace.__dict__["NestedNamespace"], x.BarNamespace.NestedNamespace) + AreEqual(x.BarNamespace.NestedNamespace.__name__, "NestedNamespace") + AreEqual(x.BarNamespace.NestedNamespace.__file__, "c3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") + AssertError(AttributeError, lambda: x.BarNamespace.NestedNamespace.not_exist) + AssertError(AttributeError, lambda: x.Foo2) # assembly c3 has no type Foo2 + Assert(set(['NestedNamespace', 'Bar']) <= set(dir(x.BarNamespace))) + + def f(): x.BarNamespace.Bar = x.Foo + AssertError(AttributeError, f) + + def f(): del x.BarNamespace.NotExist + AssertError(AttributeError, f) + + def f(): del x.BarNamespace + AssertError(AttributeError, f) + +@skip("multiple_execute") +def test_namespaceimport(): + tmp = testpath.temporary_dir + if tmp not in sys.path: + sys.path.append(tmp) + + code1 = "namespace TestNamespace { public class Test1 {} }" + code2 = "namespace TestNamespace { public class Test2 {} }" + + test1_cs, test1_dll = path_combine(tmp, 'testns1.cs'), path_combine(tmp, 'testns1.dll') + test2_cs, test2_dll = path_combine(tmp, 'testns2.cs'), path_combine(tmp, 'testns2.dll') + + write_to_file(test1_cs, code1) + write_to_file(test2_cs, code2) + + AreEqual(run_csc("/nologo /target:library /out:"+ test1_dll + ' ' + test1_cs), 0) + AreEqual(run_csc("/nologo /target:library /out:"+ test2_dll + ' ' + test2_cs), 0) + + clr.AddReference('testns1') + import TestNamespace + AreEqual(dir(TestNamespace), ['Test1']) + clr.AddReference('testns2') + # verify that you don't need to import TestNamespace again to see Test2 + AreEqual(dir(TestNamespace), ['Test1', 'Test2']) + +def test_no_names_provided(): + AssertError(TypeError, clr.AddReference, None) + AssertError(TypeError, clr.AddReferenceToFile, None) + AssertError(TypeError, clr.AddReferenceByName, None) + AssertError(TypeError, clr.AddReferenceByPartialName, None) + AssertError(ValueError, clr.AddReference) + AssertError(ValueError, clr.AddReferenceToFile) + AssertError(ValueError, clr.AddReferenceByName) + AssertError(ValueError, clr.AddReferenceByPartialName) + +@skip("multiple_execute") +def test_load_count(): + # verify loading an assembly updates the assembly-loaded count in the repr + # if a new assembly gets loaded before this that contains System both numbers + # need to be updated + import clr, System + before = repr(System) + clr.AddReference('System.Drawing') + after = repr(System) + + # Strip common substring from start and end + start = 0; end = 1 + while before[start] == after[start]: start += 1 + while before[-end] == after[-end]: end += 1 + end -= 1; + + # what remains is an int - number of assemblies loaded. + # The integer must have increased value by 1 + AreEqual(int(before[start:-end]) + 1, int(after[start:-end])) + +run_test(__name__) + +# -*- coding: utf-8 -*- +## +## This file is part of Invenio. +## Copyright (C) 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. + +__revision__ = "$Id$" + +import re +from os.path import split, basename, isfile +from os import access, F_OK, R_OK, getpid, rename, unlink +from time import strftime, localtime +from invenio.websubmitadmin_dblayer import * +from invenio.websubmitadmin_config import * +from invenio.access_control_admin import acc_get_all_roles, acc_get_role_users, acc_delete_user_role +from invenio.config import CFG_SITE_LANG, CFG_WEBSUBMIT_BIBCONVERTCONFIGDIR +from invenio.access_control_engine import acc_authorize_action +from invenio.errorlib import register_exception +from invenio.websubmitadmin_config import InvenioWebSubmitWarning +from invenio.messages import gettext_set_language + +import invenio.template + +try: + websubmitadmin_templates = invenio.template.load('websubmitadmin') +except: + pass + + +## utility functions: + +def is_adminuser(req, role): + """check if user is a registered administrator. """ + return acc_authorize_action(req, role) + +def check_user(req, role, adminarea=2, authorized=0): + (auth_code, auth_message) = is_adminuser(req, role) + if not authorized and auth_code != 0: + return ("false", auth_message) + return ("", auth_message) + +def get_navtrail(ln=CFG_SITE_LANG): + """gets the navtrail for title... + @param title: title of the page + @param ln: language + @return: HTML output + """ + navtrail = websubmitadmin_templates.tmpl_navtrail(ln) + return navtrail + +def stringify_listvars(mylist): + """Accept a list (or a list of lists) (or tuples). + Convert each item in the list, into a string (replace None with the empty + string ""). + @param mylist: A list/tuple of values, or a list/tuple of value list/tuples. + @return: a tuple of string values or a tuple of string value tuples + """ + string_list = [] + try: + if type(mylist[0]) in (tuple,list): + for row in mylist: + string_list.append(map(lambda x: x is not None and str(x) or "", row)) + else: + string_list = map(lambda x: x is not None and str(x) or "", mylist) + except IndexError: + pass + return string_list + +def save_update_to_file(filepath, filecontent, notruncate=0, appendmode=0): + """Save a string value to a file. + Save will create a new file if the file does not exist. Mode can be set to truncate an older file + or to refuse to create the file if it already exists. There is also a mode to "append" the string value + to a file. + @param filepath: (string) the full path to the file + @param filecontent: (string) the content to be written to the file + @param notruncate: (integer) should be 1 or 0, defaults to 0 (ZERO). If 0, existing file will be truncated; + if 1, file will not be written if it already exists + @param appendmode: (integer) should be 1 or 0, defaults to 0 (ZERO). If 1, data will be appended to the file + if it exists; if 0, file will be truncated (or not, depending on the notruncate mode) by new data. + @return: None + @exceptions raised: + - InvenioWebSubmitAdminWarningIOError: when operations involving writing to file failed. + """ + ## sanity checking: + if notruncate not in (0, 1): + notruncate = 0 + if appendmode not in (0, 1): + appendmode = 0 + + (fpath, fname) = split(filepath) + if fname == "": + ## error opening file + msg = """Unable to open filepath [%s] - couldn't determine a valid filename""" % (filepath,) + raise InvenioWebSubmitAdminWarningIOError(msg) + + ## if fpath is not empty, append the trailing "/": + if fpath != "": + fpath += "/" + + if appendmode == 0: + if notruncate != 0 and access("%s%s" % (fpath, fname), F_OK): + ## in no-truncate mode, but file already exists! + msg = """Unable to write to file [%s] in "no-truncate mode" because file already exists"""\ + % (fname,) + raise InvenioWebSubmitAdminWarningIOError(msg) + + ## file already exists, make temporary file first, then move it later + tmpfname = "%s_%s_%s" % (fname, strftime("%Y%m%d%H%M%S", localtime()), getpid()) + + ## open temp file for writing: + try: + fp = open("%s%s" % (fpath, tmpfname), "w") + except IOError, e: + ## cannot open file + msg = """Unable to write to file [%s%s] - cannot open file for writing""" % (fpath, fname) + raise InvenioWebSubmitAdminWarningIOError(msg) + ## write contents to temp file: + try: + fp.write(filecontent) + fp.flush() + fp.close() + except IOError, e: + ## could not write to temp file + msg = """Unable to write to file [%s]""" % (tmpfname,) + ## remove the "temp file" + try: + fp.close() + unlink("%s%s" % (fpath, tmpfname)) + except IOError: + pass + raise InvenioWebSubmitAdminWarningIOError(msg) + + ## rename temp file to final filename: + try: + rename("%s%s" % (fpath, tmpfname), "%s%s" % (fpath, fname)) + except OSError: + ## couldnt rename the tmp file to final file name + msg = """Unable to write to file [%s] - created temporary file [%s], but could not then rename it to [%s]"""\ + % (fname, tmpfname, fname) + raise InvenioWebSubmitAdminWarningIOError(msg) + else: + ## append mode: + try: + fp = open("%s%s" % (fpath, fname), "a") + except IOError, e: + ## cannot open file + msg = """Unable to write to file [%s] - cannot open file for writing in append mode""" % (fname,) + raise InvenioWebSubmitAdminWarningIOError(msg) + + ## write contents to temp file: + try: + fp.write(filecontent) + fp.flush() + fp.close() + except IOError, e: + ## could not write to temp file + msg = """Unable to write to file [%s] in append mode""" % (fname,) + ## close the file + try: + fp.close() + except IOError: + pass + raise InvenioWebSubmitAdminWarningIOError(msg) + return + +def string_is_alphanumeric_including_underscore(txtstring): + p_txtstring = re.compile(r'^\w*$') + m_txtstring = p_txtstring.search(txtstring) + if m_txtstring is not None: + return 1 + else: + return 0 + +def function_name_is_valid(fname): + p_fname = re.compile(r'^(_|[a-zA-Z])\w*$') + m_fname = p_fname.search(fname) + if m_fname is not None: + return 1 + else: + return 0 + +def wash_single_urlarg(urlarg, argreqdtype, argdefault, maxstrlen=None, minstrlen=None, truncatestr=0): + """Wash a single argument according to some specifications. + @param urlarg: the argument to be tested, as passed from the form/url, etc + @param argreqdtype: (a python type) the type that the argument should conform to (argument required + type) + @argdefault: the default value that should be returned for the argument in the case that it + doesn't comply with the washing specifications + @param maxstrlen: (integer) the maximum length for a string argument; defaults to None, which means + that no maximum length is forced upon the string + @param minstrlen: (integer) the minimum length for a string argument; defaults to None, which means + that no minimum length is forced upon the string + @truncatestr: (integer) should be 1 or 0 (ZERO). A flag used to determine whether or not a string + argument that overstretches the maximum length (if one if provided) should be truncated, or reset + to the default for the argument. 0, means don't truncate and reset the argument; 1 means truncate + the string. + @return: the washed argument + @exceptions raised: + - ValueError: when it is not possible to cast an argument to the type passed as argreqdtype + """ + ## sanity checking: + if maxstrlen is not None and type(maxstrlen) is not int: + maxstrlen = None + elif maxstrlen is int and maxstrlen < 1: + maxstrlen = None + if minstrlen is not None and type(minstrlen) is not int: + minstrlen = None + elif minstrlen is int and minstrlen < 1: + minstrlen = None + + result = "" + arg_dst_type = argreqdtype + + ## if no urlarg, return the default for that argument: + if urlarg is None: + result = argdefault + return result + + ## get the type of the argument passed: + arg_src_type = type(urlarg) + value = urlarg + + # First, handle the case where we want all the results. In + # this case, we need to ensure all the elements are strings, + # and not Field instances. + if arg_src_type in (list, tuple): + if arg_dst_type is list: + result = [str(x) for x in value] + return result + + if arg_dst_type is tuple: + result = tuple([str(x) for x in value]) + return result + + # in all the other cases, we are only interested in the + # first value. + value = value[0] + + # Maybe we already have what is expected? Then don't change + # anything. + if arg_src_type is arg_dst_type: + result = value + if arg_dst_type is str and maxstrlen is not None and len(result) > maxstrlen: + if truncatestr != 0: + result = result[0:maxstrlen] + else: + result = argdefault + elif arg_dst_type is str and minstrlen is not None and len(result) < minstrlen: + result = argdefault + return result + + if arg_dst_type in (str, int): + try: + result = arg_dst_type(value) + + if arg_dst_type is str and maxstrlen is not None and len(result) > maxstrlen: + if truncatestr != 0: + result = result[0:maxstrlen] + else: + result = argdefault + elif arg_dst_type is str and minstrlen is not None and len(result) < minstrlen: + result = argdefault + except: + result = argdefault + elif arg_dst_type is tuple: + result = (value,) + + elif arg_dst_type is list: + result = [value] + + elif arg_dst_type is dict: + result = {0: str(value)} + + else: + raise ValueError('cannot cast form argument into type %r' % (arg_dst_type,)) + + return result + + +## Internal Business-Logic functions + +## Functions for managing collection order, etc: + +def build_submission_collection_tree(collection_id, has_brother_above=0, has_brother_below=0): + ## get the name of this collection: + collection_name = get_collection_name(collection_id) + if collection_name is None: + collection_name = "Unknown Collection" + + ## make a data-structure containing the details of the collection: + collection_node = { 'collection_id' : collection_id, ## collection ID + 'collection_name' : collection_name, ## collection Name + 'collection_children' : [], ## list of 'collection' children nodes + 'doctype_children' : [], ## list of 'doctype' children + 'has_brother_above' : has_brother_above, ## has a sibling collection above in score + 'has_brother_below' : has_brother_below, ## has a sibling collection below in score + } + + ## get the IDs and names of all doctypes attached to this collection: + res_doctype_children = get_doctype_children_of_collection(collection_id) + ## for each child, add its details to the list of doctype children for this node: + for doctype in res_doctype_children: + doctype_node = { 'doctype_id' : doctype[0], + 'doctype_lname' : doctype[1], + 'catalogue_order' : doctype[2], + } + collection_node['doctype_children'].append(doctype_node) + + ## now get details of all collections attached to this one: + res_collection_children = get_collection_children_of_collection(collection_id) + + num_collection_children = len(res_collection_children) + for child_num in xrange(0, num_collection_children): + brother_below = brother_above = 0 + if child_num > 0: + ## this is not the first brother - it has a brother above + brother_above = 1 + if child_num < num_collection_children - 1: + ## this is not the last brother - it has a brother below + brother_below = 1 + collection_node['collection_children'].append(\ + build_submission_collection_tree(collection_id=res_collection_children[child_num][0], + has_brother_above=brother_above, + has_brother_below=brother_below)) + + + ## return the built collection tree: + return collection_node + +def _organise_submission_page_display_submission_tree(user_msg=""): + title = "Organise WebSubmit Main Page" + body = "" + if user_msg == "" or type(user_msg) not in (list, tuple, str, unicode): + user_msg = [] + ## Get the submissions tree: + submission_collection_tree = build_submission_collection_tree(0) + ## Get all 'submission collections': + submission_collections = get_details_of_all_submission_collections() + sub_col = [('0', 'Top Level')] + for collection in submission_collections: + sub_col.append((str(collection[0]), str(collection[1]))) + ## Get all document types: + doctypes = get_docid_docname_and_docid_alldoctypes() + + ## build the page: + body = websubmitadmin_templates.tmpl_display_submission_page_organisation(submission_collection_tree=submission_collection_tree, + submission_collections=sub_col, + doctypes=doctypes, + user_msg=user_msg) + return (title, body) + +def _delete_submission_collection(sbmcolid): + """Recursively calls itself to delete a submission-collection and all of its + attached children (and their children, etc) from the submission-tree. + @param sbmcolid: (integer) - the ID of the submission-collection to be deleted. + @return: None + @Exceptions raised: InvenioWebSubmitAdminWarningDeleteFailed when it was not + possible to delete the submission-collection or some of its children. + """ + ## Get the collection-children of this submission-collection: + collection_children = get_collection_children_of_collection(sbmcolid) + + ## recursively move through each collection-child: + for collection_child in collection_children: + _delete_submission_collection(collection_child[0]) + + ## delete all document-types attached to this submission-collection: + error_code = delete_doctype_children_from_submission_collection(sbmcolid) + if error_code != 0: + ## Unable to delete all doctype-children: + err_msg = "Unable to delete doctype children of submission-collection [%s]" % sbmcolid + raise InvenioWebSubmitAdminWarningDeleteFailed(err_msg) + + ## delete this submission-collection's entry from the sbmCOLLECTION_sbmCOLLECTION table: + error_code = delete_submission_collection_from_submission_tree(sbmcolid) + if error_code != 0: + ## Unable to delete submission-collection from the submission-tree: + err_msg = "Unable to delete submission-collection [%s] from submission-tree" % sbmcolid + raise InvenioWebSubmitAdminWarningDeleteFailed(err_msg) + + ## Now delete this submission-collection's details: + error_code = delete_submission_collection_details(sbmcolid) + if error_code != 0: + ## Unable to delete the details of the submission-collection: + err_msg = "Unable to delete details of submission-collection [%s]" % sbmcolid + raise InvenioWebSubmitAdminWarningDeleteFailed(err_msg) + + ## return + return + + +def perform_request_organise_submission_page(doctype="", + sbmcolid="", + catscore="", + addsbmcollection="", + deletesbmcollection="", + addtosbmcollection="", + adddoctypes="", + movesbmcollectionup="", + movesbmcollectiondown="", + deletedoctypefromsbmcollection="", + movedoctypeupinsbmcollection="", + movedoctypedowninsbmcollection=""): + user_msg = [] + body = "" + if "" not in (deletedoctypefromsbmcollection, sbmcolid, catscore, doctype): + ## delete a document type from it's position in the tree + error_code = delete_doctype_from_position_on_submission_page(doctype, sbmcolid, catscore) + if error_code == 0: + ## doctype deleted - now normalize scores of remaining doctypes: + normalize_scores_of_doctype_children_for_submission_collection(sbmcolid) + user_msg.append("Document type successfully deleted from submissions tree") + else: + user_msg.append("Unable to delete document type from submission-collection") + ## display submission-collections: + (title, body) = _organise_submission_page_display_submission_tree(user_msg=user_msg) + elif "" not in (deletesbmcollection, sbmcolid): + ## try to delete the submission-collection from the tree: + try: + _delete_submission_collection(sbmcolid) + user_msg.append("Submission-collection successfully deleted from submissions tree") + except InvenioWebSubmitAdminWarningDeleteFailed, excptn: + user_msg.append(str(excptn)) + ## re-display submission-collections: + (title, body) = _organise_submission_page_display_submission_tree(user_msg=user_msg) + elif "" not in (movedoctypedowninsbmcollection, sbmcolid, doctype, catscore): + ## move a doctype down in order for a submission-collection: + ## normalize scores of all doctype-children of the submission-collection: + normalize_scores_of_doctype_children_for_submission_collection(sbmcolid) + ## swap this doctype with that below it: + ## Get score of doctype to move: + score_doctype_to_move = get_catalogue_score_of_doctype_child_of_submission_collection(sbmcolid, doctype) + ## Get score of the doctype brother directly below the doctype to be moved: + score_brother_below = get_score_of_next_doctype_child_below(sbmcolid, score_doctype_to_move) + if None in (score_doctype_to_move, score_brother_below): + user_msg.append("Unable to move document type down") + else: + ## update the brother below the doctype to be moved to have a score the same as the doctype to be moved: + update_score_of_doctype_child_of_submission_collection_at_scorex(sbmcolid, score_brother_below, score_doctype_to_move) + ## Update the doctype to be moved to have a score of the brother directly below it: + update_score_of_doctype_child_of_submission_collection_with_doctypeid_and_scorex(sbmcolid, + doctype, + score_doctype_to_move, + score_brother_below) + user_msg.append("Document type moved down") + (title, body) = _organise_submission_page_display_submission_tree(user_msg=user_msg) + elif "" not in (movedoctypeupinsbmcollection, sbmcolid, doctype, catscore): + ## move a doctype up in order for a submission-collection: + ## normalize scores of all doctype-children of the submission-collection: + normalize_scores_of_doctype_children_for_submission_collection(sbmcolid) + ## swap this doctype with that above it: + ## Get score of doctype to move: + score_doctype_to_move = get_catalogue_score_of_doctype_child_of_submission_collection(sbmcolid, doctype) + ## Get score of the doctype brother directly above the doctype to be moved: + score_brother_above = get_score_of_previous_doctype_child_above(sbmcolid, score_doctype_to_move) + if None in (score_doctype_to_move, score_brother_above): + user_msg.append("Unable to move document type up") + else: + ## update the brother above the doctype to be moved to have a score the same as the doctype to be moved: + update_score_of_doctype_child_of_submission_collection_at_scorex(sbmcolid, score_brother_above, score_doctype_to_move) + ## Update the doctype to be moved to have a score of the brother directly above it: + update_score_of_doctype_child_of_submission_collection_with_doctypeid_and_scorex(sbmcolid, + doctype, + score_doctype_to_move, + score_brother_above) + user_msg.append("Document type moved up") + (title, body) = _organise_submission_page_display_submission_tree(user_msg=user_msg) + elif "" not in (movesbmcollectiondown, sbmcolid): + ## move a submission-collection down in order: + + ## Sanity checking: + try: + int(sbmcolid) + except ValueError: + sbmcolid = 0 + + if int(sbmcolid) != 0: + ## Get father ID of submission-collection: + sbmcolidfather = get_id_father_of_collection(sbmcolid) + if sbmcolidfather is None: + user_msg.append("Unable to move submission-collection downwards") + else: + ## normalize scores of all collection-children of the father submission-collection: + normalize_scores_of_collection_children_of_collection(sbmcolidfather) + ## swap this collection with the one above it: + ## get the score of the collection to move: + score_col_to_move = get_score_of_collection_child_of_submission_collection(sbmcolidfather, sbmcolid) + ## get the score of the collection brother directly below the collection to be moved: + score_brother_below = get_score_of_next_collection_child_below(sbmcolidfather, score_col_to_move) + if None in (score_col_to_move, score_brother_below): + ## Invalid movement + user_msg.append("Unable to move submission collection downwards") + else: + ## update the brother below the collection to be moved to have a score the same as the collection to be moved: + update_score_of_collection_child_of_submission_collection_at_scorex(sbmcolidfather, + score_brother_below, + score_col_to_move) + ## Update the collection to be moved to have a score of the brother directly below it: + update_score_of_collection_child_of_submission_collection_with_colid_and_scorex(sbmcolidfather, + sbmcolid, + score_col_to_move, + score_brother_below) + user_msg.append("Submission-collection moved downwards") + + else: + ## cannot move the master (0) collection + user_msg.append("Unable to move submission-collection downwards") + (title, body) = _organise_submission_page_display_submission_tree(user_msg=user_msg) + elif "" not in (movesbmcollectionup, sbmcolid): + ## move a submission-collection up in order: + + ## Sanity checking: + try: + int(sbmcolid) + except ValueError: + sbmcolid = 0 + + if int(sbmcolid) != 0: + ## Get father ID of submission-collection: + sbmcolidfather = get_id_father_of_collection(sbmcolid) + if sbmcolidfather is None: + user_msg.append("Unable to move submission-collection upwards") + else: + ## normalize scores of all collection-children of the father submission-collection: + normalize_scores_of_collection_children_of_collection(sbmcolidfather) + ## swap this collection with the one above it: + ## get the score of the collection to move: + score_col_to_move = get_score_of_collection_child_of_submission_collection(sbmcolidfather, sbmcolid) + ## get the score of the collection brother directly above the collection to be moved: + score_brother_above = get_score_of_previous_collection_child_above(sbmcolidfather, score_col_to_move) + if None in (score_col_to_move, score_brother_above): + ## Invalid movement + user_msg.append("Unable to move submission collection upwards") + else: + ## update the brother above the collection to be moved to have a score the same as the collection to be moved: + update_score_of_collection_child_of_submission_collection_at_scorex(sbmcolidfather, + score_brother_above, + score_col_to_move) + ## Update the collection to be moved to have a score of the brother directly above it: + update_score_of_collection_child_of_submission_collection_with_colid_and_scorex(sbmcolidfather, + sbmcolid, + score_col_to_move, + score_brother_above) + user_msg.append("Submission-collection moved upwards") + else: + ## cannot move the master (0) collection + user_msg.append("Unable to move submission-collection upwards") + (title, body) = _organise_submission_page_display_submission_tree(user_msg=user_msg) + elif "" not in (addsbmcollection, addtosbmcollection): + ## Add a submission-collection, attached to a submission-collection: + ## check that the collection to attach to exists: + parent_ok = 0 + if int(addtosbmcollection) != 0: + parent_name = get_collection_name(addtosbmcollection) + if parent_name is not None: + parent_ok = 1 + else: + parent_ok = 1 + if parent_ok != 0: + ## create the new collection: + id_son = insert_submission_collection(addsbmcollection) + ## get the maximum catalogue score of the existing collection children: + max_child_score = \ + get_maximum_catalogue_score_of_collection_children_of_submission_collection(addtosbmcollection) + ## add it to the collection, at a higher score than the others have: + new_score = max_child_score + 1 + insert_collection_child_for_submission_collection(addtosbmcollection, id_son, new_score) + user_msg.append("Submission-collection added to submissions tree") + else: + ## Parent submission-collection does not exist: + user_msg.append("Unable to add submission-collection - parent unknown") + (title, body) = _organise_submission_page_display_submission_tree(user_msg=user_msg) + elif "" not in (adddoctypes, addtosbmcollection): + ## Add document type(s) to a submission-collection: + if type(adddoctypes) == str: + adddoctypes = [adddoctypes,] + ## Does submission-collection exist? + num_collections_sbmcolid = get_number_of_rows_for_submission_collection(addtosbmcollection) + if num_collections_sbmcolid > 0: + for doctypeid in adddoctypes: + ## Check that Doctype exists: + num_doctypes_doctypeid = get_number_doctypes_docid(doctypeid) + + if num_doctypes_doctypeid < 1: + ## Cannot connect an unknown doctype: + user_msg.append("Unable to connect unknown document-type [%s] to a submission-collection" \ + % doctypeid) + continue + else: + ## insert the submission-collection/doctype link: + ## get the maximum catalogue score of the existing doctype children: + max_child_score = \ + get_maximum_catalogue_score_of_doctype_children_of_submission_collection(addtosbmcollection) + ## add it to the new doctype, at a higher score than the others have: + new_score = max_child_score + 1 + insert_doctype_child_for_submission_collection(addtosbmcollection, doctypeid, new_score) + user_msg.append("Document-type added to submissions tree") + else: + ## submission-collection didn't exist + user_msg.append("The selected submission-collection doesn't seem to exist") + ## Check that submission-collection exists: + ## insert + (title, body) = _organise_submission_page_display_submission_tree(user_msg=user_msg) + else: + ## default action - display submission-collections: + (title, body) = _organise_submission_page_display_submission_tree(user_msg=user_msg) + return (title, body) + + + +## Functions for adding new catalgue to DB: +def _add_new_action(actid,actname,working_dir,status_text): + """Insert the details of a new action into the websubmit system database. + @param actid: unique action id (sactname) + @param actname: action name (lactname) + @param working_dir: directory action works from (dir) + @param status_text: text string indicating action status (statustext) + """ + (actid,actname,working_dir,status_text) = (str(actid).upper(),str(actname),str(working_dir),str(status_text)) + err_code = insert_action_details(actid,actname,working_dir,status_text) + return err_code + +def perform_request_add_function(funcname=None, funcdescr=None, funcaddcommit=""): + user_msg = [] + body = "" + title = "Create New WebSubmit Function" + commit_error=0 + + ## wash args: + if funcname is not None: + try: + funcname = wash_single_urlarg(urlarg=funcname, argreqdtype=str, argdefault="", maxstrlen=40, minstrlen=1) + if function_name_is_valid(fname=funcname) == 0: + funcname = "" + except ValueError, e: + funcname = "" + else: + funcname = "" + if funcdescr is not None: + try: + funcdescr = wash_single_urlarg(urlarg=funcdescr, argreqdtype=str, argdefault="") + except ValueError, e: + funcdescr = "" + else: + funcdescr = "" + + ## process request: + if funcaddcommit != "" and funcaddcommit is not None: + if funcname == "": + funcname = "" + user_msg.append("""Function name is mandatory and must be a string with no more than 40 characters""") + user_msg.append("""It must contain only alpha-numeric and underscore characters, beginning with a """\ + """letter or underscore""") + commit_error = 1 + + if commit_error != 0: + ## don't commit - just re-display page with message to user + body = websubmitadmin_templates.tmpl_display_addfunctionform(funcdescr=funcdescr, user_msg=user_msg) + return (title, body) + + ## Add a new function definition - IF it is not already present + err_code = insert_function_details(funcname, funcdescr) + + ## Handle error code - redisplay form with warning about no DB commit, or display with options + ## to edit function: + if err_code == 0: + user_msg.append("""'%s' Function Added to WebSubmit""" % (funcname,)) + all_function_parameters = get_distinct_paramname_all_websubmit_function_parameters() + body = websubmitadmin_templates.tmpl_display_addfunctionform(funcname=funcname, + funcdescr=funcdescr, + all_websubmit_func_parameters=all_function_parameters, + perform_act="functionedit", + user_msg=user_msg) + else: + ## Could not commit function to WebSubmit DB - redisplay form with function description: + user_msg.append("""Could Not Add '%s' Function to WebSubmit""" % (funcname,)) + body = websubmitadmin_templates.tmpl_display_addfunctionform(funcdescr=funcdescr, user_msg=user_msg) + + else: + ## Display Web form for new function addition: + body = websubmitadmin_templates.tmpl_display_addfunctionform() + + return (title, body) + +def perform_request_add_action(actid=None, actname=None, working_dir=None, status_text=None, actcommit=""): + """An interface for the addition of a new WebSubmit action. + If form fields filled, will insert new action into WebSubmit database, else will display + web form prompting for action details. + @param actid: unique id for new action + @param actname: name of new action + @param working_dir: action working directory for WebSubmit core + @param status_text: status text displayed at end of action + @return: tuple containing "title" (title of page), body (page body). + """ + user_msg = [] + body = "" + title = "Create New WebSubmit Action" + commit_error=0 + + ## wash args: + if actid is not None: + try: + actid = wash_single_urlarg(urlarg=actid, argreqdtype=str, argdefault="", maxstrlen=3, minstrlen=3) + if string_is_alphanumeric_including_underscore(txtstring=actid) == 0: + actid = "" + except ValueError, e: + actid = "" + else: + actid = "" + if actname is not None: + try: + actname = wash_single_urlarg(urlarg=actname, argreqdtype=str, argdefault="") + except ValueError, e: + actname = "" + else: + actname = "" + if working_dir is not None: + try: + working_dir = wash_single_urlarg(urlarg=working_dir, argreqdtype=str, argdefault="") + except ValueError, e: + working_dir = "" + else: + working_dir = "" + if status_text is not None: + try: + status_text = wash_single_urlarg(urlarg=status_text, argreqdtype=str, argdefault="") + except ValueError, e: + status_text = "" + else: + status_text = "" + + ## process request: + if actcommit != "" and actcommit is not None: + if actid in ("", None): + actid = "" + user_msg.append("""Action ID is mandatory and must be a 3 letter string""") + commit_error = 1 + if actname in ("", None): + actname = "" + user_msg.append("""Action description is mandatory""") + commit_error = 1 + + if commit_error != 0: + ## don't commit - just re-display page with message to user + body = websubmitadmin_templates.tmpl_display_addactionform(actid=actid, actname=actname, working_dir=working_dir,\ + status_text=status_text, user_msg=user_msg) + return (title, body) + + ## Commit new action to WebSubmit DB: + err_code = _add_new_action(actid,actname,working_dir,status_text) + + ## Handle error code - redisplay form with warning about no DB commit, or move to list + ## of actions + if err_code == 0: + ## Action added: show page listing WebSubmit actions + user_msg = """'%s' Action Added to WebSubmit""" % (actid,) + all_actions = get_actid_actname_allactions() + body = websubmitadmin_templates.tmpl_display_allactions(all_actions,user_msg=user_msg) + title = "Available WebSubmit Actions" + else: + ## Could not commit action to WebSubmit DB redisplay form with completed details and error message + ## warnings.append(('ERR_WEBSUBMIT_ADMIN_ADDACTIONFAILDUPLICATE',actid) ## TODO + user_msg = """Could Not Add '%s' Action to WebSubmit""" % (actid,) + body = websubmitadmin_templates.tmpl_display_addactionform(actid=actid, actname=actname, working_dir=working_dir, \ + status_text=status_text, user_msg=user_msg) + else: + ## Display Web form for new action details: + body = websubmitadmin_templates.tmpl_display_addactionform() + return (title, body) + +def perform_request_add_jscheck(chname=None, chdesc=None, chcommit=""): + """An interface for the addition of a new WebSubmit JavaScript Check, as used on form elements. + If form fields filled, will insert new Check into WebSubmit database, else will display + Web form prompting for Check details. + @param chname: unique id/name for new Check + @param chdesc: description (JavaScript code body) of new Check + @return: tuple containing "title" (title of page), body (page body). + """ + user_msg = [] + body = "" + title = "Create New WebSubmit Checking Function" + commit_error=0 + + ## wash args: + if chname is not None: + try: + chname = wash_single_urlarg(urlarg=chname, argreqdtype=str, argdefault="", maxstrlen=15, minstrlen=1) + if function_name_is_valid(fname=chname) == 0: + chname = "" + except ValueError, e: + chname = "" + else: + chname = "" + if chdesc is not None: + try: + chdesc = wash_single_urlarg(urlarg=chdesc, argreqdtype=str, argdefault="") + except ValueError, e: + chdesc = "" + else: + chdesc = "" + + ## process request: + if chcommit != "" and chcommit is not None: + if chname in ("", None): + chname = "" + user_msg.append("""Check name is mandatory and must be a string with no more than 15 characters""") + user_msg.append("""It must contain only alpha-numeric and underscore characters, beginning with a """\ + """letter or underscore""") + commit_error = 1 + + if commit_error != 0: + ## don't commit - just re-display page with message to user + body = websubmitadmin_templates.tmpl_display_addjscheckform(chname=chname, chdesc=chdesc, user_msg=user_msg) + return (title, body) + + ## Commit new check to WebSubmit DB: + err_code = insert_jscheck_details(chname, chdesc) + + ## Handle error code - redisplay form wih warning about no DB commit, or move to list + ## of checks + if err_code == 0: + ## Check added: show page listing WebSubmit JS Checks + user_msg.append("""'%s' Checking Function Added to WebSubmit""" % (chname,)) + all_jschecks = get_chname_alljschecks() + body = websubmitadmin_templates.tmpl_display_alljschecks(all_jschecks, user_msg=user_msg) + title = "Available WebSubmit Checking Functions" + else: + ## Could not commit Check to WebSubmit DB: redisplay form with completed details and error message + ## TODO : Warning Message + user_msg.append("""Could Not Add '%s' Checking Function to WebSubmit""" % (chname,)) + body = websubmitadmin_templates.tmpl_display_addjscheckform(chname=chname, chdesc=chdesc, user_msg=user_msg) + else: + ## Display Web form for new check details: + body = websubmitadmin_templates.tmpl_display_addjscheckform() + return (title, body) + +def perform_request_add_element(elname=None, elmarccode=None, eltype=None, elsize=None, elrows=None, \ + elcols=None, elmaxlength=None, elval=None, elfidesc=None, \ + elmodifytext=None, elcommit=""): + """An interface for adding a new ELEMENT to the WebSubmit DB. + @param elname: (string) element name. + @param elmarccode: (string) element's MARC code. + @param eltype: (character) element type. + @param elsize: (integer) element size. + @param elrows: (integer) number of rows in element. + @param elcols: (integer) number of columns in element. + @param elmaxlength: (integer) maximum length of element + @param elval: (string) default value of element + @param elfidesc: (string) description of element + @param elmodifytext: (string) modification text of element + @param elcommit: (string) If this value is not empty, attempt to commit element details to WebSubmit DB + @return: tuple containing "title" (title of page), body (page body). + """ + user_msg = [] + body = "" + title = "Create New WebSubmit Element" + commit_error=0 + + ## wash args: + if elname is not None: + try: + elname = wash_single_urlarg(urlarg=elname, argreqdtype=str, argdefault="", maxstrlen=15, minstrlen=1) + if string_is_alphanumeric_including_underscore(txtstring=elname) == 0: + elname = "" + except ValueError, e: + elname = "" + else: + elname = "" + if elmarccode is not None: + try: + elmarccode = wash_single_urlarg(urlarg=elmarccode, argreqdtype=str, argdefault="") + except ValueError, e: + elmarccode = "" + else: + elmarccode = "" + if eltype is not None: + try: + eltype = wash_single_urlarg(urlarg=eltype, argreqdtype=str, argdefault="", maxstrlen=1, minstrlen=1) + except ValueError, e: + eltype = "" + else: + eltype = "" + if elsize is not None: + try: + elsize = wash_single_urlarg(urlarg=elsize, argreqdtype=int, argdefault="") + except ValueError, e: + elsize = "" + else: + elsize = "" + if elrows is not None: + try: + elrows = wash_single_urlarg(urlarg=elrows, argreqdtype=int, argdefault="") + except ValueError, e: + elrows = "" + else: + elrows = "" + if elcols is not None: + try: + elcols = wash_single_urlarg(urlarg=elcols, argreqdtype=int, argdefault="") + except ValueError, e: + elcols = "" + else: + elcols = "" + if elmaxlength is not None: + try: + elmaxlength = wash_single_urlarg(urlarg=elmaxlength, argreqdtype=int, argdefault="") + except ValueError, e: + elmaxlength = "" + else: + elmaxlength = "" + if elval is not None: + try: + elval = wash_single_urlarg(urlarg=elval, argreqdtype=str, argdefault="") + except ValueError, e: + elval = "" + else: + elval = "" + if elfidesc is not None: + try: + elfidesc = wash_single_urlarg(urlarg=elfidesc, argreqdtype=str, argdefault="") + except ValueError, e: + elfidesc = "" + else: + elfidesc = "" + if elmodifytext is not None: + try: + elmodifytext = wash_single_urlarg(urlarg=elmodifytext, argreqdtype=str, argdefault="") + except ValueError, e: + elmodifytext = "" + else: + elmodifytext = "" + + ## process request: + if elcommit != "" and elcommit is not None: + if elname == "": + elname = "" + user_msg.append("""The element name is mandatory and must be a string with no more than 15 characters""") + user_msg.append("""It must contain only alpha-numeric and underscore characters""") + commit_error = 1 + if eltype == "" or eltype not in ("D", "F", "H", "I", "R", "S", "T"): + eltype = "" + user_msg.append("""The element type is mandatory and must be selected from the list""") + commit_error = 1 + + if commit_error != 0: + ## don't commit - just re-display page with message to user + body = websubmitadmin_templates.tmpl_display_addelementform(elname=elname, + elmarccode=elmarccode, + eltype=eltype, + elsize=str(elsize), + elrows=str(elrows), + elcols=str(elcols), + elmaxlength=str(elmaxlength), + elval=elval, + elfidesc=elfidesc, + elmodifytext=elmodifytext, + user_msg=user_msg, + ) + return (title, body) + + ## Commit new element description to WebSubmit DB: + err_code = insert_element_details(elname=elname, elmarccode=elmarccode, eltype=eltype, \ + elsize=elsize, elrows=elrows, elcols=elcols, \ + elmaxlength=elmaxlength, elval=elval, elfidesc=elfidesc, \ + elmodifytext=elmodifytext) + if err_code == 0: + ## Element added: show page listing WebSubmit elements + user_msg.append("""'%s' Element Added to WebSubmit""" % (elname,)) + title = "Available WebSubmit Elements" + all_elements = get_elename_allelements() + body = websubmitadmin_templates.tmpl_display_allelements(all_elements, user_msg=user_msg) + else: + ## Could not commit element to WebSubmit DB: redisplay form with completed details and error message + ## TODO : Warning Message + user_msg.append("""Could Not Add '%s' Element to WebSubmit""" % (elname,)) + body = websubmitadmin_templates.tmpl_display_addelementform(elname=elname, + elmarccode=elmarccode, + eltype=eltype, + elsize=str(elsize), + elrows=str(elrows), + elcols=str(elcols), + elmaxlength=str(elmaxlength), + elval=elval, + elfidesc=elfidesc, + elmodifytext=elmodifytext, + user_msg=user_msg, + ) + else: + ## Display Web form for new element details: + body = websubmitadmin_templates.tmpl_display_addelementform() + return (title, body) + +def perform_request_edit_element(elname, elmarccode=None, eltype=None, elsize=None, \ + elrows=None, elcols=None, elmaxlength=None, elval=None, \ + elfidesc=None, elmodifytext=None, elcommit=""): + """An interface for the editing and updating the details of a WebSubmit ELEMENT. + @param elname: element name. + @param elmarccode: element's MARC code. + @param eltype: element type. + @param elsize: element size. + @param elrows: number of rows in element. + @param elcols: number of columns in element. + @param elmaxlength: maximum length of element + @param elval: default value of element + @param elfidesc: description of element + @param elmodifytext: modification text of element + @param elcommit: If this value is not empty, attempt to commit element details to WebSubmit DB + @return: tuple containing "title" (title of page), body (page body). + """ + user_msg = [] + body = "" + title = "Edit WebSubmit Element" + commit_error=0 + + ## wash args: + if elname is not None: + try: + elname = wash_single_urlarg(urlarg=elname, argreqdtype=str, argdefault="", maxstrlen=15, minstrlen=1) + if string_is_alphanumeric_including_underscore(txtstring=elname) == 0: + elname = "" + except ValueError, e: + elname = "" + else: + elname = "" + if elmarccode is not None: + try: + elmarccode = wash_single_urlarg(urlarg=elmarccode, argreqdtype=str, argdefault="") + except ValueError, e: + elmarccode = "" + else: + elmarccode = "" + if eltype is not None: + try: + eltype = wash_single_urlarg(urlarg=eltype, argreqdtype=str, argdefault="", maxstrlen=1, minstrlen=1) + except ValueError, e: + eltype = "" + else: + eltype = "" + if elsize is not None: + try: + elsize = wash_single_urlarg(urlarg=elsize, argreqdtype=int, argdefault="") + except ValueError, e: + elsize = "" + else: + elsize = "" + if elrows is not None: + try: + elrows = wash_single_urlarg(urlarg=elrows, argreqdtype=int, argdefault="") + except ValueError, e: + elrows = "" + else: + elrows = "" + if elcols is not None: + try: + elcols = wash_single_urlarg(urlarg=elcols, argreqdtype=int, argdefault="") + except ValueError, e: + elcols = "" + else: + elcols = "" + if elmaxlength is not None: + try: + elmaxlength = wash_single_urlarg(urlarg=elmaxlength, argreqdtype=int, argdefault="") + except ValueError, e: + elmaxlength = "" + else: + elmaxlength = "" + if elval is not None: + try: + elval = wash_single_urlarg(urlarg=elval, argreqdtype=str, argdefault="") + except ValueError, e: + elval = "" + else: + elval = "" + if elfidesc is not None: + try: + elfidesc = wash_single_urlarg(urlarg=elfidesc, argreqdtype=str, argdefault="") + except ValueError, e: + elfidesc = "" + else: + elfidesc = "" + if elmodifytext is not None: + try: + elmodifytext = wash_single_urlarg(urlarg=elmodifytext, argreqdtype=str, argdefault="") + except ValueError, e: + elmodifytext = "" + else: + elmodifytext = "" + + ## process request: + if elcommit != "" and elcommit is not None: + if elname == "": + elname = "" + user_msg.append("""Invalid Element Name!""") + commit_error = 1 + if eltype == "" or eltype not in ("D", "F", "H", "I", "R", "S", "T"): + eltype = "" + user_msg.append("""Invalid Element Type!""") + commit_error = 1 + + if commit_error != 0: + ## don't commit - just re-display page with message to user + all_elements = get_elename_allelements() + user_msg.append("""Could Not Update Element""") + title = "Available WebSubmit Elements" + body = websubmitadmin_templates.tmpl_display_allelements(all_elements, user_msg=user_msg) + return (title, body) + + ## Commit updated element description to WebSubmit DB: + err_code = update_element_details(elname=elname, elmarccode=elmarccode, eltype=eltype, \ + elsize=elsize, elrows=elrows, elcols=elcols, \ + elmaxlength=elmaxlength, elval=elval, elfidesc=elfidesc, \ + elmodifytext=elmodifytext) + if err_code == 0: + ## Element Updated: Show All Element Details Again + user_msg.append("""'%s' Element Updated""" % (elname,)) + ## Get submission page usage of element: + el_use = get_doctype_action_pagenb_for_submissions_using_element(elname) + element_dets = get_element_details(elname) + element_dets = stringify_listvars(element_dets) + ## Take elements from results tuple: + (elmarccode, eltype, elsize, elrows, elcols, elmaxlength, \ + elval, elfidesc, elcd, elmd, elmodifytext) = \ + (element_dets[0][0], element_dets[0][1], element_dets[0][2], element_dets[0][3], \ + element_dets[0][4], element_dets[0][5], element_dets[0][6], element_dets[0][7], \ + element_dets[0][8], element_dets[0][9], element_dets[0][10]) + ## Pass to template: + body = websubmitadmin_templates.tmpl_display_addelementform(elname=elname, + elmarccode=elmarccode, + eltype=eltype, + elsize=elsize, + elrows=elrows, + elcols=elcols, + elmaxlength=elmaxlength, + elval=elval, + elfidesc=elfidesc, + elcd=elcd, + elmd=elmd, + elmodifytext=elmodifytext, + perform_act="elementedit", + user_msg=user_msg, + el_use_tuple=el_use + ) + else: + ## Could Not Update Element: Maybe Key Violation, or Invalid elname? Redisplay all elements. + ## TODO : LOGGING + all_elements = get_elename_allelements() + user_msg.append("""Could Not Update Element '%s'""" % (elname,)) + title = "Available WebSubmit Elements" + body = websubmitadmin_templates.tmpl_display_allelements(all_elements, user_msg=user_msg) + else: + ## Display Web form containing existing details of element: + element_dets = get_element_details(elname) + ## Get submission page usage of element: + el_use = get_doctype_action_pagenb_for_submissions_using_element(elname) + num_rows_ret = len(element_dets) + element_dets = stringify_listvars(element_dets) + if num_rows_ret == 1: + ## Display Element details + ## Take elements from results tuple: + (elmarccode, eltype, elsize, elrows, elcols, elmaxlength, \ + elval, elfidesc, elcd, elmd, elmodifytext) = \ + (element_dets[0][0], element_dets[0][1], element_dets[0][2], element_dets[0][3], \ + element_dets[0][4], element_dets[0][5], element_dets[0][6], element_dets[0][7], \ + element_dets[0][8], element_dets[0][9], element_dets[0][10]) + ## Pass to template: + body = websubmitadmin_templates.tmpl_display_addelementform(elname=elname, + elmarccode=elmarccode, + eltype=eltype, + elsize=elsize, + elrows=elrows, + elcols=elcols, + elmaxlength=elmaxlength, + elval=elval, + elfidesc=elfidesc, + elcd=elcd, + elmd=elmd, + elmodifytext=elmodifytext, + perform_act="elementedit", + el_use_tuple=el_use + ) + else: + ## Either no rows, or more than one row for ELEMENT: log error, and display all Elements + ## TODO : LOGGING + title = "Available WebSubmit Elements" + all_elements = get_elename_allelements() + if num_rows_ret > 1: + ## Key Error - duplicated elname + user_msg.append("""Found Several Rows for Element with Name '%s' - Inform Administrator""" % (elname,)) + ## LOG MESSAGE + else: + ## No rows for ELEMENT + user_msg.append("""Could Not Find Any Rows for Element with Name '%s'""" % (elname,)) + ## LOG MESSAGE + body = websubmitadmin_templates.tmpl_display_allelements(all_elements, user_msg=user_msg) + return (title, body) + +def _display_edit_check_form(chname, user_msg=""): + title = "Edit WebSubmit Checking Function" + if user_msg == "": + user_msg = [] + jscheck_dets = get_jscheck_details(chname) + num_rows_ret = len(jscheck_dets) + if num_rows_ret == 1: + ## Display Check details + body = websubmitadmin_templates.tmpl_display_addjscheckform(chname=jscheck_dets[0][0], + chdesc=jscheck_dets[0][1], + perform_act="jscheckedit", + cd=jscheck_dets[0][2], + md=jscheck_dets[0][3], + user_msg=user_msg) + else: + ## Either no rows, or more than one row for Check: log error, and display all Checks + ## TODO : LOGGING + title = "Available WebSubmit Checking Functions" + all_jschecks = get_chname_alljschecks() + if num_rows_ret > 1: + ## Key Error - duplicated chname + user_msg.append("""Found Several Rows for Checking Function with Name '%s' - Inform Administrator""" % (chname,)) + ## LOG MESSAGE + else: + ## No rows for action + user_msg.append("""Could Not Find Any Rows for Checking Function with Name '%s'""" % (chname,)) + ## LOG MESSAGE + body = websubmitadmin_templates.tmpl_display_alljschecks(all_jschecks, user_msg=user_msg) + return (title, body) + + +def perform_request_edit_jscheck(chname, chdesc=None, chcommit=""): + """Interface for editing and updating the details of a WebSubmit Check. + If only "chname" provided, will display the details of a Check in a Web form. + If "chdesc" not empty, will assume that this is a call to commit update to Check details. + @param chname: unique id for Check + @param chdesc: modified value for WebSubmit Check description (code body) - (presence invokes update) + @return: tuple containing "title" (title of page), body (page body). + """ + user_msg = [] + body = "" + title = "Edit WebSubmit Checking Function" + commit_error=0 + + ## wash args: + if chname is not None: + try: + chname = wash_single_urlarg(urlarg=chname, argreqdtype=str, argdefault="", maxstrlen=15, minstrlen=1) + if function_name_is_valid(fname=chname) == 0: + chname = "" + except ValueError, e: + chname = "" + else: + chname = "" + if chdesc is not None: + try: + chdesc = wash_single_urlarg(urlarg=chdesc, argreqdtype=str, argdefault="") + except ValueError, e: + chdesc = "" + else: + chdesc = "" + (chname, chdesc) = (str(chname), str(chdesc)) + + if chcommit != "" and chcommit is not None: + if chname in ("", None): + chname = "" + user_msg.append("""Check name is mandatory and must be a string with no more than 15 characters""") + user_msg.append("""It must contain only alpha-numeric and underscore characters, beginning with a """\ + """letter or underscore""") + commit_error = 1 + + if commit_error != 0: + ## don't commit - just re-display page with message to user + all_jschecks = get_chname_alljschecks() + user_msg.append("""Could Not Update Checking Function""") + body = websubmitadmin_templates.tmpl_display_alljschecks(all_jschecks, user_msg=user_msg) + title = "Available WebSubmit Checking Functions" + return (title, body) + + ## Commit updated Check details to WebSubmit DB: + err_code = update_jscheck_details(chname, chdesc) + if err_code == 0: + ## Check Updated: Show All Check Details Again + user_msg.append("""'%s' Check Updated""" % (chname,)) + jscheck_dets = get_jscheck_details(chname) + body = websubmitadmin_templates.tmpl_display_addjscheckform(chname=jscheck_dets[0][0], + chdesc=jscheck_dets[0][1], + perform_act="jscheckedit", + cd=jscheck_dets[0][2], + md=jscheck_dets[0][3], + user_msg=user_msg + ) + else: + ## Could Not Update Check: Maybe Key Violation, or Invalid chname? Redisplay all Checks. + ## TODO : LOGGING + all_jschecks = get_chname_alljschecks() + user_msg.append("""Could Not Update Checking Function '%s'""" % (chname,)) + body = websubmitadmin_templates.tmpl_display_alljschecks(all_jschecks, user_msg=user_msg) + title = "Available WebSubmit Checking Functions" + else: + ## Display Web form containing existing details of Check: + (title, body) = _display_edit_check_form(chname=chname) + return (title, body) + +def _display_edit_action_form(actid, user_msg=""): + title = "Edit WebSubmit Action" + if user_msg == "": + user_msg = [] + action_dets = get_action_details(actid) + num_rows_ret = len(action_dets) + if num_rows_ret == 1: + ## Display action details + body = websubmitadmin_templates.tmpl_display_addactionform(actid=action_dets[0][0], + actname=action_dets[0][1], + working_dir=action_dets[0][2], + status_text=action_dets[0][3], + perform_act="actionedit", + cd=action_dets[0][4], + md=action_dets[0][5], + user_msg=user_msg) + else: + ## Either no rows, or more than one row for action: log error, and display all actions + ## TODO : LOGGING + title = "Available WebSubmit Actions" + all_actions = get_actid_actname_allactions() + if num_rows_ret > 1: + ## Key Error - duplicated actid + user_msg.append("""Found Several Rows for Action with ID '%s' - Inform Administrator""" % (actid,)) + ## LOG MESSAGE + else: + ## No rows for action + user_msg.append("""Could Not Find Any Rows for Action with ID '%s'""" % (actid,)) + ## LOG MESSAGE + body = websubmitadmin_templates.tmpl_display_allactions(all_actions, user_msg=user_msg) + return (title, body) + +def perform_request_edit_action(actid, actname=None, working_dir=None, status_text=None, actcommit=""): + """Interface for editing and updating the details of a WebSubmit action. + If only "actid" provided, will display the details of an action in a Web form. + If "actname" not empty, will assume that this is a call to commit update to action details. + @param actid: unique id for action + @param actname: modified value for WebSubmit action name/description (presence invokes update) + @param working_dir: modified value for WebSubmit action working_dir + @param status_text: modified value for WebSubmit action status text + @return: tuple containing "title" (title of page), body (page body). + """ + user_msg = [] + body = "" + title = "Edit WebSubmit Action" + commit_error = 0 + + ## wash args: + if actid is not None: + try: + actid = wash_single_urlarg(urlarg=actid, argreqdtype=str, argdefault="", maxstrlen=3, minstrlen=3) + if string_is_alphanumeric_including_underscore(txtstring=actid) == 0: + actid = "" + except ValueError, e: + actid = "" + actid = actid.upper() + else: + actid = "" + if actname is not None: + try: + actname = wash_single_urlarg(urlarg=actname, argreqdtype=str, argdefault="") + except ValueError, e: + actname = "" + else: + actname = "" + if working_dir is not None: + try: + working_dir = wash_single_urlarg(urlarg=working_dir, argreqdtype=str, argdefault="") + except ValueError, e: + working_dir = "" + else: + working_dir = "" + if status_text is not None: + try: + status_text = wash_single_urlarg(urlarg=status_text, argreqdtype=str, argdefault="") + except ValueError, e: + status_text = "" + else: + status_text = "" + + ## process request: + if actcommit != "" and actcommit is not None: + if actname in ("", None): + actname = "" + user_msg.append("""Action description is mandatory""") + commit_error = 1 + + if commit_error != 0: + ## don't commit - just re-display page with message to user + (title, body) = _display_edit_action_form(actid=actid, user_msg=user_msg) + return (title, body) + + ## Commit updated action details to WebSubmit DB: + err_code = update_action_details(actid, actname, working_dir, status_text) + if err_code == 0: + ## Action Updated: Show Action Details Again + user_msg.append("""'%s' Action Updated""" % (actid,)) + action_dets = get_action_details(actid) + body = websubmitadmin_templates.tmpl_display_addactionform(actid=action_dets[0][0], + actname=action_dets[0][1], + working_dir=action_dets[0][2], + status_text=action_dets[0][3], + perform_act="actionedit", + cd=action_dets[0][4], + md=action_dets[0][5], + user_msg=user_msg + ) + else: + ## Could Not Update Action: Maybe Key Violation, or Invalid actid? Redisplay all actions. + ## TODO : LOGGING + all_actions = get_actid_actname_allactions() + user_msg.append("""Could Not Update Action '%s'""" % (actid,)) + body = websubmitadmin_templates.tmpl_display_allactions(all_actions, user_msg=user_msg) + title = "Available WebSubmit Actions" + else: + ## Display Web form containing existing details of action: + (title, body) = _display_edit_action_form(actid=actid) + return (title, body) + +def _functionedit_display_function_details(funcname, user_msg=""): + """Display the details of a function, along with any message to the user that may have been provided. + @param funcname: unique name of function to be updated + @param user_msg: Any message to the user that is to be displayed on the page. + @return: tuple containing (page title, HTML page body). + """ + if user_msg == "": + user_msg = [] + title = "Edit WebSubmit Function" + func_descr_res = get_function_description(function=funcname) + num_rows_ret = len(func_descr_res) + if num_rows_ret == 1: + ## Display action details + funcdescr = func_descr_res[0][0] + if funcdescr is None: + funcdescr = "" + ## get parameters for this function: + this_function_parameters = get_function_parameters(function=funcname) + ## get all function parameters in WebSubmit: + all_function_parameters = get_distinct_paramname_all_websubmit_function_parameters() + + ## get the docstring of the function. Remove leading empty + ## lines and remove unnecessary leading whitespaces + docstring = None + try: + websubmit_function = __import__('invenio.websubmit_functions.%s' % funcname, + globals(), locals(), [funcname]) + if hasattr(websubmit_function, funcname) and getattr(websubmit_function, funcname).__doc__: + docstring = getattr(websubmit_function, funcname).__doc__ + except Exception, e: + docstring = '''Function documentation could + not be loaded.
Please check function definition. Error was:
%s''' % str(e) + + if docstring: + docstring = '
' + _format_function_docstring(docstring) + '
' + + body = websubmitadmin_templates.tmpl_display_addfunctionform(funcname=funcname, + funcdescr=funcdescr, + func_parameters=this_function_parameters, + all_websubmit_func_parameters=all_function_parameters, + perform_act="functionedit", + user_msg=user_msg, + func_docstring = docstring + ) + + else: + ## Either no rows, or more than one row for function: log error, and display all functions + ## TODO : LOGGING + title = "Available WebSubmit Functions" + all_functions = get_funcname_funcdesc_allfunctions() + if num_rows_ret > 1: + ## Key Error - duplicated function name + user_msg.append("""Found Several Rows for Function with Name '%s' - Inform Administrator""" % (funcname,)) + ## LOG MESSAGE + else: + ## No rows for function + user_msg.append("""Could Not Find Any Rows for Function with Name '%s'""" % (funcname,)) + ## LOG MESSAGE + body = websubmitadmin_templates.tmpl_display_allfunctions(all_functions, user_msg=user_msg) + return (title, body) + +def _format_function_docstring(docstring): + """ + Remove unnecessary leading and trailing empty lines, as well as + meaningless leading and trailing whitespaces on every lines + + @param docstring: the input docstring to format + @type docstring: string + @return: a formatted docstring + @rtype: string + """ + def count_leading_whitespaces(line): + "Count enumber of leading whitespaces" + line_length = len(line) + pos = 0 + while pos < line_length and line[pos] == " ": + pos += 1 + return pos + + new_docstring_list = [] + min_nb_leading_whitespace = len(docstring) # this is really the max possible + + # First count min number of leading whitespaces of all lines. Also + # remove leading empty lines. + docstring_has_started_p = False + for line in docstring.splitlines(): + if docstring_has_started_p or line.strip(): + # A non-empty line has been found, or an emtpy line after + # the beginning of some text was found + docstring_has_started_p = True + new_docstring_list.append(line) + if line.strip(): + # If line has some meaningful char, count leading whitespaces + line_nb_spaces = count_leading_whitespaces(line) + if line_nb_spaces < min_nb_leading_whitespace: + min_nb_leading_whitespace = line_nb_spaces + + return '\n'.join([line[min_nb_leading_whitespace:] for line in new_docstring_list]).rstrip() + +def _functionedit_update_description(funcname, funcdescr): + """Perform an update of the description for a given function. + @param funcname: unique name of function to be updated + @param funcdescr: description to be updated for funcname + @return: a tuple containing (page title, HTML body content) + """ + user_msg = [] + err_code = update_function_description(funcname, funcdescr) + if err_code == 0: + ## Function updated - redisplay + user_msg.append("""'%s' Function Description Updated""" % (funcname,)) + else: + ## Could not update function description +## TODO : ERROR LIBS + user_msg.append("""Could Not Update Description for Function '%s'""" % (funcname,)) + ## Display function details + (title, body) = _functionedit_display_function_details(funcname=funcname, user_msg=user_msg) + return (title, body) + +def _functionedit_delete_parameter(funcname, deleteparam): + """Delete a parameter from a given function. + Important: if any document types have been using the function from which this parameter will be deleted, + and therefore have values for this parameter, these values will not be deleted from the WebSubmit DB. + The deleted parameter therefore may continue to exist in the WebSubmit DB, but will be disassociated + from this function. + @param funcname: unique name of the function from which the parameter is to be deleted. + @param deleteparam: the name of the parameter to be deleted from the function. + @return: tuple containing (title, HTML body content) + """ + user_msg = [] + err_code = delete_function_parameter(function=funcname, parameter_name=deleteparam) + if err_code == 0: + ## Parameter deleted - redisplay function details + user_msg.append("""'%s' Parameter Deleted from '%s' Function""" % (deleteparam, funcname)) + else: + ## could not delete param - it does not exist for this function +## TODO : ERROR LIBS + user_msg.append("""'%s' Parameter Does not Seem to Exist for Function '%s' - Could not Delete""" \ + % (deleteparam, funcname)) + ## Display function details + (title, body) = _functionedit_display_function_details(funcname=funcname, user_msg=user_msg) + return (title, body) + +def _functionedit_add_parameter(funcname, funceditaddparam="", funceditaddparamfree=""): + """Add (connect) a parameter to a given WebSubmit function. + @param funcname: unique name of the function to which the parameter is to be added. + @param funceditaddparam: the value of a HTML select list: if present, will contain the name of the + parameter to be added to the function. May also be empty - the user may have used the free-text field + (funceditaddparamfree) to manually enter the name of a parameter. The important thing is that one + must be present for the parameter to be added sucessfully. + @param funceditaddparamfree: The name of the parameter to be added to the function, as taken from a free- + text HTML input field. May also be empty - the user may have used the HTML select-list (funceditaddparam) + field to choose the parameter. The important thing is that one must be present for the parameter to be + added sucessfully. The value "funceditaddparamfree" value will take priority over the "funceditaddparam" + list value. + @return: tuple containing (title, HTML body content) + """ + user_msg = [] + if funceditaddparam in ("", None, "NO_VALUE") and funceditaddparamfree in ("", None): + ## no parameter chosen +## TODO : ERROR LIBS + user_msg.append("""Unable to Find the Parameter to be Added to Function '%s' - Could not Add""" % (funcname,)) + else: + add_parameter = "" + if funceditaddparam not in ("", None) and funceditaddparamfree not in ("", None): + ## both select box and free-text values provided for parameter - prefer free-text + add_parameter = funceditaddparamfree + elif funceditaddparam not in ("", None): + ## take add select-box chosen parameter + add_parameter = funceditaddparam + else: + ## take add free-text chosen parameter + add_parameter = funceditaddparamfree + ## attempt to commit parameter: + err_code = add_function_parameter(function=funcname, parameter_name=add_parameter) + if err_code == 0: + ## Parameter added - redisplay function details + user_msg.append("""'%s' Parameter Added to '%s' Function""" % (add_parameter, funcname)) + else: + ## could not add param - perhaps it already exists for this function +## TODO : ERROR LIBS + user_msg.append("""Could not Add '%s' Parameter to Function '%s' - It Already Exists for this Function""" \ + % (add_parameter, funcname)) + ## Display function details + (title, body) = _functionedit_display_function_details(funcname=funcname, user_msg=user_msg) + return (title, body) + +def perform_request_edit_function(funcname, funcdescr=None, funceditaddparam=None, funceditaddparamfree=None, + funceditdelparam=None, funcdescreditcommit="", funcparamdelcommit="", + funcparamaddcommit=""): + """Edit a WebSubmit function. 3 possibilities: edit the function description; delete a parameter from the + function; add a new parameter to the function. + @param funcname: the name of the function to be modified + @param funcdescr: the new function description + @param funceditaddparam: the name of the parameter to be added to the function (taken from HTML SELECT-list) + @param funceditaddparamfree: the name of the parameter to be added to the function (taken from free-text input) + @param funceditdelparam: the name of the parameter to be deleted from the function + @param funcdescreditcommit: a flag to indicate that this request is to update the description of a function + @param funcparamdelcommit: a flag to indicate that this request is to delete a parameter from a function + @param funcparamaddcommit: a flag to indicate that this request is to add a new parameter to a function + @return: tuple containing (page title, HTML page body) + """ + body = "" + title = "Edit WebSubmit Function" + commit_error = 0 + + ## wash args: + if funcname is not None: + try: + funcname = wash_single_urlarg(urlarg=funcname, argreqdtype=str, argdefault="") + if string_is_alphanumeric_including_underscore(txtstring=funcname) == 0: + funcname = "" + except ValueError, e: + funcname = "" + else: + funcname = "" + if funcdescr is not None: + try: + funcdescr = wash_single_urlarg(urlarg=funcdescr, argreqdtype=str, argdefault="") + except ValueError, e: + funcdescr = "" + else: + funcdescr = "" + if funceditaddparam is not None: + try: + funceditaddparam = wash_single_urlarg(urlarg=funceditaddparam, argreqdtype=str, argdefault="") + if string_is_alphanumeric_including_underscore(txtstring=funceditaddparam) == 0: + funceditaddparam = "" + except ValueError, e: + funceditaddparam = "" + else: + funceditaddparam = "" + if funceditaddparamfree is not None: + try: + funceditaddparamfree = wash_single_urlarg(urlarg=funceditaddparamfree, argreqdtype=str, argdefault="") + if string_is_alphanumeric_including_underscore(txtstring=funceditaddparamfree) == 0: + funceditaddparamfree = "" + except ValueError, e: + funceditaddparamfree = "" + else: + funceditaddparamfree = "" + if funceditdelparam is not None: + try: + funceditdelparam = wash_single_urlarg(urlarg=funceditdelparam, argreqdtype=str, argdefault="") + except ValueError, e: + funceditdelparam = "" + else: + funceditdelparam = "" + + if funcname == "": + (title, body) = _functionedit_display_function_details(funcname=funcname) + return (title, body) + + if funcdescreditcommit != "" and funcdescreditcommit is not None: + ## Update the definition of a function: + (title, body) = _functionedit_update_description(funcname=funcname, funcdescr=funcdescr) + elif funcparamaddcommit != "" and funcparamaddcommit is not None: + ## Request to add a new parameter to a function + (title, body) = _functionedit_add_parameter(funcname=funcname, + funceditaddparam=funceditaddparam, funceditaddparamfree=funceditaddparamfree) + elif funcparamdelcommit != "" and funcparamdelcommit is not None: + ## Request to delete a parameter from a function + (title, body) = _functionedit_delete_parameter(funcname=funcname, deleteparam=funceditdelparam) + else: + ## Display Web form for new function addition: + (title, body) = _functionedit_display_function_details(funcname=funcname) + return (title, body) + +def perform_request_function_usage(funcname): + """Display a page containing the usage details of a given function. + @param funcname: the function name + @return: page body + """ + func_usage = get_function_usage_details(function=funcname) + func_usage = stringify_listvars(func_usage) + body = websubmitadmin_templates.tmpl_display_function_usage(funcname, func_usage) + return body + +def perform_request_list_actions(): + """Display a list of all WebSubmit actions. + @return: body where body is a string of HTML, which is a page body. + """ + body = "" + all_actions = get_actid_actname_allactions() + body = websubmitadmin_templates.tmpl_display_allactions(all_actions) + return body + +def perform_request_list_doctypes(): + """Display a list of all WebSubmit document types. + @return: body where body is a string of HTML, which is a page body. + """ + body = "" + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(all_doctypes) + return body + +def perform_request_list_jschecks(): + """Display a list of all WebSubmit JavaScript element checking functions. + @return: body, where body is a string of HTML, which is a page body. + """ + body = "" + all_jschecks = get_chname_alljschecks() + body = websubmitadmin_templates.tmpl_display_alljschecks(all_jschecks) + return body + +def perform_request_list_functions(): + """Display a list of all WebSubmit FUNCTIONS. + @return: body where body is a string of HTML, which is a page body. + """ + body = "" + all_functions = get_funcname_funcdesc_allfunctions() + body = websubmitadmin_templates.tmpl_display_allfunctions(all_functions) + return body + +def perform_request_list_elements(): + """Display a list of all WebSubmit ELEMENTS. + @return: body where body is a string of HTML, which is a page body. + """ + body = "" + all_elements = get_elename_allelements() + body = websubmitadmin_templates.tmpl_display_allelements(all_elements) + return body + +def _remove_doctype(doctype): + """Process removal of a document type. + @param doctype: the document type to be removed. + @return: a tuple containing page title, and HTML page body) + """ + title = "" + body = "" + user_msg = [] + numrows_doctype = get_number_doctypes_docid(docid=doctype) + if numrows_doctype == 1: + ## Doctype is unique and can therefore be deleted: + ## Delete any function parameters for this document type: + error_code = delete_all_parameters_doctype(doctype=doctype) + if error_code != 0: + ## problem deleting some or all parameters - inform user and log error + ## TODO : ERROR LOGGING + user_msg.append("""Unable to delete some or all function parameter values for document type "%s".""" % (doctype,)) + ## delete all functions called by this doctype's actions + error_code = delete_all_functions_doctype(doctype=doctype) + if error_code != 0: + ## problem deleting some or all functions - inform user and log error + ## TODO : ERROR LOGGING + user_msg.append("""Unable to delete some or all functions for document type "%s".""" % (doctype,)) + ## delete all categories of this doctype + error_code = delete_all_categories_doctype(doctype=doctype) + if error_code != 0: + ## problem deleting some or all categories - inform user and log error + ## TODO : ERROR LOGGING + user_msg.append("""Unable to delete some or all parameters for document type "%s".""" % (doctype,)) + ## delete all submission interface fields for this doctype + error_code = delete_all_submissionfields_doctype(doctype=doctype) + if error_code != 0: + ## problem deleting some or all submission fields - inform user and log error + ## TODO : ERROR LOGGING + user_msg.append("""Unable to delete some or all submission fields for document type "%s".""" % (doctype,)) + ## delete all submissions for this doctype + error_code = delete_all_submissions_doctype(doctype) + if error_code != 0: + ## problem deleting some or all submissions - inform user and log error + ## TODO : ERROR LOGGING + user_msg.append("""Unable to delete some or all submissions for document type "%s".""" % (doctype,)) + ## delete entry for this doctype in the collection-doctypes table + error_code = delete_collection_doctype_entry_doctype(doctype) + if error_code != 0: + ## problem deleting this doctype from the collection-doctypes table + ## TODO : ERROR LOGGING + user_msg.append("""Unable to delete document type "%s" from the collection-doctypes table.""" % (doctype,)) + ## delete the doctype itself + error_code = delete_doctype(doctype) + if error_code != 0: + ## problem deleting this doctype from the doctypes table + ## TODO : ERROR LOGGING + user_msg.append("""Unable to delete document type "%s" from the document types table.""" % (doctype,)) + user_msg.append("""The "%s" document type should now have been deleted, but you should not ignore any warnings.""" % (doctype,)) + title = """Available WebSubmit Document Types""" + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + else: + ## doctype is not unique and cannot be deleted + if numrows_doctype > 1: + ## doctype is duplicated - cannot delete - needs admin intervention + ## TODO : LOG ERROR + user_msg.append("""%s WebSubmit document types have been identified for doctype id "%s" - unable to delete.""" \ + """ Please inform administrator.""" % (numrows_doctype, doctype)) + else: + ## no document types found for this doctype id + ## TODO : LOG ERROR + user_msg.append("""Unable to find any document types in the WebSubmit database for doctype id "%s" - unable to delete""" \ + % (doctype,)) + ## get a list of all document types, and once more display the delete form, with the message + alldoctypes = get_docid_docname_and_docid_alldoctypes() + title = "Remove WebSubmit Doctument Type" + body = websubmitadmin_templates.tmpl_display_delete_doctype_form(doctype="", alldoctypes=alldoctypes, user_msg=user_msg) + return (title, body) + +def perform_request_remove_doctype(doctype="", doctypedelete="", doctypedeleteconfirm=""): + """Remove a document type from WebSubmit. + @param doctype: the document type to be removed + @doctypedelete: flag to signal that a confirmation for deletion should be displayed + @doctypedeleteconfirm: flag to signal that confirmation for deletion has been received and + the doctype should be removed + @return: a tuple (title, body) + """ + body = "" + title = "Remove WebSubmit Document Type" + if doctypedeleteconfirm not in ("", None): + ## Delete the document type: + (title, body) = _remove_doctype(doctype=doctype) + else: + ## Display "doctype delete form" + if doctypedelete not in ("", None) and doctype not in ("", None): + ## don't bother to get list of doctypes - user will be prompted to confirm the deletion of "doctype" + alldoctypes = None + else: + ## get list of all doctypes to pass to template so that it can prompt the user to choose a doctype to delete + ## alldoctypes = get_docid_docname_alldoctypes() + alldoctypes = get_docid_docname_and_docid_alldoctypes() + body = websubmitadmin_templates.tmpl_display_delete_doctype_form(doctype=doctype, alldoctypes=alldoctypes) + return (title, body) + +def _create_add_doctype_form(doctype="", doctypename="", doctypedescr="", clonefrom="", user_msg=""): + """Perform the steps necessary to create the "add a new doctype" form. + @param doctype: The unique ID that is to be used for the new doctype. + @param doctypename: the name that is to be given to a doctype. + @param doctypedescr: the description to be allocated to the new doctype. + @param user_msg: any message to be displayed to the user. + @return: a tuple containing page title and HTML body of page: (title, body) + """ + title = """Add New WebSubmit Document Type""" + alldoctypes = get_docid_docname_and_docid_alldoctypes() + body = websubmitadmin_templates.tmpl_display_doctypedetails_form(doctype=doctype, + doctypename=doctypename, + doctypedescr=doctypedescr, + clonefrom=clonefrom, + alldoctypes=alldoctypes, + user_msg=user_msg + ) + return (title, body) + +def _clone_categories_doctype(user_msg, fromdoctype, todoctype): + """Clone the categories of one document type, to another document type. + @param user_msg: any message to be displayed to the user (this is a list) + @param fromdoctype: the doctype from which categories are to be cloned + @param todoctype: the doctype into which categories are to be cloned + @return: integer value (0/1/2) - if doctype's categories couldn't be deleted, return 0 (cloning failed); + if some categories could be cloned, return 1 (cloning partially successful); if all categories could be + cloned, return 2 (cloning successful). + """ + error_code = clone_categories_fromdoctype_todoctype(fromdoctype=fromdoctype, todoctype=todoctype) + if error_code == 1: + ## doctype had existing categories and they could not be deleted + ## TODO : LOG ERRORS + user_msg.append("""Categories already existed for the document type "%s" but could not be deleted. Unable to clone""" \ + """ categories of doctype "%s".""" % (todoctype, fromdoctype)) + return 1 ## cloning failed + elif error_code == 2: + ## could not clone all categories for new doctype + ## TODO : LOG ERRORS + user_msg.append("""Unable to clone all categories from doctype "%s", for doctype "%s".""" % (fromdoctype, todoctype)) + return 2 ## cloning at least partially successful + else: + return 0 ## cloning successful + +def _clone_functions_foraction_doctype(user_msg, fromdoctype, todoctype, action): + """Clone the functions of a given action of one document type, to the same action on another document type. + @param user_msg: any message to be displayed to the user (this is a list) + @param fromdoctype: the doctype from which functions are to be cloned + @param todoctype: the doctype into which functions are to be cloned + @param action: the action for which functions are to be cloned + @return: an integer value (0/1/2). In the case that todoctype had existing functions for the given action and + they could not be deleted return 0, signalling that this is a serious problem; in the case that some + functions were cloned, return 1; in the case that all functions were cloned, return 2. + """ + error_code = clone_functions_foraction_fromdoctype_todoctype(fromdoctype=fromdoctype, todoctype=todoctype, action=action) + if error_code == 1: + ## doctype had existing functions for the given action and they could not be deleted + ## TODO : LOG ERRORS + user_msg.append("""Functions already existed for the "%s" action of the document type "%s" but they could not be """ \ + """deleted. Unable to clone the functions of Document Type "%s" for action "%s".""" \ + % (action, todoctype, fromdoctype, action)) + ## critical - return 1 to signal this + return 1 + elif error_code == 2: + ## could not clone all functions for given action for new doctype + ## TODO : LOG ERRORS + user_msg.append("""Unable to clone all functions for the "%s" action from doctype "%s", for doctype "%s".""" \ + % (action, fromdoctype, todoctype)) + return 2 ## not critical + else: + return 0 ## total success + +def _clone_functionparameters_foraction_fromdoctype_todoctype(user_msg, fromdoctype, todoctype, action): + """Clone the parameters/values of a given action of one document type, to the same action on another document type. + @param user_msg: any message to be displayed to the user (this is a list) + @param fromdoctype: the doctype from which parameters are to be cloned + @param todoctype: the doctype into which parameters are to be cloned + @param action: the action for which parameters are to be cloned + @return: 0 if it was not possible to clone all parameters/values; 1 if all parameters/values were cloned successfully. + """ + error_code = clone_functionparameters_foraction_fromdoctype_todoctype(fromdoctype=fromdoctype, \ + todoctype=todoctype, action=action) + if error_code in (1, 2): + ## something went wrong and it was not possible to clone all parameters/values of "action"/"fromdoctype" for "action"/"todoctype" + ## TODO : LOG ERRORS + user_msg.append("""It was not possible to clone all parameter values from the action "%(act)s" of the document type""" \ + """ "%(fromdt)s" for the action "%(act)s" of the document type "%(todt)s".""" \ + % { 'act' : action, 'fromdt' : fromdoctype, 'todt' : todoctype } + ) + return 2 ## to signal that addition wasn't 100% successful + else: + return 0 ## all parameters were cloned + +def _add_doctype(doctype, doctypename, doctypedescr, clonefrom): + title = "" + body = "" + user_msg = [] + commit_error = 0 + if doctype == "": + user_msg.append("""The Document Type ID is mandatory and must be a string with no more than 10 alpha-numeric characters""") + commit_error = 1 + + if commit_error != 0: + ## don't commit - just re-display page with message to user + (title, body) = _create_add_doctype_form(doctypename=doctypename, doctypedescr=doctypedescr, clonefrom=clonefrom, user_msg=user_msg) + return (title, body) + + + numrows_doctype = get_number_doctypes_docid(docid=doctype) + if numrows_doctype > 0: + ## this document type already exists - do not add + ## TODO : LOG ERROR + user_msg.append("""A document type identified by "%s" already seems to exist and there cannot be added. Choose another ID.""" \ + % (doctype,)) + (title, body) = _create_add_doctype_form(doctypename=doctypename, doctypedescr=doctypedescr, clonefrom=clonefrom, user_msg=user_msg) + else: + ## proceed with addition + ## add the document type details: + error_code = insert_doctype_details(doctype=doctype, doctypename=doctypename, doctypedescr=doctypedescr) + if error_code == 0: + ## added successfully + if clonefrom not in ("", "None", None): + ## document type should be cloned from "clonefrom" + ## first, clone the categories from another doctype: + error_code = _clone_categories_doctype(user_msg=user_msg, + fromdoctype=clonefrom, + todoctype=doctype) + ## get details of clonefrom's submissions + all_actnames_submissions_clonefrom = get_actname_all_submissions_doctype(doctype=clonefrom) + if len(all_actnames_submissions_clonefrom) > 0: + ## begin cloning + for doc_submission_actname in all_actnames_submissions_clonefrom: + ## clone submission details: + action_name = doc_submission_actname[0] + _clone_submission_fromdoctype_todoctype(user_msg=user_msg, + todoctype=doctype, action=action_name, clonefrom=clonefrom) + + user_msg.append("""The "%s" document type has been added.""" % (doctype,)) + title = """Available WebSubmit Document Types""" + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + else: + ## could not add document type details - do no more + ## TODO : LOG ERROR! + user_msg.append("""Unable to add details for document type "%s".""" % (doctype,)) + (title, body) = _create_add_doctype_form(user_msg=user_msg) + + return (title, body) + +def perform_request_add_doctype(doctype=None, doctypename=None, doctypedescr=None, clonefrom=None, doctypedetailscommit=""): + body = "" + + ## wash args: + if doctype is not None: + try: + doctype = wash_single_urlarg(urlarg=doctype, argreqdtype=str, argdefault="", maxstrlen=10, minstrlen=1) + if string_is_alphanumeric_including_underscore(txtstring=doctype) == 0: + doctype = "" + except ValueError, e: + doctype = "" + else: + doctype = "" + if doctypename is not None: + try: + doctypename = wash_single_urlarg(urlarg=doctypename, argreqdtype=str, argdefault="") + except ValueError, e: + doctypename = "" + else: + doctypename = "" + if doctypedescr is not None: + try: + doctypedescr = wash_single_urlarg(urlarg=doctypedescr, argreqdtype=str, argdefault="") + except ValueError, e: + doctypedescr = "" + else: + doctypedescr = "" + if clonefrom is not None: + try: + clonefrom = wash_single_urlarg(urlarg=clonefrom, argreqdtype=str, argdefault="None") + except ValueError, e: + clonefrom = "None" + else: + clonefrom = "None" + + if doctypedetailscommit not in ("", None): + (title, body) = _add_doctype(doctype=doctype, + doctypename=doctypename, doctypedescr=doctypedescr, clonefrom=clonefrom) + else: + (title, body) = _create_add_doctype_form() + return (title, body) + +def _delete_referee_doctype(doctype, categid, refereeid): + """Delete a referee from a given category of a document type. + @param doctype: the document type from whose category the referee is to be removed + @param categid: the name/ID of the category from which the referee is to be removed + @param refereeid: the id of the referee to be removed from the given category + @return: a tuple containing 2 strings: (page title, page body) + """ + user_msg = [] + role_name = """referee_%s_%s""" % (doctype, categid) + error_code = acc_delete_user_role(id_user=refereeid, name_role=role_name) + if error_code > 0: + ## referee was deleted from category + user_msg.append(""" "%s".""" % (doctype,)) + +def _create_list_referees_doctype(doctype): + referees = {} + referees_details = {} + ## get all Invenio roles: + all_roles = acc_get_all_roles() + for role in all_roles: + (roleid, rolename) = (role[0], role[1]) + if re.match("^referee_%s_" % (doctype,), rolename): + ## this is a "referee" role - get users of this role: + role_users = acc_get_role_users(roleid) + if role_users is not None and (type(role_users) in (tuple, list) and len(role_users) > 0): + ## this role has users, record them in dictionary: + referees[rolename] = role_users + ## for each "group" of referees: + for ref_role in referees.keys(): + ## get category ID for this referee-role: + try: + categid = re.match("^referee_%s_(.*)" % (doctype,), ref_role).group(1) + ## from WebSubmit DB, get categ name for "categid": + if categid != "*": + categ_details = get_all_categories_sname_lname_for_doctype_categsname(doctype=doctype, categsname=categid) + if len(categ_details) > 0: + ## if possible to receive details of this category, record them in a tuple in the format: + ## ("categ name", (tuple of users details)): + referees_details[ref_role] = (categid, categ_details[0][1], referees[ref_role]) + else: + ## general referee entry: + referees_details[ref_role] = (categid, "General Referee(s)", referees[ref_role]) + except AttributeError: + ## there is no category for this role - it is broken, so pass it + pass + return referees_details + +def _create_edit_doctype_details_form(doctype, doctypename="", doctypedescr="", doctypedetailscommit="", user_msg=""): + if user_msg == "" or type(user_msg) not in (list, tuple, str, unicode): + user_msg = [] + elif type(user_msg) in (str, unicode): + user_msg = [user_msg] + title = "Edit Document Type Details" + doctype_details = get_doctype_docname_descr_cd_md_fordoctype(doctype) + if len(doctype_details) == 1: + docname = doctype_details[0][1] + docdescr = doctype_details[0][2] + (cd, md) = (doctype_details[0][3], doctype_details[0][4]) + if doctypedetailscommit != "": + ## could not commit details + docname = doctypename + docdescr = doctypedescr + body = websubmitadmin_templates.tmpl_display_doctypedetails_form(doctype=doctype, + doctypename=docname, + doctypedescr=docdescr, + cd=cd, + md=md, + user_msg=user_msg, + perform_act="doctypeconfigure") + else: + ## problem retrieving details of doctype: + user_msg.append("""Unable to retrieve details of doctype '%s' - cannot edit.""" % (doctype,),) + ## TODO : LOG ERROR + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + +def _create_add_submission_choose_clonefrom_form(doctype, action, user_msg=""): + if user_msg == "" or type(user_msg) not in (list, tuple, str, unicode): + user_msg = [] + elif type(user_msg) in (str, unicode): + user_msg = [user_msg] + + if action in ("", None): + user_msg.append("""Unknown Submission""") + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + ## does this doctype already have this action? + numrows_doctype_action = get_number_submissions_doctype_action(doctype=doctype, action=action) + if numrows_doctype_action < 1: + ## action not present for this doctype - can be added + ## get list of all doctypes implementing this action (for possible cloning purposes) + doctypes_implementing_action = get_doctypeid_doctypes_implementing_action(action=action) + ## create form to display document types to clone from + title = "Add Submission '%s' to Document Type '%s'" % (action, doctype) + body = websubmitadmin_templates.tmpl_display_submission_clone_form(doctype=doctype, + action=action, + clonefrom_list=doctypes_implementing_action, + user_msg=user_msg + ) + else: + ## warn user that action already exists for doctype and canot be added, then display all + ## details of doctype again + user_msg.append("The Document Type '%s' already implements the Submission '%s' - cannot add it again" \ + % (doctype, action)) + ## TODO : LOG WARNING + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _create_add_submission_form(doctype, action, displayed="", buttonorder="", statustext="", + level="", score="", stpage="", endtxt="", user_msg=""): + if user_msg == "" or type(user_msg) not in (list, tuple, str, unicode): + user_msg = [] + elif type(user_msg) in (str, unicode): + user_msg = [user_msg] + + if action in ("", None): + user_msg.append("""Unknown Submission""") + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + title = "Add Submission '%s' to Document Type '%s'" % (action, doctype) + body = websubmitadmin_templates.tmpl_display_submissiondetails_form(doctype=doctype, + action=action, + displayed=displayed, + buttonorder=buttonorder, + statustext=statustext, + level=level, + score=score, + stpage=stpage, + endtxt=endtxt, + user_msg=user_msg, + saveaction="add" + ) + return (title, body) + +def _create_delete_submission_form(doctype, action): + user_msg = [] + title = """Delete Submission "%s" from Document Type "%s" """ % (action, doctype) + numrows_doctypesubmission = get_number_submissions_doctype_action(doctype=doctype, action=action) + if numrows_doctypesubmission > 0: + ## submission exists: create form to delete it: + body = websubmitadmin_templates.tmpl_display_delete_doctypesubmission_form(doctype=doctype, action=action) + else: + ## submission doesn't seem to exist. Display details of doctype only: + user_msg.append("""The Submission "%s" doesn't seem to exist for the Document Type "%s" - unable to delete it""" % (action, doctype)) + ## TODO : LOG ERRORS + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _create_edit_submission_form(doctype, action, user_msg=""): + if user_msg == "" or type(user_msg) not in (list, tuple, str, unicode): + user_msg = [] + elif type(user_msg) in (str, unicode): + user_msg = [user_msg] + submission_details = get_submissiondetails_doctype_action(doctype=doctype, action=action) + numrows_submission_details = len(submission_details) + if numrows_submission_details == 1: + ## correctly retrieved details of submission - display: + submission_details = stringify_listvars(submission_details) + displayed = submission_details[0][3] + buttonorder = submission_details[0][7] + statustext = submission_details[0][8] + level = submission_details[0][9] + score = submission_details[0][10] + stpage = submission_details[0][11] + endtxt = submission_details[0][12] + cd = submission_details[0][5] + md = submission_details[0][6] + title = "Edit Details of '%s' Submission of '%s' Document Type" % (action, doctype) + body = websubmitadmin_templates.tmpl_display_submissiondetails_form(doctype=doctype, + action=action, + displayed=displayed, + buttonorder=buttonorder, + statustext=statustext, + level=level, + score=score, + stpage=stpage, + endtxt=endtxt, + cd=cd, + md=md, + user_msg=user_msg + ) + else: + if numrows_submission_details > 1: + ## multiple rows for this submission - this is a key violation + user_msg.append("Found multiple rows for the Submission '%s' of the Document Type '%s'" \ + % (action, doctype)) + else: + ## submission does not exist + user_msg.append("The Submission '%s' of the Document Type '%s' doesn't seem to exist." \ + % (action, doctype)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _create_edit_category_form(doctype, categid): + title = "Edit Category Description" + categ_details = get_all_categories_sname_lname_for_doctype_categsname(doctype=doctype, categsname=categid) + if len(categ_details) == 1: + ## disaply details + retrieved_categid=categ_details[0][0] + retrieved_categdescr=categ_details[0][1] + body = websubmitadmin_templates.tmpl_display_edit_category_form(doctype=doctype, + categid=retrieved_categid, + categdescr=retrieved_categdescr + ) + else: + ## problem retrieving details of categ + user_msg = """Unable to retrieve details of category '%s'""" % (categid,) + ## TODO : LOG ERRORS + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _create_configure_doctype_form(doctype, jumpcategout="", user_msg=""): + title = "Configure Document Type" + body = "" + if user_msg == "" or type(user_msg) not in (list, tuple, str, unicode): + user_msg = [] + ## get details of doctype: + doctype_details = get_doctype_docname_descr_cd_md_fordoctype(doctype) + docname = doctype_details[0][1] + docdescr = doctype_details[0][2] + (cd, md) = (doctype_details[0][3], doctype_details[0][4]) + ## get categories for doctype: + doctype_categs = get_all_category_details_for_doctype(doctype=doctype) + + ## get submissions for doctype: + doctype_submissions = get_submissiondetails_all_submissions_doctype(doctype=doctype) + ## get list of actions that this doctype doesn't have: + unlinked_actions = get_actions_sname_lname_not_linked_to_doctype(doctype=doctype) + ## get referees for doctype: + referees_dets = _create_list_referees_doctype(doctype=doctype) + body = websubmitadmin_templates.tmpl_configure_doctype_overview(doctype=doctype, doctypename=docname, + doctypedescr=docdescr, doctype_cdate=cd, + doctype_mdate=md, doctype_categories=doctype_categs, + jumpcategout=jumpcategout, + doctype_submissions=doctype_submissions, + doctype_referees=referees_dets, + add_actions_list=unlinked_actions, + user_msg=user_msg) + return (title, body) + +def _clone_submission_fromdoctype_todoctype(user_msg, todoctype, action, clonefrom): + ## first, delete the submission from todoctype (if it exists): + error_code = delete_submissiondetails_doctype(doctype=todoctype, action=action) + if error_code == 0: + ## could be deleted - now clone it + error_code = insert_submission_details_clonefrom_submission(addtodoctype=todoctype, action=action, clonefromdoctype=clonefrom) + if error_code == 0: + ## submission inserted + ## now clone functions: + error_code = _clone_functions_foraction_doctype(user_msg=user_msg, \ + fromdoctype=clonefrom, todoctype=todoctype, action=action) + if error_code in (0, 2): + ## no serious error - clone parameters: + error_code = _clone_functionparameters_foraction_fromdoctype_todoctype(user_msg=user_msg, + fromdoctype=clonefrom, + todoctype=todoctype, + action=action) + ## now clone pages/elements + error_code = clone_submissionfields_from_doctypesubmission_to_doctypesubmission(fromsub="%s%s" % (action, clonefrom), + tosub="%s%s" % (action, todoctype)) + if error_code == 1: + ## could not delete all existing submission fields and therefore could no clone submission fields at all + ## TODO : LOG ERROR + user_msg.append("""Unable to delete existing submission fields for Submission "%s" of Document Type "%s" - """ \ + """cannot clone submission fields!""" % (action, todoctype)) + elif error_code == 2: + ## could not clone all fields + ## TODO : LOG ERROR + user_msg.append("""Unable to clone all submission fields for submission "%s" on Document Type "%s" from Document""" \ + """ Type "%s" """ % (action, todoctype, clonefrom)) + else: + ## could not insert submission details! + user_msg.append("""Unable to successfully insert details of submission "%s" into Document Type "%s" - cannot clone from "%s" """ \ + % (action, todoctype, clonefrom)) + ## TODO : LOG ERROR + else: + ## could not delete details of existing submission (action) from 'todoctype' - cannot clone it as new + user_msg.append("""Unable to delete details of existing Submission "%s" from Document Type "%s" - cannot clone it from "%s" """ \ + % (action, todoctype, clonefrom)) + ## TODO : LOG ERROR + +def _add_submission_to_doctype_clone(doctype, action, clonefrom): + user_msg = [] + + if action in ("", None) or clonefrom in ("", None): + user_msg.append("Unknown action or document type to clone from - cannot add submission") + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + ## does action exist? + numrows_action = get_number_actions_with_actid(actid=action) + if numrows_action > 0: + ## The action exists, but is it already implemented as a submission by doctype? + numrows_submission_doctype = get_number_submissions_doctype_action(doctype=doctype, action=action) + if numrows_submission_doctype > 0: + ## this submission already exists for this document type - unable to add it again + user_msg.append("""The Submission "%s" already exists for Document Type "%s" - cannot add it again""" \ + %(action, doctype)) + ## TODO : LOG ERROR + else: + ## clone the submission + _clone_submission_fromdoctype_todoctype(user_msg=user_msg, + todoctype=doctype, action=action, clonefrom=clonefrom) + user_msg.append("""Cloning of Submission "%s" from Document Type "%s" has been carried out. You should not""" \ + """ ignore any warnings that you may have seen.""" % (action, clonefrom)) + ## TODO : LOG WARNING OF NEW SUBMISSION CREATION BY CLONING + else: + ## this action doesn't exist! cannot add a submission based upon it! + user_msg.append("The Action '%s' does not seem to exist in WebSubmit. Cannot add it as a Submission!" \ + % (action)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _add_submission_to_doctype(doctype, action, displayed, buttonorder, + statustext, level, score, stpage, endtxt): + user_msg = [] + + ## does "action" exist? + numrows_action = get_number_actions_with_actid(actid=action) + if numrows_action < 1: + ## this action does not exist! Can't add a submission based upon it! + user_msg.append("'%s' does not exist in WebSubmit as an Action! Unable to add this submission."\ + % (action,)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + ## Insert the new submission + error_code = insert_submission_details(doctype=doctype, action=action, displayed=displayed, + nbpg="0", buttonorder=buttonorder, statustext=statustext, + level=level, score=score, stpage=stpage, endtext=endtxt) + if error_code == 0: + ## successful insert + user_msg.append("""'%s' Submission Successfully Added to Document Type '%s'""" % (action, doctype)) + else: + ## could not insert submission into doctype + user_msg.append("""Unable to Add '%s' Submission to '%s' Document Type""" % (action, doctype)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _delete_submission_from_doctype(doctype, action): + """Delete a submission (action) from the document type identified by "doctype". + @param doctype: the unique ID of the document type from which the submission is to be deleted + @param categid: the action ID of the submission to be deleted from doctype + @return: a tuple containing 2 strings: (page title, page body) + """ + user_msg = [] + + if action in ("", None): + user_msg.append("Unknown action - cannot delete submission") + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + ## delete fields for this submission: + error_code = delete_all_submissionfields_submission("""%s%s""" % (action, doctype) ) + if error_code != 0: + ## could not successfully delete all fields - report error + user_msg.append("""When deleting Submission "%s" from Document Type "%s", it wasn't possible to delete all Submission Fields""" \ + % (action, doctype)) + ## TODO : LOG ERROR + ## delete parameters for this submission: + error_code = delete_functionparameters_doctype_submission(doctype=doctype, action=action) + if error_code != 0: + ## could not successfully delete all functions - report error + user_msg.append("""When deleting Submission "%s" from Document Type "%s", it wasn't possible to delete all Function Parameters""" \ + % (action, doctype)) + ## TODO : LOG ERROR + ## delete functions for this submission: + error_code = delete_all_functions_foraction_doctype(doctype=doctype, action=action) + if error_code != 0: + ## could not successfully delete all functions - report error + user_msg.append("""When deleting Submission "%s" from Document Type "%s", it wasn't possible to delete all Functions""" \ + % (action, doctype)) + ## TODO : LOG ERROR + ## delete this submission itself: + error_code = delete_submissiondetails_doctype(doctype=doctype, action=action) + if error_code == 0: + ## successful delete + user_msg.append("""The "%s" Submission has been deleted from the "%s" Document Type""" % (action, doctype)) + else: + ## could not delete category + user_msg.append("""Unable to successfully delete the "%s" Submission from the "%s" Document Type""" % (action, doctype)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _edit_submission_for_doctype(doctype, action, displayed, buttonorder, + statustext, level, score, stpage, endtxt): + """Update the details of a given submission belonging to the document type identified by "doctype". + @param doctype: the unique ID of the document type for which the submission is to be updated + @param action: action name of the submission to be updated + @param displayed: displayed on main submission page? (Y/N) + @param buttonorder: button order + @param statustext: statustext + @param level: level + @param score: score + @param stpage: stpage + @param endtxt: endtxt + @return: a tuple of 2 strings: (page title, page body) + """ + user_msg = [] + commit_error = 0 + if action in ("", None): + user_msg.append("Unknown Action - cannot update submission") + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + error_code = update_submissiondetails_doctype_action(doctype=doctype, action=action, displayed=displayed, + buttonorder=buttonorder, statustext=statustext, level=level, + score=score, stpage=stpage, endtxt=endtxt) + if error_code == 0: + ## successful update + user_msg.append("'%s' Submission of '%s' Document Type updated." % (action, doctype) ) + else: + ## could not update + user_msg.append("Unable to update '%s' Submission of '%s' Document Type." % (action, doctype) ) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _edit_doctype_details(doctype, doctypename, doctypedescr): + """Update the details (name and/or description) of a document type (identified by doctype.) + @param doctype: the unique ID of the document type to be updated + @param doctypename: the new/updated name for the doctype + @param doctypedescr: the new/updated description for the doctype + @return: a tuple containing 2 strings: (page title, page body) + """ + user_msg = [] + error_code = update_doctype_details(doctype=doctype, doctypename=doctypename, doctypedescr=doctypedescr) + if error_code == 0: + ## successful update + user_msg.append("""'%s' Document Type Updated""" % (doctype,)) + else: + ## could not update + user_msg.append("""Unable to Update Doctype '%s'""" % (doctype,)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _edit_category_for_doctype(doctype, categid, categdescr): + """Edit the description of a given category (identified by categid), belonging to + the document type identified by doctype. + @param doctype: the unique ID of the document type for which the category is to be modified + @param categid: the unique category ID of the category to be modified + @param categdescr: the new description for the category + @return: at tuple containing 2 strings: (page title, page body) + """ + user_msg = [] + + if categid in ("", None) or categdescr in ("", None): + ## cannot edit unknown category! + user_msg.append("Category ID and Description are both mandatory") + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + error_code = update_category_description_doctype_categ(doctype=doctype, categ=categid, categdescr=categdescr) + if error_code == 0: + ## successful update + user_msg.append("""'%s' Category Description Successfully Updated""" % (categid,)) + else: + ## could not update category description + user_msg.append("""Unable to Description for Category '%s'""" % (categid,)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _add_category_to_doctype(doctype, categid, categdescr): + """Add a new category to the document type identified by "doctype". + Category ID, and category description are both mandatory. + @param doctype: the unique ID of the document type to which the category is to be added + @param categid: the unique category ID of the category to be added to doctype + @param categdescr: the description of the category to be added + @return: at tuple containing 2 strings: (page title, page body) + """ + user_msg = [] + + if categid in ("", None) or categdescr in ("", None): + ## cannot add unknown category! + user_msg.append("Category ID and Description are both mandatory") + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + error_code = insert_category_into_doctype(doctype=doctype, categ=categid, categdescr=categdescr) + if error_code == 0: + ## successful insert + user_msg.append("""'%s' Category Successfully Added""" % (categid,)) + else: + ## could not insert category into doctype + user_msg.append("""Unable to Add '%s' Category""" % (categid,)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _delete_category_from_doctype(doctype, categid): + """Delete a category (categid) from the document type identified by "doctype". + @param doctype: the unique ID of the document type from which the category is to be deleted + @param categid: the unique category ID of the category to be deleted from doctype + @return: a tuple containing 2 strings: (page title, page body) + """ + user_msg = [] + + if categid in ("", None): + ## cannot delete unknown category! + user_msg.append("Category ID is mandatory") + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + error_code = delete_category_doctype(doctype=doctype, categ=categid) + if error_code == 0: + ## successful delete + user_msg.append("""'%s' Category Successfully Deleted""" % (categid,)) + else: + ## could not delete category + user_msg.append("""Unable to Delete '%s' Category""" % (categid,)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _jump_category_to_new_score(doctype, jumpcategout, jumpcategin): + user_msg = [] + if jumpcategout in ("", None) or jumpcategin in ("", None): + ## need both jumpcategout and jumpcategin to move a category: + user_msg.append("Unable to move category - unknown source and/or destination score(s)") + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + ## FIXME TODO: + error_code = move_category_to_new_score(doctype, jumpcategout, jumpcategin) + + if error_code == 0: + ## successful jump of category + user_msg.append("""Successfully Moved [%s] Category""" % (jumpcategout,)) + else: + ## could not delete category + user_msg.append("""Unable to Move [%s] Category""" % (jumpcategout,)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _move_category(doctype, categid, movecategup=""): + user_msg = [] + if categid in ("", None): + ## cannot move unknown category! + user_msg.append("Cannot move an unknown category - category ID is mandatory") + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + if movecategup not in ("", None): + ## move the category up in score: + error_code = move_category_by_one_place_in_score(doctype=doctype, + categsname=categid, + direction="up") + else: + ## move the category down in score: + error_code = move_category_by_one_place_in_score(doctype=doctype, + categsname=categid, + direction="down") + + if error_code == 0: + ## successful move of category + user_msg.append("""[%s] Category Successfully Moved""" % (categid,)) + else: + ## could not delete category + user_msg.append("""Unable to Move [%s] Category""" % (categid,)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def perform_request_configure_doctype(doctype, + doctypename=None, + doctypedescr=None, + doctypedetailsedit="", + doctypedetailscommit="", + doctypecategoryadd="", + doctypecategoryedit="", + doctypecategoryeditcommit="", + doctypecategorydelete="", + doctypesubmissionadd="", + doctypesubmissiondelete="", + doctypesubmissiondeleteconfirm="", + doctypesubmissionedit="", + doctypesubmissionaddclonechosen="", + doctypesubmissionadddetailscommit="", + doctypesubmissioneditdetailscommit="", + categid=None, + categdescr=None, + movecategup=None, + movecategdown=None, + jumpcategout=None, + jumpcategin=None, + action=None, + doctype_cloneactionfrom=None, + displayed=None, + buttonorder=None, + statustext=None, + level=None, + score=None, + stpage=None, + endtxt=None + ): + user_msg = [] + body = "" + + if doctype is not None: + try: + doctype = wash_single_urlarg(urlarg=doctype, argreqdtype=str, argdefault="", maxstrlen=10, minstrlen=1) + if string_is_alphanumeric_including_underscore(txtstring=doctype) == 0: + doctype = "" + except ValueError, e: + doctype = "" + else: + doctype = "" + if action is not None: + try: + action = wash_single_urlarg(urlarg=action, argreqdtype=str, argdefault="", maxstrlen=3, minstrlen=1) + if string_is_alphanumeric_including_underscore(txtstring=action) == 0: + action = "" + except ValueError, e: + action = "" + else: + action = "" + if doctypename is not None: + try: + doctypename = wash_single_urlarg(urlarg=doctypename, argreqdtype=str, argdefault="") + except ValueError, e: + doctypename = "" + else: + doctypename = "" + if doctypedescr is not None: + try: + doctypedescr = wash_single_urlarg(urlarg=doctypedescr, argreqdtype=str, argdefault="") + except ValueError, e: + doctypedescr = "" + else: + doctypedescr = "" + if categid is not None: + try: + categid = wash_single_urlarg(urlarg=categid, argreqdtype=str, argdefault="") + except ValueError, e: + categid = "" + else: + categid = "" + if categdescr is not None: + try: + categdescr = wash_single_urlarg(urlarg=categdescr, argreqdtype=str, argdefault="") + except ValueError, e: + categdescr = "" + else: + categdescr = "" + if doctype_cloneactionfrom is not None: + try: + doctype_cloneactionfrom = wash_single_urlarg(urlarg=doctype_cloneactionfrom, argreqdtype=str, argdefault="", maxstrlen=10, minstrlen=1) + if string_is_alphanumeric_including_underscore(txtstring=doctype_cloneactionfrom) == 0: + doctype_cloneactionfrom = "" + except ValueError, e: + doctype_cloneactionfrom = "" + else: + doctype_cloneactionfrom = "" + if displayed is not None: + try: + displayed = wash_single_urlarg(urlarg=displayed, argreqdtype=str, argdefault="Y", maxstrlen=1, minstrlen=1) + except ValueError, e: + displayed = "Y" + else: + displayed = "Y" + if buttonorder is not None: + try: + buttonorder = wash_single_urlarg(urlarg=buttonorder, argreqdtype=int, argdefault="") + except ValueError, e: + buttonorder = "" + else: + buttonorder = "" + if level is not None: + try: + level = wash_single_urlarg(urlarg=level, argreqdtype=str, argdefault="", maxstrlen=1, minstrlen=1) + except ValueError, e: + level = "" + else: + level = "" + if score is not None: + try: + score = wash_single_urlarg(urlarg=score, argreqdtype=int, argdefault="") + except ValueError, e: + score = "" + else: + score = "" + if stpage is not None: + try: + stpage = wash_single_urlarg(urlarg=stpage, argreqdtype=int, argdefault="") + except ValueError, e: + stpage = "" + else: + stpage = "" + if statustext is not None: + try: + statustext = wash_single_urlarg(urlarg=statustext, argreqdtype=str, argdefault="") + except ValueError, e: + statustext = "" + else: + statustext = "" + if endtxt is not None: + try: + endtxt = wash_single_urlarg(urlarg=endtxt, argreqdtype=str, argdefault="") + except ValueError, e: + endtxt = "" + else: + endtxt = "" + + ## ensure that there is only one doctype for this doctype ID - simply display all doctypes with warning if not + numrows_doctype = get_number_doctypes_docid(docid=doctype) + if numrows_doctype > 1: + ## there are multiple doctypes with this doctype ID: + ## TODO : LOG ERROR + user_msg.append("""Multiple document types identified by "%s" exist - cannot configure at this time.""" \ + % (doctype,)) + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + elif numrows_doctype == 0: + ## this doctype does not seem to exist: + user_msg.append("""The document type identified by "%s" doesn't exist - cannot configure at this time.""" \ + % (doctype,)) + ## TODO : LOG ERROR + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + + ## since doctype ID is OK, process doctype configuration request: + if doctypedetailsedit not in ("", None): + (title, body) = _create_edit_doctype_details_form(doctype=doctype) + elif doctypedetailscommit not in ("", None): + ## commit updated document type details + (title, body) = _edit_doctype_details(doctype=doctype, + doctypename=doctypename, doctypedescr=doctypedescr) + elif doctypecategoryadd not in ("", None): + ## add new category: + (title, body) = _add_category_to_doctype(doctype=doctype, categid=categid, categdescr=categdescr) + elif doctypecategoryedit not in ("", None): + ## create form to update category description: + (title, body) = _create_edit_category_form(doctype=doctype, + categid=categid) + elif doctypecategoryeditcommit not in ("", None): + ## commit updated category description: + (title, body) = _edit_category_for_doctype(doctype=doctype, categid=categid, categdescr=categdescr) + elif doctypecategorydelete not in ("", None): + ## delete a category + (title, body) = _delete_category_from_doctype(doctype=doctype, categid=categid) + elif movecategup not in ("", None) or movecategdown not in ("", None): + ## move a category up or down in score: + (title, body) = _move_category(doctype=doctype, categid=categid, + movecategup=movecategup) + elif jumpcategout not in ("", None) and jumpcategin not in ("", None): + ## jump a category from one score to another: + (title, body) = _jump_category_to_new_score(doctype=doctype, jumpcategout=jumpcategout, + jumpcategin=jumpcategin) + elif doctypesubmissionadd not in ("", None): + ## form displaying option of adding doctype: + (title, body) = _create_add_submission_choose_clonefrom_form(doctype=doctype, action=action) + elif doctypesubmissionaddclonechosen not in ("", None): + ## add a submission. if there is a document type to be cloned from, then process clone; + ## otherwise, present form with details of doctype + if doctype_cloneactionfrom in ("", None, "None"): + ## no clone - present form into which details of new submission should be entered + (title, body) = _create_add_submission_form(doctype=doctype, action=action) + else: + ## new submission should be cloned from doctype_cloneactionfrom + (title, body) = _add_submission_to_doctype_clone(doctype=doctype, action=action, clonefrom=doctype_cloneactionfrom) + elif doctypesubmissiondelete not in ("", None): + ## create form to prompt for confirmation of deletion of a submission: + (title, body) = _create_delete_submission_form(doctype=doctype, action=action) + elif doctypesubmissiondeleteconfirm not in ("", None): + ## process the deletion of a submission from the doctype concerned: + (title, body) = _delete_submission_from_doctype(doctype=doctype, action=action) + elif doctypesubmissionedit not in ("", None): + ## create form to update details of a submission + (title, body) = _create_edit_submission_form(doctype=doctype, action=action) + elif doctypesubmissioneditdetailscommit not in ("", None): + ## commit updated submission details: + (title, body) = _edit_submission_for_doctype(doctype=doctype, action=action, + displayed=displayed, buttonorder=buttonorder, statustext=statustext, + level=level, score=score, stpage=stpage, endtxt=endtxt) + elif doctypesubmissionadddetailscommit not in ("", None): + ## commit new submission to doctype (not by cloning) + (title, body) = _add_submission_to_doctype(doctype=doctype, action=action, + displayed=displayed, buttonorder=buttonorder, statustext=statustext, + level=level, score=score, stpage=stpage, endtxt=endtxt) + else: + ## default - display root of edit doctype + (title, body) = _create_configure_doctype_form(doctype=doctype, jumpcategout=jumpcategout) + return (title, body) + +def _create_configure_doctype_submission_functions_form(doctype, + action, + movefromfunctionname="", + movefromfunctionstep="", + movefromfunctionscore="", + user_msg=""): + title = """Functions of the "%s" Submission of the "%s" Document Type:""" % (action, doctype) + submission_functions = get_functionname_step_score_allfunctions_doctypesubmission(doctype=doctype, action=action) + body = websubmitadmin_templates.tmpl_configuredoctype_display_submissionfunctions(doctype=doctype, + action=action, + movefromfunctionname=movefromfunctionname, + movefromfunctionstep=movefromfunctionstep, + movefromfunctionscore=movefromfunctionscore, + submissionfunctions=submission_functions, + user_msg=user_msg) + return (title, body) + +def _create_configure_doctype_submission_functions_add_function_form(doctype, action, addfunctionname="", + addfunctionstep="", addfunctionscore="", user_msg=""): + """Create a form that allows a user to add a function a submission. + @param doctype: (string) the unique ID of a document type + @param action: (string) the unique ID of an action + @param addfunctionname: (string) the name of the function to be added to the submission (passed in case of page refresh) + @param addfunctionstep: (integer) the step of the submission into which the function is to be added (passed in case of + page refresh) + @param addfunctionscore: (integer) the score at at which the function is to be added (passed in case of page refresh) + @param user_msg: (string or list of strings) any message(s) to be displayed to the user + @return: (tuple) containing 2 strings - (page-title, HTML page-body) + """ + title = """Add a function to the [%s] submission of the [%s] document type""" % (action, doctype) + submission_functions = get_functionname_step_score_allfunctions_doctypesubmission(doctype=doctype, action=action) + ## get names of all WebSubmit functions: + all_websubmit_functions = get_names_of_all_functions() + ## put names into a list of single-element tuples, so that template can make HTML select list with them: + all_websubmit_functions = map(lambda x: (str(x),), all_websubmit_functions) + ## create page body: + body = websubmitadmin_templates.tmpl_configuredoctype_add_submissionfunction(doctype=doctype, + action=action, + cursubmissionfunctions=submission_functions, + allWSfunctions=all_websubmit_functions, + addfunctionname=addfunctionname, + addfunctionstep=addfunctionstep, + addfunctionscore=addfunctionscore, + user_msg=user_msg) + return (title, body) + +def _create_configure_doctype_submission_functions_list_parameters_form(doctype, + action, + functionname, + user_msg=""): + title = """Parameters of the %s function, as used in the %s document type"""\ + % (functionname, doctype) + funcparams = get_function_parameters(function=functionname) + if len(funcparams) > 0: + ## get the values + paramslist = map(lambda x: str(x[0]), funcparams) + params = get_function_parameter_vals_doctype(doctype=doctype, paramlist=paramslist) + else: + params = () +## params = get_parameters_name_and_value_for_function_of_doctype(doctype=doctype, function=functionname) + body = websubmitadmin_templates.tmpl_configuredoctype_list_functionparameters(doctype=doctype, + action=action, + function=functionname, + params=params, + user_msg=user_msg) + return (title, body) + +def _update_submission_function_parameter_file(doctype, action, functionname, + paramname, paramfilecontent): + user_msg = [] + ## get the filename: + paramval_res = get_value_of_parameter_for_doctype(doctype=doctype, parameter=paramname) + if paramval_res is None: + ## this parameter doesn't exist for this doctype! + user_msg.append("The parameter [%s] doesn't exist for the document type [%s]!" % (paramname, doctype)) + (title, body) = _create_configure_doctype_submission_functions_list_parameters_form(doctype=doctype, + action=action, + functionname=functionname, + user_msg=user_msg) + return (title, body) + paramval = str(paramval_res) + filename = basename(paramval) + if filename == "": + ## invalid filename + user_msg.append("[%s] is an invalid filename - cannot save details" % (paramval,)) + (title, body) = _create_configure_doctype_submission_functions_list_parameters_form(doctype=doctype, + action=action, + functionname=functionname, + user_msg=user_msg) + return (title, body) + + ## save file: + try: + save_update_to_file(filepath="%s/%s" % (CFG_WEBSUBMIT_BIBCONVERTCONFIGDIR, filename), filecontent=paramfilecontent) + except InvenioWebSubmitAdminWarningIOError, e: + ## could not correctly update the file! + user_msg.append(str(e)) + (title, body) = _create_configure_doctype_submission_functions_list_parameters_form(doctype=doctype, + action=action, + functionname=functionname, + user_msg=user_msg) + return (title, body) + + ## redisplay form + user_msg.append("""[%s] file updated""" % (filename,)) + (title, body) = _create_configure_doctype_submission_functions_edit_parameter_file_form(doctype=doctype, + action=action, + functionname=functionname, + paramname=paramname, + user_msg=user_msg) + return (title, body) + +def _create_configure_doctype_submission_functions_edit_parameter_file_form(doctype, + action, + functionname, + paramname, + user_msg=""): + if type(user_msg) is not list: + user_msg = [] + + paramval_res = get_value_of_parameter_for_doctype(doctype=doctype, parameter=paramname) + if paramval_res is None: + ## this parameter doesn't exist for this doctype! + user_msg.append("The parameter [%s] doesn't exist for the document type [%s]!" % (paramname, doctype)) + (title, body) = _create_configure_doctype_submission_functions_list_parameters_form(doctype=doctype, + action=action, + functionname=functionname) + return (title, body) + paramval = str(paramval_res) + title = "Edit the [%s] file for the [%s] document type" % (paramval, doctype) + ## get basename of file: + filecontent = "" + filename = basename(paramval) + if filename == "": + ## invalid filename + user_msg.append("[%s] is an invalid filename" % (paramval,)) + (title, body) = _create_configure_doctype_submission_functions_list_parameters_form(doctype=doctype, + action=action, + functionname=functionname, + user_msg=user_msg) + return (title, body) + ## try to read file contents: + if access("%s/%s" % (CFG_WEBSUBMIT_BIBCONVERTCONFIGDIR, filename), F_OK): + ## file exists + if access("%s/%s" % (CFG_WEBSUBMIT_BIBCONVERTCONFIGDIR, filename), R_OK) and \ + isfile("%s/%s" % (CFG_WEBSUBMIT_BIBCONVERTCONFIGDIR, filename)): + ## file is a regular file and is readable - get contents + filecontent = open("%s/%s" % (CFG_WEBSUBMIT_BIBCONVERTCONFIGDIR, filename), "r").read() + else: + if not isfile("%s/%s" % (CFG_WEBSUBMIT_BIBCONVERTCONFIGDIR, filename)): + ## file is not a regular file + user_msg.append("The parameter file [%s] is not regular file - unable to read" % (filename,)) + else: + ## file is not readable - error message + user_msg.append("The parameter file [%s] could not be read - check permissions" % (filename,)) + + ## display page listing the parameters of this function: + (title, body) = _create_configure_doctype_submission_functions_list_parameters_form(doctype=doctype, + action=action, + functionname=functionname, + user_msg=user_msg) + return (title, body) + else: + ## file does not exist: + user_msg.append("The parameter file [%s] does not exist - it will be created" % (filename,)) + + ## make page body: + body = websubmitadmin_templates.tmpl_configuredoctype_edit_functionparameter_file(doctype=doctype, + action=action, + function=functionname, + paramname=paramname, + paramfilename=filename, + paramfilecontent=filecontent, + user_msg=user_msg) + return (title, body) + +def _create_configure_doctype_submission_functions_edit_parameter_value_form(doctype, + action, + functionname, + paramname, + paramval="", + user_msg=""): + title = """Edit the value of the [%s] Parameter""" % (paramname,) + ## get the parameter's value from the DB: + paramval_res = get_value_of_parameter_for_doctype(doctype=doctype, parameter=paramname) + if paramval_res is None: + ## this parameter doesn't exist for this doctype! + (title, body) = _create_configure_doctype_submission_functions_list_parameters_form(doctype=doctype, + action=action, + functionname=functionname) + if paramval == "": + ## use whatever retrieved paramval_res contains: + paramval = str(paramval_res) + + body = websubmitadmin_templates.tmpl_configuredoctype_edit_functionparameter_value(doctype=doctype, + action=action, + function=functionname, + paramname=paramname, + paramval=paramval) + return (title, body) + +def _update_submissionfunction_parameter_value(doctype, action, functionname, paramname, paramval): + user_msg = [] + try: + update_value_of_function_parameter_for_doctype(doctype=doctype, paramname=paramname, paramval=paramval) + user_msg.append("""The value of the parameter [%s] was updated for document type [%s]""" % (paramname, doctype)) + except InvenioWebSubmitAdminWarningTooManyRows, e: + ## multiple rows found for param - update not carried out + user_msg.append(str(e)) + except InvenioWebSubmitAdminWarningNoRowsFound, e: + ## no rows found - parameter does not exist for doctype, therefore no update + user_msg.append(str(e)) + (title, body) = \ + _create_configure_doctype_submission_functions_list_parameters_form(doctype=doctype, action=action, + functionname=functionname, user_msg=user_msg) + return (title, body) + +def perform_request_configure_doctype_submissionfunctions_parameters(doctype, + action, + functionname, + functionstep, + functionscore, + paramname="", + paramval="", + editfunctionparametervalue="", + editfunctionparametervaluecommit="", + editfunctionparameterfile="", + editfunctionparameterfilecommit="", + paramfilename="", + paramfilecontent=""): + + body = "" + user_msg = [] + ## ensure that there is only one doctype for this doctype ID - simply display all doctypes with warning if not + if doctype in ("", None): + user_msg.append("""Unknown Document Type""") + ## TODO : LOG ERROR + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + + numrows_doctype = get_number_doctypes_docid(docid=doctype) + if numrows_doctype > 1: + ## there are multiple doctypes with this doctype ID: + ## TODO : LOG ERROR + user_msg.append("""Multiple document types identified by "%s" exist - cannot configure at this time.""" \ + % (doctype,)) + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + elif numrows_doctype == 0: + ## this doctype does not seem to exist: + user_msg.append("""The document type identified by "%s" doesn't exist - cannot configure at this time.""" \ + % (doctype,)) + ## TODO : LOG ERROR + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + + ## ensure that this submission exists for this doctype: + numrows_submission = get_number_submissions_doctype_action(doctype=doctype, action=action) + if numrows_submission > 1: + ## there are multiple submissions for this doctype/action ID: + ## TODO : LOG ERROR + user_msg.append("""The Submission "%s" seems to exist multiple times for the Document Type "%s" - cannot configure at this time.""" \ + % (action, doctype)) + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + elif numrows_submission == 0: + ## this submission does not seem to exist for this doctype: + user_msg.append("""The Submission "%s" doesn't exist for the "%s" Document Type - cannot configure at this time.""" \ + % (action, doctype)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + if editfunctionparametervaluecommit not in ("", None): + ## commit an update to a function parameter: + (title, body) = _update_submissionfunction_parameter_value(doctype=doctype, action=action, functionname=functionname, + paramname=paramname, paramval=paramval) + elif editfunctionparametervalue not in ("", None): + ## display a form for editing the value of a parameter: + (title, body) = _create_configure_doctype_submission_functions_edit_parameter_value_form(doctype=doctype, + action=action, + functionname=functionname, + paramname=paramname, + paramval=paramval) + elif editfunctionparameterfile not in ("", None): + ## display a form for editing the contents of a file, named by the parameter's value: + (title, body) = _create_configure_doctype_submission_functions_edit_parameter_file_form(doctype=doctype, + action=action, + functionname=functionname, + paramname=paramname) + elif editfunctionparameterfilecommit not in ("", None): + (title, body) = _update_submission_function_parameter_file(doctype=doctype, action=action, functionname=functionname, + paramname=paramname, paramfilecontent=paramfilecontent) + else: + ## default - display list of parameters for function: + (title, body) = _create_configure_doctype_submission_functions_list_parameters_form(doctype=doctype, + action=action, + functionname=functionname) + return (title, body) + +def perform_request_configure_doctype_submissionfunctions(doctype, + action, + moveupfunctionname="", + moveupfunctionstep="", + moveupfunctionscore="", + movedownfunctionname="", + movedownfunctionstep="", + movedownfunctionscore="", + movefromfunctionname="", + movefromfunctionstep="", + movefromfunctionscore="", + movetofunctionname="", + movetofunctionstep="", + movetofunctionscore="", + deletefunctionname="", + deletefunctionstep="", + deletefunctionscore="", + configuresubmissionaddfunction="", + configuresubmissionaddfunctioncommit="", + addfunctionname="", + addfunctionstep="", + addfunctionscore=""): + + body = "" + user_msg = [] + + if addfunctionstep != "": + try: + addfunctionstep = str(wash_single_urlarg(urlarg=addfunctionstep, argreqdtype=int, argdefault="")) + except ValueError, e: + addfunctionstep = "" + if addfunctionscore != "": + try: + addfunctionscore = str(wash_single_urlarg(urlarg=addfunctionscore, argreqdtype=int, argdefault="")) + except ValueError, e: + addfunctionscore = "" + if deletefunctionstep != "": + try: + deletefunctionstep = str(wash_single_urlarg(urlarg=deletefunctionstep, argreqdtype=int, argdefault="")) + except ValueError, e: + deletefunctionstep = "" + if deletefunctionscore != "": + try: + deletefunctionscore = str(wash_single_urlarg(urlarg=deletefunctionscore, argreqdtype=int, argdefault="")) + except ValueError, e: + deletefunctionscore = "" + if movetofunctionstep != "": + try: + movetofunctionstep = str(wash_single_urlarg(urlarg=movetofunctionstep, argreqdtype=int, argdefault="")) + except ValueError, e: + movetofunctionstep = "" + if movetofunctionscore != "": + try: + movetofunctionscore = str(wash_single_urlarg(urlarg=movetofunctionscore, argreqdtype=int, argdefault="")) + except ValueError, e: + movetofunctionscore = "" + if moveupfunctionstep != "": + try: + moveupfunctionstep = str(wash_single_urlarg(urlarg=moveupfunctionstep, argreqdtype=int, argdefault="")) + except ValueError, e: + moveupfunctionstep = "" + if moveupfunctionscore != "": + try: + moveupfunctionscore = str(wash_single_urlarg(urlarg=moveupfunctionscore, argreqdtype=int, argdefault="")) + except ValueError, e: + moveupfunctionscore = "" + if movedownfunctionstep != "": + try: + movedownfunctionstep = str(wash_single_urlarg(urlarg=movedownfunctionstep, argreqdtype=int, argdefault="")) + except ValueError, e: + movedownfunctionstep = "" + if movedownfunctionscore != "": + try: + movedownfunctionscore = str(wash_single_urlarg(urlarg=movedownfunctionscore, argreqdtype=int, argdefault="")) + except ValueError, e: + movedownfunctionscore = "" + + + ## ensure that there is only one doctype for this doctype ID - simply display all doctypes with warning if not + if doctype in ("", None): + user_msg.append("""Unknown Document Type""") + ## TODO : LOG ERROR + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + + numrows_doctype = get_number_doctypes_docid(docid=doctype) + if numrows_doctype > 1: + ## there are multiple doctypes with this doctype ID: + ## TODO : LOG ERROR + user_msg.append("""Multiple document types identified by "%s" exist - cannot configure at this time.""" \ + % (doctype,)) + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + elif numrows_doctype == 0: + ## this doctype does not seem to exist: + user_msg.append("""The document type identified by "%s" doesn't exist - cannot configure at this time.""" \ + % (doctype,)) + ## TODO : LOG ERROR + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + + ## ensure that this submission exists for this doctype: + numrows_submission = get_number_submissions_doctype_action(doctype=doctype, action=action) + if numrows_submission > 1: + ## there are multiple submissions for this doctype/action ID: + ## TODO : LOG ERROR + user_msg.append("""The Submission "%s" seems to exist multiple times for the Document Type "%s" - cannot configure at this time.""" \ + % (action, doctype)) + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + elif numrows_submission == 0: + ## this submission does not seem to exist for this doctype: + user_msg.append("""The Submission "%s" doesn't exist for the "%s" Document Type - cannot configure at this time.""" \ + % (action, doctype)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + + ## submission valid + if movefromfunctionname != "" and movefromfunctionstep != "" and movefromfunctionscore != "" and \ + movetofunctionname != "" and movetofunctionstep != "" and movetofunctionscore != "": + ## process moving the function by jumping it to another position + try: + move_submission_function_from_one_position_to_another_position(doctype=doctype, action=action, + movefuncname=movefromfunctionname, + movefuncfromstep=movefromfunctionstep, + movefuncfromscore=movefromfunctionscore, + movefunctostep=movetofunctionstep, + movefunctoscore=movetofunctionscore) + user_msg.append("""The function [%s] at step [%s], score [%s] was successfully moved."""\ + % (movefromfunctionname, movefromfunctionstep, movefromfunctionscore)) + except Exception, e: + ## there was a problem + user_msg.append(str(e)) + (title, body) = _create_configure_doctype_submission_functions_form(doctype=doctype, + action=action, + user_msg=user_msg) + elif moveupfunctionname != "" and moveupfunctionstep != "" and moveupfunctionscore != "": + ## process moving the function up one position + error_code = move_position_submissionfunction_up(doctype=doctype, + action=action, + function=moveupfunctionname, + funccurstep=moveupfunctionstep, + funccurscore=moveupfunctionscore) + if error_code == 0: + ## success + user_msg.append("""The Function "%s" that was located at step %s, score %s, has been moved upwards""" \ + % (moveupfunctionname, moveupfunctionstep, moveupfunctionscore)) + else: + ## could not move it + user_msg.append("""Unable to move the Function "%s" that is located at step %s, score %s""" \ + % (moveupfunctionname, moveupfunctionstep, moveupfunctionscore)) + (title, body) = _create_configure_doctype_submission_functions_form(doctype=doctype, + action=action, + user_msg=user_msg) + elif movedownfunctionname != "" and movedownfunctionstep != "" and movedownfunctionscore != "": + ## process moving the function down one position + error_code = move_position_submissionfunction_down(doctype=doctype, + action=action, + function=movedownfunctionname, + funccurstep=movedownfunctionstep, + funccurscore=movedownfunctionscore) + if error_code == 0: + ## success + user_msg.append("""The Function "%s" that was located at step %s, score %s, has been moved downwards""" \ + % (movedownfunctionname, movedownfunctionstep, movedownfunctionscore)) + else: + ## could not move it + user_msg.append("""Unable to move the Function "%s" that is located at step %s, score %s""" \ + % (movedownfunctionname, movedownfunctionstep, movedownfunctionscore)) + (title, body) = _create_configure_doctype_submission_functions_form(doctype=doctype, + action=action, + user_msg=user_msg) + elif deletefunctionname != "" and deletefunctionstep != "" and deletefunctionscore != "": + ## process deletion of function from the given position + (title, body) = _delete_submission_function(doctype=doctype, action=action, deletefunctionname=deletefunctionname, + deletefunctionstep=deletefunctionstep, deletefunctionscore=deletefunctionscore) + elif configuresubmissionaddfunction != "": + ## display a form that allows the addition of a new WebSubmit function + (title, body) = _create_configure_doctype_submission_functions_add_function_form(doctype=doctype, + action=action) + elif configuresubmissionaddfunctioncommit != "": + ## process the addition of the new WebSubmit function to the submission: + (title, body) = _add_function_to_submission(doctype=doctype, action=action, addfunctionname=addfunctionname, + addfunctionstep=addfunctionstep, addfunctionscore=addfunctionscore) + else: + ## default - display functions for this submission + (title, body) = _create_configure_doctype_submission_functions_form(doctype=doctype, + action=action, + movefromfunctionname=movefromfunctionname, + movefromfunctionstep=movefromfunctionstep, + movefromfunctionscore=movefromfunctionscore + ) + return (title, body) + +def _add_function_to_submission(doctype, action, addfunctionname, addfunctionstep, addfunctionscore): + """Process the addition of a function to a submission. + The user can decide in which step and at which score to insert the function. + @param doctype: (string) the unique ID of a document type + @param action: (string) the unique ID of an action + @param addfunctionname: (string) the name of the function to be added to the submission + @param addfunctionstep: (integer) the step at which the function is to be added + @param addfunctionscore: (integer) the score at which the function is to be added + @return: a tuple containing 2 strings: (page-title, page-body) + """ + user_msg = [] + if addfunctionname == "" or addfunctionstep == "" or addfunctionscore == "": + ## invalid details! + user_msg.append("""Invalid function coordinates supplied!""") + (title, body) = _create_configure_doctype_submission_functions_add_function_form(doctype=doctype, + action=action, + user_msg=user_msg) + return (title, body) + try: + if int(addfunctionstep) < 1 or int(addfunctionscore) < 1: + ## invalid details! + user_msg.append("""Invalid function step and/or score!""") + (title, body) = _create_configure_doctype_submission_functions_add_function_form(doctype=doctype, + action=action, + user_msg=user_msg) + return (title, body) + except ValueError: + user_msg.append("""Invalid function step and/or score!""") + (title, body) = _create_configure_doctype_submission_functions_add_function_form(doctype=doctype, + action=action, + user_msg=user_msg) + + try: + insert_function_into_submission_at_step_and_score_then_regulate_scores_of_functions_in_step(doctype=doctype, + action=action, + function=addfunctionname, + step=addfunctionstep, + score=addfunctionscore) + except InvenioWebSubmitAdminWarningReferentialIntegrityViolation, e: + ## Function didn't exist in WebSubmit! Not added to submission. + user_msg.append(str(e)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_submission_functions_add_function_form(doctype=doctype, + action=action, + addfunctionstep=addfunctionstep, + addfunctionscore=addfunctionscore, + user_msg=user_msg) + return (title, body) + except InvenioWebSubmitAdminWarningInsertFailed, e: + ## insert failed - some functions within the step may have been corrupted! + user_msg.append(str(e)) + ## TODO : LOG ERROR + (title, body) = \ + _create_configure_doctype_submission_functions_form(doctype=doctype, action=action, user_msg=user_msg) + return (title, body) + except InvenioWebSubmitAdminWarningDeleteFailed, e: + ## when regulating the scores of functions within the step, could not delete some or all of the functions + ## within the step that the function was added to. Some functions may have been lost! + user_msg.append(str(e)) + ## TODO : LOG ERROR + (title, body) = \ + _create_configure_doctype_submission_functions_form(doctype=doctype, action=action, user_msg=user_msg) + return (title, body) + + ## Successfully added + user_msg.append("""The function [%s] has been added to submission [%s] at step [%s], score [%s]."""\ + % (addfunctionname, "%s%s" % (action, doctype), addfunctionstep, addfunctionscore)) + (title, body) = \ + _create_configure_doctype_submission_functions_form(doctype=doctype, action=action, user_msg=user_msg) + return (title, body) + +def _delete_submission_function(doctype, action, deletefunctionname, deletefunctionstep, deletefunctionscore): + """Delete a submission function from a given submission. Re-order all functions below it (within the same step) + to fill the gap left by the deleted function. + @param doctype: (string) the unique ID of a document type + @param action: (string) the unique ID of an action + @param deletefunctionname: (string) the name of the function to be deleted from the submission + @param deletefunctionstep: (string) the step of the function to be deleted from the submission + @param deletefunctionscore: (string) the score of the function to be deleted from the submission + @return: tuple containing 2 strings: (page-title, page-body) + """ + user_msg = [] + ## first, delete the function: + try: + delete_function_at_step_and_score_from_submission(doctype=doctype, action=action, + function=deletefunctionname, step=deletefunctionstep, + score=deletefunctionscore) + except InvenioWebSubmitAdminWarningDeleteFailed, e: + ## unable to delete function - error message and return + user_msg.append("""Unable to delete function [%s] at step [%s], score [%s] from submission [%s]""" \ + % (deletefunctionname, deletefunctionstep, deletefunctionscore, "%s%s" % (action, doctype))) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_submission_functions_form(doctype=doctype, action=action, user_msg=user_msg) + return (title, body) + ## now, correct the scores of all functions in the step from which a function was just deleted: + try: + regulate_score_of_all_functions_in_step_to_ascending_multiples_of_10_for_submission(doctype=doctype, + action=action, + step=deletefunctionstep) + except InvenioWebSubmitAdminWarningDeleteFailed, e: + ## couldnt delete the functions before reordering them + user_msg.append("""Deleted function [%s] at step [%s], score [%s] from submission [%s], but could not re-order""" \ + """ scores of remaining functions within step [%s]""" \ + % (deletefunctionname, deletefunctionstep, deletefunctionscore, + "%s%s" % (action, doctype), deletefunctionstep)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_submission_functions_form(doctype=doctype, action=action, user_msg=user_msg) + return (title, body) + ## update submission "last-modification" date: + update_modification_date_for_submission(doctype=doctype, action=action) + ## success message: + user_msg.append("""Successfully deleted function [%s] at step [%s], score [%s] from submission [%s]""" \ + % (deletefunctionname, deletefunctionstep, deletefunctionscore, "%s%s" % (action, doctype))) + ## TODO : LOG function Deletion + (title, body) = _create_configure_doctype_submission_functions_form(doctype=doctype, action=action, user_msg=user_msg) + return (title, body) + +def perform_request_configure_doctype_submissionpage_preview(doctype, action, pagenum): + """Display a preview of a Submission Page and its fields. + @param doctype: (string) the unique ID of a document type + @param action: (string) the unique ID of an action + @param pagenum: (integer) the number of the submission page to be previewed + @return: a tuple of four elements. (page-title, page-body) + """ + body = "" + user_msg = [] + + try: + pagenum = str(pagenum) + except ValueError: + pagenum = "" + + if pagenum != "": + try: + pagenum = str(wash_single_urlarg(urlarg=pagenum, argreqdtype=int, argdefault="")) + except ValueError, e: + pagenum = "" + ## ensure that the page number for this submission is valid: + num_pages_submission = get_numbersubmissionpages_doctype_action(doctype=doctype, action=action) + try: + if not (int(pagenum) > 0 and int(pagenum) <= num_pages_submission): + user_msg.append("Invalid page number - out of range") + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, action=action, user_msg=user_msg) + return (title, body) + except ValueError: + ## invalid page number + user_msg.append("Invalid page number - must be an integer value!") + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, action=action, user_msg=user_msg) + return (title, body) + + ## get details of all fields on submission page: + fields = get_details_and_description_of_all_fields_on_submissionpage(doctype=doctype, action=action, pagenum=pagenum) + ## ensure all values for each field are strings: + string_fields = [] + for field in fields: + string_fields.append(stringify_list_elements(field)) + title = """A preview of Page %s of the %s Submission""" % (pagenum, "%s%s" % (action, doctype)) + body = websubmitadmin_templates.tmpl_configuredoctype_display_submissionpage_preview(doctype=doctype, + action=action, + pagenum=pagenum, + fields=string_fields) + return (title, body) + +def perform_request_configure_doctype_submissionpage_elements(doctype, action, pagenum, movefieldfromposn="", + movefieldtoposn="", deletefieldposn="", editfieldposn="", + editfieldposncommit="", fieldname="", fieldtext="", fieldlevel="", + fieldshortdesc="", fieldcheck="", addfield="", addfieldcommit=""): + """Process requests relating to the elements of a particular submission page""" + + body = "" + user_msg = [] + try: + pagenum = str(pagenum) + except ValueError: + pagenum = "" + + if pagenum != "": + try: + pagenum = str(wash_single_urlarg(urlarg=pagenum, argreqdtype=int, argdefault="")) + except ValueError, e: + pagenum = "" + if fieldname != "": + try: + fieldname = wash_single_urlarg(urlarg=fieldname, argreqdtype=str, argdefault="", maxstrlen=15, minstrlen=1) + if string_is_alphanumeric_including_underscore(txtstring=fieldname) == 0: + fieldname = "" + except ValueError, e: + fieldname = "" + if fieldtext != "": + try: + fieldtext = wash_single_urlarg(urlarg=fieldtext, argreqdtype=str, argdefault="") + except ValueError, e: + fieldtext = "" + if fieldlevel != "": + try: + fieldlevel = wash_single_urlarg(urlarg=fieldlevel, argreqdtype=str, argdefault="O", maxstrlen=1, minstrlen=1) + if string_is_alphanumeric_including_underscore(txtstring=fieldlevel) == 0: + fieldlevel = "O" + if fieldlevel not in ("m", "M", "o", "O"): + fieldlevel = "O" + fieldlevel = fieldlevel.upper() + except ValueError, e: + fieldlevel = "O" + if fieldshortdesc != "": + try: + fieldshortdesc = wash_single_urlarg(urlarg=fieldshortdesc, argreqdtype=str, argdefault="") + except ValueError, e: + fieldshortdesc = "" + if fieldcheck != "": + try: + fieldcheck = wash_single_urlarg(urlarg=fieldcheck, argreqdtype=str, argdefault="", maxstrlen=15, minstrlen=1) + if string_is_alphanumeric_including_underscore(txtstring=fieldcheck) == 0: + fieldcheck = "" + except ValueError, e: + fieldcheck = "" + if editfieldposn != "": + try: + editfieldposn = str(wash_single_urlarg(urlarg=editfieldposn, argreqdtype=int, argdefault="")) + except ValueError, e: + editfieldposn = "" + if deletefieldposn != "": + try: + deletefieldposn = str(wash_single_urlarg(urlarg=deletefieldposn, argreqdtype=int, argdefault="")) + except ValueError, e: + deletefieldposn = "" + if movefieldfromposn != "": + try: + movefieldfromposn = str(wash_single_urlarg(urlarg=movefieldfromposn, argreqdtype=int, argdefault="")) + except ValueError, e: + movefieldfromposn = "" + if movefieldtoposn != "": + try: + movefieldtoposn = str(wash_single_urlarg(urlarg=movefieldtoposn, argreqdtype=int, argdefault="")) + except ValueError, e: + movefieldtoposn = "" + + ## ensure that there is only one doctype for this doctype ID - simply display all doctypes with warning if not + if doctype in ("", None): + user_msg.append("""Unknown Document Type""") + ## TODO : LOG ERROR + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + + numrows_doctype = get_number_doctypes_docid(docid=doctype) + if numrows_doctype > 1: + ## there are multiple doctypes with this doctype ID: + ## TODO : LOG ERROR + user_msg.append("""Multiple document types identified by "%s" exist - cannot configure at this time.""" \ + % (doctype,)) + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + elif numrows_doctype == 0: + ## this doctype does not seem to exist: + user_msg.append("""The document type identified by "%s" doesn't exist - cannot configure at this time.""" \ + % (doctype,)) + ## TODO : LOG ERROR + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + + ## ensure that this submission exists for this doctype: + numrows_submission = get_number_submissions_doctype_action(doctype=doctype, action=action) + if numrows_submission > 1: + ## there are multiple submissions for this doctype/action ID: + ## TODO : LOG ERROR + user_msg.append("""The Submission "%s" seems to exist multiple times for the Document Type "%s" - cannot configure at this time.""" \ + % (action, doctype)) + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + elif numrows_submission == 0: + ## this submission does not seem to exist for this doctype: + user_msg.append("""The Submission "%s" doesn't exist for the "%s" Document Type - cannot configure at this time.""" \ + % (action, doctype)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + ## ensure that the page number for this submission is valid: + num_pages_submission = get_numbersubmissionpages_doctype_action(doctype=doctype, action=action) + try: + if not (int(pagenum) > 0 and int(pagenum) <= num_pages_submission): + user_msg.append("Invalid page number - out of range") + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, action=action, user_msg=user_msg) + return (title, body) + except ValueError: + ## invalid page number + user_msg.append("Invalid page number - must be an integer value!") + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, action=action, user_msg=user_msg) + return (title, body) + + + ## submission valid + if editfieldposn != "" and editfieldposncommit == "": + ## display form for editing field + (title, body) = _configure_doctype_edit_field_on_submissionpage_display_field_details(doctype=doctype, action=action, + pagenum=pagenum, fieldposn=editfieldposn) + elif editfieldposn != "" and editfieldposncommit != "": + ## commit changes to element + (title, body) = _configure_doctype_edit_field_on_submissionpage(doctype=doctype, action=action, + pagenum=pagenum, fieldposn=editfieldposn, fieldtext=fieldtext, + fieldlevel=fieldlevel, fieldshortdesc=fieldshortdesc, fieldcheck=fieldcheck) + elif movefieldfromposn != "" and movefieldtoposn != "": + ## move a field + (title, body) = _configure_doctype_move_field_on_submissionpage(doctype=doctype, + action=action, pagenum=pagenum, movefieldfromposn=movefieldfromposn, + movefieldtoposn=movefieldtoposn) + elif addfield != "": + ## request to add a new field to a page - display form + (title, body) = _configure_doctype_add_field_to_submissionpage_display_form(doctype=doctype, action=action, pagenum=pagenum) + elif addfieldcommit != "": + ## commit a new field to the page + (title, body) = _configure_doctype_add_field_to_submissionpage(doctype=doctype, action=action, + pagenum=pagenum, fieldname=fieldname, fieldtext=fieldtext, + fieldlevel=fieldlevel, fieldshortdesc=fieldshortdesc, fieldcheck=fieldcheck) + elif deletefieldposn != "": + ## user wishes to delete a field from the page: + (title, body) = _configure_doctype_delete_field_from_submissionpage(doctype=doctype, + action=action, pagenum=pagenum, fieldnum=deletefieldposn) + else: + ## default visit to page - list its elements: + (title, body) = _create_configure_doctype_submission_page_elements_form(doctype=doctype, action=action, + pagenum=pagenum, movefieldfromposn=movefieldfromposn) + return (title, body) + +def stringify_list_elements(elementslist): + o = [] + for el in elementslist: + o.append(str(el)) + return o + +def _configure_doctype_edit_field_on_submissionpage(doctype, action, pagenum, fieldposn, + fieldtext, fieldlevel, fieldshortdesc, fieldcheck): + """Perform an update to the details of a field on a submission page. + @param doctype: (string) the unique ID of a document type + @param action: (string) the unique ID of an action + @param pagenum: (integer) the number of the page on which the element to be updated is found + @param fieldposn: (integer) the numeric position of the field to be editied + @param fieldtext: (string) the text label displayed with a field + @param fieldlevel: (char) M or O (whether the field is mandatory or optional) + @param fieldshortdesc: (string) the short description of a field + @param fieldcheck: (string) the name of a JavaScript check to be applied to a field + @return: a tuple containing 2 strings - (page-title, page-body) + """ + user_msg = [] + if fieldcheck not in ("", None): + ## ensure check exists: + checkres = get_number_jschecks_with_chname(chname=fieldcheck) + if checkres < 1: + user_msg.append("The Check '%s' does not exist in WebSubmit - changes to field not saved" % (fieldcheck,)) + (title, body) = _configure_doctype_edit_field_on_submissionpage_display_field_details(doctype=doctype, action=action, + pagenum=pagenum, fieldposn=fieldposn, + fieldtext=fieldtext, fieldlevel=fieldlevel, + fieldshortdesc=fieldshortdesc, user_msg=user_msg) + return (title, body) + + try: + update_details_of_a_field_on_a_submissionpage(doctype=doctype, action=action, pagenum=pagenum, fieldposn=fieldposn, + fieldtext=fieldtext, fieldlevel=fieldlevel, fieldshortdesc=fieldshortdesc, + fieldcheck=fieldcheck) + user_msg.append("The details of the field at position %s have been updated successfully" % (fieldposn,)) + update_modification_date_for_submission(doctype=doctype, action=action) + except InvenioWebSubmitAdminWarningTooManyRows, e: + ## multiple rows found at page position - not safe to edit: + user_msg.append("Unable to update details of field at position %s on submission page %s - multiple fields found at this position" \ + % (fieldposn, pagenum)) + ## TODO : LOG WARNING + except InvenioWebSubmitAdminWarningNoRowsFound, e: + ## field not found - cannot edit + user_msg.append("Unable to update details of field at position %s on submission page %s - field doesn't seem to exist there!" \ + % (fieldposn, pagenum)) + ## TODO : LOG WARNING + + (title, body) = _create_configure_doctype_submission_page_elements_form(doctype=doctype, action=action, pagenum=pagenum, user_msg=user_msg) + return (title, body) + +def _configure_doctype_edit_field_on_submissionpage_display_field_details(doctype, action, pagenum, fieldposn, + fieldtext=None, fieldlevel=None, fieldshortdesc=None, + fieldcheck=None, user_msg=""): + """Display a form used to edit a field on a submission page. + @param doctype: (string) the unique ID of a document type + @param action: (string) the unique ID of an action + @param pagenum: (integer) the number of the page on which the element to be updated is found + @param fieldposn: (integer) the numeric position of the field to be editied + @param fieldtext: (string) the text label displayed with a field + @param fieldlevel: (char) M or O (whether the field is mandatory or optional) + @param fieldshortdesc: (string) the short description of a field + @param fieldcheck: (string) the name of a JavaScript check to be applied to a field + @param user_msg: (list of strings, or string) any warning/error message to be displayed to the user + @return: a tuple containing 2 strings (page-title, page-body) + """ + if type(user_msg) not in (list, tuple) or user_msg == "": + user_msg = [] + ## get a list of all check names: + checks_res = get_all_jscheck_names() + allchecks=[] + for check in checks_res: + allchecks.append((check,)) + ## get the details for the field to be edited: + fielddets = get_details_of_field_at_positionx_on_submissionpage(doctype=doctype, action=action, pagenum=pagenum, fieldposition=fieldposn) + + if len(fielddets) < 1: + (title, body) = _create_configure_doctype_submission_page_elements_form(doctype=doctype, action=action, pagenum=pagenum) + return (title, body) + + fieldname = str(fielddets[2]) + if fieldtext is not None: + fieldtext = str(fieldtext) + else: + fieldtext = str(fielddets[3]) + if fieldlevel is not None: + fieldlevel = str(fieldlevel) + else: + fieldlevel = str(fielddets[4]) + if fieldshortdesc is not None: + fieldshortdesc = str(fieldshortdesc) + else: + fieldshortdesc = str(fielddets[5]) + if fieldcheck is not None: + fieldcheck = str(fieldcheck) + else: + fieldcheck = str(fielddets[6]) + cd = str(fielddets[7]) + md = str(fielddets[8]) + title = """Edit the %(fieldname)s field as it appears at position %(fieldnum)s on Page %(pagenum)s of the %(submission)s Submission""" \ + % { 'fieldname' : fieldname, 'fieldnum' : fieldposn, 'pagenum' : pagenum, 'submission' : "%s%s" % (action, doctype) } + + body = websubmitadmin_templates.tmpl_configuredoctype_edit_submissionfield(doctype=doctype, + action=action, + pagenum=pagenum, + fieldnum=fieldposn, + fieldname=fieldname, + fieldtext=fieldtext, + fieldlevel=fieldlevel, + fieldshortdesc=fieldshortdesc, + fieldcheck=fieldcheck, + cd=cd, + md=md, + allchecks=allchecks, + user_msg=user_msg) + return (title, body) + +def _configure_doctype_add_field_to_submissionpage(doctype, action, pagenum, fieldname="", + fieldtext="", fieldlevel="", fieldshortdesc="", fieldcheck=""): + """Add a field to a submission page. + @param doctype: (string) the unique ID of a document type + @param action: (string) the unique ID of an action + @param pagenum: (integer) the number of the page on which the element to be updated is found + @param fieldname: (string) the name of the field to be added to the page + @param fieldtext: (string) the text label displayed with a field + @param fieldlevel: (char) M or O (whether the field is mandatory or optional) + @param fieldshortdesc: (string) the short description of a field + @param fieldcheck: (string) the name of a JavaScript check to be applied to a field + @return: a tuple containing 2 strings - (page-title, page-body) + """ + user_msg = [] + ## ensure that a field "fieldname" actually exists: + if fieldname == "": + ## the field to be added has no element description in the WebSubmit DB - cannot add + user_msg.append("""The field that you have chosen to add does not seem to exist in WebSubmit - cannot add""") + (title, body) = _configure_doctype_add_field_to_submissionpage_display_form(doctype, action, pagenum, + fieldtext=fieldtext, + fieldlevel=fieldlevel, fieldshortdesc=fieldshortdesc, + fieldcheck=fieldcheck, user_msg=user_msg) + return (title, body) + + numelements_elname = get_number_elements_with_elname(elname=fieldname) + if numelements_elname < 1: + ## the field to be added has no element description in the WebSubmit DB - cannot add + user_msg.append("""The field that you have chosen to add (%s) does not seem to exist in WebSubmit - cannot add""" % (fieldname,)) + (title, body) = _configure_doctype_add_field_to_submissionpage_display_form(doctype, action, pagenum, + fieldtext=fieldtext, + fieldlevel=fieldlevel, fieldshortdesc=fieldshortdesc, + fieldcheck=fieldcheck, user_msg=user_msg) + return (title, body) + ## if fieldcheck has been provided, ensure that it is a valid check name: + if fieldcheck not in ("", None): + ## ensure check exists: + checkres = get_number_jschecks_with_chname(chname=fieldcheck) + if checkres < 1: + user_msg.append("The Check '%s' does not exist in WebSubmit - new field not saved to page" % (fieldcheck,)) + (title, body) = _configure_doctype_add_field_to_submissionpage_display_form(doctype, action, pagenum, + fieldname=fieldname, fieldtext=fieldtext, + fieldlevel=fieldlevel, fieldshortdesc=fieldshortdesc, + user_msg=user_msg) + return (title, body) + ## now add the new field to the page: + try: + insert_field_onto_submissionpage(doctype=doctype, action=action, pagenum=pagenum, fieldname=fieldname, fieldtext=fieldtext, + fieldlevel=fieldlevel, fieldshortdesc=fieldshortdesc, fieldcheck=fieldcheck) + user_msg.append("""Successfully added the field "%s" to the last position on page %s of submission %s""" \ + % (fieldname, pagenum, "%s%s" % (action, doctype))) + update_modification_date_for_submission(doctype=doctype, action=action) + (title, body) = _create_configure_doctype_submission_page_elements_form(doctype=doctype, action=action, pagenum=pagenum, user_msg=user_msg) + except InvenioWebSubmitAdminWarningInsertFailed, e: + ## the insert of the new field failed for some reason + ## TODO : LOG ERROR + user_msg.append("""Couldn't add the field "%s" to page %s of submission %s - please try again""" \ + % (fieldname, pagenum, "%s%s" % (action, doctype))) + (title, body) = _configure_doctype_add_field_to_submissionpage_display_form(doctype, action, pagenum, + fieldname=fieldname, fieldtext=fieldtext, + fieldlevel=fieldlevel, fieldshortdesc=fieldshortdesc, + fieldcheck=fieldcheck, user_msg=user_msg) + return (title, body) + +def _configure_doctype_add_field_to_submissionpage_display_form(doctype, action, pagenum, fieldname="", fieldtext="", + fieldlevel="", fieldshortdesc="", fieldcheck="", user_msg=""): + title = """Add a Field to Page %(pagenum)s of the %(submission)s Submission""" \ + % { 'pagenum' : pagenum, 'submission' : "%s%s" % (action, doctype) } + + ## sanity checking: + if type(user_msg) not in (list, tuple) or user_msg == "": + user_msg = [] + ## get a list of all check names: + checks_res = get_all_jscheck_names() + allchecks=[] + for check in checks_res: + allchecks.append((check,)) + ## get a list of all WebSubmit element names: + elements_res = get_all_element_names() + allelements = [] + for el in elements_res: + allelements.append((el,)) + + ## get form: + body = websubmitadmin_templates.tmpl_configuredoctype_add_submissionfield(doctype=doctype, + action=action, + pagenum=pagenum, + fieldname=fieldname, + fieldtext=fieldtext, + fieldlevel=fieldlevel, + fieldshortdesc=fieldshortdesc, + fieldcheck=fieldcheck, + allchecks=allchecks, + allelements=allelements, + user_msg=user_msg) + return (title, body) + +def _configure_doctype_move_field_on_submissionpage(doctype, action, pagenum, movefieldfromposn, movefieldtoposn): + user_msg = [] + _ = gettext_set_language(CFG_SITE_LANG) + movefield_res = move_field_on_submissionpage_from_positionx_to_positiony(doctype=doctype, action=action, pagenum=pagenum, + movefieldfrom=movefieldfromposn, movefieldto=movefieldtoposn) + + if movefield_res == 1: + ## invalid field numbers + try: + raise InvenioWebSubmitWarning(_('Unable to move field at position %s to position %s on page %s of submission \'%s%s\' - Invalid Field Position Numbers') % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype)) + except InvenioWebSubmitWarning, exc: + register_exception(stream='warning') + #warnings.append(exc.message) + #warnings.append(('WRN_WEBSUBMITADMIN_INVALID_FIELD_NUMBERS_SUPPLIED_WHEN_TRYING_TO_MOVE_FIELD_ON_SUBMISSION_PAGE', \ + #movefieldfromposn, movefieldtoposn, pagenum, "%s%s" % (action, doctype))) + user_msg.append("""Unable to move field from position %s to position %s on page %s of submission %s%s - field position numbers invalid""" \ + % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype)) + elif movefield_res == 2: + ## failed to swap 2 fields - couldn't move field1 to temp position + try: + raise InvenioWebSubmitWarning(_('Unable to swap field at position %s with field at position %s on page %s of submission %s - could not move field at position %s to temporary field location') % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype)) + except InvenioWebSubmitWarning, exc: + register_exception(stream='warning') + #warnings.append(exc.message) + #warnings.append(('WRN_WEBSUBMITADMIN_UNABLE_TO_SWAP_TWO_FIELDS_ON_SUBMISSION_PAGE_COULDNT_MOVE_FIELD1_TO_TEMP_POSITION', \ + #movefieldfromposn, movefieldtoposn, pagenum, "%s%s" % (action, doctype))) + user_msg.append("""Unable to move field from position %s to position %s on page %s of submission %s%s""" \ + % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype)) + elif movefield_res == 3: + ## failed to swap 2 fields on submission page - couldn't move field2 to field1 position + try: + raise InvenioWebSubmitWarning(_('Unable to swap field at position %s with field at position %s on page %s of submission %s - could not move field at position %s to position %s. Please ask Admin to check that a field was not stranded in a temporary position') % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype)) + except InvenioWebSubmitWarning, exc: + register_exception(stream='warning') + #warnings.append(exc.message) + #warnings.append(('WRN_WEBSUBMITADMIN_UNABLE_TO_SWAP_TWO_FIELDS_ON_SUBMISSION_PAGE_COULDNT_MOVE_FIELD2_TO_FIELD1_POSITION', \ + #movefieldfromposn, movefieldtoposn, pagenum, "%s%s" % (action, doctype), movefieldtoposn, movefieldfromposn)) + user_msg.append("""Unable to move field from position %s to position %s on page %s of submission %s%s - See Admin if field order is broken""" \ + % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype)) + elif movefield_res == 4: + ## failed to swap 2 fields in submission page - couldnt swap field at temp position to field2 position + try: + raise InvenioWebSubmitWarning(_('Unable to swap field at position %s with field at position %s on page %s of submission %s - could not move field that was located at position %s to position %s from temporary position. Field is now stranded in temporary position and must be corrected manually by an Admin') % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype, movefieldfromposn, movefieldtoposn)) + except InvenioWebSubmitWarning, exc: + register_exception(stream='warning') + #warnings.append(exc.message) + #warnings.append(('WRN_WEBSUBMITADMIN_UNABLE_TO_SWAP_TWO_FIELDS_ON_SUBMISSION_PAGE_COULDNT_MOVE_FIELD1_TO_POSITION_FIELD2_FROM_TEMPORARY_POSITION', \ + #movefieldfromposn, movefieldtoposn, pagenum, "%s%s" % (action, doctype), movefieldfromposn, movefieldtoposn)) + user_msg.append("""Unable to move field from position %s to position %s on page %s of submission %s%s - Field-order is now broken and must be corrected by Admin""" \ + % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype)) + elif movefield_res == 5: + ## failed to decrement the position of all fields below the field that was moved to a temp position + try: + raise InvenioWebSubmitWarning(_('Unable to move field at position %s to position %s on page %s of submission %s - could not decrement the position of the fields below position %s. Tried to recover - please check that field ordering is not broken') % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype, movefieldfromposn)) + except InvenioWebSubmitWarning, exc: + register_exception(stream='warning') + #warnings.append(exc.message) + #warnings.append(('WRN_WEBSUBMITADMIN_UNABLE_TO_MOVE_FIELD_TO_NEW_POSITION_ON_SUBMISSION_PAGE_COULDNT_DECREMENT_POSITION_OF_FIELDS_BELOW_FIELD1', \ + #movefieldfromposn, movefieldtoposn, pagenum, "%s%s" % (action, doctype), movefieldfromposn)) + user_msg.append("""Unable to move field from position %s to position %s on page %s of submission %s%s - See Admin if field-order is broken""" \ + % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype)) + elif movefield_res == 6: + ## failed to increment position of fields in and below position into which 'movefromfieldposn' is to be inserted + try: + raise InvenioWebSubmitWarning(_('Unable to move field at position %s to position %s on page %s of submission %s%s - could not increment the position of the fields at and below position %s. The field that was at position %s is now stranded in a temporary position.') % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype, movefieldtoposn, movefieldfromposn)) + except InvenioWebSubmitWarning, exc: + register_exception(stream='warning') + #warnings.append(exc.message) + #warnings.append(('WRN_WEBSUBMITADMIN_UNABLE_TO_MOVE_FIELD_TO_NEW_POSITION_ON_SUBMISSION_PAGE_COULDNT_INCREMENT_POSITION_OF_FIELDS_AT_AND_BELOW_FIELD2', \ + #movefieldfromposn, movefieldtoposn, pagenum, "%s%s" % (action, doctype), movefieldtoposn, movefieldfromposn)) + user_msg.append("""Unable to move field from position %s to position %s on page %s of submission %s%s - Field-order is now broken and must be corrected by Admin""" \ + % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype)) + else: + ## successful update: + try: + raise InvenioWebSubmitWarning(_('Moved field from position %s to position %s on page %s of submission \'%s%s\'.') % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype)) + except InvenioWebSubmitWarning, exc: + register_exception(stream='warning') + #warnings.append(exc.message) + #warnings.append(('WRN_WEBSUBMITADMIN_MOVED_FIELD_ON_SUBMISSION_PAGE', movefieldfromposn, movefieldtoposn, pagenum, "%s%s" % (action, doctype))) + user_msg.append("""Successfully moved field from position %s to position %s on page %s of submission %s%s""" \ + % (movefieldfromposn, movefieldtoposn, pagenum, action, doctype)) + + (title, body) = _create_configure_doctype_submission_page_elements_form(doctype=doctype, action=action, pagenum=pagenum, user_msg=user_msg) + return (title, body) + +def _configure_doctype_delete_field_from_submissionpage(doctype, action, pagenum, fieldnum): + """Delete a field from a submission page""" + _ = gettext_set_language(CFG_SITE_LANG) + user_msg = [] + del_res = delete_a_field_from_submissionpage_then_reorder_fields_below_to_fill_vacant_position(doctype=doctype, + action=action, + pagenum=pagenum, + fieldposn=fieldnum) + if del_res == 1: + try: + raise InvenioWebSubmitWarning(_('Unable to delete field at position %s from page %s of submission \'%s\'') % (fieldnum, pagenum, action, doctype)) + except InvenioWebSubmitWarning, exc: + register_exception(stream='warning') + #warnings.append(exc.message) + #warnings.append(('WRN_WEBSUBMITADMIN_UNABLE_TO_DELETE_FIELD_FROM_SUBMISSION_PAGE', fieldnum, pagenum, "%s%s" % (action, doctype))) + user_msg.append("Unable to delete field at position %s from page number %s of submission %s%s" % (fieldnum, pagenum, action, doctype)) + else: + ## deletion was OK + user_msg.append("Field deleted") + try: + raise InvenioWebSubmitWarning(_('Unable to delete field at position %s from page %s of submission \'%s%s\'') % (fieldnum, pagenum, action, doctype)) + except InvenioWebSubmitWarning, exc: + register_exception(stream='warning') + #warnings.append(exc.message) + #warnings.append(('WRN_WEBSUBMITADMIN_DELETED_FIELD_FROM_SUBMISSION_PAGE', fieldnum, pagenum, "%s%s" % (action, doctype))) + (title, body) = _create_configure_doctype_submission_page_elements_form(doctype=doctype, action=action, pagenum=pagenum, user_msg=user_msg) + return (title, body) + +def _create_configure_doctype_submission_page_elements_form(doctype, action, pagenum, movefieldfromposn="", user_msg=""): + ## get list of elements for page: + title = """Submission Elements found on Page %s of the "%s" Submission of the "%s" Document Type:"""\ + % (pagenum, action, doctype) + body = "" + raw_page_elements = get_details_allsubmissionfields_on_submission_page(doctype=doctype, action=action, pagenum=pagenum) + ## correctly stringify page elements for the template: + page_elements = [] + for element in raw_page_elements: + page_elements.append(stringify_list_elements(element)) + body = websubmitadmin_templates.tmpl_configuredoctype_list_submissionelements(doctype=doctype, + action=action, + pagenum=pagenum, + page_elements=page_elements, + movefieldfromposn=movefieldfromposn, + user_msg=user_msg) + return (title, body) + +def perform_request_configure_doctype_submissionpages(doctype, + action, + pagenum="", + movepage="", + movepagedirection="", + deletepage="", + deletepageconfirm="", + addpage=""): + """Process requests relating to the submission pages of a doctype/submission""" + body = "" + user_msg = [] + try: + pagenum = int(pagenum) + except ValueError: + pagenum = "" + + ## ensure that there is only one doctype for this doctype ID - simply display all doctypes with warning if not + if doctype in ("", None): + user_msg.append("""Unknown Document Type""") + ## TODO : LOG ERROR + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + + numrows_doctype = get_number_doctypes_docid(docid=doctype) + if numrows_doctype > 1: + ## there are multiple doctypes with this doctype ID: + ## TODO : LOG ERROR + user_msg.append("""Multiple document types identified by "%s" exist - cannot configure at this time.""" \ + % (doctype,)) + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + elif numrows_doctype == 0: + ## this doctype does not seem to exist: + user_msg.append("""The document type identified by "%s" doesn't exist - cannot configure at this time.""" \ + % (doctype,)) + ## TODO : LOG ERROR + all_doctypes = get_docid_docname_alldoctypes() + body = websubmitadmin_templates.tmpl_display_alldoctypes(doctypes=all_doctypes, user_msg=user_msg) + title = "Available WebSubmit Document Types" + return (title, body) + + ## ensure that this submission exists for this doctype: + numrows_submission = get_number_submissions_doctype_action(doctype=doctype, action=action) + if numrows_submission > 1: + ## there are multiple submissions for this doctype/action ID: + ## TODO : LOG ERROR + user_msg.append("""The Submission "%s" seems to exist multiple times for the Document Type "%s" - cannot configure at this time.""" \ + % (action, doctype)) + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + elif numrows_submission == 0: + ## this submission does not seem to exist for this doctype: + user_msg.append("""The Submission "%s" doesn't exist for the "%s" Document Type - cannot configure at this time.""" \ + % (action, doctype)) + ## TODO : LOG ERROR + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + + ## submission valid + if addpage != "": + ## add a new page to a submission: + error_code = add_submission_page_doctype_action(doctype=doctype, action=action) + if error_code == 0: + ## success + user_msg.append("""A new Submission Page has been added into the last position""") + else: + ## could not move it + user_msg.append("""Unable to add a new Submission Page""") + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, + action=action, + user_msg=user_msg) + elif movepage != "": + ## user wants to move a page upwards in the order + (title, body) = _configure_doctype_move_submission_page(doctype=doctype, + action=action, pagenum=pagenum, direction=movepagedirection) + elif deletepage != "": + ## user wants to delete a page: + if deletepageconfirm != "": + ## confirmation of deletion has been provided - proceed + (title, body) = _configure_doctype_delete_submission_page(doctype=doctype, + action=action, pagenum=pagenum) + else: + ## user has not yet confirmed the deletion of a page - prompt for confirmation + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, + action=action, + deletepagenum=pagenum) + else: + ## default - display details of submission pages for this submission: + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, action=action) + return (title, body) + +def _configure_doctype_move_submission_page(doctype, action, pagenum, direction): + user_msg = [] + ## Sanity checking: + if direction.lower() not in ("up", "down"): + ## invalid direction: + user_msg.append("""Invalid Page destination - no action was taken""") + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, + action=action, + user_msg=user_msg) + return (title, body) + + ## swap the pages: + if direction.lower() == "up": + error_code = swap_elements_adjacent_pages_doctype_action(doctype=doctype, action=action, + page1=pagenum, page2=pagenum-1) + else: + error_code = swap_elements_adjacent_pages_doctype_action(doctype=doctype, action=action, + page1=pagenum, page2=pagenum+1) + if error_code == 0: + ## pages swapped successfully: + ## TODO : LOG PAGE SWAP + user_msg.append("""Page %s was successfully moved %swards""" % (pagenum, direction.capitalize())) + elif error_code == 1: + ## pages are not adjacent: + user_msg.append("""Unable to move page - only adjacent pages can be swapped around""") + elif error_code == 2: + ## at least one page out of legal range (e.g. trying to move a page to a position higher or lower + ## than the number of pages: + user_msg.append("""Unable to move page to illegal position""") + elif error_code in (3, 4): + ## Some sort of problem moving fields around! + ## TODO : LOG ERROR + user_msg.append("""Error: there was a problem swapping the submission elements to their new pages.""") + user_msg.append("""An attempt was made to return the elements to their original pages - you """\ + """should verify that this was successful, or ask your administrator"""\ + """ to fix the problem manually""") + elif error_code == 5: + ## the elements from the first page were left stranded in the temporary page! + ## TODO : LOG ERROR + user_msg.append("""Error: there was a problem swapping the submission elements to their new pages.""") + user_msg.append("""Some elements were left stranded on a temporary page. Please ask your administrator to"""\ + """ fix this problem manually""") + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, action=action, user_msg=user_msg) + return (title, body) + +def _configure_doctype_delete_submission_page(doctype, action, pagenum): + user_msg = [] + num_pages = get_numbersubmissionpages_doctype_action(doctype=doctype, action=action) + if num_pages > 0: + ## proceed with deletion + error_code = delete_allfields_submissionpage_doctype_action(doctype=doctype, action=action, pagenum=pagenum) + if error_code == 0: + ## everything OK + ## move elements from pages above the deleted page down by one page: + decrement_by_one_pagenumber_submissionelements_abovepage(doctype=doctype, action=action, frompage=pagenum) + ## now decrement the number of pages associated with the submission: + error_code = decrement_by_one_number_submissionpages_doctype_action(doctype=doctype, action=action) + if error_code == 0: + ## successfully deleted submission page + ## TODO : LOG DELETION + user_msg.append("""Page number %s of Submission %s was successfully deleted."""\ + % (pagenum, action)) + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, + action=action, + user_msg=user_msg) + else: + ## error - either submission didn't exist, or multiple instances found + ## TODO : LOG ERROR + user_msg.append("""The Submission elements were deleted from Page %s of the Submission "%s"."""\ + """ However, it was not possible to delete the page itself."""\ + % (pagenum, action)) + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, + action=action, + user_msg=user_msg) + else: + ## unable to delete some or all fields from the page + ## TODO : LOG ERROR + user_msg.append("""Error: Unable to delete some field elements from Page %s of Submission %s%s - """\ + """Page not deleted!""" % (pagenum, action, doctype)) + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, + action=action, + user_msg=user_msg) + elif num_pages == 0: + ## no pages to delete for this submission + user_msg.append("""This Submission has no Pages - Cannot delete a Page!""") + (title, body) = _create_configure_doctype_submission_pages_form(doctype=doctype, + action=action, + user_msg=user_msg) + else: + ## error - couldn't determine the number of pages for submission + ## TODO : LOG ERROR + user_msg.append("""Unable to determine number of Submission Pages for Submission "%s" - """\ + """Cannot delete page %s"""\ + % (action, pagenum)) + (title, body) = _create_configure_doctype_form(doctype=doctype, user_msg=user_msg) + return (title, body) + +def _create_configure_doctype_submission_pages_form(doctype, + action, + deletepagenum="", + user_msg=""): + """Perform the necessary steps in order to display a list of the pages belonging to a given + submission of a given document type. + @param doctype: (string) the unique ID of the document type. + @param action: (string) the unique name/ID of the action. + @param user_msg: (string, or list) any message(s) to be displayed to the user. + @return: a tuple containing 2 strings - the page title and the page body. + """ + title = """Details of the Pages of the "%s" Submission of the "%s" Document Type:""" % (action, doctype) + submission_dets = get_cd_md_numbersubmissionpages_doctype_action(doctype=doctype, action=action) + if len(submission_dets) > 0: + cd = str(submission_dets[0][0]) + md = str(submission_dets[0][1]) + num_pages = submission_dets[0][2] + else: + (cd, md, num_pages) = ("", "", "0") + body = websubmitadmin_templates.tmpl_configuredoctype_list_submissionpages(doctype=doctype, + action=action, + number_pages=num_pages, + cd=cd, + md=md, + deletepagenum=deletepagenum, + user_msg=user_msg) + return (title, body) + +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +import re + +from .common import InfoExtractor +from ..utils import ( + qualities, + determine_ext, +) + + +class TeacherTubeIE(InfoExtractor): + IE_NAME = 'teachertube' + IE_DESC = 'teachertube.com videos' + + _VALID_URL = r'https?://(?:www\.)?teachertube\.com/(viewVideo\.php\?video_id=|music\.php\?music_id=|video/(?:[\da-z-]+-)?|audio/)(?P\d+)' + + _TESTS = [{ + 'url': 'http://www.teachertube.com/viewVideo.php?video_id=339997', + 'md5': 'f9434ef992fd65936d72999951ee254c', + 'info_dict': { + 'id': '339997', + 'ext': 'mp4', + 'title': 'Measures of dispersion from a frequency table', + 'description': 'Measures of dispersion from a frequency table', + 'thumbnail': 're:http://.*\.jpg', + }, + }, { + 'url': 'http://www.teachertube.com/viewVideo.php?video_id=340064', + 'md5': '0d625ec6bc9bf50f70170942ad580676', + 'info_dict': { + 'id': '340064', + 'ext': 'mp4', + 'title': 'How to Make Paper Dolls _ Paper Art Projects', + 'description': 'Learn how to make paper dolls in this simple', + 'thumbnail': 're:http://.*\.jpg', + }, + }, { + 'url': 'http://www.teachertube.com/music.php?music_id=8805', + 'md5': '01e8352006c65757caf7b961f6050e21', + 'info_dict': { + 'id': '8805', + 'ext': 'mp3', + 'title': 'PER ASPERA AD ASTRA', + 'description': 'RADIJSKA EMISIJA ZRAKOPLOVNE TEHNI?KE ?KOLE P', + }, + }, { + 'url': 'http://www.teachertube.com/video/intro-video-schleicher-297790', + 'md5': '9c79fbb2dd7154823996fc28d4a26998', + 'info_dict': { + 'id': '297790', + 'ext': 'mp4', + 'title': 'Intro Video - Schleicher', + 'description': 'Intro Video - Why to flip, how flipping will', + }, + }] + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + + title = self._html_search_meta('title', webpage, 'title', fatal=True) + TITLE_SUFFIX = ' - TeacherTube' + if title.endswith(TITLE_SUFFIX): + title = title[:-len(TITLE_SUFFIX)].strip() + + description = self._html_search_meta('description', webpage, 'description') + if description: + description = description.strip() + + quality = qualities(['mp3', 'flv', 'mp4']) + + media_urls = re.findall(r'data-contenturl="([^"]+)"', webpage) + media_urls.extend(re.findall(r'var\s+filePath\s*=\s*"([^"]+)"', webpage)) + media_urls.extend(re.findall(r'\'file\'\s*:\s*["\']([^"\']+)["\'],', webpage)) + + formats = [ + { + 'url': media_url, + 'quality': quality(determine_ext(media_url)) + } for media_url in set(media_urls) + ] + + self._sort_formats(formats) + + return { + 'id': video_id, + 'title': title, + 'thumbnail': self._html_search_regex(r'\'image\'\s*:\s*["\']([^"\']+)["\']', webpage, 'thumbnail'), + 'formats': formats, + 'description': description, + } + + +class TeacherTubeUserIE(InfoExtractor): + IE_NAME = 'teachertube:user:collection' + IE_DESC = 'teachertube.com user and collection videos' + + _VALID_URL = r'https?://(?:www\.)?teachertube\.com/(user/profile|collection)/(?P[0-9a-zA-Z]+)/?' + + _MEDIA_RE = r'''(?sx) + class="?sidebar_thumb_time"?>[0-9:]+ + \s* + . + +__metaclass__ = type + +ANSIBLE_METADATA = {'status': ['preview'], + 'supported_by': 'community', + 'metadata_version': '1.1'} + +DOCUMENTATION = ''' +--- +module: fortios_system_network_visibility +short_description: Configure network visibility settings in Fortinet's FortiOS and FortiGate. +description: + - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the + user to set and modify system feature and network_visibility category. + Examples include all parameters and values need to be adjusted to datasources before usage. + Tested with FOS v6.0.5 +version_added: "2.9" +author: + - Miguel Angel Munoz (@mamunozgonzalez) + - Nicolas Thomas (@thomnico) +notes: + - Requires fortiosapi library developed by Fortinet + - Run as a local_action in your playbook +requirements: + - fortiosapi>=0.9.8 +options: + host: + description: + - FortiOS or FortiGate IP address. + type: str + required: false + username: + description: + - FortiOS or FortiGate username. + type: str + required: false + password: + description: + - FortiOS or FortiGate password. + type: str + default: "" + vdom: + description: + - Virtual domain, among those defined previously. A vdom is a + virtual instance of the FortiGate that can be configured and + used as a different unit. + type: str + default: root + https: + description: + - Indicates if the requests towards FortiGate must use HTTPS protocol. + type: bool + default: true + ssl_verify: + description: + - Ensures FortiGate certificate must be verified by a proper CA. + type: bool + default: true + system_network_visibility: + description: + - Configure network visibility settings. + default: null + type: dict + suboptions: + destination_hostname_visibility: + description: + - Enable/disable logging of destination hostname visibility. + type: str + choices: + - disable + - enable + destination_location: + description: + - Enable/disable logging of destination geographical location visibility. + type: str + choices: + - disable + - enable + destination_visibility: + description: + - Enable/disable logging of destination visibility. + type: str + choices: + - disable + - enable + hostname_limit: + description: + - Limit of the number of hostname table entries (0 - 50000). + type: int + hostname_ttl: + description: + - TTL of hostname table entries (60 - 86400). + type: int + source_location: + description: + - Enable/disable logging of source geographical location visibility. + type: str + choices: + - disable + - enable +''' + +EXAMPLES = ''' +- hosts: localhost + vars: + host: "192.168.122.40" + username: "admin" + password: "" + vdom: "root" + ssl_verify: "False" + tasks: + - name: Configure network visibility settings. + fortios_system_network_visibility: + host: "{{ host }}" + username: "{{ username }}" + password: "{{ password }}" + vdom: "{{ vdom }}" + https: "False" + system_network_visibility: + destination_hostname_visibility: "disable" + destination_location: "disable" + destination_visibility: "disable" + hostname_limit: "6" + hostname_ttl: "7" + source_location: "disable" +''' + +RETURN = ''' +build: + description: Build number of the fortigate image + returned: always + type: str + sample: '1547' +http_method: + description: Last method used to provision the content into FortiGate + returned: always + type: str + sample: 'PUT' +http_status: + description: Last result given by FortiGate on last operation applied + returned: always + type: str + sample: "200" +mkey: + description: Master key (id) used in the last call to FortiGate + returned: success + type: str + sample: "id" +name: + description: Name of the table used to fulfill the request + returned: always + type: str + sample: "urlfilter" +path: + description: Path of the table used to fulfill the request + returned: always + type: str + sample: "webfilter" +revision: + description: Internal revision number + returned: always + type: str + sample: "17.0.2.10658" +serial: + description: Serial number of the unit + returned: always + type: str + sample: "FGVMEVYYQT3AB5352" +status: + description: Indication of the operation's result + returned: always + type: str + sample: "success" +vdom: + description: Virtual domain used + returned: always + type: str + sample: "root" +version: + description: Version of the FortiGate + returned: always + type: str + sample: "v5.6.3" + +''' + +from ansible.module_utils.basic import AnsibleModule +from ansible.module_utils.connection import Connection +from ansible.module_utils.network.fortios.fortios import FortiOSHandler +from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG + + +def login(data, fos): + host = data['host'] + username = data['username'] + password = data['password'] + ssl_verify = data['ssl_verify'] + + fos.debug('on') + if 'https' in data and not data['https']: + fos.https('off') + else: + fos.https('on') + + fos.login(host, username, password, verify=ssl_verify) + + +def filter_system_network_visibility_data(json): + option_list = ['destination_hostname_visibility', 'destination_location', 'destination_visibility', + 'hostname_limit', 'hostname_ttl', 'source_location'] + dictionary = {} + + for attribute in option_list: + if attribute in json and json[attribute] is not None: + dictionary[attribute] = json[attribute] + + return dictionary + + +def underscore_to_hyphen(data): + if isinstance(data, list): + for elem in data: + elem = underscore_to_hyphen(elem) + elif isinstance(data, dict): + new_data = {} + for k, v in data.items(): + new_data[k.replace('_', '-')] = underscore_to_hyphen(v) + data = new_data + + return data + + +def system_network_visibility(data, fos): + vdom = data['vdom'] + system_network_visibility_data = data['system_network_visibility'] + filtered_data = underscore_to_hyphen(filter_system_network_visibility_data(system_network_visibility_data)) + + return fos.set('system', + 'network-visibility', + data=filtered_data, + vdom=vdom) + + +def is_successful_status(status): + return status['status'] == "success" or \ + status['http_method'] == "DELETE" and status['http_status'] == 404 + + +def fortios_system(data, fos): + + if data['system_network_visibility']: + resp = system_network_visibility(data, fos) + + return not is_successful_status(resp), \ + resp['status'] == "success", \ + resp + + +def main(): + fields = { + "host": {"required": False, "type": "str"}, + "username": {"required": False, "type": "str"}, + "password": {"required": False, "type": "str", "default": "", "no_log": True}, + "vdom": {"required": False, "type": "str", "default": "root"}, + "https": {"required": False, "type": "bool", "default": True}, + "ssl_verify": {"required": False, "type": "bool", "default": True}, + "system_network_visibility": { + "required": False, "type": "dict", "default": None, + "options": { + "destination_hostname_visibility": {"required": False, "type": "str", + "choices": ["disable", "enable"]}, + "destination_location": {"required": False, "type": "str", + "choices": ["disable", "enable"]}, + "destination_visibility": {"required": False, "type": "str", + "choices": ["disable", "enable"]}, + "hostname_limit": {"required": False, "type": "int"}, + "hostname_ttl": {"required": False, "type": "int"}, + "source_location": {"required": False, "type": "str", + "choices": ["disable", "enable"]} + + } + } + } + + module = AnsibleModule(argument_spec=fields, + supports_check_mode=False) + + # legacy_mode refers to using fortiosapi instead of HTTPAPI + legacy_mode = 'host' in module.params and module.params['host'] is not None and \ + 'username' in module.params and module.params['username'] is not None and \ + 'password' in module.params and module.params['password'] is not None + + if not legacy_mode: + if module._socket_path: + connection = Connection(module._socket_path) + fos = FortiOSHandler(connection) + + is_error, has_changed, result = fortios_system(module.params, fos) + else: + module.fail_json(**FAIL_SOCKET_MSG) + else: + try: + from fortiosapi import FortiOSAPI + except ImportError: + module.fail_json(msg="fortiosapi module is required") + + fos = FortiOSAPI() + + login(module.params, fos) + is_error, has_changed, result = fortios_system(module.params, fos) + fos.logout() + + if not is_error: + module.exit_json(changed=has_changed, meta=result) + else: + module.fail_json(msg="Error in repo", meta=result) + + +if __name__ == '__main__': + main() + +# WPA2-Enterprise PMKSA caching tests +# Copyright (c) 2013-2014, Jouni Malinen +# +# This software may be distributed under the terms of the BSD license. +# See README for more details. + +import logging +logger = logging.getLogger() +import subprocess +import time + +import hostapd +from wpasupplicant import WpaSupplicant +from test_ap_eap import eap_connect + +def test_pmksa_cache_on_roam_back(dev, apdev): + """PMKSA cache to skip EAP on reassociation back to same AP""" + params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache") + hostapd.add_ap(apdev[0]['ifname'], params) + bssid = apdev[0]['bssid'] + dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk user", + password="abcdefghijklmnop0123456789abcdef", + scan_freq="2412") + pmksa = dev[0].get_pmksa(bssid) + if pmksa is None: + raise Exception("No PMKSA cache entry created") + if pmksa['opportunistic'] != '0': + raise Exception("Unexpected opportunistic PMKSA cache entry") + + hostapd.add_ap(apdev[1]['ifname'], params) + bssid2 = apdev[1]['bssid'] + + dev[0].dump_monitor() + logger.info("Roam to AP2") + # It can take some time for the second AP to become ready to reply to Probe + # Request frames especially under heavy CPU load, so allow couple of rounds + # of scanning to avoid reporting errors incorrectly just because of scans + # not having seen the target AP. + for i in range(0, 10): + dev[0].scan(freq="2412") + if dev[0].get_bss(bssid2) is not None: + break + logger.info("Scan again to find target AP") + dev[0].request("ROAM " + bssid2) + ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10) + if ev is None: + raise Exception("EAP success timed out") + ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + pmksa2 = dev[0].get_pmksa(bssid2) + if pmksa2 is None: + raise Exception("No PMKSA cache entry found") + if pmksa2['opportunistic'] != '0': + raise Exception("Unexpected opportunistic PMKSA cache entry") + + dev[0].dump_monitor() + logger.info("Roam back to AP1") + dev[0].scan(freq="2412") + dev[0].request("ROAM " + bssid) + ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + if "CTRL-EVENT-EAP-STARTED" in ev: + raise Exception("Unexpected EAP exchange") + pmksa1b = dev[0].get_pmksa(bssid) + if pmksa1b is None: + raise Exception("No PMKSA cache entry found") + if pmksa['pmkid'] != pmksa1b['pmkid']: + raise Exception("Unexpected PMKID change for AP1") + + dev[0].dump_monitor() + if "FAIL" in dev[0].request("PMKSA_FLUSH"): + raise Exception("PMKSA_FLUSH failed") + if dev[0].get_pmksa(bssid) is not None or dev[0].get_pmksa(bssid2) is not None: + raise Exception("PMKSA_FLUSH did not remove PMKSA entries") + ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=5) + if ev is None: + raise Exception("Disconnection event timed out") + ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=15) + if ev is None: + raise Exception("Reconnection timed out") + +def test_pmksa_cache_opportunistic_only_on_sta(dev, apdev): + """Opportunistic PMKSA caching enabled only on station""" + params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache") + hostapd.add_ap(apdev[0]['ifname'], params) + bssid = apdev[0]['bssid'] + dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk user", + password="abcdefghijklmnop0123456789abcdef", okc=True, + scan_freq="2412") + pmksa = dev[0].get_pmksa(bssid) + if pmksa is None: + raise Exception("No PMKSA cache entry created") + if pmksa['opportunistic'] != '0': + raise Exception("Unexpected opportunistic PMKSA cache entry") + + hostapd.add_ap(apdev[1]['ifname'], params) + bssid2 = apdev[1]['bssid'] + + dev[0].dump_monitor() + logger.info("Roam to AP2") + dev[0].scan(freq="2412") + dev[0].request("ROAM " + bssid2) + ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10) + if ev is None: + raise Exception("EAP success timed out") + ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + pmksa2 = dev[0].get_pmksa(bssid2) + if pmksa2 is None: + raise Exception("No PMKSA cache entry found") + if pmksa2['opportunistic'] != '0': + raise Exception("Unexpected opportunistic PMKSA cache entry") + + dev[0].dump_monitor() + logger.info("Roam back to AP1") + dev[0].scan(freq="2412") + dev[0].request("ROAM " + bssid) + ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + if "CTRL-EVENT-EAP-STARTED" in ev: + raise Exception("Unexpected EAP exchange") + pmksa1b = dev[0].get_pmksa(bssid) + if pmksa1b is None: + raise Exception("No PMKSA cache entry found") + if pmksa['pmkid'] != pmksa1b['pmkid']: + raise Exception("Unexpected PMKID change for AP1") + +def test_pmksa_cache_opportunistic(dev, apdev): + """Opportunistic PMKSA caching""" + params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache") + params['okc'] = "1" + hostapd.add_ap(apdev[0]['ifname'], params) + bssid = apdev[0]['bssid'] + dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk user", + password="abcdefghijklmnop0123456789abcdef", okc=True, + scan_freq="2412") + pmksa = dev[0].get_pmksa(bssid) + if pmksa is None: + raise Exception("No PMKSA cache entry created") + if pmksa['opportunistic'] != '0': + raise Exception("Unexpected opportunistic PMKSA cache entry") + + hostapd.add_ap(apdev[1]['ifname'], params) + bssid2 = apdev[1]['bssid'] + + dev[0].dump_monitor() + logger.info("Roam to AP2") + dev[0].scan(freq="2412") + dev[0].request("ROAM " + bssid2) + ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + if "CTRL-EVENT-EAP-STARTED" in ev: + raise Exception("Unexpected EAP exchange") + pmksa2 = dev[0].get_pmksa(bssid2) + if pmksa2 is None: + raise Exception("No PMKSA cache entry created") + + dev[0].dump_monitor() + logger.info("Roam back to AP1") + dev[0].scan(freq="2412") + dev[0].request("ROAM " + bssid) + ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + if "CTRL-EVENT-EAP-STARTED" in ev: + raise Exception("Unexpected EAP exchange") + + pmksa1b = dev[0].get_pmksa(bssid) + if pmksa1b is None: + raise Exception("No PMKSA cache entry found") + if pmksa['pmkid'] != pmksa1b['pmkid']: + raise Exception("Unexpected PMKID change for AP1") + +def test_pmksa_cache_opportunistic_connect(dev, apdev): + """Opportunistic PMKSA caching with connect API""" + params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache") + params['okc'] = "1" + hostapd.add_ap(apdev[0]['ifname'], params) + bssid = apdev[0]['bssid'] + wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') + wpas.interface_add("wlan5", drv_params="force_connect_cmd=1") + wpas.connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk user", + password="abcdefghijklmnop0123456789abcdef", okc=True, + scan_freq="2412") + pmksa = wpas.get_pmksa(bssid) + if pmksa is None: + raise Exception("No PMKSA cache entry created") + if pmksa['opportunistic'] != '0': + raise Exception("Unexpected opportunistic PMKSA cache entry") + + hostapd.add_ap(apdev[1]['ifname'], params) + bssid2 = apdev[1]['bssid'] + + wpas.dump_monitor() + logger.info("Roam to AP2") + wpas.scan(freq="2412") + wpas.request("ROAM " + bssid2) + ev = wpas.wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + if "CTRL-EVENT-EAP-STARTED" in ev: + raise Exception("Unexpected EAP exchange") + pmksa2 = wpas.get_pmksa(bssid2) + if pmksa2 is None: + raise Exception("No PMKSA cache entry created") + + wpas.dump_monitor() + logger.info("Roam back to AP1") + wpas.scan(freq="2412") + wpas.request("ROAM " + bssid) + ev = wpas.wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + if "CTRL-EVENT-EAP-STARTED" in ev: + raise Exception("Unexpected EAP exchange") + + pmksa1b = wpas.get_pmksa(bssid) + if pmksa1b is None: + raise Exception("No PMKSA cache entry found") + if pmksa['pmkid'] != pmksa1b['pmkid']: + raise Exception("Unexpected PMKID change for AP1") + +def test_pmksa_cache_expiration(dev, apdev): + """PMKSA cache entry expiration""" + params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache") + hostapd.add_ap(apdev[0]['ifname'], params) + bssid = apdev[0]['bssid'] + dev[0].request("SET dot11RSNAConfigPMKLifetime 10") + dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk user", + password="abcdefghijklmnop0123456789abcdef", + scan_freq="2412") + pmksa = dev[0].get_pmksa(bssid) + if pmksa is None: + raise Exception("No PMKSA cache entry created") + logger.info("Wait for PMKSA cache entry to expire") + ev = dev[0].wait_event(["WPA: Key negotiation completed", + "CTRL-EVENT-DISCONNECTED"], timeout=15) + if ev is None: + raise Exception("No EAP reauthentication seen") + if "CTRL-EVENT-DISCONNECTED" in ev: + raise Exception("Unexpected disconnection") + pmksa2 = dev[0].get_pmksa(bssid) + if pmksa['pmkid'] == pmksa2['pmkid']: + raise Exception("PMKID did not change") + +def test_pmksa_cache_expiration_disconnect(dev, apdev): + """PMKSA cache entry expiration (disconnect)""" + params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache") + hapd = hostapd.add_ap(apdev[0]['ifname'], params) + bssid = apdev[0]['bssid'] + dev[0].request("SET dot11RSNAConfigPMKLifetime 2") + dev[0].request("SET dot11RSNAConfigPMKReauthThreshold 100") + dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk user", + password="abcdefghijklmnop0123456789abcdef", + scan_freq="2412") + pmksa = dev[0].get_pmksa(bssid) + if pmksa is None: + raise Exception("No PMKSA cache entry created") + hapd.request("SET auth_server_shared_secret incorrect") + logger.info("Wait for PMKSA cache entry to expire") + ev = dev[0].wait_event(["WPA: Key negotiation completed", + "CTRL-EVENT-DISCONNECTED"], timeout=15) + if ev is None: + raise Exception("No EAP reauthentication seen") + if "CTRL-EVENT-DISCONNECTED" not in ev: + raise Exception("Missing disconnection") + hapd.request("SET auth_server_shared_secret radius") + ev = dev[0].wait_event(["WPA: Key negotiation completed"], timeout=15) + if ev is None: + raise Exception("No EAP reauthentication seen") + pmksa2 = dev[0].get_pmksa(bssid) + if pmksa['pmkid'] == pmksa2['pmkid']: + raise Exception("PMKID did not change") + +def test_pmksa_cache_and_cui(dev, apdev): + """PMKSA cache and Chargeable-User-Identity""" + params = hostapd.wpa2_eap_params(ssid="cui") + params['radius_request_cui'] = '1' + params['acct_server_addr'] = "127.0.0.1" + params['acct_server_port'] = "1813" + params['acct_server_shared_secret'] = "radius" + hostapd.add_ap(apdev[0]['ifname'], params) + bssid = apdev[0]['bssid'] + dev[0].connect("cui", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk-cui", + password="abcdefghijklmnop0123456789abcdef", + scan_freq="2412") + pmksa = dev[0].get_pmksa(bssid) + if pmksa is None: + raise Exception("No PMKSA cache entry created") + + dev[0].dump_monitor() + logger.info("Disconnect and reconnect to the same AP") + dev[0].request("DISCONNECT") + dev[0].request("RECONNECT") + ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Reconnect timed out") + if "CTRL-EVENT-EAP-STARTED" in ev: + raise Exception("Unexpected EAP exchange") + pmksa1b = dev[0].get_pmksa(bssid) + if pmksa1b is None: + raise Exception("No PMKSA cache entry found") + if pmksa['pmkid'] != pmksa1b['pmkid']: + raise Exception("Unexpected PMKID change for AP1") + + dev[0].request("REAUTHENTICATE") + ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10) + if ev is None: + raise Exception("EAP success timed out") + for i in range(0, 20): + state = dev[0].get_status_field("wpa_state") + if state == "COMPLETED": + break + time.sleep(0.1) + if state != "COMPLETED": + raise Exception("Reauthentication did not complete") + +def test_pmksa_cache_preauth(dev, apdev): + """RSN pre-authentication to generate PMKSA cache entry""" + try: + params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap") + params['bridge'] = 'ap-br0' + hostapd.add_ap(apdev[0]['ifname'], params) + subprocess.call(['sudo', 'brctl', 'setfd', 'ap-br0', '0']) + subprocess.call(['sudo', 'ip', 'link', 'set', 'dev', 'ap-br0', 'up']) + eap_connect(dev[0], apdev[0], "PAX", "pax.user@example.com", + password_hex="0123456789abcdef0123456789abcdef") + + params = hostapd.wpa2_eap_params(ssid="test-wpa2-eap") + params['bridge'] = 'ap-br0' + params['rsn_preauth'] = '1' + params['rsn_preauth_interfaces'] = 'ap-br0' + hostapd.add_ap(apdev[1]['ifname'], params) + bssid1 = apdev[1]['bssid'] + dev[0].scan(freq="2412") + success = False + status_seen = False + for i in range(0, 50): + if not status_seen: + status = dev[0].request("STATUS") + if "Pre-authentication EAPOL state machines:" in status: + status_seen = True + time.sleep(0.1) + pmksa = dev[0].get_pmksa(bssid1) + if pmksa: + success = True + break + if not success: + raise Exception("No PMKSA cache entry created from pre-authentication") + if not status_seen: + raise Exception("Pre-authentication EAPOL status was not available") + + dev[0].scan(freq="2412") + if "[WPA2-EAP-CCMP-preauth]" not in dev[0].request("SCAN_RESULTS"): + raise Exception("Scan results missing RSN element info") + dev[0].request("ROAM " + bssid1) + ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + if "CTRL-EVENT-EAP-STARTED" in ev: + raise Exception("Unexpected EAP exchange") + pmksa2 = dev[0].get_pmksa(bssid1) + if pmksa2 is None: + raise Exception("No PMKSA cache entry") + if pmksa['pmkid'] != pmksa2['pmkid']: + raise Exception("Unexpected PMKID change") + + finally: + subprocess.call(['sudo', 'ip', 'link', 'set', 'dev', 'ap-br0', 'down']) + subprocess.call(['sudo', 'brctl', 'delbr', 'ap-br0']) + +def test_pmksa_cache_disabled(dev, apdev): + """PMKSA cache disabling on AP""" + params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache") + params['disable_pmksa_caching'] = '1' + hostapd.add_ap(apdev[0]['ifname'], params) + bssid = apdev[0]['bssid'] + dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk user", + password="abcdefghijklmnop0123456789abcdef", + scan_freq="2412") + + hostapd.add_ap(apdev[1]['ifname'], params) + bssid2 = apdev[1]['bssid'] + + dev[0].dump_monitor() + logger.info("Roam to AP2") + dev[0].scan_for_bss(bssid2, freq="2412") + dev[0].request("ROAM " + bssid2) + ev = dev[0].wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10) + if ev is None: + raise Exception("EAP success timed out") + ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + + dev[0].dump_monitor() + logger.info("Roam back to AP1") + dev[0].scan(freq="2412") + dev[0].request("ROAM " + bssid) + ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=20) + if ev is None: + raise Exception("Roaming with the AP timed out") + if "CTRL-EVENT-CONNECTED" in ev: + raise Exception("EAP exchange missing") + ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=20) + if ev is None: + raise Exception("Roaming with the AP timed out") + +def test_pmksa_cache_ap_expiration(dev, apdev): + """PMKSA cache entry expiring on AP""" + params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache") + hostapd.add_ap(apdev[0]['ifname'], params) + bssid = apdev[0]['bssid'] + dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk-user-session-timeout", + password="abcdefghijklmnop0123456789abcdef", + scan_freq="2412") + dev[0].request("DISCONNECT") + time.sleep(5) + dev[0].dump_monitor() + dev[0].request("RECONNECT") + ev = dev[0].wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=20) + if ev is None: + raise Exception("Roaming with the AP timed out") + if "CTRL-EVENT-CONNECTED" in ev: + raise Exception("EAP exchange missing") + ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=20) + if ev is None: + raise Exception("Reassociation with the AP timed out") + dev[0].dump_monitor() + ev = dev[0].wait_event(["CTRL-EVENT-DISCONNECTED"], timeout=20) + if ev is None: + raise Exception("Disconnection event timed out") + ev = dev[0].wait_event(["CTRL-EVENT-CONNECTED"], timeout=20) + if ev is None: + raise Exception("Reassociation with the AP timed out") + +def test_pmksa_cache_multiple_sta(dev, apdev): + """PMKSA cache with multiple stations""" + params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache") + hostapd.add_ap(apdev[0]['ifname'], params) + bssid = apdev[0]['bssid'] + dev[0].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk-user-session-timeout", + password="abcdefghijklmnop0123456789abcdef", + scan_freq="2412") + dev[1].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk user", + password="abcdefghijklmnop0123456789abcdef", + scan_freq="2412") + dev[2].connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk-user-session-timeout", + password="abcdefghijklmnop0123456789abcdef", + scan_freq="2412") + + wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') + wpas.interface_add("wlan5") + wpas.connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk user", + password="abcdefghijklmnop0123456789abcdef", + scan_freq="2412") + + hostapd.add_ap(apdev[1]['ifname'], params) + bssid2 = apdev[1]['bssid'] + + logger.info("Roam to AP2") + for sta in [ dev[1], dev[0], dev[2], wpas ]: + sta.dump_monitor() + sta.scan_for_bss(bssid2, freq="2412") + sta.request("ROAM " + bssid2) + ev = sta.wait_event(["CTRL-EVENT-EAP-SUCCESS"], timeout=10) + if ev is None: + raise Exception("EAP success timed out") + ev = sta.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + + logger.info("Roam back to AP1") + for sta in [ dev[1], wpas, dev[0], dev[2] ]: + sta.dump_monitor() + sta.scan(freq="2412") + sta.dump_monitor() + sta.request("ROAM " + bssid) + ev = sta.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + sta.dump_monitor() + + time.sleep(4) + + logger.info("Roam back to AP2") + for sta in [ dev[1], wpas, dev[0], dev[2] ]: + sta.dump_monitor() + sta.scan(freq="2412") + sta.dump_monitor() + sta.request("ROAM " + bssid2) + ev = sta.wait_event(["CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + sta.dump_monitor() + +def test_pmksa_cache_opportunistic_multiple_sta(dev, apdev): + """Opportunistic PMKSA caching with multiple stations""" + params = hostapd.wpa2_eap_params(ssid="test-pmksa-cache") + params['okc'] = "1" + hostapd.add_ap(apdev[0]['ifname'], params) + bssid = apdev[0]['bssid'] + wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5') + wpas.interface_add("wlan5") + for sta in [ dev[0], dev[1], dev[2], wpas ]: + sta.connect("test-pmksa-cache", proto="RSN", key_mgmt="WPA-EAP", + eap="GPSK", identity="gpsk user", + password="abcdefghijklmnop0123456789abcdef", okc=True, + scan_freq="2412") + + hostapd.add_ap(apdev[1]['ifname'], params) + bssid2 = apdev[1]['bssid'] + + logger.info("Roam to AP2") + for sta in [ dev[2], dev[0], wpas, dev[1] ]: + sta.dump_monitor() + sta.scan_for_bss(bssid2, freq="2412") + sta.request("ROAM " + bssid2) + ev = sta.wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + if "CTRL-EVENT-EAP-STARTED" in ev: + raise Exception("Unexpected EAP exchange") + pmksa2 = sta.get_pmksa(bssid2) + if pmksa2 is None: + raise Exception("No PMKSA cache entry created") + + logger.info("Roam back to AP1") + for sta in [ dev[0], dev[1], dev[2], wpas ]: + sta.dump_monitor() + sta.scan_for_bss(bssid, freq="2412") + sta.request("ROAM " + bssid) + ev = sta.wait_event(["CTRL-EVENT-EAP-STARTED", + "CTRL-EVENT-CONNECTED"], timeout=10) + if ev is None: + raise Exception("Roaming with the AP timed out") + if "CTRL-EVENT-EAP-STARTED" in ev: + raise Exception("Unexpected EAP exchange") + +# coding: utf-8 + +from __future__ import unicode_literals + +from .common import InfoExtractor +from ..utils import js_to_json + + +class HelsinkiIE(InfoExtractor): + IE_DESC = 'helsinki.fi' + _VALID_URL = r'https?://video\.helsinki\.fi/Arkisto/flash\.php\?id=(?P\d+)' + _TEST = { + 'url': 'http://video.helsinki.fi/Arkisto/flash.php?id=20258', + 'info_dict': { + 'id': '20258', + 'ext': 'mp4', + 'title': 'Tietotekniikkafoorumi-iltapäivä', + 'description': 'md5:f5c904224d43c133225130fe156a5ee0', + }, + 'params': { + 'skip_download': True, # RTMP + } + } + + def _real_extract(self, url): + video_id = self._match_id(url) + webpage = self._download_webpage(url, video_id) + + params = self._parse_json(self._html_search_regex( + r'(?s)jwplayer\("player"\).setup\((\{.*?\})\);', + webpage, 'player code'), video_id, transform_source=js_to_json) + formats = [{ + 'url': s['file'], + 'ext': 'mp4', + } for s in params['sources']] + self._sort_formats(formats) + + return { + 'id': video_id, + 'title': self._og_search_title(webpage).replace('Video: ', ''), + 'description': self._og_search_description(webpage), + 'formats': formats, + } + +# -*- coding: utf-8 -*- +r''' + werkzeug.script + ~~~~~~~~~~~~~~~ + + .. admonition:: Deprecated Functionality + + ``werkzeug.script`` is deprecated without replacement functionality. + Python's command line support improved greatly with :mod:`argparse` + and a bunch of alternative modules. + + Most of the time you have recurring tasks while writing an application + such as starting up an interactive python interpreter with some prefilled + imports, starting the development server, initializing the database or + something similar. + + For that purpose werkzeug provides the `werkzeug.script` module which + helps you writing such scripts. + + + Basic Usage + ----------- + + The following snippet is roughly the same in every werkzeug script:: + + #!/usr/bin/env python + # -*- coding: utf-8 -*- + from werkzeug import script + + # actions go here + + if __name__ == '__main__': + script.run() + + Starting this script now does nothing because no actions are defined. + An action is a function in the same module starting with ``"action_"`` + which takes a number of arguments where every argument has a default. The + type of the default value specifies the type of the argument. + + Arguments can then be passed by position or using ``--name=value`` from + the shell. + + Because a runserver and shell command is pretty common there are two + factory functions that create such commands:: + + def make_app(): + from yourapplication import YourApplication + return YourApplication(...) + + action_runserver = script.make_runserver(make_app, use_reloader=True) + action_shell = script.make_shell(lambda: {'app': make_app()}) + + + Using The Scripts + ----------------- + + The script from above can be used like this from the shell now: + + .. sourcecode:: text + + $ ./manage.py --help + $ ./manage.py runserver localhost 8080 --debugger --no-reloader + $ ./manage.py runserver -p 4000 + $ ./manage.py shell + + As you can see it's possible to pass parameters as positional arguments + or as named parameters, pretty much like Python function calls. + + + :copyright: (c) 2013 by the Werkzeug Team, see AUTHORS for more details. + :license: BSD, see LICENSE for more details. +''' +from __future__ import print_function + +import sys +import inspect +import getopt +from os.path import basename +from werkzeug._compat import iteritems + + +argument_types = { + bool: 'boolean', + str: 'string', + int: 'integer', + float: 'float' +} + + +converters = { + 'boolean': lambda x: x.lower() in ('1', 'true', 'yes', 'on'), + 'string': str, + 'integer': int, + 'float': float +} + + +def run(namespace=None, action_prefix='action_', args=None): + """Run the script. Participating actions are looked up in the caller's + namespace if no namespace is given, otherwise in the dict provided. + Only items that start with action_prefix are processed as actions. If + you want to use all items in the namespace provided as actions set + action_prefix to an empty string. + + :param namespace: An optional dict where the functions are looked up in. + By default the local namespace of the caller is used. + :param action_prefix: The prefix for the functions. Everything else + is ignored. + :param args: the arguments for the function. If not specified + :data:`sys.argv` without the first argument is used. + """ + if namespace is None: + namespace = sys._getframe(1).f_locals + actions = find_actions(namespace, action_prefix) + + if args is None: + args = sys.argv[1:] + if not args or args[0] in ('-h', '--help'): + return print_usage(actions) + elif args[0] not in actions: + fail('Unknown action \'%s\'' % args[0]) + + arguments = {} + types = {} + key_to_arg = {} + long_options = [] + formatstring = '' + func, doc, arg_def = actions[args.pop(0)] + for idx, (arg, shortcut, default, option_type) in enumerate(arg_def): + real_arg = arg.replace('-', '_') + if shortcut: + formatstring += shortcut + if not isinstance(default, bool): + formatstring += ':' + key_to_arg['-' + shortcut] = real_arg + long_options.append(isinstance(default, bool) and arg or arg + '=') + key_to_arg['--' + arg] = real_arg + key_to_arg[idx] = real_arg + types[real_arg] = option_type + arguments[real_arg] = default + + try: + optlist, posargs = getopt.gnu_getopt(args, formatstring, long_options) + except getopt.GetoptError as e: + fail(str(e)) + + specified_arguments = set() + for key, value in enumerate(posargs): + try: + arg = key_to_arg[key] + except IndexError: + fail('Too many parameters') + specified_arguments.add(arg) + try: + arguments[arg] = converters[types[arg]](value) + except ValueError: + fail('Invalid value for argument %s (%s): %s' % (key, arg, value)) + + for key, value in optlist: + arg = key_to_arg[key] + if arg in specified_arguments: + fail('Argument \'%s\' is specified twice' % arg) + if types[arg] == 'boolean': + if arg.startswith('no_'): + value = 'no' + else: + value = 'yes' + try: + arguments[arg] = converters[types[arg]](value) + except ValueError: + fail('Invalid value for \'%s\': %s' % (key, value)) + + newargs = {} + for k, v in iteritems(arguments): + newargs[k.startswith('no_') and k[3:] or k] = v + arguments = newargs + return func(**arguments) + + +def fail(message, code=-1): + """Fail with an error.""" + print('Error: %s' % message, file=sys.stderr) + sys.exit(code) + + +def find_actions(namespace, action_prefix): + """Find all the actions in the namespace.""" + actions = {} + for key, value in iteritems(namespace): + if key.startswith(action_prefix): + actions[key[len(action_prefix):]] = analyse_action(value) + return actions + + +def print_usage(actions): + """Print the usage information. (Help screen)""" + actions = actions.items() + actions.sort() + print('usage: %s []' % basename(sys.argv[0])) + print(' %s --help' % basename(sys.argv[0])) + print() + print('actions:') + for name, (func, doc, arguments) in actions: + print(' %s:' % name) + for line in doc.splitlines(): + print(' %s' % line) + if arguments: + print() + for arg, shortcut, default, argtype in arguments: + if isinstance(default, bool): + print(' %s' % ( + (shortcut and '-%s, ' % shortcut or '') + '--' + arg + )) + else: + print(' %-30s%-10s%s' % ( + (shortcut and '-%s, ' % shortcut or '') + '--' + arg, + argtype, default + )) + print() + + +def analyse_action(func): + """Analyse a function.""" + description = inspect.getdoc(func) or 'undocumented action' + arguments = [] + args, varargs, kwargs, defaults = inspect.getargspec(func) + if varargs or kwargs: + raise TypeError('variable length arguments for action not allowed.') + if len(args) != len(defaults or ()): + raise TypeError('not all arguments have proper definitions') + + for idx, (arg, definition) in enumerate(zip(args, defaults or ())): + if arg.startswith('_'): + raise TypeError('arguments may not start with an underscore') + if not isinstance(definition, tuple): + shortcut = None + default = definition + else: + shortcut, default = definition + argument_type = argument_types[type(default)] + if isinstance(default, bool) and default is True: + arg = 'no-' + arg + arguments.append((arg.replace('_', '-'), shortcut, + default, argument_type)) + return func, description, arguments + + +def make_shell(init_func=None, banner=None, use_ipython=True): + """Returns an action callback that spawns a new interactive + python shell. + + :param init_func: an optional initialization function that is + called before the shell is started. The return + value of this function is the initial namespace. + :param banner: the banner that is displayed before the shell. If + not specified a generic banner is used instead. + :param use_ipython: if set to `True` ipython is used if available. + """ + if banner is None: + banner = 'Interactive Werkzeug Shell' + if init_func is None: + init_func = dict + def action(ipython=use_ipython): + """Start a new interactive python session.""" + namespace = init_func() + if ipython: + try: + try: + from IPython.frontend.terminal.embed import InteractiveShellEmbed + sh = InteractiveShellEmbed(banner1=banner) + except ImportError: + from IPython.Shell import IPShellEmbed + sh = IPShellEmbed(banner=banner) + except ImportError: + pass + else: + sh(global_ns={}, local_ns=namespace) + return + from code import interact + interact(banner, local=namespace) + return action + + +def make_runserver(app_factory, hostname='localhost', port=5000, + use_reloader=False, use_debugger=False, use_evalex=True, + threaded=False, processes=1, static_files=None, + extra_files=None, ssl_context=None): + """Returns an action callback that spawns a new development server. + + .. versionadded:: 0.5 + `static_files` and `extra_files` was added. + + ..versionadded:: 0.6.1 + `ssl_context` was added. + + :param app_factory: a function that returns a new WSGI application. + :param hostname: the default hostname the server should listen on. + :param port: the default port of the server. + :param use_reloader: the default setting for the reloader. + :param use_evalex: the default setting for the evalex flag of the debugger. + :param threaded: the default threading setting. + :param processes: the default number of processes to start. + :param static_files: optional dict of static files. + :param extra_files: optional list of extra files to track for reloading. + :param ssl_context: optional SSL context for running server in HTTPS mode. + """ + def action(hostname=('h', hostname), port=('p', port), + reloader=use_reloader, debugger=use_debugger, + evalex=use_evalex, threaded=threaded, processes=processes): + """Start a new development server.""" + from werkzeug.serving import run_simple + app = app_factory() + run_simple(hostname, port, app, reloader, debugger, evalex, + extra_files, 1, threaded, processes, + static_files=static_files, ssl_context=ssl_context) + return action + +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2009 Tiny SPRL (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +import socket +import cPickle +import cStringIO + +import openerp.netsvc as netsvc + +# Pickle protocol version 2 is optimized compared to default (version 0) +PICKLE_PROTOCOL = 2 + +class Myexception(Exception): + """ + custom exception object store + * faultcode + * faulestring + * args + """ + + def __init__(self, faultCode, faultString): + self.faultCode = faultCode + self.faultString = faultString + self.args = (faultCode, faultString) + +class mysocket: + + def __init__(self, sock=None): + if sock is None: + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + else: + self.sock = sock + # self.sock.settimeout(120) + # prepare this socket for long operations: it may block for infinite + # time, but should exit as soon as the net is down + self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + + def connect(self, host, port=False): + if not port: + protocol, buf = host.split('//') + host, port = buf.split(':') + self.sock.connect((host, int(port))) + + def disconnect(self): + netsvc.close_socket(self.sock) + + def mysend(self, msg, exception=False, traceback=None): + msg = cPickle.dumps([msg, traceback], PICKLE_PROTOCOL) + self.sock.sendall('%8d%d%s' % (len(msg), bool(exception), msg)) + + def myreceive(self): + buf='' + while len(buf) < 9: + chunk = self.sock.recv(9 - len(buf)) + if not chunk: + raise socket.timeout + buf += chunk + size = int(buf[:8]) + if buf[8] != "0": + exception = buf[8] + else: + exception = False + msg = '' + while len(msg) < size: + chunk = self.sock.recv(size-len(msg)) + if not chunk: + raise socket.timeout + msg = msg + chunk + msgio = cStringIO.StringIO(msg) + unpickler = cPickle.Unpickler(msgio) + unpickler.find_global = None + res = unpickler.load() + + if isinstance(res[0],Exception): + if exception: + raise Myexception(str(res[0]), str(res[1])) + raise res[0] + else: + return res[0] + +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: + +from __future__ import division, absolute_import, print_function + +import sys, re, inspect, textwrap, pydoc +import sphinx +import collections +from .docscrape import NumpyDocString, FunctionDoc, ClassDoc + +if sys.version_info[0] >= 3: + sixu = lambda s: s +else: + sixu = lambda s: unicode(s, 'unicode_escape') + + +class SphinxDocString(NumpyDocString): + def __init__(self, docstring, config={}): + NumpyDocString.__init__(self, docstring, config=config) + self.load_config(config) + + def load_config(self, config): + self.use_plots = config.get('use_plots', False) + self.class_members_toctree = config.get('class_members_toctree', True) + + # string conversion routines + def _str_header(self, name, symbol='`'): + return ['.. rubric:: ' + name, ''] + + def _str_field_list(self, name): + return [':' + name + ':'] + + def _str_indent(self, doc, indent=4): + out = [] + for line in doc: + out += [' '*indent + line] + return out + + def _str_signature(self): + return [''] + if self['Signature']: + return ['``%s``' % self['Signature']] + [''] + else: + return [''] + + def _str_summary(self): + return self['Summary'] + [''] + + def _str_extended_summary(self): + return self['Extended Summary'] + [''] + + def _str_returns(self): + out = [] + if self['Returns']: + out += self._str_field_list('Returns') + out += [''] + for param, param_type, desc in self['Returns']: + if param_type: + out += self._str_indent(['**%s** : %s' % (param.strip(), + param_type)]) + else: + out += self._str_indent([param.strip()]) + if desc: + out += [''] + out += self._str_indent(desc, 8) + out += [''] + return out + + def _str_param_list(self, name): + out = [] + if self[name]: + out += self._str_field_list(name) + out += [''] + for param, param_type, desc in self[name]: + if param_type: + out += self._str_indent(['**%s** : %s' % (param.strip(), + param_type)]) + else: + out += self._str_indent(['**%s**' % param.strip()]) + if desc: + out += [''] + out += self._str_indent(desc, 8) + out += [''] + return out + + @property + def _obj(self): + if hasattr(self, '_cls'): + return self._cls + elif hasattr(self, '_f'): + return self._f + return None + + def _str_member_list(self, name): + """ + Generate a member listing, autosummary:: table where possible, + and a table where not. + + """ + out = [] + if self[name]: + out += ['.. rubric:: %s' % name, ''] + prefix = getattr(self, '_name', '') + + if prefix: + prefix = '~%s.' % prefix + + autosum = [] + others = [] + for param, param_type, desc in self[name]: + param = param.strip() + + # Check if the referenced member can have a docstring or not + param_obj = getattr(self._obj, param, None) + if not (callable(param_obj) + or isinstance(param_obj, property) + or inspect.isgetsetdescriptor(param_obj)): + param_obj = None + + if param_obj and (pydoc.getdoc(param_obj) or not desc): + # Referenced object has a docstring + autosum += [" %s%s" % (prefix, param)] + else: + others.append((param, param_type, desc)) + + if autosum: + out += ['.. autosummary::'] + if self.class_members_toctree: + out += [' :toctree:'] + out += [''] + autosum + + if others: + maxlen_0 = max(3, max([len(x[0]) for x in others])) + hdr = sixu("=")*maxlen_0 + sixu(" ") + sixu("=")*10 + fmt = sixu('%%%ds %%s ') % (maxlen_0,) + out += ['', hdr] + for param, param_type, desc in others: + desc = sixu(" ").join(x.strip() for x in desc).strip() + if param_type: + desc = "(%s) %s" % (param_type, desc) + out += [fmt % (param.strip(), desc)] + out += [hdr] + out += [''] + return out + + def _str_section(self, name): + out = [] + if self[name]: + out += self._str_header(name) + out += [''] + content = textwrap.dedent("\n".join(self[name])).split("\n") + out += content + out += [''] + return out + + def _str_see_also(self, func_role): + out = [] + if self['See Also']: + see_also = super(SphinxDocString, self)._str_see_also(func_role) + out = ['.. seealso::', ''] + out += self._str_indent(see_also[2:]) + return out + + def _str_warnings(self): + out = [] + if self['Warnings']: + out = ['.. warning::', ''] + out += self._str_indent(self['Warnings']) + return out + + def _str_index(self): + idx = self['index'] + out = [] + if len(idx) == 0: + return out + + out += ['.. index:: %s' % idx.get('default','')] + for section, references in idx.items(): + if section == 'default': + continue + elif section == 'refguide': + out += [' single: %s' % (', '.join(references))] + else: + out += [' %s: %s' % (section, ','.join(references))] + return out + + def _str_references(self): + out = [] + if self['References']: + out += self._str_header('References') + if isinstance(self['References'], str): + self['References'] = [self['References']] + out.extend(self['References']) + out += [''] + # Latex collects all references to a separate bibliography, + # so we need to insert links to it + if sphinx.__version__ >= "0.6": + out += ['.. only:: latex',''] + else: + out += ['.. latexonly::',''] + items = [] + for line in self['References']: + m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I) + if m: + items.append(m.group(1)) + out += [' ' + ", ".join(["[%s]_" % item for item in items]), ''] + return out + + def _str_examples(self): + examples_str = "\n".join(self['Examples']) + + if (self.use_plots and 'import matplotlib' in examples_str + and 'plot::' not in examples_str): + out = [] + out += self._str_header('Examples') + out += ['.. plot::', ''] + out += self._str_indent(self['Examples']) + out += [''] + return out + else: + return self._str_section('Examples') + + def __str__(self, indent=0, func_role="obj"): + out = [] + out += self._str_signature() + out += self._str_index() + [''] + out += self._str_summary() + out += self._str_extended_summary() + out += self._str_param_list('Parameters') + out += self._str_returns() + for param_list in ('Other Parameters', 'Raises', 'Warns'): + out += self._str_param_list(param_list) + out += self._str_warnings() + out += self._str_see_also(func_role) + out += self._str_section('Notes') + out += self._str_references() + out += self._str_examples() + for param_list in ('Attributes', 'Methods'): + out += self._str_member_list(param_list) + out = self._str_indent(out,indent) + return '\n'.join(out) + +class SphinxFunctionDoc(SphinxDocString, FunctionDoc): + def __init__(self, obj, doc=None, config={}): + self.load_config(config) + FunctionDoc.__init__(self, obj, doc=doc, config=config) + +class SphinxClassDoc(SphinxDocString, ClassDoc): + def __init__(self, obj, doc=None, func_doc=None, config={}): + self.load_config(config) + ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config) + +class SphinxObjDoc(SphinxDocString): + def __init__(self, obj, doc=None, config={}): + self._f = obj + self.load_config(config) + SphinxDocString.__init__(self, doc, config=config) + +def get_doc_object(obj, what=None, doc=None, config={}): + if what is None: + if inspect.isclass(obj): + what = 'class' + elif inspect.ismodule(obj): + what = 'module' + elif isinstance(obj, collections.Callable): + what = 'function' + else: + what = 'object' + if what == 'class': + return SphinxClassDoc(obj, func_doc=SphinxFunctionDoc, doc=doc, + config=config) + elif what in ('function', 'method'): + return SphinxFunctionDoc(obj, doc=doc, config=config) + else: + if doc is None: + doc = pydoc.getdoc(obj) + return SphinxObjDoc(obj, doc, config=config) + +# Copyright (c) 2017-2019 Uber Technologies, Inc. +# SPDX-License-Identifier: Apache-2.0 + +import warnings + +from pyro import params +from pyro.distributions.distribution import Distribution +from pyro.poutine.util import is_validation_enabled + +from .messenger import Messenger + + +class LiftMessenger(Messenger): + """ + Given a stochastic function with param calls and a prior distribution, + create a stochastic function where all param calls are replaced by sampling from prior. + Prior should be a callable or a dict of names to callables. + + Consider the following Pyro program: + + >>> def model(x): + ... s = pyro.param("s", torch.tensor(0.5)) + ... z = pyro.sample("z", dist.Normal(x, s)) + ... return z ** 2 + >>> lifted_model = pyro.poutine.lift(model, prior={"s": dist.Exponential(0.3)}) + + ``lift`` makes ``param`` statements behave like ``sample`` statements + using the distributions in ``prior``. In this example, site `s` will now behave + as if it was replaced with ``s = pyro.sample("s", dist.Exponential(0.3))``: + + >>> tr = pyro.poutine.trace(lifted_model).get_trace(0.0) + >>> tr.nodes["s"]["type"] == "sample" + True + >>> tr2 = pyro.poutine.trace(lifted_model).get_trace(0.0) + >>> bool((tr2.nodes["s"]["value"] == tr.nodes["s"]["value"]).all()) + False + + :param fn: function whose parameters will be lifted to random values + :param prior: prior function in the form of a Distribution or a dict of stochastic fns + :returns: ``fn`` decorated with a :class:`~pyro.poutine.lift_messenger.LiftMessenger` + """ + + def __init__(self, prior): + """ + :param prior: prior used to lift parameters. Prior can be of type + dict, pyro.distributions, or a python stochastic fn + + Constructor + """ + super().__init__() + self.prior = prior + self._samples_cache = {} + + def __enter__(self): + self._samples_cache = {} + if is_validation_enabled() and isinstance(self.prior, dict): + self._param_hits = set() + self._param_misses = set() + return super().__enter__() + + def __exit__(self, *args, **kwargs): + self._samples_cache = {} + if is_validation_enabled() and isinstance(self.prior, dict): + extra = set(self.prior) - self._param_hits + if extra: + warnings.warn( + "pyro.module prior did not find params ['{}']. " + "Did you instead mean one of ['{}']?" + .format("', '".join(extra), "', '".join(self._param_misses))) + return super().__exit__(*args, **kwargs) + + def _pyro_sample(self, msg): + return None + + def _pyro_param(self, msg): + """ + Overrides the `pyro.param` call with samples sampled from the + distribution specified in the prior. The prior can be a + pyro.distributions object or a dict of distributions keyed + on the param names. If the param name does not match the + name the keys in the prior, that param name is unchanged. + """ + name = msg["name"] + param_name = params.user_param_name(name) + if isinstance(self.prior, dict): + # prior is a dict of distributions + if param_name in self.prior.keys(): + msg["fn"] = self.prior[param_name] + msg["args"] = msg["args"][1:] + if isinstance(msg['fn'], Distribution): + msg["args"] = () + msg["kwargs"] = {} + msg["infer"] = {} + if is_validation_enabled(): + self._param_hits.add(param_name) + else: + if is_validation_enabled(): + self._param_misses.add(param_name) + return None + elif isinstance(self.prior, Distribution): + # prior is a distribution + msg["fn"] = self.prior + msg["args"] = () + msg["kwargs"] = {} + msg["infer"] = {} + elif callable(self.prior): + if not isinstance(self.prior, Distribution): + # prior is a stochastic fn. block sample + msg["stop"] = True + msg["fn"] = self.prior + msg["args"] = msg["args"][1:] + else: + # otherwise leave as is + return None + msg["type"] = "sample" + if name in self._samples_cache: + # Multiple pyro.param statements with the same + # name. Block the site and fix the value. + msg['value'] = self._samples_cache[name]['value'] + msg["is_observed"] = True + msg["stop"] = True + else: + self._samples_cache[name] = msg + msg["is_observed"] = False + return self._pyro_sample(msg) + +#!/usr/bin/env python +# Copyright (c) 2011 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +import os +import logging + +import pyauto_functional # Must be imported before pyauto +import pyauto +import test_utils + +class PopupsTest(pyauto.PyUITest): + """TestCase for Popup blocking.""" + + def Debug(self): + """Test method for experimentation. + + This method will not run automatically. + """ + while True: + raw_input('Interact with the browser and hit ') + self.pprint(self.GetBlockedPopupsInfo()) + + def testPopupBlockerEnabled(self): + """Verify popup blocking is enabled.""" + self.assertFalse(self.GetBlockedPopupsInfo(), + msg='Should have no blocked popups on startup') + file_url = self.GetFileURLForPath(os.path.join( + self.DataDir(), 'popup_blocker', 'popup-window-open.html')) + self.NavigateToURL(file_url) + blocked_popups = self.GetBlockedPopupsInfo() + self.assertEqual(1, len(blocked_popups), msg='Popup not blocked') + # It might take a while for the title to get set. Don't need to check it. + # self.assertEqual('Popup Success!', blocked_popups[0]['title']) + + def testLaunchBlockedPopup(self): + """Verify that a blocked popup can be unblocked.""" + file_url = self.GetFileURLForPath(os.path.join( + self.DataDir(), 'popup_blocker', 'popup-window-open.html')) + self.NavigateToURL(file_url) + self.assertEqual(1, len(self.GetBlockedPopupsInfo())) + self.UnblockAndLaunchBlockedPopup(0) + # Verify that no more popups are blocked + self.assertFalse(self.GetBlockedPopupsInfo()) + # Verify that popup window was created + self.assertEqual(2, self.GetBrowserWindowCount(), + msg='Popup could not be launched'); + # Wait until popup title is read correctly. + self.assertTrue(self.WaitUntil(lambda: + self.GetActiveTabTitle(1), expect_retval='Popup Success!'), + msg='Popup title is wrong.') + + def testPopupBlockerInIncognito(self): + """Verify popup blocking is enabled in incognito windows.""" + self.RunCommand(pyauto.IDC_NEW_INCOGNITO_WINDOW) + file_url = self.GetFileURLForPath(os.path.join( + self.DataDir(), 'popup_blocker', 'popup-window-open.html')) + self.NavigateToURL(file_url, 1, 0) + blocked_popups = self.GetBlockedPopupsInfo(tab_index=0, windex=1) + self.assertEqual(1, len(blocked_popups), msg='Popup not blocked') + + def testLaunchBlockedPopupInIncognito(self): + """Verify that a blocked popup can be unblocked in incognito.""" + self.RunCommand(pyauto.IDC_NEW_INCOGNITO_WINDOW) + self.assertTrue(2, self.GetBrowserWindowCount()) + file_url = self.GetFileURLForPath(os.path.join( + self.DataDir(), 'popup_blocker', 'popup-window-open.html')) + self.NavigateToURL(file_url, 1, 0) + self.assertEquals('Popup created using window.open', + self.GetActiveTabTitle(window_index=1)) + # Wait until the popup is blocked + self.assertTrue(self.WaitUntil(lambda: + len(self.GetBlockedPopupsInfo(tab_index=0, windex=1)) is 1), + msg='Popup not blocked') + self.UnblockAndLaunchBlockedPopup(0, tab_index=0, windex=1) + # Verify that no more popups are blocked + self.assertFalse(self.GetBlockedPopupsInfo(tab_index=0, windex=1)) + # Verify that popup window was created + self.assertEqual(3, self.GetBrowserWindowCount(), + msg='Popup could not be launched'); + # Wait until popup title is read correctly. + self.assertTrue(self.WaitUntil(lambda: + self.GetActiveTabTitle(2), expect_retval='Popup Success!'), + msg='Popup title is wrong.') + + def testMultiplePopups(self): + """Verify multiple popups are blocked.""" + url = self.GetHttpURLForDataPath( + os.path.join('pyauto_private', 'popup_blocker', + 'PopupTest1.html')) + self.NavigateToURL(url) + self.assertEqual(6, len(self.GetBlockedPopupsInfo()), + msg='Did not block 6 popups.') + + def testPopupBlockedEverySec(self): + """Verify that a popup is blocked every second.""" + url = self.GetHttpURLForDataPath( + os.path.join('pyauto_private', 'popup_blocker', + 'PopupTest4.html')) + self.NavigateToURL(url) + self.assertTrue(self.WaitUntil(lambda: len(self.GetBlockedPopupsInfo()), + expect_retval=2)) + + def _SetPopupsException(self): + """Set an exception to allow popups from www.popuptest.com.""" + value = {'[*.]www.popuptest.com': {'popups': 1}} + return self.SetPrefs(pyauto.kContentSettingsPatterns, value) + + def testAllowPopupsFromExternalSite(self): + """Verify that popups are allowed from an external website.""" + self._SetPopupsException() + self.NavigateToURL('http://www.popuptest.com/popuptest1.html') + self.assertEqual(7, self.GetBrowserWindowCount(), + msg='Popups did not launch from the external site.') + + def testPopupsLaunchUponBrowserBackButton(self): + """Verify that popups are launched on browser back button.""" + self._SetPopupsException() + url = self.GetHttpURLForDataPath( + os.path.join('popup_blocker', 'popup-blocked-to-post-blank.html')) + self.NavigateToURL(url) + self.NavigateToURL('http://www.popuptest.com/popuptest1.html') + self.assertEqual(7, self.GetBrowserWindowCount(), + msg='Popups did not launch from the external site.') + self.GetBrowserWindow(0).GetTab(0).GoBack() + # Check if two additional popups launch when navigating away from the page. + self.assertEqual(9, self.GetBrowserWindowCount(), + msg='Additional popups did not launch.') + + def testPopupsLaunchWhenTabIsClosed(self): + """Verify popups are launched when closing a tab.""" + self._SetPopupsException() + self.AppendTab(pyauto.GURL('http://www.popuptest.com/popuptest12.html')) + self.assertEqual(4, self.GetBrowserWindowCount(), + msg='Popups did not launch from the external site.') + self.GetBrowserWindow(0).GetTab(1).Close(True) + # Check if last popup is launched when the tab is closed. + self.assertEqual(5, self.GetBrowserWindowCount(), + msg='Last popup did not launch when the tab is closed.') + + def testUnblockedPopupShowsInHistory(self): + """Verify that when you unblock popup, the popup shows in history.""" + file_url = self.GetFileURLForDataPath('popup_blocker', + 'popup-window-open.html') + self.NavigateToURL(file_url) + self.assertEqual(1, len(self.GetBlockedPopupsInfo())) + self.UnblockAndLaunchBlockedPopup(0) + self.assertTrue(self.WaitUntil( + lambda: len(self.GetHistoryInfo().History()) == 2)) + self.assertEqual('Popup Success!', + self.GetHistoryInfo().History()[0]['title']) + + def testBlockedPopupNotShowInHistory(self): + """Verify that a blocked popup does not show up in history.""" + file_url = self.GetFileURLForDataPath('popup_blocker', + 'popup-window-open.html') + self.NavigateToURL(file_url) + self.assertEqual(1, len(self.GetBlockedPopupsInfo())) + self.assertEqual(1, len(self.GetHistoryInfo().History())) + + def testUnblockedPopupAddedToOmnibox(self): + """Verify that an unblocked popup shows up in omnibox suggestions.""" + file_url = self.GetFileURLForDataPath('popup_blocker', + 'popup-window-open.html') + self.NavigateToURL(file_url) + self.assertEqual(1, len(self.GetBlockedPopupsInfo())) + self.UnblockAndLaunchBlockedPopup(0) + search_string = 'data:text/html,Popup Success! \ + you should not see this message if popup blocker is enabled' + matches = test_utils.GetOmniboxMatchesFor(self, search_string) + self.assertEqual(search_string, matches[0]['destination_url']) + self.assertEqual(search_string, matches[0]['contents']) + + +if __name__ == '__main__': + pyauto_functional.Main() + +# -*- coding: utf-8 -*- +""" + pygments.formatters.latex + ~~~~~~~~~~~~~~~~~~~~~~~~~ + + Formatter for LaTeX fancyvrb output. + + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +from __future__ import division + +from pygments.formatter import Formatter +from pygments.token import Token, STANDARD_TYPES +from pygments.util import get_bool_opt, get_int_opt, StringIO, xrange, \ + iteritems + + +__all__ = ['LatexFormatter'] + + +def escape_tex(text, commandprefix): + return text.replace('\\', '\x00'). \ + replace('{', '\x01'). \ + replace('}', '\x02'). \ + replace('\x00', r'\%sZbs{}' % commandprefix). \ + replace('\x01', r'\%sZob{}' % commandprefix). \ + replace('\x02', r'\%sZcb{}' % commandprefix). \ + replace('^', r'\%sZca{}' % commandprefix). \ + replace('_', r'\%sZus{}' % commandprefix). \ + replace('&', r'\%sZam{}' % commandprefix). \ + replace('<', r'\%sZlt{}' % commandprefix). \ + replace('>', r'\%sZgt{}' % commandprefix). \ + replace('#', r'\%sZsh{}' % commandprefix). \ + replace('%', r'\%sZpc{}' % commandprefix). \ + replace('$', r'\%sZdl{}' % commandprefix). \ + replace('-', r'\%sZhy{}' % commandprefix). \ + replace("'", r'\%sZsq{}' % commandprefix). \ + replace('"', r'\%sZdq{}' % commandprefix). \ + replace('~', r'\%sZti{}' % commandprefix) + + +DOC_TEMPLATE = r''' +\documentclass{%(docclass)s} +\usepackage{fancyvrb} +\usepackage{color} +\usepackage[%(encoding)s]{inputenc} +%(preamble)s + +%(styledefs)s + +\begin{document} + +\section*{%(title)s} + +%(code)s +\end{document} +''' + +## Small explanation of the mess below :) +# +# The previous version of the LaTeX formatter just assigned a command to +# each token type defined in the current style. That obviously is +# problematic if the highlighted code is produced for a different style +# than the style commands themselves. +# +# This version works much like the HTML formatter which assigns multiple +# CSS classes to each tag, from the most specific to the least +# specific token type, thus falling back to the parent token type if one +# is not defined. Here, the classes are there too and use the same short +# forms given in token.STANDARD_TYPES. +# +# Highlighted code now only uses one custom command, which by default is +# \PY and selectable by the commandprefix option (and in addition the +# escapes \PYZat, \PYZlb and \PYZrb which haven't been renamed for +# backwards compatibility purposes). +# +# \PY has two arguments: the classes, separated by +, and the text to +# render in that style. The classes are resolved into the respective +# style commands by magic, which serves to ignore unknown classes. +# +# The magic macros are: +# * \PY@it, \PY@bf, etc. are unconditionally wrapped around the text +# to render in \PY@do. Their definition determines the style. +# * \PY@reset resets \PY@it etc. to do nothing. +# * \PY@toks parses the list of classes, using magic inspired by the +# keyval package (but modified to use plusses instead of commas +# because fancyvrb redefines commas inside its environments). +# * \PY@tok processes one class, calling the \PY@tok@classname command +# if it exists. +# * \PY@tok@classname sets the \PY@it etc. to reflect the chosen style +# for its class. +# * \PY resets the style, parses the classnames and then calls \PY@do. +# +# Tip: to read this code, print it out in substituted form using e.g. +# >>> print STYLE_TEMPLATE % {'cp': 'PY'} + +STYLE_TEMPLATE = r''' +\makeatletter +\def\%(cp)s@reset{\let\%(cp)s@it=\relax \let\%(cp)s@bf=\relax%% + \let\%(cp)s@ul=\relax \let\%(cp)s@tc=\relax%% + \let\%(cp)s@bc=\relax \let\%(cp)s@ff=\relax} +\def\%(cp)s@tok#1{\csname %(cp)s@tok@#1\endcsname} +\def\%(cp)s@toks#1+{\ifx\relax#1\empty\else%% + \%(cp)s@tok{#1}\expandafter\%(cp)s@toks\fi} +\def\%(cp)s@do#1{\%(cp)s@bc{\%(cp)s@tc{\%(cp)s@ul{%% + \%(cp)s@it{\%(cp)s@bf{\%(cp)s@ff{#1}}}}}}} +\def\%(cp)s#1#2{\%(cp)s@reset\%(cp)s@toks#1+\relax+\%(cp)s@do{#2}} + +%(styles)s + +\def\%(cp)sZbs{\char`\\} +\def\%(cp)sZus{\char`\_} +\def\%(cp)sZob{\char`\{} +\def\%(cp)sZcb{\char`\}} +\def\%(cp)sZca{\char`\^} +\def\%(cp)sZam{\char`\&} +\def\%(cp)sZlt{\char`\<} +\def\%(cp)sZgt{\char`\>} +\def\%(cp)sZsh{\char`\#} +\def\%(cp)sZpc{\char`\%%} +\def\%(cp)sZdl{\char`\$} +\def\%(cp)sZhy{\char`\-} +\def\%(cp)sZsq{\char`\'} +\def\%(cp)sZdq{\char`\"} +\def\%(cp)sZti{\char`\~} +%% for compatibility with earlier versions +\def\%(cp)sZat{@} +\def\%(cp)sZlb{[} +\def\%(cp)sZrb{]} +\makeatother +''' + + +def _get_ttype_name(ttype): + fname = STANDARD_TYPES.get(ttype) + if fname: + return fname + aname = '' + while fname is None: + aname = ttype[-1] + aname + ttype = ttype.parent + fname = STANDARD_TYPES.get(ttype) + return fname + aname + + +class LatexFormatter(Formatter): + r""" + Format tokens as LaTeX code. This needs the `fancyvrb` and `color` + standard packages. + + Without the `full` option, code is formatted as one ``Verbatim`` + environment, like this: + + .. sourcecode:: latex + + \begin{Verbatim}[commandchars=\\\{\}] + \PY{k}{def }\PY{n+nf}{foo}(\PY{n}{bar}): + \PY{k}{pass} + \end{Verbatim} + + The special command used here (``\PY``) and all the other macros it needs + are output by the `get_style_defs` method. + + With the `full` option, a complete LaTeX document is output, including + the command definitions in the preamble. + + The `get_style_defs()` method of a `LatexFormatter` returns a string + containing ``\def`` commands defining the macros needed inside the + ``Verbatim`` environments. + + Additional options accepted: + + `style` + The style to use, can be a string or a Style subclass (default: + ``'default'``). + + `full` + Tells the formatter to output a "full" document, i.e. a complete + self-contained document (default: ``False``). + + `title` + If `full` is true, the title that should be used to caption the + document (default: ``''``). + + `docclass` + If the `full` option is enabled, this is the document class to use + (default: ``'article'``). + + `preamble` + If the `full` option is enabled, this can be further preamble commands, + e.g. ``\usepackage`` (default: ``''``). + + `linenos` + If set to ``True``, output line numbers (default: ``False``). + + `linenostart` + The line number for the first line (default: ``1``). + + `linenostep` + If set to a number n > 1, only every nth line number is printed. + + `verboptions` + Additional options given to the Verbatim environment (see the *fancyvrb* + docs for possible values) (default: ``''``). + + `commandprefix` + The LaTeX commands used to produce colored output are constructed + using this prefix and some letters (default: ``'PY'``). + + .. versionadded:: 0.7 + .. versionchanged:: 0.10 + The default is now ``'PY'`` instead of ``'C'``. + + `texcomments` + If set to ``True``, enables LaTeX comment lines. That is, LaTex markup + in comment tokens is not escaped so that LaTeX can render it (default: + ``False``). + + .. versionadded:: 1.2 + + `mathescape` + If set to ``True``, enables LaTeX math mode escape in comments. That + is, ``'$...$'`` inside a comment will trigger math mode (default: + ``False``). + + .. versionadded:: 1.2 + """ + name = 'LaTeX' + aliases = ['latex', 'tex'] + filenames = ['*.tex'] + + def __init__(self, **options): + Formatter.__init__(self, **options) + self.docclass = options.get('docclass', 'article') + self.preamble = options.get('preamble', '') + self.linenos = get_bool_opt(options, 'linenos', False) + self.linenostart = abs(get_int_opt(options, 'linenostart', 1)) + self.linenostep = abs(get_int_opt(options, 'linenostep', 1)) + self.verboptions = options.get('verboptions', '') + self.nobackground = get_bool_opt(options, 'nobackground', False) + self.commandprefix = options.get('commandprefix', 'PY') + self.texcomments = get_bool_opt(options, 'texcomments', False) + self.mathescape = get_bool_opt(options, 'mathescape', False) + + self._create_stylesheet() + + + def _create_stylesheet(self): + t2n = self.ttype2name = {Token: ''} + c2d = self.cmd2def = {} + cp = self.commandprefix + + def rgbcolor(col): + if col: + return ','.join(['%.2f' %(int(col[i] + col[i + 1], 16) / 255.0) + for i in (0, 2, 4)]) + else: + return '1,1,1' + + for ttype, ndef in self.style: + name = _get_ttype_name(ttype) + cmndef = '' + if ndef['bold']: + cmndef += r'\let\$$@bf=\textbf' + if ndef['italic']: + cmndef += r'\let\$$@it=\textit' + if ndef['underline']: + cmndef += r'\let\$$@ul=\underline' + if ndef['roman']: + cmndef += r'\let\$$@ff=\textrm' + if ndef['sans']: + cmndef += r'\let\$$@ff=\textsf' + if ndef['mono']: + cmndef += r'\let\$$@ff=\textsf' + if ndef['color']: + cmndef += (r'\def\$$@tc##1{\textcolor[rgb]{%s}{##1}}' % + rgbcolor(ndef['color'])) + if ndef['border']: + cmndef += (r'\def\$$@bc##1{\setlength{\fboxsep}{0pt}' + r'\fcolorbox[rgb]{%s}{%s}{\strut ##1}}' % + (rgbcolor(ndef['border']), + rgbcolor(ndef['bgcolor']))) + elif ndef['bgcolor']: + cmndef += (r'\def\$$@bc##1{\setlength{\fboxsep}{0pt}' + r'\colorbox[rgb]{%s}{\strut ##1}}' % + rgbcolor(ndef['bgcolor'])) + if cmndef == '': + continue + cmndef = cmndef.replace('$$', cp) + t2n[ttype] = name + c2d[name] = cmndef + + def get_style_defs(self, arg=''): + """ + Return the command sequences needed to define the commands + used to format text in the verbatim environment. ``arg`` is ignored. + """ + cp = self.commandprefix + styles = [] + for name, definition in iteritems(self.cmd2def): + styles.append(r'\expandafter\def\csname %s@tok@%s\endcsname{%s}' % + (cp, name, definition)) + return STYLE_TEMPLATE % {'cp': self.commandprefix, + 'styles': '\n'.join(styles)} + + def format_unencoded(self, tokensource, outfile): + # TODO: add support for background colors + t2n = self.ttype2name + cp = self.commandprefix + + if self.full: + realoutfile = outfile + outfile = StringIO() + + outfile.write(r'\begin{Verbatim}[commandchars=\\\{\}') + if self.linenos: + start, step = self.linenostart, self.linenostep + outfile.write(u',numbers=left' + + (start and u',firstnumber=%d' % start or u'') + + (step and u',stepnumber=%d' % step or u'')) + if self.mathescape or self.texcomments: + outfile.write(r',codes={\catcode`\$=3\catcode`\^=7\catcode`\_=8}') + if self.verboptions: + outfile.write(u',' + self.verboptions) + outfile.write(u']\n') + + for ttype, value in tokensource: + if ttype in Token.Comment: + if self.texcomments: + # Try to guess comment starting lexeme and escape it ... + start = value[0:1] + for i in xrange(1, len(value)): + if start[0] != value[i]: + break + start += value[i] + + value = value[len(start):] + start = escape_tex(start, self.commandprefix) + + # ... but do not escape inside comment. + value = start + value + elif self.mathescape: + # Only escape parts not inside a math environment. + parts = value.split('$') + in_math = False + for i, part in enumerate(parts): + if not in_math: + parts[i] = escape_tex(part, self.commandprefix) + in_math = not in_math + value = '$'.join(parts) + else: + value = escape_tex(value, self.commandprefix) + else: + value = escape_tex(value, self.commandprefix) + styles = [] + while ttype is not Token: + try: + styles.append(t2n[ttype]) + except KeyError: + # not in current style + styles.append(_get_ttype_name(ttype)) + ttype = ttype.parent + styleval = '+'.join(reversed(styles)) + if styleval: + spl = value.split('\n') + for line in spl[:-1]: + if line: + outfile.write("\\%s{%s}{%s}" % (cp, styleval, line)) + outfile.write('\n') + if spl[-1]: + outfile.write("\\%s{%s}{%s}" % (cp, styleval, spl[-1])) + else: + outfile.write(value) + + outfile.write(u'\\end{Verbatim}\n') + + if self.full: + realoutfile.write(DOC_TEMPLATE % + dict(docclass = self.docclass, + preamble = self.preamble, + title = self.title, + encoding = self.encoding or 'latin1', + styledefs = self.get_style_defs(), + code = outfile.getvalue())) + +# coding=utf-8 +# Copyright 2021 The Google Research Authors. +# +# 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. + +# Copyright 2020 Google LLC +# +# 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 +# +# https://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. +# ============================================================================== + +"""Setup the package with pip.""" + + +import os +import sys + +import setuptools + + +# https://packaging.python.org/guides/making-a-pypi-friendly-readme/ +this_directory = os.path.abspath(os.path.dirname(__file__)) +with open(os.path.join(this_directory, 'README.md'), encoding='utf-8') as f: + long_description = f.read() + + +INSTALL_REQUIRES = [ + 'jax', 'jaxlib' +] + + +def _get_version() -> str: + """Returns the package version. + + Adapted from: + https://github.com/deepmind/dm-haiku/blob/d4807e77b0b03c41467e24a247bed9d1897d336c/setup.py#L22 + + Returns: + Version number. + """ + path = '__init__.py' + version = '__version__' + with open(path) as fp: + for line in fp: + if line.startswith(version): + g = {} + exec(line, g) # pylint: disable=exec-used + return g[version] # pytype: disable=key-error + raise ValueError(f'`{version}` not defined in `{path}`.') + + +setuptools.setup( + name='jax2tex', + version=_get_version(), + license='Apache 2.0', + author='Google', + author_email='schsam@google.com', + install_requires=INSTALL_REQUIRES, + long_description=long_description, + long_description_content_type='text/markdown', + description='Convert jax functions to latex output.', + python_requires='>=3.6') + +#!/usr/bin/python +import time +import re +import logging +import socket +import ssl +from logging.handlers import RotatingFileHandler +from multiprocessing.dummy import Pool, Process +from multiprocessing import cpu_count + +SSLPORTS = [6697, 7000, 7070] +NONSSLPORTS = [6665, 6666, 6667, 8000, 8001, 8002] + +class CommandHandle(object): + """ Base Class for commands """ + def __init__(self, regex, function): + if not isinstance(regex, list): + regex = [regex] + self.regex = regex + self.function = function + self.cregex = [] + +class Channel(object): + """ Base class for channels""" + def __init__(self): + self.users = {} + #{'name': 'ACC level'}, + self.ops = [] + self.voices = [] + self.modes = [] + self.topic = "" + +class IRCServer(object): + """ Manages Irc server connection """ + def __init__( + self, nick, host="chat.freenode.net", + autojoin=['#stirbot'], ssl=False, timeout=60*4, + threads=cpu_count()**3, pswrd=False + ): + self.nick, self.host, self.pswrd = nick, host, pswrd + self.ssl, self.threads = ssl, threads + if not self.ssl: + self.port = 6666 + else: + self.port = 7070 + self.timeout, self.threads = timeout, threads + self._listenThread = self._sock = None + self._connected = self._running = self._authed = False + self.channels, self.joinChans = {}, autojoin + self.commands = {} + self._pool = Pool(int(self.threads)) + self._listenPool = Pool(int(self.threads)) + self.nickserv = 'NickServ!NickServ@services.' + self.servHost = None +#------------------------------------------------------------------------------- + self._serverRe = { + '_002': CommandHandle(r'^:(.*) 002 (.*) :.*', self._got002), + '_Ping': CommandHandle(r'^PING :(.*)', self._pong), + '_Sniff': CommandHandle( + [ + r'^:(.*)!(.*) PRIVMSG (.*) :(.*)', + r'^:(.*)!(.*) NOTICE (.*) :(.*)' + ], + self._sniffMessage + ), + '_332': CommandHandle( + [ + r'^:(.*) 332 %s (.*) :(.*)' % self.nick, + r'^:(.*) TOPIC (.*) :(.*)' + ], + self._updateTopic + ), + '_353': CommandHandle( + r'^:.* 353 %s . (.*) :(.*)' % self.nick, + self._updateNames + ), + '_Quit': CommandHandle( + r'^:(.*)!.* QUIT :', self._somebodyQuit + ), + '_Modeset': CommandHandle( + r'^:.* MODE (.*) \+([A-Za-z]) (.*)', self._modeSet + ), + '_Modeunset': CommandHandle( + r'^:.* MODE (.*) -([A-Za-z]) (.*)', self._modeUnset + ), + '_Join': CommandHandle( + r'^:(.*)!.* JOIN (.*)', self._joinedUser + ), + '_Part': CommandHandle( + r'^:(.*)!.* PART (.*) :.*', self._removeUser + ), + '_ACC': CommandHandle( + r'^:(.+) NOTICE %s :(.+) ACC (\d)(.*)?' % self.nick, + self._updateACC + ), + '_Identify': CommandHandle( + r'^:(.+) NOTICE (.+) :You are now identified for', + self._identified + ) + } + + def _got002(self, match): + """ Fills Serverhost name attribute""" + if match.group(2) == self.nick: + self.servHost = match.group(1) + logging.info("Our server host is: %s" % self.servHost) + + def _pong(self, match): + """ Pong the Ping """ + logging.debug(match.group(0)) + if match.group(1) == self.servHost: + self._send("PONG :%s" % self.servHost) + + def _identified(self, match): + """ Tells the bot it is authenticated with Nickserv """ + logging.debug(match.group(0)) + if match.group(1) == self.nickserv and match.group(2) == self.nick: + self._authed = True + logging.info('%s is authenticated with Nickserv!' % self.nick) + + def _joinedUser(self, match): + """ Fires when a user joins a channel """ + logging.debug(match.group(0)) + nick, channel = match.group(1), match.group(2) + if channel not in self.channels: + self.channels[channel] = Channel() + self.channels[channel].users[nick] = 0 + logging.info('%s joined %s' % (nick, channel)) + + def _somebodyQuit(self, match): + """ Fires when a user quits """ + logging.debug(match.group(0)) + nick = match.group(1) + # if it is us quiting + if nick == self.nick: + self.disconnect() + else: + for channel in self.channels: + if nick in self.channels[channel].users: + del self.channels[channel].users[nick] + if nick in self.channels[channel].ops: + del self.channels[channel].ops[nick] + if nick in self.channels[channel].voices: + del self.channels[channel].voices[nick] + logging.info('%s quit!' % nick) + + def _removeUser(self, match): + """ Removes a user from a channel """ + logging.debug(match.group(0)) + nick, channel = match.group(1), match.group(2) + if nick is self.nick: + del self.channels[channel] + else: + del self.channels[channel].users[nick] + if nick in self.channels[channel].ops: + del self.channels[channel].ops[nick] + if nick in self.channels[channel].voices: + del self.channels[channel].voices[nick] + logging.info('%s parted %s' % (nick, channel)) + logging.debug(self.channels[channel].users) + + def _updateTopic(self, match): + """ Update the topic for a channel """ + logging.debug(match.group(0)) + host, channel, topic = match.group(1), match.group(2), match.group(3) + if channel not in self.channels: + self.channels[channel] = Channel() + self.channels[channel].topic = topic + logging.info('[%s] TOPIC: %s' % (channel, self.channels[channel].topic)) + + def _updateNames(self, match): + """ Takes names from a 353 and populates the channels users """ + logging.debug(match.group(0)) + channel, names = match.group(1), match.group(2).split(' ') + if channel not in self.channels: + self.channels[channel] = Channel() + for name in names: + if name[0] == '@': + name = name[1:] + if name not in self.channels[channel].ops: + self.channels[channel].ops.append(name) + if name[0] == '+': + name = name[1:] + if name not in self.channels[channel].voices: + self.channels[channel].voices.append(name) + if name not in self.channels[channel].users: + self.channels[channel].users[name] = 0 + logging.info('[%s] USERS: %s' % ( + channel, str(self.channels[channel].users) + )) + logging.info('[%s] OPS: %s' % ( + channel, str(self.channels[channel].ops) + )) + logging.info('[%s] VOICES: %s' % ( + channel, str(self.channels[channel].voices) + )) + + def _updateACC(self, match): + """ Updates an users ACC level """ + logging.debug(match.group(0)) + nick, acc = match.group(2), match.group(3) + if match.group(1) == self.nickserv: + for channel in self.channels: + self.channels[channel].users[nick] = acc + logging.info('ACC: %s [%d]' % (nick, acc))